var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b ||= {})
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));

// node_modules/@ungap/custom-elements/index.js
(function() {
  "use strict";
  var attributesObserver = function(whenDefined2, MutationObserver2) {
    var attributeChanged = function attributeChanged2(records) {
      for (var i = 0, length = records.length; i < length; i++) {
        dispatch(records[i]);
      }
    };
    var dispatch = function dispatch2(_ref2) {
      var target = _ref2.target, attributeName = _ref2.attributeName, oldValue = _ref2.oldValue;
      target.attributeChangedCallback(attributeName, oldValue, target.getAttribute(attributeName));
    };
    return function(target, is2) {
      var attributeFilter = target.constructor.observedAttributes;
      if (attributeFilter) {
        whenDefined2(is2).then(function() {
          new MutationObserver2(attributeChanged).observe(target, {
            attributes: true,
            attributeOldValue: true,
            attributeFilter
          });
          for (var i = 0, length = attributeFilter.length; i < length; i++) {
            if (target.hasAttribute(attributeFilter[i]))
              dispatch({
                target,
                attributeName: attributeFilter[i],
                oldValue: null
              });
          }
        });
      }
      return target;
    };
  };
  function _unsupportedIterableToArray(o, minLen) {
    if (!o)
      return;
    if (typeof o === "string")
      return _arrayLikeToArray(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor)
      n = o.constructor.name;
    if (n === "Map" || n === "Set")
      return Array.from(o);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
      return _arrayLikeToArray(o, minLen);
  }
  function _arrayLikeToArray(arr, len) {
    if (len == null || len > arr.length)
      len = arr.length;
    for (var i = 0, arr2 = new Array(len); i < len; i++)
      arr2[i] = arr[i];
    return arr2;
  }
  function _createForOfIteratorHelper(o, allowArrayLike) {
    var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
    if (!it) {
      if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
        if (it)
          o = it;
        var i = 0;
        var F = function() {
        };
        return {
          s: F,
          n: function() {
            if (i >= o.length)
              return {
                done: true
              };
            return {
              done: false,
              value: o[i++]
            };
          },
          e: function(e3) {
            throw e3;
          },
          f: F
        };
      }
      throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
    }
    var normalCompletion = true, didErr = false, err2;
    return {
      s: function() {
        it = it.call(o);
      },
      n: function() {
        var step = it.next();
        normalCompletion = step.done;
        return step;
      },
      e: function(e3) {
        didErr = true;
        err2 = e3;
      },
      f: function() {
        try {
          if (!normalCompletion && it.return != null)
            it.return();
        } finally {
          if (didErr)
            throw err2;
        }
      }
    };
  }
  var TRUE = true, FALSE = false, QSA$1 = "querySelectorAll";
  var notify2 = function notify3(callback) {
    var root2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : document;
    var MO = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : MutationObserver;
    var query2 = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : ["*"];
    var loop = function loop2(nodes, selectors, added, removed, connected, pass) {
      var _iterator = _createForOfIteratorHelper(nodes), _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done; ) {
          var node = _step.value;
          if (pass || QSA$1 in node) {
            if (connected) {
              if (!added.has(node)) {
                added.add(node);
                removed["delete"](node);
                callback(node, connected);
              }
            } else if (!removed.has(node)) {
              removed.add(node);
              added["delete"](node);
              callback(node, connected);
            }
            if (!pass)
              loop2(node[QSA$1](selectors), selectors, added, removed, connected, TRUE);
          }
        }
      } catch (err2) {
        _iterator.e(err2);
      } finally {
        _iterator.f();
      }
    };
    var mo = new MO(function(records) {
      if (query2.length) {
        var selectors = query2.join(",");
        var added = /* @__PURE__ */ new Set(), removed = /* @__PURE__ */ new Set();
        var _iterator2 = _createForOfIteratorHelper(records), _step2;
        try {
          for (_iterator2.s(); !(_step2 = _iterator2.n()).done; ) {
            var _step2$value = _step2.value, addedNodes = _step2$value.addedNodes, removedNodes = _step2$value.removedNodes;
            loop(removedNodes, selectors, added, removed, FALSE, FALSE);
            loop(addedNodes, selectors, added, removed, TRUE, FALSE);
          }
        } catch (err2) {
          _iterator2.e(err2);
        } finally {
          _iterator2.f();
        }
      }
    });
    var observe = mo.observe;
    (mo.observe = function(node) {
      return observe.call(mo, node, {
        subtree: TRUE,
        childList: TRUE
      });
    })(root2);
    return mo;
  };
  var QSA = "querySelectorAll";
  var _self$1 = self, document$2 = _self$1.document, Element$1 = _self$1.Element, MutationObserver$2 = _self$1.MutationObserver, Set$2 = _self$1.Set, WeakMap$1 = _self$1.WeakMap;
  var elements = function elements2(element2) {
    return QSA in element2;
  };
  var filter2 = [].filter;
  var qsaObserver = function(options2) {
    var live = new WeakMap$1();
    var drop2 = function drop3(elements2) {
      for (var i = 0, length = elements2.length; i < length; i++) {
        live["delete"](elements2[i]);
      }
    };
    var flush2 = function flush3() {
      var records = observer.takeRecords();
      for (var i = 0, length = records.length; i < length; i++) {
        parse2(filter2.call(records[i].removedNodes, elements), false);
        parse2(filter2.call(records[i].addedNodes, elements), true);
      }
    };
    var matches = function matches2(element2) {
      return element2.matches || element2.webkitMatchesSelector || element2.msMatchesSelector;
    };
    var notifier = function notifier2(element2, connected) {
      var selectors;
      if (connected) {
        for (var q, m = matches(element2), i = 0, length = query2.length; i < length; i++) {
          if (m.call(element2, q = query2[i])) {
            if (!live.has(element2))
              live.set(element2, new Set$2());
            selectors = live.get(element2);
            if (!selectors.has(q)) {
              selectors.add(q);
              options2.handle(element2, connected, q);
            }
          }
        }
      } else if (live.has(element2)) {
        selectors = live.get(element2);
        live["delete"](element2);
        selectors.forEach(function(q2) {
          options2.handle(element2, connected, q2);
        });
      }
    };
    var parse2 = function parse3(elements2) {
      var connected = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
      for (var i = 0, length = elements2.length; i < length; i++) {
        notifier(elements2[i], connected);
      }
    };
    var query2 = options2.query;
    var root2 = options2.root || document$2;
    var observer = notify2(notifier, root2, MutationObserver$2, query2);
    var attachShadow2 = Element$1.prototype.attachShadow;
    if (attachShadow2)
      Element$1.prototype.attachShadow = function(init3) {
        var shadowRoot = attachShadow2.call(this, init3);
        observer.observe(shadowRoot);
        return shadowRoot;
      };
    if (query2.length)
      parse2(root2[QSA](query2));
    return {
      drop: drop2,
      flush: flush2,
      observer,
      parse: parse2
    };
  };
  var _self = self, document$1 = _self.document, Map2 = _self.Map, MutationObserver$1 = _self.MutationObserver, Object$1 = _self.Object, Set$1 = _self.Set, WeakMap2 = _self.WeakMap, Element2 = _self.Element, HTMLElement2 = _self.HTMLElement, Node3 = _self.Node, Error2 = _self.Error, TypeError$1 = _self.TypeError, Reflect2 = _self.Reflect;
  var defineProperty = Object$1.defineProperty, keys = Object$1.keys, getOwnPropertyNames = Object$1.getOwnPropertyNames, setPrototypeOf = Object$1.setPrototypeOf;
  var legacy = !self.customElements;
  var expando = function expando2(element2) {
    var key = keys(element2);
    var value = [];
    var length = key.length;
    for (var i = 0; i < length; i++) {
      value[i] = element2[key[i]];
      delete element2[key[i]];
    }
    return function() {
      for (var _i = 0; _i < length; _i++) {
        element2[key[_i]] = value[_i];
      }
    };
  };
  if (legacy) {
    var HTMLBuiltIn = function HTMLBuiltIn2() {
      var constructor = this.constructor;
      if (!classes.has(constructor))
        throw new TypeError$1("Illegal constructor");
      var is2 = classes.get(constructor);
      if (override)
        return augment(override, is2);
      var element2 = createElement.call(document$1, is2);
      return augment(setPrototypeOf(element2, constructor.prototype), is2);
    };
    var createElement = document$1.createElement;
    var classes = new Map2();
    var defined = new Map2();
    var prototypes = new Map2();
    var registry = new Map2();
    var query = [];
    var handle = function handle2(element2, connected, selector) {
      var proto = prototypes.get(selector);
      if (connected && !proto.isPrototypeOf(element2)) {
        var redefine = expando(element2);
        override = setPrototypeOf(element2, proto);
        try {
          new proto.constructor();
        } finally {
          override = null;
          redefine();
        }
      }
      var method = "".concat(connected ? "" : "dis", "connectedCallback");
      if (method in proto)
        element2[method]();
    };
    var _qsaObserver = qsaObserver({
      query,
      handle
    }), parse = _qsaObserver.parse;
    var override = null;
    var whenDefined = function whenDefined2(name2) {
      if (!defined.has(name2)) {
        var _2, $ = new Promise(function($2) {
          _2 = $2;
        });
        defined.set(name2, {
          $,
          _: _2
        });
      }
      return defined.get(name2).$;
    };
    var augment = attributesObserver(whenDefined, MutationObserver$1);
    defineProperty(self, "customElements", {
      configurable: true,
      value: {
        define: function define2(is2, Class) {
          if (registry.has(is2))
            throw new Error2('the name "'.concat(is2, '" has already been used with this registry'));
          classes.set(Class, is2);
          prototypes.set(is2, Class.prototype);
          registry.set(is2, Class);
          query.push(is2);
          whenDefined(is2).then(function() {
            parse(document$1.querySelectorAll(is2));
          });
          defined.get(is2)._(Class);
        },
        get: function get3(is2) {
          return registry.get(is2);
        },
        whenDefined
      }
    });
    defineProperty(HTMLBuiltIn.prototype = HTMLElement2.prototype, "constructor", {
      value: HTMLBuiltIn
    });
    defineProperty(self, "HTMLElement", {
      configurable: true,
      value: HTMLBuiltIn
    });
    defineProperty(document$1, "createElement", {
      configurable: true,
      value: function value(name2, options2) {
        var is2 = options2 && options2.is;
        var Class = is2 ? registry.get(is2) : registry.get(name2);
        return Class ? new Class() : createElement.call(document$1, name2);
      }
    });
    if (!("isConnected" in Node3.prototype))
      defineProperty(Node3.prototype, "isConnected", {
        configurable: true,
        get: function get3() {
          return !(this.ownerDocument.compareDocumentPosition(this) & this.DOCUMENT_POSITION_DISCONNECTED);
        }
      });
  } else {
    legacy = !self.customElements.get("extends-li");
    if (legacy) {
      try {
        var LI = function LI2() {
          return self.Reflect.construct(HTMLLIElement, [], LI2);
        };
        LI.prototype = HTMLLIElement.prototype;
        var is = "extends-li";
        self.customElements.define("extends-li", LI, {
          "extends": "li"
        });
        legacy = document$1.createElement("li", {
          is
        }).outerHTML.indexOf(is) < 0;
        var _self$customElements = self.customElements, get2 = _self$customElements.get, _whenDefined = _self$customElements.whenDefined;
        defineProperty(self.customElements, "whenDefined", {
          configurable: true,
          value: function value(is2) {
            var _this = this;
            return _whenDefined.call(this, is2).then(function(Class) {
              return Class || get2.call(_this, is2);
            });
          }
        });
      } catch (o_O) {
      }
    }
  }
  if (legacy) {
    var parseShadow = function parseShadow2(element2) {
      var root2 = shadowRoots.get(element2);
      _parse(root2.querySelectorAll(this), element2.isConnected);
    };
    var customElements2 = self.customElements;
    var _createElement = document$1.createElement;
    var define = customElements2.define, _get = customElements2.get, upgrade = customElements2.upgrade;
    var _ref = Reflect2 || {
      construct: function construct2(HTMLElement3) {
        return HTMLElement3.call(this);
      }
    }, construct = _ref.construct;
    var shadowRoots = new WeakMap2();
    var shadows = new Set$1();
    var _classes = new Map2();
    var _defined = new Map2();
    var _prototypes = new Map2();
    var _registry = new Map2();
    var shadowed = [];
    var _query = [];
    var getCE = function getCE2(is2) {
      return _registry.get(is2) || _get.call(customElements2, is2);
    };
    var _handle = function _handle2(element2, connected, selector) {
      var proto = _prototypes.get(selector);
      if (connected && !proto.isPrototypeOf(element2)) {
        var redefine = expando(element2);
        _override = setPrototypeOf(element2, proto);
        try {
          new proto.constructor();
        } finally {
          _override = null;
          redefine();
        }
      }
      var method = "".concat(connected ? "" : "dis", "connectedCallback");
      if (method in proto)
        element2[method]();
    };
    var _qsaObserver2 = qsaObserver({
      query: _query,
      handle: _handle
    }), _parse = _qsaObserver2.parse;
    var _qsaObserver3 = qsaObserver({
      query: shadowed,
      handle: function handle2(element2, connected) {
        if (shadowRoots.has(element2)) {
          if (connected)
            shadows.add(element2);
          else
            shadows["delete"](element2);
          if (_query.length)
            parseShadow.call(_query, element2);
        }
      }
    }), parseShadowed = _qsaObserver3.parse;
    var attachShadow = Element2.prototype.attachShadow;
    if (attachShadow)
      Element2.prototype.attachShadow = function(init3) {
        var root2 = attachShadow.call(this, init3);
        shadowRoots.set(this, root2);
        return root2;
      };
    var _whenDefined2 = function _whenDefined22(name2) {
      if (!_defined.has(name2)) {
        var _2, $ = new Promise(function($2) {
          _2 = $2;
        });
        _defined.set(name2, {
          $,
          _: _2
        });
      }
      return _defined.get(name2).$;
    };
    var _augment = attributesObserver(_whenDefined2, MutationObserver$1);
    var _override = null;
    getOwnPropertyNames(self).filter(function(k) {
      return /^HTML.*Element$/.test(k);
    }).forEach(function(k) {
      var HTMLElement3 = self[k];
      function HTMLBuiltIn2() {
        var constructor = this.constructor;
        if (!_classes.has(constructor))
          throw new TypeError$1("Illegal constructor");
        var _classes$get = _classes.get(constructor), is2 = _classes$get.is, tag2 = _classes$get.tag;
        if (is2) {
          if (_override)
            return _augment(_override, is2);
          var element2 = _createElement.call(document$1, tag2);
          element2.setAttribute("is", is2);
          return _augment(setPrototypeOf(element2, constructor.prototype), is2);
        } else
          return construct.call(this, HTMLElement3, [], constructor);
      }
      defineProperty(HTMLBuiltIn2.prototype = HTMLElement3.prototype, "constructor", {
        value: HTMLBuiltIn2
      });
      defineProperty(self, k, {
        value: HTMLBuiltIn2
      });
    });
    defineProperty(document$1, "createElement", {
      configurable: true,
      value: function value(name2, options2) {
        var is2 = options2 && options2.is;
        if (is2) {
          var Class = _registry.get(is2);
          if (Class && _classes.get(Class).tag === name2)
            return new Class();
        }
        var element2 = _createElement.call(document$1, name2);
        if (is2)
          element2.setAttribute("is", is2);
        return element2;
      }
    });
    defineProperty(customElements2, "get", {
      configurable: true,
      value: getCE
    });
    defineProperty(customElements2, "whenDefined", {
      configurable: true,
      value: _whenDefined2
    });
    defineProperty(customElements2, "upgrade", {
      configurable: true,
      value: function value(element2) {
        var is2 = element2.getAttribute("is");
        if (is2) {
          var _constructor = _registry.get(is2);
          if (_constructor) {
            _augment(setPrototypeOf(element2, _constructor.prototype), is2);
            return;
          }
        }
        upgrade.call(customElements2, element2);
      }
    });
    defineProperty(customElements2, "define", {
      configurable: true,
      value: function value(is2, Class, options2) {
        if (getCE(is2))
          throw new Error2("'".concat(is2, "' has already been defined as a custom element"));
        var selector;
        var tag2 = options2 && options2["extends"];
        _classes.set(Class, tag2 ? {
          is: is2,
          tag: tag2
        } : {
          is: "",
          tag: is2
        });
        if (tag2) {
          selector = "".concat(tag2, '[is="').concat(is2, '"]');
          _prototypes.set(selector, Class.prototype);
          _registry.set(is2, Class);
          _query.push(selector);
        } else {
          define.apply(customElements2, arguments);
          shadowed.push(selector = is2);
        }
        _whenDefined2(is2).then(function() {
          if (tag2) {
            _parse(document$1.querySelectorAll(selector));
            shadows.forEach(parseShadow, [selector]);
          } else
            parseShadowed(document$1.querySelectorAll(selector));
        });
        _defined.get(is2)._(Class);
      }
    });
  }
})();

// node_modules/svelte/internal/index.mjs
function noop() {
}
function assign(tar, src) {
  for (const k in src)
    tar[k] = src[k];
  return tar;
}
function is_promise(value) {
  return value && typeof value === "object" && typeof value.then === "function";
}
function run(fn) {
  return fn();
}
function blank_object() {
  return /* @__PURE__ */ Object.create(null);
}
function run_all(fns) {
  fns.forEach(run);
}
function is_function(thing) {
  return typeof thing === "function";
}
function safe_not_equal(a, b) {
  return a != a ? b == b : a !== b || (a && typeof a === "object" || typeof a === "function");
}
var src_url_equal_anchor;
function src_url_equal(element_src, url) {
  if (!src_url_equal_anchor) {
    src_url_equal_anchor = document.createElement("a");
  }
  src_url_equal_anchor.href = url;
  return element_src === src_url_equal_anchor.href;
}
function is_empty(obj) {
  return Object.keys(obj).length === 0;
}
function subscribe(store, ...callbacks) {
  if (store == null) {
    return noop;
  }
  const unsub = store.subscribe(...callbacks);
  return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}
function get_store_value(store) {
  let value;
  subscribe(store, (_2) => value = _2)();
  return value;
}
function component_subscribe(component, store, callback) {
  component.$$.on_destroy.push(subscribe(store, callback));
}
function create_slot(definition, ctx2, $$scope, fn) {
  if (definition) {
    const slot_ctx = get_slot_context(definition, ctx2, $$scope, fn);
    return definition[0](slot_ctx);
  }
}
function get_slot_context(definition, ctx2, $$scope, fn) {
  return definition[1] && fn ? assign($$scope.ctx.slice(), definition[1](fn(ctx2))) : $$scope.ctx;
}
function get_slot_changes(definition, $$scope, dirty, fn) {
  if (definition[2] && fn) {
    const lets = definition[2](fn(dirty));
    if ($$scope.dirty === void 0) {
      return lets;
    }
    if (typeof lets === "object") {
      const merged = [];
      const len = Math.max($$scope.dirty.length, lets.length);
      for (let i = 0; i < len; i += 1) {
        merged[i] = $$scope.dirty[i] | lets[i];
      }
      return merged;
    }
    return $$scope.dirty | lets;
  }
  return $$scope.dirty;
}
function update_slot_base(slot, slot_definition, ctx2, $$scope, slot_changes, get_slot_context_fn) {
  if (slot_changes) {
    const slot_context = get_slot_context(slot_definition, ctx2, $$scope, get_slot_context_fn);
    slot.p(slot_context, slot_changes);
  }
}
function get_all_dirty_from_scope($$scope) {
  if ($$scope.ctx.length > 32) {
    const dirty = [];
    const length = $$scope.ctx.length / 32;
    for (let i = 0; i < length; i++) {
      dirty[i] = -1;
    }
    return dirty;
  }
  return -1;
}
function compute_slots(slots) {
  const result = {};
  for (const key in slots) {
    result[key] = true;
  }
  return result;
}
function null_to_empty(value) {
  return value == null ? "" : value;
}
function set_store_value(store, ret, value) {
  store.set(value);
  return ret;
}
function action_destroyer(action_result) {
  return action_result && is_function(action_result.destroy) ? action_result.destroy : noop;
}
var is_hydrating = false;
function start_hydrating() {
  is_hydrating = true;
}
function end_hydrating() {
  is_hydrating = false;
}
function append(target, node) {
  target.appendChild(node);
}
function insert(target, node, anchor) {
  target.insertBefore(node, anchor || null);
}
function detach(node) {
  node.parentNode.removeChild(node);
}
function destroy_each(iterations, detaching) {
  for (let i = 0; i < iterations.length; i += 1) {
    if (iterations[i])
      iterations[i].d(detaching);
  }
}
function element(name2) {
  return document.createElement(name2);
}
function svg_element(name2) {
  return document.createElementNS("http://www.w3.org/2000/svg", name2);
}
function text(data) {
  return document.createTextNode(data);
}
function space() {
  return text(" ");
}
function empty() {
  return text("");
}
function listen(node, event, handler, options2) {
  node.addEventListener(event, handler, options2);
  return () => node.removeEventListener(event, handler, options2);
}
function prevent_default(fn) {
  return function(event) {
    event.preventDefault();
    return fn.call(this, event);
  };
}
function attr(node, attribute, value) {
  if (value == null)
    node.removeAttribute(attribute);
  else if (node.getAttribute(attribute) !== value)
    node.setAttribute(attribute, value);
}
function children(element2) {
  return Array.from(element2.childNodes);
}
function set_data(text2, data) {
  data = "" + data;
  if (text2.wholeText !== data)
    text2.data = data;
}
function set_input_value(input, value) {
  input.value = value == null ? "" : value;
}
function set_style(node, key, value, important) {
  if (value === null) {
    node.style.removeProperty(key);
  } else {
    node.style.setProperty(key, value, important ? "important" : "");
  }
}
function select_option(select, value) {
  for (let i = 0; i < select.options.length; i += 1) {
    const option = select.options[i];
    if (option.__value === value) {
      option.selected = true;
      return;
    }
  }
  select.selectedIndex = -1;
}
function select_value(select) {
  const selected_option = select.querySelector(":checked") || select.options[0];
  return selected_option && selected_option.__value;
}
var crossorigin;
function is_crossorigin() {
  if (crossorigin === void 0) {
    crossorigin = false;
    try {
      if (typeof window !== "undefined" && window.parent) {
        void window.parent.document;
      }
    } catch (error) {
      crossorigin = true;
    }
  }
  return crossorigin;
}
function add_resize_listener(node, fn) {
  const computed_style = getComputedStyle(node);
  if (computed_style.position === "static") {
    node.style.position = "relative";
  }
  const iframe = element("iframe");
  iframe.setAttribute("style", "display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; border: 0; opacity: 0; pointer-events: none; z-index: -1;");
  iframe.setAttribute("aria-hidden", "true");
  iframe.tabIndex = -1;
  const crossorigin2 = is_crossorigin();
  let unsubscribe;
  if (crossorigin2) {
    iframe.src = "data:text/html,<script>onresize=function(){parent.postMessage(0,'*')}<\/script>";
    unsubscribe = listen(window, "message", (event) => {
      if (event.source === iframe.contentWindow)
        fn();
    });
  } else {
    iframe.src = "about:blank";
    iframe.onload = () => {
      unsubscribe = listen(iframe.contentWindow, "resize", fn);
    };
  }
  append(node, iframe);
  return () => {
    if (crossorigin2) {
      unsubscribe();
    } else if (unsubscribe && iframe.contentWindow) {
      unsubscribe();
    }
    detach(iframe);
  };
}
function toggle_class(element2, name2, toggle2) {
  element2.classList[toggle2 ? "add" : "remove"](name2);
}
function custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {
  const e3 = document.createEvent("CustomEvent");
  e3.initCustomEvent(type, bubbles, cancelable, detail);
  return e3;
}
var HtmlTag = class {
  constructor(is_svg = false) {
    this.is_svg = false;
    this.is_svg = is_svg;
    this.e = this.n = null;
  }
  c(html) {
    this.h(html);
  }
  m(html, target, anchor = null) {
    if (!this.e) {
      if (this.is_svg)
        this.e = svg_element(target.nodeName);
      else
        this.e = element(target.nodeName);
      this.t = target;
      this.c(html);
    }
    this.i(anchor);
  }
  h(html) {
    this.e.innerHTML = html;
    this.n = Array.from(this.e.childNodes);
  }
  i(anchor) {
    for (let i = 0; i < this.n.length; i += 1) {
      insert(this.t, this.n[i], anchor);
    }
  }
  p(html) {
    this.d();
    this.h(html);
    this.i(this.a);
  }
  d() {
    this.n.forEach(detach);
  }
};
function construct_svelte_component(component, props) {
  return new component(props);
}
var current_component;
function set_current_component(component) {
  current_component = component;
}
function get_current_component() {
  if (!current_component)
    throw new Error("Function called outside component initialization");
  return current_component;
}
function onMount(fn) {
  get_current_component().$$.on_mount.push(fn);
}
function createEventDispatcher() {
  const component = get_current_component();
  return (type, detail, { cancelable = false } = {}) => {
    const callbacks = component.$$.callbacks[type];
    if (callbacks) {
      const event = custom_event(type, detail, { cancelable });
      callbacks.slice().forEach((fn) => {
        fn.call(component, event);
      });
      return !event.defaultPrevented;
    }
    return true;
  };
}
function setContext(key, context) {
  get_current_component().$$.context.set(key, context);
  return context;
}
function getContext(key) {
  return get_current_component().$$.context.get(key);
}
var dirty_components = [];
var binding_callbacks = [];
var render_callbacks = [];
var flush_callbacks = [];
var resolved_promise = Promise.resolve();
var update_scheduled = false;
function schedule_update() {
  if (!update_scheduled) {
    update_scheduled = true;
    resolved_promise.then(flush);
  }
}
function tick() {
  schedule_update();
  return resolved_promise;
}
function add_render_callback(fn) {
  render_callbacks.push(fn);
}
function add_flush_callback(fn) {
  flush_callbacks.push(fn);
}
var seen_callbacks = /* @__PURE__ */ new Set();
var flushidx = 0;
function flush() {
  const saved_component = current_component;
  do {
    while (flushidx < dirty_components.length) {
      const component = dirty_components[flushidx];
      flushidx++;
      set_current_component(component);
      update(component.$$);
    }
    set_current_component(null);
    dirty_components.length = 0;
    flushidx = 0;
    while (binding_callbacks.length)
      binding_callbacks.pop()();
    for (let i = 0; i < render_callbacks.length; i += 1) {
      const callback = render_callbacks[i];
      if (!seen_callbacks.has(callback)) {
        seen_callbacks.add(callback);
        callback();
      }
    }
    render_callbacks.length = 0;
  } while (dirty_components.length);
  while (flush_callbacks.length) {
    flush_callbacks.pop()();
  }
  update_scheduled = false;
  seen_callbacks.clear();
  set_current_component(saved_component);
}
function update($$) {
  if ($$.fragment !== null) {
    $$.update();
    run_all($$.before_update);
    const dirty = $$.dirty;
    $$.dirty = [-1];
    $$.fragment && $$.fragment.p($$.ctx, dirty);
    $$.after_update.forEach(add_render_callback);
  }
}
var outroing = /* @__PURE__ */ new Set();
var outros;
function group_outros() {
  outros = {
    r: 0,
    c: [],
    p: outros
  };
}
function check_outros() {
  if (!outros.r) {
    run_all(outros.c);
  }
  outros = outros.p;
}
function transition_in(block, local) {
  if (block && block.i) {
    outroing.delete(block);
    block.i(local);
  }
}
function transition_out(block, local, detach2, callback) {
  if (block && block.o) {
    if (outroing.has(block))
      return;
    outroing.add(block);
    outros.c.push(() => {
      outroing.delete(block);
      if (callback) {
        if (detach2)
          block.d(1);
        callback();
      }
    });
    block.o(local);
  } else if (callback) {
    callback();
  }
}
function handle_promise(promise, info) {
  const token = info.token = {};
  function update2(type, index2, key, value) {
    if (info.token !== token)
      return;
    info.resolved = value;
    let child_ctx = info.ctx;
    if (key !== void 0) {
      child_ctx = child_ctx.slice();
      child_ctx[key] = value;
    }
    const block = type && (info.current = type)(child_ctx);
    let needs_flush = false;
    if (info.block) {
      if (info.blocks) {
        info.blocks.forEach((block2, i) => {
          if (i !== index2 && block2) {
            group_outros();
            transition_out(block2, 1, 1, () => {
              if (info.blocks[i] === block2) {
                info.blocks[i] = null;
              }
            });
            check_outros();
          }
        });
      } else {
        info.block.d(1);
      }
      block.c();
      transition_in(block, 1);
      block.m(info.mount(), info.anchor);
      needs_flush = true;
    }
    info.block = block;
    if (info.blocks)
      info.blocks[index2] = block;
    if (needs_flush) {
      flush();
    }
  }
  if (is_promise(promise)) {
    const current_component2 = get_current_component();
    promise.then((value) => {
      set_current_component(current_component2);
      update2(info.then, 1, info.value, value);
      set_current_component(null);
    }, (error) => {
      set_current_component(current_component2);
      update2(info.catch, 2, info.error, error);
      set_current_component(null);
      if (!info.hasCatch) {
        throw error;
      }
    });
    if (info.current !== info.pending) {
      update2(info.pending, 0);
      return true;
    }
  } else {
    if (info.current !== info.then) {
      update2(info.then, 1, info.value, promise);
      return true;
    }
    info.resolved = promise;
  }
}
function update_await_block_branch(info, ctx2, dirty) {
  const child_ctx = ctx2.slice();
  const { resolved } = info;
  if (info.current === info.then) {
    child_ctx[info.value] = resolved;
  }
  if (info.current === info.catch) {
    child_ctx[info.error] = resolved;
  }
  info.block.p(child_ctx, dirty);
}
var globals = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : global;
function outro_and_destroy_block(block, lookup) {
  transition_out(block, 1, 1, () => {
    lookup.delete(block.key);
  });
}
function update_keyed_each(old_blocks, dirty, get_key, dynamic, ctx2, list, lookup, node, destroy, create_each_block25, next, get_context) {
  let o = old_blocks.length;
  let n = list.length;
  let i = o;
  const old_indexes = {};
  while (i--)
    old_indexes[old_blocks[i].key] = i;
  const new_blocks = [];
  const new_lookup = /* @__PURE__ */ new Map();
  const deltas = /* @__PURE__ */ new Map();
  i = n;
  while (i--) {
    const child_ctx = get_context(ctx2, list, i);
    const key = get_key(child_ctx);
    let block = lookup.get(key);
    if (!block) {
      block = create_each_block25(key, child_ctx);
      block.c();
    } else if (dynamic) {
      block.p(child_ctx, dirty);
    }
    new_lookup.set(key, new_blocks[i] = block);
    if (key in old_indexes)
      deltas.set(key, Math.abs(i - old_indexes[key]));
  }
  const will_move = /* @__PURE__ */ new Set();
  const did_move = /* @__PURE__ */ new Set();
  function insert3(block) {
    transition_in(block, 1);
    block.m(node, next);
    lookup.set(block.key, block);
    next = block.first;
    n--;
  }
  while (o && n) {
    const new_block = new_blocks[n - 1];
    const old_block = old_blocks[o - 1];
    const new_key = new_block.key;
    const old_key = old_block.key;
    if (new_block === old_block) {
      next = new_block.first;
      o--;
      n--;
    } else if (!new_lookup.has(old_key)) {
      destroy(old_block, lookup);
      o--;
    } else if (!lookup.has(new_key) || will_move.has(new_key)) {
      insert3(new_block);
    } else if (did_move.has(old_key)) {
      o--;
    } else if (deltas.get(new_key) > deltas.get(old_key)) {
      did_move.add(new_key);
      insert3(new_block);
    } else {
      will_move.add(old_key);
      o--;
    }
  }
  while (o--) {
    const old_block = old_blocks[o];
    if (!new_lookup.has(old_block.key))
      destroy(old_block, lookup);
  }
  while (n)
    insert3(new_blocks[n - 1]);
  return new_blocks;
}
function bind(component, name2, callback) {
  const index2 = component.$$.props[name2];
  if (index2 !== void 0) {
    component.$$.bound[index2] = callback;
    callback(component.$$.ctx[index2]);
  }
}
function create_component(block) {
  block && block.c();
}
function mount_component(component, target, anchor, customElement) {
  const { fragment, after_update } = component.$$;
  fragment && fragment.m(target, anchor);
  if (!customElement) {
    add_render_callback(() => {
      const new_on_destroy = component.$$.on_mount.map(run).filter(is_function);
      if (component.$$.on_destroy) {
        component.$$.on_destroy.push(...new_on_destroy);
      } else {
        run_all(new_on_destroy);
      }
      component.$$.on_mount = [];
    });
  }
  after_update.forEach(add_render_callback);
}
function destroy_component(component, detaching) {
  const $$ = component.$$;
  if ($$.fragment !== null) {
    run_all($$.on_destroy);
    $$.fragment && $$.fragment.d(detaching);
    $$.on_destroy = $$.fragment = null;
    $$.ctx = [];
  }
}
function make_dirty(component, i) {
  if (component.$$.dirty[0] === -1) {
    dirty_components.push(component);
    schedule_update();
    component.$$.dirty.fill(0);
  }
  component.$$.dirty[i / 31 | 0] |= 1 << i % 31;
}
function init(component, options2, instance51, create_fragment52, not_equal, props, append_styles, dirty = [-1]) {
  const parent_component = current_component;
  set_current_component(component);
  const $$ = component.$$ = {
    fragment: null,
    ctx: [],
    props,
    update: noop,
    not_equal,
    bound: blank_object(),
    on_mount: [],
    on_destroy: [],
    on_disconnect: [],
    before_update: [],
    after_update: [],
    context: new Map(options2.context || (parent_component ? parent_component.$$.context : [])),
    callbacks: blank_object(),
    dirty,
    skip_bound: false,
    root: options2.target || parent_component.$$.root
  };
  append_styles && append_styles($$.root);
  let ready = false;
  $$.ctx = instance51 ? instance51(component, options2.props || {}, (i, ret, ...rest) => {
    const value = rest.length ? rest[0] : ret;
    if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
      if (!$$.skip_bound && $$.bound[i])
        $$.bound[i](value);
      if (ready)
        make_dirty(component, i);
    }
    return ret;
  }) : [];
  $$.update();
  ready = true;
  run_all($$.before_update);
  $$.fragment = create_fragment52 ? create_fragment52($$.ctx) : false;
  if (options2.target) {
    if (options2.hydrate) {
      start_hydrating();
      const nodes = children(options2.target);
      $$.fragment && $$.fragment.l(nodes);
      nodes.forEach(detach);
    } else {
      $$.fragment && $$.fragment.c();
    }
    if (options2.intro)
      transition_in(component.$$.fragment);
    mount_component(component, options2.target, options2.anchor, options2.customElement);
    end_hydrating();
    flush();
  }
  set_current_component(parent_component);
}
var SvelteElement;
if (typeof HTMLElement === "function") {
  SvelteElement = class extends HTMLElement {
    constructor() {
      super();
      this.attachShadow({ mode: "open" });
    }
    connectedCallback() {
      const { on_mount } = this.$$;
      this.$$.on_disconnect = on_mount.map(run).filter(is_function);
      for (const key in this.$$.slotted) {
        this.appendChild(this.$$.slotted[key]);
      }
    }
    attributeChangedCallback(attr2, _oldValue, newValue) {
      this[attr2] = newValue;
    }
    disconnectedCallback() {
      run_all(this.$$.on_disconnect);
    }
    $destroy() {
      destroy_component(this, 1);
      this.$destroy = noop;
    }
    $on(type, callback) {
      if (!is_function(callback)) {
        return noop;
      }
      const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []);
      callbacks.push(callback);
      return () => {
        const index2 = callbacks.indexOf(callback);
        if (index2 !== -1)
          callbacks.splice(index2, 1);
      };
    }
    $set($$props) {
      if (this.$$set && !is_empty($$props)) {
        this.$$.skip_bound = true;
        this.$$set($$props);
        this.$$.skip_bound = false;
      }
    }
  };
}
var SvelteComponent = class {
  $destroy() {
    destroy_component(this, 1);
    this.$destroy = noop;
  }
  $on(type, callback) {
    if (!is_function(callback)) {
      return noop;
    }
    const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []);
    callbacks.push(callback);
    return () => {
      const index2 = callbacks.indexOf(callback);
      if (index2 !== -1)
        callbacks.splice(index2, 1);
    };
  }
  $set($$props) {
    if (this.$$set && !is_empty($$props)) {
      this.$$.skip_bound = true;
      this.$$set($$props);
      this.$$.skip_bound = false;
    }
  }
};

// node_modules/svelte/store/index.mjs
var subscriber_queue = [];
function readable(value, start) {
  return {
    subscribe: writable(value, start).subscribe
  };
}
function writable(value, start = noop) {
  let stop;
  const subscribers = /* @__PURE__ */ new Set();
  function set(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) {
    set(fn(value));
  }
  function subscribe2(run2, invalidate = noop) {
    const subscriber = [run2, invalidate];
    subscribers.add(subscriber);
    if (subscribers.size === 1) {
      stop = start(set) || noop;
    }
    run2(value);
    return () => {
      subscribers.delete(subscriber);
      if (subscribers.size === 0) {
        stop();
        stop = null;
      }
    };
  }
  return { set, update: update2, subscribe: subscribe2 };
}
function derived(stores, fn, initial_value) {
  const single = !Array.isArray(stores);
  const stores_array = single ? [stores] : stores;
  const auto = fn.length < 2;
  return readable(initial_value, (set) => {
    let inited = false;
    const values = [];
    let pending = 0;
    let cleanup = noop;
    const sync = () => {
      if (pending) {
        return;
      }
      cleanup();
      const result = fn(single ? values[0] : values, set);
      if (auto) {
        set(result);
      } else {
        cleanup = is_function(result) ? result : noop;
      }
    };
    const unsubscribers = stores_array.map((store, i) => subscribe(store, (value) => {
      values[i] = value;
      pending &= ~(1 << i);
      if (inited) {
        sync();
      }
    }, () => {
      pending |= 1 << i;
    }));
    inited = true;
    sync();
    return function stop() {
      run_all(unsubscribers);
      cleanup();
    };
  });
}

// node_modules/d3-format/src/formatDecimal.js
function formatDecimal_default(x2) {
  return Math.abs(x2 = Math.round(x2)) >= 1e21 ? x2.toLocaleString("en").replace(/,/g, "") : x2.toString(10);
}
function formatDecimalParts(x2, p) {
  if ((i = (x2 = p ? x2.toExponential(p - 1) : x2.toExponential()).indexOf("e")) < 0)
    return null;
  var i, coefficient = x2.slice(0, i);
  return [
    coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
    +x2.slice(i + 1)
  ];
}

// node_modules/d3-format/src/exponent.js
function exponent_default(x2) {
  return x2 = formatDecimalParts(Math.abs(x2)), x2 ? x2[1] : NaN;
}

// node_modules/d3-format/src/formatGroup.js
function formatGroup_default(grouping, thousands) {
  return function(value, width) {
    var i = value.length, t4 = [], j = 0, g = grouping[0], length = 0;
    while (i > 0 && g > 0) {
      if (length + g + 1 > width)
        g = Math.max(1, width - length);
      t4.push(value.substring(i -= g, i + g));
      if ((length += g + 1) > width)
        break;
      g = grouping[j = (j + 1) % grouping.length];
    }
    return t4.reverse().join(thousands);
  };
}

// node_modules/d3-format/src/formatNumerals.js
function formatNumerals_default(numerals) {
  return function(value) {
    return value.replace(/[0-9]/g, function(i) {
      return numerals[+i];
    });
  };
}

// node_modules/d3-format/src/formatSpecifier.js
var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
function formatSpecifier(specifier) {
  if (!(match = re.exec(specifier)))
    throw new Error("invalid format: " + specifier);
  var match;
  return new FormatSpecifier({
    fill: match[1],
    align: match[2],
    sign: match[3],
    symbol: match[4],
    zero: match[5],
    width: match[6],
    comma: match[7],
    precision: match[8] && match[8].slice(1),
    trim: match[9],
    type: match[10]
  });
}
formatSpecifier.prototype = FormatSpecifier.prototype;
function FormatSpecifier(specifier) {
  this.fill = specifier.fill === void 0 ? " " : specifier.fill + "";
  this.align = specifier.align === void 0 ? ">" : specifier.align + "";
  this.sign = specifier.sign === void 0 ? "-" : specifier.sign + "";
  this.symbol = specifier.symbol === void 0 ? "" : specifier.symbol + "";
  this.zero = !!specifier.zero;
  this.width = specifier.width === void 0 ? void 0 : +specifier.width;
  this.comma = !!specifier.comma;
  this.precision = specifier.precision === void 0 ? void 0 : +specifier.precision;
  this.trim = !!specifier.trim;
  this.type = specifier.type === void 0 ? "" : specifier.type + "";
}
FormatSpecifier.prototype.toString = function() {
  return this.fill + this.align + this.sign + this.symbol + (this.zero ? "0" : "") + (this.width === void 0 ? "" : Math.max(1, this.width | 0)) + (this.comma ? "," : "") + (this.precision === void 0 ? "" : "." + Math.max(0, this.precision | 0)) + (this.trim ? "~" : "") + this.type;
};

// node_modules/d3-format/src/formatTrim.js
function formatTrim_default(s) {
  out:
    for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
      switch (s[i]) {
        case ".":
          i0 = i1 = i;
          break;
        case "0":
          if (i0 === 0)
            i0 = i;
          i1 = i;
          break;
        default:
          if (!+s[i])
            break out;
          if (i0 > 0)
            i0 = 0;
          break;
      }
    }
  return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
}

// node_modules/d3-format/src/formatPrefixAuto.js
var prefixExponent;
function formatPrefixAuto_default(x2, p) {
  var d = formatDecimalParts(x2, p);
  if (!d)
    return x2 + "";
  var coefficient = d[0], exponent = d[1], i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1, n = coefficient.length;
  return i === n ? coefficient : i > n ? coefficient + new Array(i - n + 1).join("0") : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i) : "0." + new Array(1 - i).join("0") + formatDecimalParts(x2, Math.max(0, p + i - 1))[0];
}

// node_modules/d3-format/src/formatRounded.js
function formatRounded_default(x2, p) {
  var d = formatDecimalParts(x2, p);
  if (!d)
    return x2 + "";
  var coefficient = d[0], exponent = d[1];
  return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1) : coefficient + new Array(exponent - coefficient.length + 2).join("0");
}

// node_modules/d3-format/src/formatTypes.js
var formatTypes_default = {
  "%": (x2, p) => (x2 * 100).toFixed(p),
  "b": (x2) => Math.round(x2).toString(2),
  "c": (x2) => x2 + "",
  "d": formatDecimal_default,
  "e": (x2, p) => x2.toExponential(p),
  "f": (x2, p) => x2.toFixed(p),
  "g": (x2, p) => x2.toPrecision(p),
  "o": (x2) => Math.round(x2).toString(8),
  "p": (x2, p) => formatRounded_default(x2 * 100, p),
  "r": formatRounded_default,
  "s": formatPrefixAuto_default,
  "X": (x2) => Math.round(x2).toString(16).toUpperCase(),
  "x": (x2) => Math.round(x2).toString(16)
};

// node_modules/d3-format/src/identity.js
function identity_default(x2) {
  return x2;
}

// node_modules/d3-format/src/locale.js
var map = Array.prototype.map;
var prefixes = ["y", "z", "a", "f", "p", "n", "\xB5", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y"];
function locale_default(locale3) {
  var group2 = locale3.grouping === void 0 || locale3.thousands === void 0 ? identity_default : formatGroup_default(map.call(locale3.grouping, Number), locale3.thousands + ""), currencyPrefix = locale3.currency === void 0 ? "" : locale3.currency[0] + "", currencySuffix = locale3.currency === void 0 ? "" : locale3.currency[1] + "", decimal2 = locale3.decimal === void 0 ? "." : locale3.decimal + "", numerals = locale3.numerals === void 0 ? identity_default : formatNumerals_default(map.call(locale3.numerals, String)), percent = locale3.percent === void 0 ? "%" : locale3.percent + "", minus = locale3.minus === void 0 ? "\u2212" : locale3.minus + "", nan = locale3.nan === void 0 ? "NaN" : locale3.nan + "";
  function newFormat(specifier) {
    specifier = formatSpecifier(specifier);
    var fill = specifier.fill, align = specifier.align, sign = specifier.sign, symbol = specifier.symbol, zero3 = specifier.zero, width = specifier.width, comma = specifier.comma, precision = specifier.precision, trim = specifier.trim, type = specifier.type;
    if (type === "n")
      comma = true, type = "g";
    else if (!formatTypes_default[type])
      precision === void 0 && (precision = 12), trim = true, type = "g";
    if (zero3 || fill === "0" && align === "=")
      zero3 = true, fill = "0", align = "=";
    var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "", suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : "";
    var formatType = formatTypes_default[type], maybeSuffix = /[defgprs%]/.test(type);
    precision = precision === void 0 ? 6 : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision));
    function format3(value) {
      var valuePrefix = prefix, valueSuffix = suffix, i, n, c;
      if (type === "c") {
        valueSuffix = formatType(value) + valueSuffix;
        value = "";
      } else {
        value = +value;
        var valueNegative = value < 0 || 1 / value < 0;
        value = isNaN(value) ? nan : formatType(Math.abs(value), precision);
        if (trim)
          value = formatTrim_default(value);
        if (valueNegative && +value === 0 && sign !== "+")
          valueNegative = false;
        valuePrefix = (valueNegative ? sign === "(" ? sign : minus : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
        valueSuffix = (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");
        if (maybeSuffix) {
          i = -1, n = value.length;
          while (++i < n) {
            if (c = value.charCodeAt(i), 48 > c || c > 57) {
              valueSuffix = (c === 46 ? decimal2 + value.slice(i + 1) : value.slice(i)) + valueSuffix;
              value = value.slice(0, i);
              break;
            }
          }
        }
      }
      if (comma && !zero3)
        value = group2(value, Infinity);
      var length = valuePrefix.length + value.length + valueSuffix.length, padding = length < width ? new Array(width - length + 1).join(fill) : "";
      if (comma && zero3)
        value = group2(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";
      switch (align) {
        case "<":
          value = valuePrefix + value + valueSuffix + padding;
          break;
        case "=":
          value = valuePrefix + padding + value + valueSuffix;
          break;
        case "^":
          value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length);
          break;
        default:
          value = padding + valuePrefix + value + valueSuffix;
          break;
      }
      return numerals(value);
    }
    format3.toString = function() {
      return specifier + "";
    };
    return format3;
  }
  function formatPrefix2(specifier, value) {
    var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)), e3 = Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3, k = Math.pow(10, -e3), prefix = prefixes[8 + e3 / 3];
    return function(value2) {
      return f(k * value2) + prefix;
    };
  }
  return {
    format: newFormat,
    formatPrefix: formatPrefix2
  };
}

// node_modules/d3-format/src/defaultLocale.js
var locale;
var format;
var formatPrefix;
defaultLocale({
  thousands: ",",
  grouping: [3],
  currency: ["$", ""]
});
function defaultLocale(definition) {
  locale = locale_default(definition);
  format = locale.format;
  formatPrefix = locale.formatPrefix;
  return locale;
}

// node_modules/d3-format/src/precisionFixed.js
function precisionFixed_default(step) {
  return Math.max(0, -exponent_default(Math.abs(step)));
}

// node_modules/d3-format/src/precisionPrefix.js
function precisionPrefix_default(step, value) {
  return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3 - exponent_default(Math.abs(step)));
}

// node_modules/d3-format/src/precisionRound.js
function precisionRound_default(step, max3) {
  step = Math.abs(step), max3 = Math.abs(max3) - step;
  return Math.max(0, exponent_default(max3) - exponent_default(step)) + 1;
}

// node_modules/d3-time/src/interval.js
var t0 = new Date();
var t1 = new Date();
function newInterval(floori, offseti, count2, field) {
  function interval2(date5) {
    return floori(date5 = arguments.length === 0 ? new Date() : new Date(+date5)), date5;
  }
  interval2.floor = function(date5) {
    return floori(date5 = new Date(+date5)), date5;
  };
  interval2.ceil = function(date5) {
    return floori(date5 = new Date(date5 - 1)), offseti(date5, 1), floori(date5), date5;
  };
  interval2.round = function(date5) {
    var d0 = interval2(date5), d1 = interval2.ceil(date5);
    return date5 - d0 < d1 - date5 ? d0 : d1;
  };
  interval2.offset = function(date5, step) {
    return offseti(date5 = new Date(+date5), step == null ? 1 : Math.floor(step)), date5;
  };
  interval2.range = function(start, stop, step) {
    var range2 = [], previous;
    start = interval2.ceil(start);
    step = step == null ? 1 : Math.floor(step);
    if (!(start < stop) || !(step > 0))
      return range2;
    do
      range2.push(previous = new Date(+start)), offseti(start, step), floori(start);
    while (previous < start && start < stop);
    return range2;
  };
  interval2.filter = function(test) {
    return newInterval(function(date5) {
      if (date5 >= date5)
        while (floori(date5), !test(date5))
          date5.setTime(date5 - 1);
    }, function(date5, step) {
      if (date5 >= date5) {
        if (step < 0)
          while (++step <= 0) {
            while (offseti(date5, -1), !test(date5)) {
            }
          }
        else
          while (--step >= 0) {
            while (offseti(date5, 1), !test(date5)) {
            }
          }
      }
    });
  };
  if (count2) {
    interval2.count = function(start, end) {
      t0.setTime(+start), t1.setTime(+end);
      floori(t0), floori(t1);
      return Math.floor(count2(t0, t1));
    };
    interval2.every = function(step) {
      step = Math.floor(step);
      return !isFinite(step) || !(step > 0) ? null : !(step > 1) ? interval2 : interval2.filter(field ? function(d) {
        return field(d) % step === 0;
      } : function(d) {
        return interval2.count(0, d) % step === 0;
      });
    };
  }
  return interval2;
}

// node_modules/d3-time/src/millisecond.js
var millisecond = newInterval(function() {
}, function(date5, step) {
  date5.setTime(+date5 + step);
}, function(start, end) {
  return end - start;
});
millisecond.every = function(k) {
  k = Math.floor(k);
  if (!isFinite(k) || !(k > 0))
    return null;
  if (!(k > 1))
    return millisecond;
  return newInterval(function(date5) {
    date5.setTime(Math.floor(date5 / k) * k);
  }, function(date5, step) {
    date5.setTime(+date5 + step * k);
  }, function(start, end) {
    return (end - start) / k;
  });
};
var millisecond_default = millisecond;
var milliseconds = millisecond.range;

// node_modules/d3-time/src/duration.js
var durationSecond = 1e3;
var durationMinute = durationSecond * 60;
var durationHour = durationMinute * 60;
var durationDay = durationHour * 24;
var durationWeek = durationDay * 7;
var durationMonth = durationDay * 30;
var durationYear = durationDay * 365;

// node_modules/d3-time/src/second.js
var second = newInterval(function(date5) {
  date5.setTime(date5 - date5.getMilliseconds());
}, function(date5, step) {
  date5.setTime(+date5 + step * durationSecond);
}, function(start, end) {
  return (end - start) / durationSecond;
}, function(date5) {
  return date5.getUTCSeconds();
});
var second_default = second;
var seconds = second.range;

// node_modules/d3-time/src/minute.js
var minute = newInterval(function(date5) {
  date5.setTime(date5 - date5.getMilliseconds() - date5.getSeconds() * durationSecond);
}, function(date5, step) {
  date5.setTime(+date5 + step * durationMinute);
}, function(start, end) {
  return (end - start) / durationMinute;
}, function(date5) {
  return date5.getMinutes();
});
var minute_default = minute;
var minutes = minute.range;

// node_modules/d3-time/src/hour.js
var hour = newInterval(function(date5) {
  date5.setTime(date5 - date5.getMilliseconds() - date5.getSeconds() * durationSecond - date5.getMinutes() * durationMinute);
}, function(date5, step) {
  date5.setTime(+date5 + step * durationHour);
}, function(start, end) {
  return (end - start) / durationHour;
}, function(date5) {
  return date5.getHours();
});
var hour_default = hour;
var hours = hour.range;

// node_modules/d3-time/src/day.js
var day = newInterval(
  (date5) => date5.setHours(0, 0, 0, 0),
  (date5, step) => date5.setDate(date5.getDate() + step),
  (start, end) => (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay,
  (date5) => date5.getDate() - 1
);
var day_default = day;
var days = day.range;

// node_modules/d3-time/src/week.js
function weekday(i) {
  return newInterval(function(date5) {
    date5.setDate(date5.getDate() - (date5.getDay() + 7 - i) % 7);
    date5.setHours(0, 0, 0, 0);
  }, function(date5, step) {
    date5.setDate(date5.getDate() + step * 7);
  }, function(start, end) {
    return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek;
  });
}
var sunday = weekday(0);
var monday = weekday(1);
var tuesday = weekday(2);
var wednesday = weekday(3);
var thursday = weekday(4);
var friday = weekday(5);
var saturday = weekday(6);
var sundays = sunday.range;
var mondays = monday.range;
var tuesdays = tuesday.range;
var wednesdays = wednesday.range;
var thursdays = thursday.range;
var fridays = friday.range;
var saturdays = saturday.range;

// node_modules/d3-time/src/month.js
var month = newInterval(function(date5) {
  date5.setDate(1);
  date5.setHours(0, 0, 0, 0);
}, function(date5, step) {
  date5.setMonth(date5.getMonth() + step);
}, function(start, end) {
  return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;
}, function(date5) {
  return date5.getMonth();
});
var month_default = month;
var months = month.range;

// node_modules/d3-time/src/year.js
var year = newInterval(function(date5) {
  date5.setMonth(0, 1);
  date5.setHours(0, 0, 0, 0);
}, function(date5, step) {
  date5.setFullYear(date5.getFullYear() + step);
}, function(start, end) {
  return end.getFullYear() - start.getFullYear();
}, function(date5) {
  return date5.getFullYear();
});
year.every = function(k) {
  return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date5) {
    date5.setFullYear(Math.floor(date5.getFullYear() / k) * k);
    date5.setMonth(0, 1);
    date5.setHours(0, 0, 0, 0);
  }, function(date5, step) {
    date5.setFullYear(date5.getFullYear() + step * k);
  });
};
var year_default = year;
var years = year.range;

// node_modules/d3-time/src/utcMinute.js
var utcMinute = newInterval(function(date5) {
  date5.setUTCSeconds(0, 0);
}, function(date5, step) {
  date5.setTime(+date5 + step * durationMinute);
}, function(start, end) {
  return (end - start) / durationMinute;
}, function(date5) {
  return date5.getUTCMinutes();
});
var utcMinute_default = utcMinute;
var utcMinutes = utcMinute.range;

// node_modules/d3-time/src/utcHour.js
var utcHour = newInterval(function(date5) {
  date5.setUTCMinutes(0, 0, 0);
}, function(date5, step) {
  date5.setTime(+date5 + step * durationHour);
}, function(start, end) {
  return (end - start) / durationHour;
}, function(date5) {
  return date5.getUTCHours();
});
var utcHour_default = utcHour;
var utcHours = utcHour.range;

// node_modules/d3-time/src/utcDay.js
var utcDay = newInterval(function(date5) {
  date5.setUTCHours(0, 0, 0, 0);
}, function(date5, step) {
  date5.setUTCDate(date5.getUTCDate() + step);
}, function(start, end) {
  return (end - start) / durationDay;
}, function(date5) {
  return date5.getUTCDate() - 1;
});
var utcDay_default = utcDay;
var utcDays = utcDay.range;

// node_modules/d3-time/src/utcWeek.js
function utcWeekday(i) {
  return newInterval(function(date5) {
    date5.setUTCDate(date5.getUTCDate() - (date5.getUTCDay() + 7 - i) % 7);
    date5.setUTCHours(0, 0, 0, 0);
  }, function(date5, step) {
    date5.setUTCDate(date5.getUTCDate() + step * 7);
  }, function(start, end) {
    return (end - start) / durationWeek;
  });
}
var utcSunday = utcWeekday(0);
var utcMonday = utcWeekday(1);
var utcTuesday = utcWeekday(2);
var utcWednesday = utcWeekday(3);
var utcThursday = utcWeekday(4);
var utcFriday = utcWeekday(5);
var utcSaturday = utcWeekday(6);
var utcSundays = utcSunday.range;
var utcMondays = utcMonday.range;
var utcTuesdays = utcTuesday.range;
var utcWednesdays = utcWednesday.range;
var utcThursdays = utcThursday.range;
var utcFridays = utcFriday.range;
var utcSaturdays = utcSaturday.range;

// node_modules/d3-time/src/utcMonth.js
var utcMonth = newInterval(function(date5) {
  date5.setUTCDate(1);
  date5.setUTCHours(0, 0, 0, 0);
}, function(date5, step) {
  date5.setUTCMonth(date5.getUTCMonth() + step);
}, function(start, end) {
  return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;
}, function(date5) {
  return date5.getUTCMonth();
});
var utcMonth_default = utcMonth;
var utcMonths = utcMonth.range;

// node_modules/d3-time/src/utcYear.js
var utcYear = newInterval(function(date5) {
  date5.setUTCMonth(0, 1);
  date5.setUTCHours(0, 0, 0, 0);
}, function(date5, step) {
  date5.setUTCFullYear(date5.getUTCFullYear() + step);
}, function(start, end) {
  return end.getUTCFullYear() - start.getUTCFullYear();
}, function(date5) {
  return date5.getUTCFullYear();
});
utcYear.every = function(k) {
  return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date5) {
    date5.setUTCFullYear(Math.floor(date5.getUTCFullYear() / k) * k);
    date5.setUTCMonth(0, 1);
    date5.setUTCHours(0, 0, 0, 0);
  }, function(date5, step) {
    date5.setUTCFullYear(date5.getUTCFullYear() + step * k);
  });
};
var utcYear_default = utcYear;
var utcYears = utcYear.range;

// node_modules/d3-array/src/ascending.js
function ascending(a, b) {
  return a == null || b == null ? NaN : a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

// node_modules/d3-array/src/descending.js
function descending(a, b) {
  return a == null || b == null ? NaN : b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
}

// node_modules/d3-array/src/bisector.js
function bisector(f) {
  let compare1, compare2, delta;
  if (f.length !== 2) {
    compare1 = ascending;
    compare2 = (d, x2) => ascending(f(d), x2);
    delta = (d, x2) => f(d) - x2;
  } else {
    compare1 = f === ascending || f === descending ? f : zero;
    compare2 = f;
    delta = f;
  }
  function left2(a, x2, lo = 0, hi = a.length) {
    if (lo < hi) {
      if (compare1(x2, x2) !== 0)
        return hi;
      do {
        const mid = lo + hi >>> 1;
        if (compare2(a[mid], x2) < 0)
          lo = mid + 1;
        else
          hi = mid;
      } while (lo < hi);
    }
    return lo;
  }
  function right2(a, x2, lo = 0, hi = a.length) {
    if (lo < hi) {
      if (compare1(x2, x2) !== 0)
        return hi;
      do {
        const mid = lo + hi >>> 1;
        if (compare2(a[mid], x2) <= 0)
          lo = mid + 1;
        else
          hi = mid;
      } while (lo < hi);
    }
    return lo;
  }
  function center2(a, x2, lo = 0, hi = a.length) {
    const i = left2(a, x2, lo, hi - 1);
    return i > lo && delta(a[i - 1], x2) > -delta(a[i], x2) ? i - 1 : i;
  }
  return { left: left2, center: center2, right: right2 };
}
function zero() {
  return 0;
}

// node_modules/d3-array/src/number.js
function number(x2) {
  return x2 === null ? NaN : +x2;
}

// node_modules/d3-array/src/bisect.js
var ascendingBisect = bisector(ascending);
var bisectRight = ascendingBisect.right;
var bisectLeft = ascendingBisect.left;
var bisectCenter = bisector(number).center;
var bisect_default = bisectRight;

// node_modules/d3-array/src/extent.js
function extent(values, valueof) {
  let min3;
  let max3;
  if (valueof === void 0) {
    for (const value of values) {
      if (value != null) {
        if (min3 === void 0) {
          if (value >= value)
            min3 = max3 = value;
        } else {
          if (min3 > value)
            min3 = value;
          if (max3 < value)
            max3 = value;
        }
      }
    }
  } else {
    let index2 = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index2, values)) != null) {
        if (min3 === void 0) {
          if (value >= value)
            min3 = max3 = value;
        } else {
          if (min3 > value)
            min3 = value;
          if (max3 < value)
            max3 = value;
        }
      }
    }
  }
  return [min3, max3];
}

// node_modules/internmap/src/index.js
var InternMap = class extends Map {
  constructor(entries, key = keyof) {
    super();
    Object.defineProperties(this, { _intern: { value: /* @__PURE__ */ new Map() }, _key: { value: key } });
    if (entries != null)
      for (const [key2, value] of entries)
        this.set(key2, value);
  }
  get(key) {
    return super.get(intern_get(this, key));
  }
  has(key) {
    return super.has(intern_get(this, key));
  }
  set(key, value) {
    return super.set(intern_set(this, key), value);
  }
  delete(key) {
    return super.delete(intern_delete(this, key));
  }
};
function intern_get({ _intern, _key }, value) {
  const key = _key(value);
  return _intern.has(key) ? _intern.get(key) : value;
}
function intern_set({ _intern, _key }, value) {
  const key = _key(value);
  if (_intern.has(key))
    return _intern.get(key);
  _intern.set(key, value);
  return value;
}
function intern_delete({ _intern, _key }, value) {
  const key = _key(value);
  if (_intern.has(key)) {
    value = _intern.get(key);
    _intern.delete(key);
  }
  return value;
}
function keyof(value) {
  return value !== null && typeof value === "object" ? value.valueOf() : value;
}

// node_modules/d3-array/src/identity.js
function identity(x2) {
  return x2;
}

// node_modules/d3-array/src/group.js
function group(values, ...keys) {
  return nest(values, identity, identity, keys);
}
function nest(values, map2, reduce, keys) {
  return function regroup(values2, i) {
    if (i >= keys.length)
      return reduce(values2);
    const groups2 = new InternMap();
    const keyof2 = keys[i++];
    let index2 = -1;
    for (const value of values2) {
      const key = keyof2(value, ++index2, values2);
      const group2 = groups2.get(key);
      if (group2)
        group2.push(value);
      else
        groups2.set(key, [value]);
    }
    for (const [key, values3] of groups2) {
      groups2.set(key, regroup(values3, i));
    }
    return map2(groups2);
  }(values, 0);
}

// node_modules/d3-array/src/ticks.js
var e10 = Math.sqrt(50);
var e5 = Math.sqrt(10);
var e2 = Math.sqrt(2);
function ticks(start, stop, count2) {
  var reverse, i = -1, n, ticks2, step;
  stop = +stop, start = +start, count2 = +count2;
  if (start === stop && count2 > 0)
    return [start];
  if (reverse = stop < start)
    n = start, start = stop, stop = n;
  if ((step = tickIncrement(start, stop, count2)) === 0 || !isFinite(step))
    return [];
  if (step > 0) {
    let r0 = Math.round(start / step), r1 = Math.round(stop / step);
    if (r0 * step < start)
      ++r0;
    if (r1 * step > stop)
      --r1;
    ticks2 = new Array(n = r1 - r0 + 1);
    while (++i < n)
      ticks2[i] = (r0 + i) * step;
  } else {
    step = -step;
    let r0 = Math.round(start * step), r1 = Math.round(stop * step);
    if (r0 / step < start)
      ++r0;
    if (r1 / step > stop)
      --r1;
    ticks2 = new Array(n = r1 - r0 + 1);
    while (++i < n)
      ticks2[i] = (r0 + i) / step;
  }
  if (reverse)
    ticks2.reverse();
  return ticks2;
}
function tickIncrement(start, stop, count2) {
  var step = (stop - start) / Math.max(0, count2), power = Math.floor(Math.log(step) / Math.LN10), error = step / Math.pow(10, power);
  return power >= 0 ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power) : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);
}
function tickStep(start, stop, count2) {
  var step0 = Math.abs(stop - start) / Math.max(0, count2), step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)), error = step0 / step1;
  if (error >= e10)
    step1 *= 10;
  else if (error >= e5)
    step1 *= 5;
  else if (error >= e2)
    step1 *= 2;
  return stop < start ? -step1 : step1;
}

// node_modules/d3-array/src/max.js
function max(values, valueof) {
  let max3;
  if (valueof === void 0) {
    for (const value of values) {
      if (value != null && (max3 < value || max3 === void 0 && value >= value)) {
        max3 = value;
      }
    }
  } else {
    let index2 = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index2, values)) != null && (max3 < value || max3 === void 0 && value >= value)) {
        max3 = value;
      }
    }
  }
  return max3;
}

// node_modules/d3-array/src/min.js
function min(values, valueof) {
  let min3;
  if (valueof === void 0) {
    for (const value of values) {
      if (value != null && (min3 > value || min3 === void 0 && value >= value)) {
        min3 = value;
      }
    }
  } else {
    let index2 = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index2, values)) != null && (min3 > value || min3 === void 0 && value >= value)) {
        min3 = value;
      }
    }
  }
  return min3;
}

// node_modules/d3-array/src/merge.js
function* flatten(arrays) {
  for (const array3 of arrays) {
    yield* array3;
  }
}
function merge(arrays) {
  return Array.from(flatten(arrays));
}

// node_modules/d3-array/src/range.js
function range(start, stop, step) {
  start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;
  var i = -1, n = Math.max(0, Math.ceil((stop - start) / step)) | 0, range2 = new Array(n);
  while (++i < n) {
    range2[i] = start + i * step;
  }
  return range2;
}

// node_modules/d3-time/src/ticks.js
function ticker(year2, month2, week, day3, hour2, minute2) {
  const tickIntervals = [
    [second_default, 1, durationSecond],
    [second_default, 5, 5 * durationSecond],
    [second_default, 15, 15 * durationSecond],
    [second_default, 30, 30 * durationSecond],
    [minute2, 1, durationMinute],
    [minute2, 5, 5 * durationMinute],
    [minute2, 15, 15 * durationMinute],
    [minute2, 30, 30 * durationMinute],
    [hour2, 1, durationHour],
    [hour2, 3, 3 * durationHour],
    [hour2, 6, 6 * durationHour],
    [hour2, 12, 12 * durationHour],
    [day3, 1, durationDay],
    [day3, 2, 2 * durationDay],
    [week, 1, durationWeek],
    [month2, 1, durationMonth],
    [month2, 3, 3 * durationMonth],
    [year2, 1, durationYear]
  ];
  function ticks2(start, stop, count2) {
    const reverse = stop < start;
    if (reverse)
      [start, stop] = [stop, start];
    const interval2 = count2 && typeof count2.range === "function" ? count2 : tickInterval(start, stop, count2);
    const ticks3 = interval2 ? interval2.range(start, +stop + 1) : [];
    return reverse ? ticks3.reverse() : ticks3;
  }
  function tickInterval(start, stop, count2) {
    const target = Math.abs(stop - start) / count2;
    const i = bisector(([, , step2]) => step2).right(tickIntervals, target);
    if (i === tickIntervals.length)
      return year2.every(tickStep(start / durationYear, stop / durationYear, count2));
    if (i === 0)
      return millisecond_default.every(Math.max(tickStep(start, stop, count2), 1));
    const [t4, step] = tickIntervals[target / tickIntervals[i - 1][2] < tickIntervals[i][2] / target ? i - 1 : i];
    return t4.every(step);
  }
  return [ticks2, tickInterval];
}
var [utcTicks, utcTickInterval] = ticker(utcYear_default, utcMonth_default, utcSunday, utcDay_default, utcHour_default, utcMinute_default);
var [timeTicks, timeTickInterval] = ticker(year_default, month_default, sunday, day_default, hour_default, minute_default);

// node_modules/d3-time-format/src/locale.js
function localDate(d) {
  if (0 <= d.y && d.y < 100) {
    var date5 = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
    date5.setFullYear(d.y);
    return date5;
  }
  return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
}
function utcDate(d) {
  if (0 <= d.y && d.y < 100) {
    var date5 = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
    date5.setUTCFullYear(d.y);
    return date5;
  }
  return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
}
function newDate(y2, m, d) {
  return { y: y2, m, d, H: 0, M: 0, S: 0, L: 0 };
}
function formatLocale(locale3) {
  var locale_dateTime = locale3.dateTime, locale_date = locale3.date, locale_time = locale3.time, locale_periods = locale3.periods, locale_weekdays = locale3.days, locale_shortWeekdays = locale3.shortDays, locale_months = locale3.months, locale_shortMonths = locale3.shortMonths;
  var periodRe = formatRe(locale_periods), periodLookup = formatLookup(locale_periods), weekdayRe = formatRe(locale_weekdays), weekdayLookup = formatLookup(locale_weekdays), shortWeekdayRe = formatRe(locale_shortWeekdays), shortWeekdayLookup = formatLookup(locale_shortWeekdays), monthRe = formatRe(locale_months), monthLookup = formatLookup(locale_months), shortMonthRe = formatRe(locale_shortMonths), shortMonthLookup = formatLookup(locale_shortMonths);
  var formats = {
    "a": formatShortWeekday,
    "A": formatWeekday,
    "b": formatShortMonth,
    "B": formatMonth,
    "c": null,
    "d": formatDayOfMonth,
    "e": formatDayOfMonth,
    "f": formatMicroseconds,
    "g": formatYearISO,
    "G": formatFullYearISO,
    "H": formatHour24,
    "I": formatHour12,
    "j": formatDayOfYear,
    "L": formatMilliseconds,
    "m": formatMonthNumber,
    "M": formatMinutes,
    "p": formatPeriod,
    "q": formatQuarter,
    "Q": formatUnixTimestamp,
    "s": formatUnixTimestampSeconds,
    "S": formatSeconds,
    "u": formatWeekdayNumberMonday,
    "U": formatWeekNumberSunday,
    "V": formatWeekNumberISO,
    "w": formatWeekdayNumberSunday,
    "W": formatWeekNumberMonday,
    "x": null,
    "X": null,
    "y": formatYear,
    "Y": formatFullYear,
    "Z": formatZone,
    "%": formatLiteralPercent
  };
  var utcFormats = {
    "a": formatUTCShortWeekday,
    "A": formatUTCWeekday,
    "b": formatUTCShortMonth,
    "B": formatUTCMonth,
    "c": null,
    "d": formatUTCDayOfMonth,
    "e": formatUTCDayOfMonth,
    "f": formatUTCMicroseconds,
    "g": formatUTCYearISO,
    "G": formatUTCFullYearISO,
    "H": formatUTCHour24,
    "I": formatUTCHour12,
    "j": formatUTCDayOfYear,
    "L": formatUTCMilliseconds,
    "m": formatUTCMonthNumber,
    "M": formatUTCMinutes,
    "p": formatUTCPeriod,
    "q": formatUTCQuarter,
    "Q": formatUnixTimestamp,
    "s": formatUnixTimestampSeconds,
    "S": formatUTCSeconds,
    "u": formatUTCWeekdayNumberMonday,
    "U": formatUTCWeekNumberSunday,
    "V": formatUTCWeekNumberISO,
    "w": formatUTCWeekdayNumberSunday,
    "W": formatUTCWeekNumberMonday,
    "x": null,
    "X": null,
    "y": formatUTCYear,
    "Y": formatUTCFullYear,
    "Z": formatUTCZone,
    "%": formatLiteralPercent
  };
  var parses = {
    "a": parseShortWeekday,
    "A": parseWeekday,
    "b": parseShortMonth,
    "B": parseMonth,
    "c": parseLocaleDateTime,
    "d": parseDayOfMonth,
    "e": parseDayOfMonth,
    "f": parseMicroseconds,
    "g": parseYear,
    "G": parseFullYear,
    "H": parseHour24,
    "I": parseHour24,
    "j": parseDayOfYear,
    "L": parseMilliseconds,
    "m": parseMonthNumber,
    "M": parseMinutes,
    "p": parsePeriod,
    "q": parseQuarter,
    "Q": parseUnixTimestamp,
    "s": parseUnixTimestampSeconds,
    "S": parseSeconds,
    "u": parseWeekdayNumberMonday,
    "U": parseWeekNumberSunday,
    "V": parseWeekNumberISO,
    "w": parseWeekdayNumberSunday,
    "W": parseWeekNumberMonday,
    "x": parseLocaleDate,
    "X": parseLocaleTime,
    "y": parseYear,
    "Y": parseFullYear,
    "Z": parseZone,
    "%": parseLiteralPercent
  };
  formats.x = newFormat(locale_date, formats);
  formats.X = newFormat(locale_time, formats);
  formats.c = newFormat(locale_dateTime, formats);
  utcFormats.x = newFormat(locale_date, utcFormats);
  utcFormats.X = newFormat(locale_time, utcFormats);
  utcFormats.c = newFormat(locale_dateTime, utcFormats);
  function newFormat(specifier, formats2) {
    return function(date5) {
      var string5 = [], i = -1, j = 0, n = specifier.length, c, pad2, format3;
      if (!(date5 instanceof Date))
        date5 = new Date(+date5);
      while (++i < n) {
        if (specifier.charCodeAt(i) === 37) {
          string5.push(specifier.slice(j, i));
          if ((pad2 = pads[c = specifier.charAt(++i)]) != null)
            c = specifier.charAt(++i);
          else
            pad2 = c === "e" ? " " : "0";
          if (format3 = formats2[c])
            c = format3(date5, pad2);
          string5.push(c);
          j = i + 1;
        }
      }
      string5.push(specifier.slice(j, i));
      return string5.join("");
    };
  }
  function newParse(specifier, Z) {
    return function(string5) {
      var d = newDate(1900, void 0, 1), i = parseSpecifier(d, specifier, string5 += "", 0), week, day3;
      if (i != string5.length)
        return null;
      if ("Q" in d)
        return new Date(d.Q);
      if ("s" in d)
        return new Date(d.s * 1e3 + ("L" in d ? d.L : 0));
      if (Z && !("Z" in d))
        d.Z = 0;
      if ("p" in d)
        d.H = d.H % 12 + d.p * 12;
      if (d.m === void 0)
        d.m = "q" in d ? d.q : 0;
      if ("V" in d) {
        if (d.V < 1 || d.V > 53)
          return null;
        if (!("w" in d))
          d.w = 1;
        if ("Z" in d) {
          week = utcDate(newDate(d.y, 0, 1)), day3 = week.getUTCDay();
          week = day3 > 4 || day3 === 0 ? utcMonday.ceil(week) : utcMonday(week);
          week = utcDay_default.offset(week, (d.V - 1) * 7);
          d.y = week.getUTCFullYear();
          d.m = week.getUTCMonth();
          d.d = week.getUTCDate() + (d.w + 6) % 7;
        } else {
          week = localDate(newDate(d.y, 0, 1)), day3 = week.getDay();
          week = day3 > 4 || day3 === 0 ? monday.ceil(week) : monday(week);
          week = day_default.offset(week, (d.V - 1) * 7);
          d.y = week.getFullYear();
          d.m = week.getMonth();
          d.d = week.getDate() + (d.w + 6) % 7;
        }
      } else if ("W" in d || "U" in d) {
        if (!("w" in d))
          d.w = "u" in d ? d.u % 7 : "W" in d ? 1 : 0;
        day3 = "Z" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay();
        d.m = 0;
        d.d = "W" in d ? (d.w + 6) % 7 + d.W * 7 - (day3 + 5) % 7 : d.w + d.U * 7 - (day3 + 6) % 7;
      }
      if ("Z" in d) {
        d.H += d.Z / 100 | 0;
        d.M += d.Z % 100;
        return utcDate(d);
      }
      return localDate(d);
    };
  }
  function parseSpecifier(d, specifier, string5, j) {
    var i = 0, n = specifier.length, m = string5.length, c, parse;
    while (i < n) {
      if (j >= m)
        return -1;
      c = specifier.charCodeAt(i++);
      if (c === 37) {
        c = specifier.charAt(i++);
        parse = parses[c in pads ? specifier.charAt(i++) : c];
        if (!parse || (j = parse(d, string5, j)) < 0)
          return -1;
      } else if (c != string5.charCodeAt(j++)) {
        return -1;
      }
    }
    return j;
  }
  function parsePeriod(d, string5, i) {
    var n = periodRe.exec(string5.slice(i));
    return n ? (d.p = periodLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }
  function parseShortWeekday(d, string5, i) {
    var n = shortWeekdayRe.exec(string5.slice(i));
    return n ? (d.w = shortWeekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }
  function parseWeekday(d, string5, i) {
    var n = weekdayRe.exec(string5.slice(i));
    return n ? (d.w = weekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }
  function parseShortMonth(d, string5, i) {
    var n = shortMonthRe.exec(string5.slice(i));
    return n ? (d.m = shortMonthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }
  function parseMonth(d, string5, i) {
    var n = monthRe.exec(string5.slice(i));
    return n ? (d.m = monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }
  function parseLocaleDateTime(d, string5, i) {
    return parseSpecifier(d, locale_dateTime, string5, i);
  }
  function parseLocaleDate(d, string5, i) {
    return parseSpecifier(d, locale_date, string5, i);
  }
  function parseLocaleTime(d, string5, i) {
    return parseSpecifier(d, locale_time, string5, i);
  }
  function formatShortWeekday(d) {
    return locale_shortWeekdays[d.getDay()];
  }
  function formatWeekday(d) {
    return locale_weekdays[d.getDay()];
  }
  function formatShortMonth(d) {
    return locale_shortMonths[d.getMonth()];
  }
  function formatMonth(d) {
    return locale_months[d.getMonth()];
  }
  function formatPeriod(d) {
    return locale_periods[+(d.getHours() >= 12)];
  }
  function formatQuarter(d) {
    return 1 + ~~(d.getMonth() / 3);
  }
  function formatUTCShortWeekday(d) {
    return locale_shortWeekdays[d.getUTCDay()];
  }
  function formatUTCWeekday(d) {
    return locale_weekdays[d.getUTCDay()];
  }
  function formatUTCShortMonth(d) {
    return locale_shortMonths[d.getUTCMonth()];
  }
  function formatUTCMonth(d) {
    return locale_months[d.getUTCMonth()];
  }
  function formatUTCPeriod(d) {
    return locale_periods[+(d.getUTCHours() >= 12)];
  }
  function formatUTCQuarter(d) {
    return 1 + ~~(d.getUTCMonth() / 3);
  }
  return {
    format: function(specifier) {
      var f = newFormat(specifier += "", formats);
      f.toString = function() {
        return specifier;
      };
      return f;
    },
    parse: function(specifier) {
      var p = newParse(specifier += "", false);
      p.toString = function() {
        return specifier;
      };
      return p;
    },
    utcFormat: function(specifier) {
      var f = newFormat(specifier += "", utcFormats);
      f.toString = function() {
        return specifier;
      };
      return f;
    },
    utcParse: function(specifier) {
      var p = newParse(specifier += "", true);
      p.toString = function() {
        return specifier;
      };
      return p;
    }
  };
}
var pads = { "-": "", "_": " ", "0": "0" };
var numberRe = /^\s*\d+/;
var percentRe = /^%/;
var requoteRe = /[\\^$*+?|[\]().{}]/g;
function pad(value, fill, width) {
  var sign = value < 0 ? "-" : "", string5 = (sign ? -value : value) + "", length = string5.length;
  return sign + (length < width ? new Array(width - length + 1).join(fill) + string5 : string5);
}
function requote(s) {
  return s.replace(requoteRe, "\\$&");
}
function formatRe(names) {
  return new RegExp("^(?:" + names.map(requote).join("|") + ")", "i");
}
function formatLookup(names) {
  return new Map(names.map((name2, i) => [name2.toLowerCase(), i]));
}
function parseWeekdayNumberSunday(d, string5, i) {
  var n = numberRe.exec(string5.slice(i, i + 1));
  return n ? (d.w = +n[0], i + n[0].length) : -1;
}
function parseWeekdayNumberMonday(d, string5, i) {
  var n = numberRe.exec(string5.slice(i, i + 1));
  return n ? (d.u = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberSunday(d, string5, i) {
  var n = numberRe.exec(string5.slice(i, i + 2));
  return n ? (d.U = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberISO(d, string5, i) {
  var n = numberRe.exec(string5.slice(i, i + 2));
  return n ? (d.V = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberMonday(d, string5, i) {
  var n = numberRe.exec(string5.slice(i, i + 2));
  return n ? (d.W = +n[0], i + n[0].length) : -1;
}
function parseFullYear(d, string5, i) {
  var n = numberRe.exec(string5.slice(i, i + 4));
  return n ? (d.y = +n[0], i + n[0].length) : -1;
}
function parseYear(d, string5, i) {
  var n = numberRe.exec(string5.slice(i, i + 2));
  return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2e3), i + n[0].length) : -1;
}
function parseZone(d, string5, i) {
  var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string5.slice(i, i + 6));
  return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1;
}
function parseQuarter(d, string5, i) {
  var n = numberRe.exec(string5.slice(i, i + 1));
  return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1;
}
function parseMonthNumber(d, string5, i) {
  var n = numberRe.exec(string5.slice(i, i + 2));
  return n ? (d.m = n[0] - 1, i + n[0].length) : -1;
}
function parseDayOfMonth(d, string5, i) {
  var n = numberRe.exec(string5.slice(i, i + 2));
  return n ? (d.d = +n[0], i + n[0].length) : -1;
}
function parseDayOfYear(d, string5, i) {
  var n = numberRe.exec(string5.slice(i, i + 3));
  return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;
}
function parseHour24(d, string5, i) {
  var n = numberRe.exec(string5.slice(i, i + 2));
  return n ? (d.H = +n[0], i + n[0].length) : -1;
}
function parseMinutes(d, string5, i) {
  var n = numberRe.exec(string5.slice(i, i + 2));
  return n ? (d.M = +n[0], i + n[0].length) : -1;
}
function parseSeconds(d, string5, i) {
  var n = numberRe.exec(string5.slice(i, i + 2));
  return n ? (d.S = +n[0], i + n[0].length) : -1;
}
function parseMilliseconds(d, string5, i) {
  var n = numberRe.exec(string5.slice(i, i + 3));
  return n ? (d.L = +n[0], i + n[0].length) : -1;
}
function parseMicroseconds(d, string5, i) {
  var n = numberRe.exec(string5.slice(i, i + 6));
  return n ? (d.L = Math.floor(n[0] / 1e3), i + n[0].length) : -1;
}
function parseLiteralPercent(d, string5, i) {
  var n = percentRe.exec(string5.slice(i, i + 1));
  return n ? i + n[0].length : -1;
}
function parseUnixTimestamp(d, string5, i) {
  var n = numberRe.exec(string5.slice(i));
  return n ? (d.Q = +n[0], i + n[0].length) : -1;
}
function parseUnixTimestampSeconds(d, string5, i) {
  var n = numberRe.exec(string5.slice(i));
  return n ? (d.s = +n[0], i + n[0].length) : -1;
}
function formatDayOfMonth(d, p) {
  return pad(d.getDate(), p, 2);
}
function formatHour24(d, p) {
  return pad(d.getHours(), p, 2);
}
function formatHour12(d, p) {
  return pad(d.getHours() % 12 || 12, p, 2);
}
function formatDayOfYear(d, p) {
  return pad(1 + day_default.count(year_default(d), d), p, 3);
}
function formatMilliseconds(d, p) {
  return pad(d.getMilliseconds(), p, 3);
}
function formatMicroseconds(d, p) {
  return formatMilliseconds(d, p) + "000";
}
function formatMonthNumber(d, p) {
  return pad(d.getMonth() + 1, p, 2);
}
function formatMinutes(d, p) {
  return pad(d.getMinutes(), p, 2);
}
function formatSeconds(d, p) {
  return pad(d.getSeconds(), p, 2);
}
function formatWeekdayNumberMonday(d) {
  var day3 = d.getDay();
  return day3 === 0 ? 7 : day3;
}
function formatWeekNumberSunday(d, p) {
  return pad(sunday.count(year_default(d) - 1, d), p, 2);
}
function dISO(d) {
  var day3 = d.getDay();
  return day3 >= 4 || day3 === 0 ? thursday(d) : thursday.ceil(d);
}
function formatWeekNumberISO(d, p) {
  d = dISO(d);
  return pad(thursday.count(year_default(d), d) + (year_default(d).getDay() === 4), p, 2);
}
function formatWeekdayNumberSunday(d) {
  return d.getDay();
}
function formatWeekNumberMonday(d, p) {
  return pad(monday.count(year_default(d) - 1, d), p, 2);
}
function formatYear(d, p) {
  return pad(d.getFullYear() % 100, p, 2);
}
function formatYearISO(d, p) {
  d = dISO(d);
  return pad(d.getFullYear() % 100, p, 2);
}
function formatFullYear(d, p) {
  return pad(d.getFullYear() % 1e4, p, 4);
}
function formatFullYearISO(d, p) {
  var day3 = d.getDay();
  d = day3 >= 4 || day3 === 0 ? thursday(d) : thursday.ceil(d);
  return pad(d.getFullYear() % 1e4, p, 4);
}
function formatZone(d) {
  var z = d.getTimezoneOffset();
  return (z > 0 ? "-" : (z *= -1, "+")) + pad(z / 60 | 0, "0", 2) + pad(z % 60, "0", 2);
}
function formatUTCDayOfMonth(d, p) {
  return pad(d.getUTCDate(), p, 2);
}
function formatUTCHour24(d, p) {
  return pad(d.getUTCHours(), p, 2);
}
function formatUTCHour12(d, p) {
  return pad(d.getUTCHours() % 12 || 12, p, 2);
}
function formatUTCDayOfYear(d, p) {
  return pad(1 + utcDay_default.count(utcYear_default(d), d), p, 3);
}
function formatUTCMilliseconds(d, p) {
  return pad(d.getUTCMilliseconds(), p, 3);
}
function formatUTCMicroseconds(d, p) {
  return formatUTCMilliseconds(d, p) + "000";
}
function formatUTCMonthNumber(d, p) {
  return pad(d.getUTCMonth() + 1, p, 2);
}
function formatUTCMinutes(d, p) {
  return pad(d.getUTCMinutes(), p, 2);
}
function formatUTCSeconds(d, p) {
  return pad(d.getUTCSeconds(), p, 2);
}
function formatUTCWeekdayNumberMonday(d) {
  var dow = d.getUTCDay();
  return dow === 0 ? 7 : dow;
}
function formatUTCWeekNumberSunday(d, p) {
  return pad(utcSunday.count(utcYear_default(d) - 1, d), p, 2);
}
function UTCdISO(d) {
  var day3 = d.getUTCDay();
  return day3 >= 4 || day3 === 0 ? utcThursday(d) : utcThursday.ceil(d);
}
function formatUTCWeekNumberISO(d, p) {
  d = UTCdISO(d);
  return pad(utcThursday.count(utcYear_default(d), d) + (utcYear_default(d).getUTCDay() === 4), p, 2);
}
function formatUTCWeekdayNumberSunday(d) {
  return d.getUTCDay();
}
function formatUTCWeekNumberMonday(d, p) {
  return pad(utcMonday.count(utcYear_default(d) - 1, d), p, 2);
}
function formatUTCYear(d, p) {
  return pad(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCYearISO(d, p) {
  d = UTCdISO(d);
  return pad(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCFullYear(d, p) {
  return pad(d.getUTCFullYear() % 1e4, p, 4);
}
function formatUTCFullYearISO(d, p) {
  var day3 = d.getUTCDay();
  d = day3 >= 4 || day3 === 0 ? utcThursday(d) : utcThursday.ceil(d);
  return pad(d.getUTCFullYear() % 1e4, p, 4);
}
function formatUTCZone() {
  return "+0000";
}
function formatLiteralPercent() {
  return "%";
}
function formatUnixTimestamp(d) {
  return +d;
}
function formatUnixTimestampSeconds(d) {
  return Math.floor(+d / 1e3);
}

// node_modules/d3-time-format/src/defaultLocale.js
var locale2;
var timeFormat;
var timeParse;
var utcFormat;
var utcParse;
defaultLocale2({
  dateTime: "%x, %X",
  date: "%-m/%-d/%Y",
  time: "%-I:%M:%S %p",
  periods: ["AM", "PM"],
  days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
});
function defaultLocale2(definition) {
  locale2 = formatLocale(definition);
  timeFormat = locale2.format;
  timeParse = locale2.parse;
  utcFormat = locale2.utcFormat;
  utcParse = locale2.utcParse;
  return locale2;
}

// src/lib/interval.ts
var DEFAULT_INTERVAL = "month";
function getInterval(s) {
  if (s && ["year", "quarter", "month", "week", "day"].includes(s)) {
    return s;
  }
  return "month";
}

// src/lib/equals.ts
function shallow_equal(a, b) {
  const l = a.length;
  if (l !== b.length) {
    return false;
  }
  for (let i = 0; i < l; i += 1) {
    if (a[i] !== b[i]) {
      return false;
    }
  }
  return true;
}

// src/lib/result.ts
function ok(value) {
  return { success: true, value };
}
function err(value) {
  return { success: false, value };
}

// src/lib/json.ts
function parseJSON(data) {
  try {
    return ok(JSON.parse(data));
  } catch (error) {
    if (error instanceof SyntaxError) {
      return err("JSON syntax error");
    }
    throw error;
  }
}

// src/lib/store.ts
function derived_array(store, getter) {
  let val = [];
  return derived(
    store,
    (store_val, set) => {
      const newVal = getter(store_val);
      if (!shallow_equal(val, newVal)) {
        set(newVal);
        val = newVal;
      }
    },
    val
  );
}
function localStorageSyncedStore(key, validator2, init3) {
  const fullKey = `fava-${key}`;
  const stored_val = localStorage.getItem(fullKey);
  let initial = null;
  if (stored_val) {
    const json = parseJSON(stored_val);
    const parsed = json.success ? validator2(json.value) : null;
    if (parsed == null ? void 0 : parsed.success) {
      initial = parsed.value;
    }
  }
  const store = writable(initial != null ? initial : init3());
  store.subscribe((val) => {
    localStorage.setItem(fullKey, JSON.stringify(val));
  });
  return store;
}

// src/lib/validation.ts
function defaultValue(validator2, value) {
  return (json) => {
    const res2 = validator2(json);
    return res2.success ? res2 : ok(value);
  };
}
var unknown = (json) => ok(json);
var string = (json) => typeof json === "string" ? ok(json) : err("string validation failed.");
var optional_string = defaultValue(string, "");
var boolean = (json) => typeof json === "boolean" ? ok(json) : err("boolean validation failed.");
var number2 = (json) => typeof json === "number" ? ok(json) : err("number validation failed.");
var date = (json) => {
  if (typeof json === "string" || json instanceof Date) {
    const parsed = new Date(json);
    if (Number.isNaN(+parsed)) {
      return err("Expected a date");
    }
    return ok(parsed);
  }
  return err("Expected a date");
};
function constant(value) {
  return (json) => json === value ? ok(json) : err("Expected a constant");
}
function union(...args) {
  return (json) => {
    for (const validator2 of args) {
      const res2 = validator2(json);
      if (res2.success) {
        return res2;
      }
    }
    return err("Validating union failed");
  };
}
function optional(validator2) {
  return (json) => json === void 0 || json === null ? ok(null) : validator2(json);
}
function lazy(func) {
  return (json) => func()(json);
}
function array(validator2) {
  return (json) => {
    if (Array.isArray(json)) {
      const result = [];
      for (const element2 of json) {
        const res2 = validator2(element2);
        if (res2.success) {
          result.push(res2.value);
        } else {
          return res2;
        }
      }
      return ok(result);
    }
    return err("array validation failed");
  };
}
function tuple(decoders) {
  return (json) => {
    if (Array.isArray(json) && json.length === 2) {
      const result = [];
      for (let i = 0; i < decoders.length; i += 1) {
        const res2 = decoders[i](json[i]);
        if (res2.success) {
          result[i] = res2.value;
        } else {
          return res2;
        }
      }
      return ok(result);
    }
    return err("Expected a tuple");
  };
}
function isJsonObject(json) {
  return typeof json === "object" && json !== null && !Array.isArray(json);
}
var { hasOwnProperty } = Object.prototype;
function object(validators) {
  return (json) => {
    if (isJsonObject(json)) {
      const obj = {};
      for (const key in validators) {
        if (hasOwnProperty.call(validators, key)) {
          const res2 = validators[key](json[key]);
          if (res2.success) {
            obj[key] = res2.value;
          } else {
            return err(
              `Validating object failed at key '${key}': ${res2.value}`
            );
          }
        }
      }
      return ok(obj);
    }
    return err("Validating object failed");
  };
}
function record(decoder) {
  return (json) => {
    if (isJsonObject(json)) {
      const ret = {};
      for (const [key, value] of Object.entries(json)) {
        const res2 = decoder(value);
        if (res2.success) {
          ret[key] = res2.value;
        } else {
          return err(`Validating record failed at key '${key}': ${res2.value}`);
        }
      }
      return ok(ret);
    }
    return err("Validating record failed");
  };
}

// src/stores/index.ts
var urlHash = writable("");
var conversion = writable("");
var interval = writable(DEFAULT_INTERVAL);
var ledgerDataValidator = object({
  accounts: array(string),
  account_details: record(
    object({
      close_date: date
    })
  ),
  base_url: string,
  currencies: array(string),
  errors: number2,
  fava_options: object({
    auto_reload: boolean,
    currency_column: number2,
    conversion_currencies: array(string),
    indent: number2,
    locale: union(string, constant(null)),
    insert_entry: array(
      object({ date: string, filename: string, lineno: number2, re: string })
    )
  }),
  have_excel: boolean,
  incognito: boolean,
  links: array(string),
  options: object({
    documents: array(string),
    filename: string,
    include: array(string),
    operating_currency: array(string)
  }),
  payees: array(string),
  precisions: record(number2),
  tags: array(string),
  years: array(string)
});
var rawLedgerData = writable("");
var ledgerData = derived(rawLedgerData, (s) => {
  const res2 = ledgerDataValidator(JSON.parse(s));
  if (!res2.success) {
    throw new Error("Loading ledger data failed.");
  }
  return res2.value;
});
var fava_options = derived(ledgerData, (val) => val.fava_options);
var options = derived(ledgerData, (val) => val.options);
var precisions = derived(ledgerData, (val) => val.precisions);
var HAVE_EXCEL = derived(ledgerData, (val) => val.have_excel);
var incognito = derived(ledgerData, (val) => val.incognito);
var base_url = derived(ledgerData, (val) => val.base_url);
var accounts = derived_array(ledgerData, (val) => val.accounts);
var account_details = derived(
  ledgerData,
  (val) => val.account_details
);
var currencies = derived_array(ledgerData, (val) => val.currencies);
var links = derived_array(ledgerData, (val) => val.links);
var payees = derived_array(ledgerData, (val) => val.payees);
var tags = derived_array(ledgerData, (val) => val.tags);
var years2 = derived_array(ledgerData, (val) => val.years);
var operating_currency = derived_array(
  ledgerData,
  (val) => val.options.operating_currency.sort()
);
var conversion_currencies = derived_array(
  ledgerData,
  (val) => val.fava_options.conversion_currencies
);
var currencies_sorted = derived_array(
  currencies,
  (val) => [...val].sort()
);
var errorCount = writable(0);
function closeOverlay() {
  if (window.location.hash) {
    window.history.pushState({}, "", "#");
  }
  urlHash.set("");
}

// src/format.ts
function localeFormatter(locale3, precision = 2) {
  if (!locale3) {
    return format(`.${precision}f`);
  }
  const opts = {
    minimumFractionDigits: Math.max(0, Math.min(precision, 20))
  };
  const fmt = new Intl.NumberFormat(locale3.replace("_", "-"), opts);
  return fmt.format.bind(fmt);
}
var replaceNumbers = (num) => num.replace(/[0-9]/g, "X");
var formatterPer = format(".2f");
function formatPercentage(number8) {
  return `${formatterPer(Math.abs(number8) * 100)}%`;
}
var formatterShort = format(".3s");
var ctx = derived(
  [incognito, fava_options, precisions],
  ([i, f, p]) => {
    const formatter = localeFormatter(f.locale);
    const currencyFormatters = Object.fromEntries(
      Object.entries(p).map(
        ([currency, prec2]) => [currency, localeFormatter(f.locale, prec2)]
      )
    );
    const formatWithCurrency = (n, c) => {
      const currencyFormatter = currencyFormatters[c];
      return currencyFormatter ? currencyFormatter(n) : formatter(n);
    };
    return i ? {
      short: (n) => replaceNumbers(formatterShort(n)),
      amount: (n, c) => `${replaceNumbers(formatter(n))} ${c}`
    } : {
      short: (n) => formatterShort(n),
      amount: (n, c) => `${formatWithCurrency(n, c)} ${c}`
    };
  }
);
var day2 = utcFormat("%Y-%m-%d");
var dateFormat = {
  year: utcFormat("%Y"),
  quarter: (date5) => `${date5.getUTCFullYear()}Q${Math.floor(date5.getUTCMonth() / 3) + 1}`,
  month: utcFormat("%b %Y"),
  week: utcFormat("%YW%W"),
  day: day2
};
var timeFilterDateFormat = {
  year: utcFormat("%Y"),
  quarter: (date5) => `${date5.getUTCFullYear()}-Q${Math.floor(date5.getUTCMonth() / 3) + 1}`,
  month: utcFormat("%Y-%m"),
  week: utcFormat("%Y-W%W"),
  day: day2
};
function todayAsString() {
  return timeFormat("%Y-%m-%d")(new Date());
}
var currentDateFormat = derived(interval, (val) => dateFormat[val]);
var currentTimeFilterDateFormat = derived(
  interval,
  (val) => timeFilterDateFormat[val]
);

// src/entries.ts
var postingValidator = object({
  account: string,
  amount: string
});
function emptyPosting() {
  return {
    account: "",
    amount: ""
  };
}
var validatorBase = {
  type: string,
  date: string,
  meta: record(
    defaultValue(union(boolean, number2, string), "Unsupported metadata value")
  )
};
var entryBaseValidator = object(validatorBase);
var EntryBase = class {
  constructor(type) {
    this.type = type;
    this.meta = {};
    this.date = todayAsString();
  }
};
var Balance = class extends EntryBase {
  constructor() {
    super("Balance");
    this.account = "";
    this.amount = {
      number: "",
      currency: ""
    };
  }
};
Balance.validator = object(__spreadProps(__spreadValues({}, validatorBase), {
  type: constant("Balance"),
  account: string,
  amount: object({ number: string, currency: string })
}));
var Note = class extends EntryBase {
  constructor() {
    super("Note");
    this.account = "";
    this.comment = "";
  }
};
Note.validator = object(__spreadProps(__spreadValues({}, validatorBase), {
  type: constant("Note"),
  account: string,
  comment: string
}));
var _Transaction = class extends EntryBase {
  constructor() {
    super("Transaction");
    this.flag = "*";
    this.payee = "";
    this.narration = "";
    this.tags = [];
    this.links = [];
    this.postings = [emptyPosting(), emptyPosting()];
  }
  toString() {
    const postings = this.postings.map((p) => `  ${p.account}  ${p.amount}`);
    return `${this.date} ${this.flag} "${this.payee}" "${this.narration}"
${postings.join("\n")}`;
  }
  static fromJSON(json) {
    return Object.assign(new _Transaction(), _Transaction.validator(json));
  }
};
var Transaction = _Transaction;
Transaction.validator = object(__spreadProps(__spreadValues({}, validatorBase), {
  type: constant("Transaction"),
  flag: string,
  payee: optional_string,
  narration: optional_string,
  tags: array(string),
  links: array(string),
  postings: array(postingValidator)
}));
var entryValidator = union(
  Balance.validator,
  Note.validator,
  Transaction.validator
);
var constructors = {
  Balance,
  Note,
  Transaction
};
function create(type) {
  return new constructors[type]();
}

// src/stores/url.ts
var urlSyncedParams = [
  "account",
  "charts",
  "conversion",
  "filter",
  "interval",
  "time"
];

// src/helpers.ts
function urlFor(report, params, update2 = true) {
  const url = `${get_store_value(base_url)}${report}`;
  const urlParams = new URLSearchParams();
  if (update2) {
    const oldParams = new URL(window.location.href).searchParams;
    for (const name2 of urlSyncedParams) {
      const value = oldParams.get(name2);
      if (value) {
        urlParams.set(name2, value);
      }
    }
  }
  if (params) {
    Object.entries(params).forEach(([key, value]) => {
      if (value !== void 0) {
        urlParams.set(key, `${value}`);
      }
    });
  }
  const urlParamString = urlParams.toString();
  return urlParamString ? `${url}?${urlParams.toString()}` : url;
}
function urlForSource(entry) {
  const file_path = entry.meta.filename.toString();
  const line = entry.meta.lineno.toString();
  return urlFor("editor/", { file_path, line });
}
function urlForAccount(account2) {
  return urlFor(`account/${account2}/`);
}

// src/lib/fetch.ts
var FetchError = class extends Error {
};
function fetch(input, init3 = {}) {
  return window.fetch(input, __spreadValues({ credentials: "same-origin" }, init3));
}
async function handleJSON(response) {
  if (!response.ok) {
    throw new FetchError(response.statusText);
  }
  const data = await response.json();
  if (!isJsonObject(data)) {
    throw new FetchError("Invalid response: not an object");
  }
  if (!data.success) {
    throw new FetchError(
      typeof data.error === "string" ? data.error : "Invalid response: missing error"
    );
  }
  return data;
}
var response_validator = object({ data: unknown });
async function fetchJSON(input, init3) {
  const res2 = await fetch(input, init3).then(handleJSON);
  const parsed = response_validator(res2);
  if (parsed.success) {
    return parsed.value.data;
  }
  throw new FetchError("Invalid response: missing data key.");
}
async function handleText(response) {
  if (!response.ok) {
    const msg = await response.text();
    throw new Error(msg || response.statusText);
  }
  return response.text();
}

// src/log.ts
function log_error(...args) {
  console.error(...args);
}

// src/notifications.ts
var notificationList = (() => {
  let value = null;
  return () => {
    if (value === null) {
      value = document.createElement("div");
      value.className = "notifications";
      document.body.appendChild(value);
    }
    return value;
  };
})();
function notify(msg, cls = "info", callback) {
  const notification = document.createElement("li");
  notification.classList.add(cls);
  notification.appendChild(document.createTextNode(msg));
  notificationList().append(notification);
  notification.addEventListener("click", () => {
    notification.remove();
    callback == null ? void 0 : callback();
  });
  setTimeout(() => {
    notification.remove();
  }, 5e3);
}

// src/lib/events.ts
var Events = class {
  constructor() {
    this.events = /* @__PURE__ */ new Map();
  }
  on(event, callback) {
    var _a2;
    const events = (_a2 = this.events.get(event)) != null ? _a2 : [];
    this.events.set(event, [...events, callback]);
  }
  once(event, callback) {
    const runOnce = () => {
      this.remove(event, runOnce);
      callback();
    };
    this.on(event, runOnce);
  }
  remove(event, callback) {
    const events = this.events.get(event);
    if (events) {
      this.events.set(
        event,
        events.filter((c) => c !== callback)
      );
    }
  }
  trigger(event) {
    const events = this.events.get(event);
    events == null ? void 0 : events.forEach((callback) => {
      callback();
    });
  }
};
function delegate(element2, type, selector, callback) {
  element2.addEventListener(type, (event) => {
    let { target } = event;
    if (!(target instanceof Node)) {
      return;
    }
    if (!(target instanceof Element)) {
      target = target.parentNode;
    }
    if (target instanceof Element) {
      const closest = target.closest(selector);
      if (closest) {
        callback(event, closest);
      }
    }
  });
}

// src/lib/dom.ts
function getScriptTagJSON(selector) {
  const el = document.querySelector(selector);
  if (!el) {
    return err(`<script> tag not found for selector '${selector}'`);
  }
  try {
    return parseJSON(el.innerHTML);
  } catch (e3) {
    return err(`<script> tag for selector '${selector}' contains invalid JSON`);
  }
}
function getScriptTagValue(selector, validator2) {
  const res2 = getScriptTagJSON(selector);
  if (!res2.success) {
    return res2;
  }
  return validator2(res2.value);
}

// src/i18n.ts
var translations;
var validator = record(string);
function _(text2) {
  if (translations === void 0) {
    const res2 = getScriptTagValue("#translations", validator);
    translations = res2.success ? res2.value : {};
    if (!res2.success) {
      log_error(`Loading translations failed: ${res2.value}`);
    }
  }
  return translations[text2] || text2;
}
function format2(text2, values) {
  return text2.replace(/%\(\w+\)s/g, (match) => values[match.slice(2, -2)]);
}

// src/lib/iso4217.ts
var iso4217_default = /* @__PURE__ */ new Set([
  "AED",
  "AFN",
  "ALL",
  "AMD",
  "ANG",
  "AOA",
  "ARS",
  "AUD",
  "AWG",
  "AZN",
  "BAM",
  "BBD",
  "BDT",
  "BGN",
  "BHD",
  "BIF",
  "BMD",
  "BND",
  "BOB",
  "BOV",
  "BRL",
  "BSD",
  "BTN",
  "BWP",
  "BYN",
  "BZD",
  "CAD",
  "CDF",
  "CHE",
  "CHF",
  "CHW",
  "CLF",
  "CLP",
  "CNY",
  "COP",
  "COU",
  "CRC",
  "CUC",
  "CUP",
  "CVE",
  "CZK",
  "DJF",
  "DKK",
  "DOP",
  "DZD",
  "EGP",
  "ERN",
  "ETB",
  "EUR",
  "FJD",
  "FKP",
  "GBP",
  "GEL",
  "GHS",
  "GIP",
  "GMD",
  "GNF",
  "GTQ",
  "GYD",
  "HKD",
  "HNL",
  "HRK",
  "HTG",
  "HUF",
  "IDR",
  "ILS",
  "INR",
  "IQD",
  "IRR",
  "ISK",
  "JMD",
  "JOD",
  "JPY",
  "KES",
  "KGS",
  "KHR",
  "KMF",
  "KPW",
  "KRW",
  "KWD",
  "KYD",
  "KZT",
  "LAK",
  "LBP",
  "LKR",
  "LRD",
  "LSL",
  "LYD",
  "MAD",
  "MDL",
  "MGA",
  "MKD",
  "MMK",
  "MNT",
  "MOP",
  "MRU",
  "MUR",
  "MVR",
  "MWK",
  "MXN",
  "MXV",
  "MYR",
  "MZN",
  "NAD",
  "NGN",
  "NIO",
  "NOK",
  "NPR",
  "NZD",
  "OMR",
  "PAB",
  "PEN",
  "PGK",
  "PHP",
  "PKR",
  "PLN",
  "PYG",
  "QAR",
  "RON",
  "RSD",
  "RUB",
  "RWF",
  "SAR",
  "SBD",
  "SCR",
  "SDG",
  "SEK",
  "SGD",
  "SHP",
  "SLL",
  "SOS",
  "SRD",
  "SSP",
  "STN",
  "SVC",
  "SYP",
  "SZL",
  "THB",
  "TJS",
  "TMT",
  "TND",
  "TOP",
  "TRY",
  "TTD",
  "TWD",
  "TZS",
  "UAH",
  "UGX",
  "USD",
  "USN",
  "UYI",
  "UYU",
  "UYW",
  "UZS",
  "VES",
  "VND",
  "VUV",
  "WST",
  "XAF",
  "XAG",
  "XAU",
  "XBA",
  "XBB",
  "XBC",
  "XBD",
  "XCD",
  "XDR",
  "XOF",
  "XPD",
  "XPF",
  "XPT",
  "XSU",
  "XTS",
  "XUA",
  "XXX",
  "YER",
  "ZAR",
  "ZMW",
  "ZWL"
]);

// src/stores/chart.ts
var showCharts = writable(true);
var lastActiveChartName = writable(void 0);
var hierarchyChartMode = localStorageSyncedStore(
  "hierarchy-chart-mode",
  union(constant("treemap"), constant("sunburst")),
  () => "treemap"
);
var lineChartMode = localStorageSyncedStore(
  "line-chart-mode",
  union(constant("line"), constant("area")),
  () => "line"
);
var barChartMode = localStorageSyncedStore(
  "bar-chart-mode",
  union(constant("stacked"), constant("single")),
  () => "stacked"
);
var chartCurrency = writable("");
var currencySuggestions = derived(
  [operating_currency, currencies_sorted, conversion_currencies],
  ([
    operating_currency_val,
    currencies_sorted_val,
    conversion_currencies_val
  ]) => conversion_currencies_val.length ? conversion_currencies_val : [
    ...operating_currency_val,
    ...currencies_sorted_val.filter(
      (c) => !operating_currency_val.includes(c) && iso4217_default.has(c)
    )
  ]
);
var conversions = derived(
  currencySuggestions,
  (currencySuggestions_val) => [
    ["at_cost", _("At Cost")],
    ["at_value", _("At Market Value")],
    ["units", _("Units")],
    ...currencySuggestions_val.map((currency) => [
      currency,
      format2(_("Converted to %(currency)s"), { currency })
    ])
  ]
);

// src/stores/filters.ts
var time_filter = writable("");
var account_filter = writable("");
var fql_filter = writable("");
function getFilterParams() {
  return {
    account: get_store_value(account_filter),
    filter: get_store_value(fql_filter),
    time: get_store_value(time_filter)
  };
}

// src/router.ts
function setStoreValuesFromURL() {
  var _a2, _b, _c, _d;
  const params = new URL(window.location.href).searchParams;
  account_filter.set((_a2 = params.get("account")) != null ? _a2 : "");
  fql_filter.set((_b = params.get("filter")) != null ? _b : "");
  time_filter.set((_c = params.get("time")) != null ? _c : "");
  interval.set(getInterval(params.get("interval")));
  conversion.set((_d = params.get("conversion")) != null ? _d : "at_cost");
  showCharts.set(params.get("charts") !== "false");
}
var Router = class extends Events {
  constructor() {
    super();
    this.hash = window.location.hash;
    this.pathname = window.location.pathname;
    this.search = window.location.search;
    this.interruptHandlers = /* @__PURE__ */ new Set();
  }
  addInteruptHandler(handler) {
    this.interruptHandlers.add(handler);
    return () => {
      this.interruptHandlers.delete(handler);
    };
  }
  shouldInterrupt() {
    for (const handler of this.interruptHandlers) {
      const ret = handler();
      if (ret) {
        return ret;
      }
    }
    return null;
  }
  init() {
    urlHash.set(window.location.hash.slice(1));
    this.updateState();
    window.addEventListener("beforeunload", (event) => {
      const leaveMessage = this.shouldInterrupt();
      if (leaveMessage) {
        event.returnValue = leaveMessage;
      }
    });
    window.addEventListener("popstate", () => {
      urlHash.set(window.location.hash.slice(1));
      if (window.location.hash !== this.hash && window.location.pathname === this.pathname && window.location.search === this.search) {
        this.updateState();
      } else if (window.location.pathname !== this.pathname || window.location.search !== this.search) {
        this.loadURL(window.location.href, false).catch(log_error);
        setStoreValuesFromURL();
      }
    });
    this.takeOverLinks();
  }
  navigate(url, load = true) {
    if (load) {
      this.loadURL(url).catch(log_error);
    } else {
      window.history.pushState(null, "", url);
      this.updateState();
    }
  }
  async loadURL(url, historyState = true) {
    var _a2;
    const leaveMessage = this.shouldInterrupt();
    if (leaveMessage) {
      if (!window.confirm(leaveMessage)) {
        return;
      }
    }
    const getUrl = new URL(url, window.location.href);
    getUrl.searchParams.set("partial", "true");
    const svg2 = document.querySelector(".fava-icon");
    svg2 == null ? void 0 : svg2.classList.add("loading");
    try {
      const content2 = await fetch(getUrl.toString()).then(handleText);
      if (historyState) {
        window.history.pushState(null, "", url);
        window.scroll(0, 0);
      }
      this.updateState();
      const article = document.querySelector("article");
      if (article) {
        article.innerHTML = content2;
      }
      this.trigger("page-loaded");
      const hash2 = window.location.hash.slice(1);
      urlHash.set(hash2);
      if (hash2) {
        (_a2 = document.getElementById(hash2)) == null ? void 0 : _a2.scrollIntoView();
      }
    } catch (error) {
      if (error instanceof Error) {
        notify(`Loading ${url} failed: ${error.message}`, "error");
      } else {
        log_error(error);
      }
    } finally {
      svg2 == null ? void 0 : svg2.classList.remove("loading");
    }
  }
  updateState() {
    this.hash = window.location.hash;
    this.pathname = window.location.pathname;
    this.search = window.location.search;
  }
  takeOverLinks() {
    delegate(
      document,
      "click",
      "a",
      (event, link2) => {
        var _a2;
        if (((_a2 = link2.getAttribute("href")) == null ? void 0 : _a2.charAt(0)) === "#" || link2.hasAttribute("data-remote") || link2.host !== window.location.host || link2.protocol.indexOf("http") !== 0 || event.defaultPrevented) {
          return;
        }
        if (link2.closest("aside")) {
          const newURL = new URL(link2.href);
          const oldParams = new URL(window.location.href).searchParams;
          for (const name2 of urlSyncedParams) {
            const value = oldParams.get(name2);
            if (value) {
              newURL.searchParams.set(name2, value);
            } else {
              newURL.searchParams.delete(name2);
            }
          }
          link2.href = newURL.toString();
        }
        if (event.button !== 0 || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
          return;
        }
        event.preventDefault();
        this.navigate(link2.href);
      }
    );
  }
  reload() {
    this.loadURL(window.location.href, false).catch(log_error);
  }
};
var router = new Router();
var router_default = router;
function syncToURL(store, name2, defaultValue3, shouldLoad = true) {
  store.subscribe((val) => {
    const newURL = new URL(window.location.href);
    newURL.searchParams.set(name2, val.toString());
    if (val === "" || val === defaultValue3) {
      newURL.searchParams.delete(name2);
    }
    if (newURL.href !== window.location.href) {
      router.navigate(newURL.href, shouldLoad);
    }
  });
}
function syncStoreValuesToURL() {
  syncToURL(account_filter, "account", "");
  syncToURL(fql_filter, "filter", "");
  syncToURL(time_filter, "time", "");
  syncToURL(interval, "interval", DEFAULT_INTERVAL);
  syncToURL(conversion, "conversion", "at_cost");
  syncToURL(showCharts, "charts", true, false);
}

// src/api.ts
async function put(endpoint, body) {
  const opts = body instanceof FormData ? { body } : {
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body)
  };
  const url = urlFor(`api/${endpoint}`);
  const json = await fetchJSON(url, __spreadValues({ method: "PUT" }, opts));
  const res2 = string(json);
  if (res2.success) {
    return res2.value;
  }
  notify(`Invalid data returned in API request: ${res2.value}`, "error");
  throw new Error(res2.value);
}
var getAPIValidators = {
  changed: boolean,
  context: object({
    entry: entryBaseValidator,
    balances_before: optional(record(array(string))),
    balances_after: optional(record(array(string))),
    sha256sum: string,
    slice: string
  }),
  errors: number2,
  extract: array(entryValidator),
  move: string,
  payee_accounts: array(string),
  payee_transaction: Transaction.validator,
  query_result: object({ chart: unknown, table: string })
};
async function get(endpoint, ...[params]) {
  const url = urlFor(`api/${endpoint}`, params, false);
  const json = await fetchJSON(url);
  const res2 = getAPIValidators[endpoint](json);
  if (res2.success) {
    return res2.value;
  }
  notify(`Invalid data returned in API request: ${res2.value}`, "error");
  throw new Error(res2.value);
}
async function moveDocument(filename, account2, new_name) {
  try {
    const msg = await get("move", { filename, account: account2, new_name });
    notify(msg);
    return true;
  } catch (error) {
    log_error(error);
    if (error instanceof Error) {
      notify(error.message, "error");
    }
    return false;
  }
}
async function deleteDocument(filename) {
  try {
    const url = urlFor("api/document", { filename }, false);
    const res2 = await fetchJSON(url, { method: "DELETE" });
    const d = string(res2);
    notify(d.value);
    return d.success;
  } catch (error) {
    log_error(error);
    if (error instanceof Error) {
      notify(error.message, "error");
    }
    return false;
  }
}
async function saveEntries(entries) {
  if (!entries.length) {
    return;
  }
  try {
    const data = await put("add_entries", { entries });
    router_default.reload();
    notify(data);
  } catch (error) {
    log_error(error);
    if (error instanceof Error) {
      notify(`Saving failed: ${error.message}`, "error");
    }
    throw error;
  }
}

// src/clipboard.ts
function copyToClipboard(text2) {
  if (!text2) {
    return;
  }
  const textarea = document.createElement("textarea");
  textarea.value = text2;
  textarea.style.position = "fixed";
  textarea.style.top = "0";
  textarea.style.left = "0";
  document.body.appendChild(textarea);
  textarea.focus();
  textarea.select();
  try {
    document.execCommand("copy");
  } catch (err2) {
    log_error(err2);
  }
  textarea.remove();
}
var CopyableText = class extends HTMLElement {
  constructor() {
    super();
    this.addEventListener("click", (event) => {
      copyToClipboard(this.getAttribute("data-clipboard-text"));
      event.stopPropagation();
    });
  }
};

// node_modules/@codemirror/state/dist/index.js
var Text = class {
  constructor() {
  }
  lineAt(pos) {
    if (pos < 0 || pos > this.length)
      throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);
    return this.lineInner(pos, false, 1, 0);
  }
  line(n) {
    if (n < 1 || n > this.lines)
      throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);
    return this.lineInner(n, true, 1, 0);
  }
  replace(from, to, text2) {
    let parts = [];
    this.decompose(0, from, parts, 2);
    if (text2.length)
      text2.decompose(0, text2.length, parts, 1 | 2);
    this.decompose(to, this.length, parts, 1);
    return TextNode.from(parts, this.length - (to - from) + text2.length);
  }
  append(other) {
    return this.replace(this.length, this.length, other);
  }
  slice(from, to = this.length) {
    let parts = [];
    this.decompose(from, to, parts, 0);
    return TextNode.from(parts, to - from);
  }
  eq(other) {
    if (other == this)
      return true;
    if (other.length != this.length || other.lines != this.lines)
      return false;
    let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1);
    let a = new RawTextCursor(this), b = new RawTextCursor(other);
    for (let skip = start, pos = start; ; ) {
      a.next(skip);
      b.next(skip);
      skip = 0;
      if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value)
        return false;
      pos += a.value.length;
      if (a.done || pos >= end)
        return true;
    }
  }
  iter(dir = 1) {
    return new RawTextCursor(this, dir);
  }
  iterRange(from, to = this.length) {
    return new PartialTextCursor(this, from, to);
  }
  iterLines(from, to) {
    let inner;
    if (from == null) {
      inner = this.iter();
    } else {
      if (to == null)
        to = this.lines + 1;
      let start = this.line(from).from;
      inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to));
    }
    return new LineCursor(inner);
  }
  toString() {
    return this.sliceString(0);
  }
  toJSON() {
    let lines = [];
    this.flatten(lines);
    return lines;
  }
  static of(text2) {
    if (text2.length == 0)
      throw new RangeError("A document must have at least one line");
    if (text2.length == 1 && !text2[0])
      return Text.empty;
    return text2.length <= 32 ? new TextLeaf(text2) : TextNode.from(TextLeaf.split(text2, []));
  }
};
var TextLeaf = class extends Text {
  constructor(text2, length = textLength(text2)) {
    super();
    this.text = text2;
    this.length = length;
  }
  get lines() {
    return this.text.length;
  }
  get children() {
    return null;
  }
  lineInner(target, isLine, line, offset) {
    for (let i = 0; ; i++) {
      let string5 = this.text[i], end = offset + string5.length;
      if ((isLine ? line : end) >= target)
        return new Line(offset, end, line, string5);
      offset = end + 1;
      line++;
    }
  }
  decompose(from, to, target, open) {
    let text2 = from <= 0 && to >= this.length ? this : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from));
    if (open & 1) {
      let prev = target.pop();
      let joined = appendText(text2.text, prev.text.slice(), 0, text2.length);
      if (joined.length <= 32) {
        target.push(new TextLeaf(joined, prev.length + text2.length));
      } else {
        let mid = joined.length >> 1;
        target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid)));
      }
    } else {
      target.push(text2);
    }
  }
  replace(from, to, text2) {
    if (!(text2 instanceof TextLeaf))
      return super.replace(from, to, text2);
    let lines = appendText(this.text, appendText(text2.text, sliceText(this.text, 0, from)), to);
    let newLen = this.length + text2.length - (to - from);
    if (lines.length <= 32)
      return new TextLeaf(lines, newLen);
    return TextNode.from(TextLeaf.split(lines, []), newLen);
  }
  sliceString(from, to = this.length, lineSep = "\n") {
    let result = "";
    for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) {
      let line = this.text[i], end = pos + line.length;
      if (pos > from && i)
        result += lineSep;
      if (from < end && to > pos)
        result += line.slice(Math.max(0, from - pos), to - pos);
      pos = end + 1;
    }
    return result;
  }
  flatten(target) {
    for (let line of this.text)
      target.push(line);
  }
  scanIdentical() {
    return 0;
  }
  static split(text2, target) {
    let part = [], len = -1;
    for (let line of text2) {
      part.push(line);
      len += line.length + 1;
      if (part.length == 32) {
        target.push(new TextLeaf(part, len));
        part = [];
        len = -1;
      }
    }
    if (len > -1)
      target.push(new TextLeaf(part, len));
    return target;
  }
};
var TextNode = class extends Text {
  constructor(children3, length) {
    super();
    this.children = children3;
    this.length = length;
    this.lines = 0;
    for (let child of children3)
      this.lines += child.lines;
  }
  lineInner(target, isLine, line, offset) {
    for (let i = 0; ; i++) {
      let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1;
      if ((isLine ? endLine : end) >= target)
        return child.lineInner(target, isLine, line, offset);
      offset = end + 1;
      line = endLine + 1;
    }
  }
  decompose(from, to, target, open) {
    for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) {
      let child = this.children[i], end = pos + child.length;
      if (from <= end && to >= pos) {
        let childOpen = open & ((pos <= from ? 1 : 0) | (end >= to ? 2 : 0));
        if (pos >= from && end <= to && !childOpen)
          target.push(child);
        else
          child.decompose(from - pos, to - pos, target, childOpen);
      }
      pos = end + 1;
    }
  }
  replace(from, to, text2) {
    if (text2.lines < this.lines)
      for (let i = 0, pos = 0; i < this.children.length; i++) {
        let child = this.children[i], end = pos + child.length;
        if (from >= pos && to <= end) {
          let updated = child.replace(from - pos, to - pos, text2);
          let totalLines = this.lines - child.lines + updated.lines;
          if (updated.lines < totalLines >> 5 - 1 && updated.lines > totalLines >> 5 + 1) {
            let copy2 = this.children.slice();
            copy2[i] = updated;
            return new TextNode(copy2, this.length - (to - from) + text2.length);
          }
          return super.replace(pos, end, updated);
        }
        pos = end + 1;
      }
    return super.replace(from, to, text2);
  }
  sliceString(from, to = this.length, lineSep = "\n") {
    let result = "";
    for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) {
      let child = this.children[i], end = pos + child.length;
      if (pos > from && i)
        result += lineSep;
      if (from < end && to > pos)
        result += child.sliceString(from - pos, to - pos, lineSep);
      pos = end + 1;
    }
    return result;
  }
  flatten(target) {
    for (let child of this.children)
      child.flatten(target);
  }
  scanIdentical(other, dir) {
    if (!(other instanceof TextNode))
      return 0;
    let length = 0;
    let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] : [this.children.length - 1, other.children.length - 1, -1, -1];
    for (; ; iA += dir, iB += dir) {
      if (iA == eA || iB == eB)
        return length;
      let chA = this.children[iA], chB = other.children[iB];
      if (chA != chB)
        return length + chA.scanIdentical(chB, dir);
      length += chA.length + 1;
    }
  }
  static from(children3, length = children3.reduce((l, ch) => l + ch.length + 1, -1)) {
    let lines = 0;
    for (let ch of children3)
      lines += ch.lines;
    if (lines < 32) {
      let flat = [];
      for (let ch of children3)
        ch.flatten(flat);
      return new TextLeaf(flat, length);
    }
    let chunk = Math.max(32, lines >> 5), maxChunk = chunk << 1, minChunk = chunk >> 1;
    let chunked = [], currentLines = 0, currentLen = -1, currentChunk = [];
    function add3(child) {
      let last;
      if (child.lines > maxChunk && child instanceof TextNode) {
        for (let node of child.children)
          add3(node);
      } else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) {
        flush2();
        chunked.push(child);
      } else if (child instanceof TextLeaf && currentLines && (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && child.lines + last.lines <= 32) {
        currentLines += child.lines;
        currentLen += child.length + 1;
        currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length);
      } else {
        if (currentLines + child.lines > chunk)
          flush2();
        currentLines += child.lines;
        currentLen += child.length + 1;
        currentChunk.push(child);
      }
    }
    function flush2() {
      if (currentLines == 0)
        return;
      chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen));
      currentLen = -1;
      currentLines = currentChunk.length = 0;
    }
    for (let child of children3)
      add3(child);
    flush2();
    return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length);
  }
};
Text.empty = /* @__PURE__ */ new TextLeaf([""], 0);
function textLength(text2) {
  let length = -1;
  for (let line of text2)
    length += line.length + 1;
  return length;
}
function appendText(text2, target, from = 0, to = 1e9) {
  for (let pos = 0, i = 0, first = true; i < text2.length && pos <= to; i++) {
    let line = text2[i], end = pos + line.length;
    if (end >= from) {
      if (end > to)
        line = line.slice(0, to - pos);
      if (pos < from)
        line = line.slice(from - pos);
      if (first) {
        target[target.length - 1] += line;
        first = false;
      } else
        target.push(line);
    }
    pos = end + 1;
  }
  return target;
}
function sliceText(text2, from, to) {
  return appendText(text2, [""], from, to);
}
var RawTextCursor = class {
  constructor(text2, dir = 1) {
    this.dir = dir;
    this.done = false;
    this.lineBreak = false;
    this.value = "";
    this.nodes = [text2];
    this.offsets = [dir > 0 ? 1 : (text2 instanceof TextLeaf ? text2.text.length : text2.children.length) << 1];
  }
  nextInner(skip, dir) {
    this.done = this.lineBreak = false;
    for (; ; ) {
      let last = this.nodes.length - 1;
      let top3 = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1;
      let size = top3 instanceof TextLeaf ? top3.text.length : top3.children.length;
      if (offset == (dir > 0 ? size : 0)) {
        if (last == 0) {
          this.done = true;
          this.value = "";
          return this;
        }
        if (dir > 0)
          this.offsets[last - 1]++;
        this.nodes.pop();
        this.offsets.pop();
      } else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) {
        this.offsets[last] += dir;
        if (skip == 0) {
          this.lineBreak = true;
          this.value = "\n";
          return this;
        }
        skip--;
      } else if (top3 instanceof TextLeaf) {
        let next = top3.text[offset + (dir < 0 ? -1 : 0)];
        this.offsets[last] += dir;
        if (next.length > Math.max(0, skip)) {
          this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip);
          return this;
        }
        skip -= next.length;
      } else {
        let next = top3.children[offset + (dir < 0 ? -1 : 0)];
        if (skip > next.length) {
          skip -= next.length;
          this.offsets[last] += dir;
        } else {
          if (dir < 0)
            this.offsets[last]--;
          this.nodes.push(next);
          this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1);
        }
      }
    }
  }
  next(skip = 0) {
    if (skip < 0) {
      this.nextInner(-skip, -this.dir);
      skip = this.value.length;
    }
    return this.nextInner(skip, this.dir);
  }
};
var PartialTextCursor = class {
  constructor(text2, start, end) {
    this.value = "";
    this.done = false;
    this.cursor = new RawTextCursor(text2, start > end ? -1 : 1);
    this.pos = start > end ? text2.length : 0;
    this.from = Math.min(start, end);
    this.to = Math.max(start, end);
  }
  nextInner(skip, dir) {
    if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {
      this.value = "";
      this.done = true;
      return this;
    }
    skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos);
    let limit = dir < 0 ? this.pos - this.from : this.to - this.pos;
    if (skip > limit)
      skip = limit;
    limit -= skip;
    let { value } = this.cursor.next(skip);
    this.pos += (value.length + skip) * dir;
    this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit);
    this.done = !this.value;
    return this;
  }
  next(skip = 0) {
    if (skip < 0)
      skip = Math.max(skip, this.from - this.pos);
    else if (skip > 0)
      skip = Math.min(skip, this.to - this.pos);
    return this.nextInner(skip, this.cursor.dir);
  }
  get lineBreak() {
    return this.cursor.lineBreak && this.value != "";
  }
};
var LineCursor = class {
  constructor(inner) {
    this.inner = inner;
    this.afterBreak = true;
    this.value = "";
    this.done = false;
  }
  next(skip = 0) {
    let { done, lineBreak, value } = this.inner.next(skip);
    if (done) {
      this.done = true;
      this.value = "";
    } else if (lineBreak) {
      if (this.afterBreak) {
        this.value = "";
      } else {
        this.afterBreak = true;
        this.next();
      }
    } else {
      this.value = value;
      this.afterBreak = false;
    }
    return this;
  }
  get lineBreak() {
    return false;
  }
};
if (typeof Symbol != "undefined") {
  Text.prototype[Symbol.iterator] = function() {
    return this.iter();
  };
  RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = LineCursor.prototype[Symbol.iterator] = function() {
    return this;
  };
}
var Line = class {
  constructor(from, to, number8, text2) {
    this.from = from;
    this.to = to;
    this.number = number8;
    this.text = text2;
  }
  get length() {
    return this.to - this.from;
  }
};
var extend = /* @__PURE__ */ "lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map((s) => s ? parseInt(s, 36) : 1);
for (let i = 1; i < extend.length; i++)
  extend[i] += extend[i - 1];
function isExtendingChar(code) {
  for (let i = 1; i < extend.length; i += 2)
    if (extend[i] > code)
      return extend[i - 1] <= code;
  return false;
}
function isRegionalIndicator(code) {
  return code >= 127462 && code <= 127487;
}
var ZWJ = 8205;
function findClusterBreak(str, pos, forward = true, includeExtending = true) {
  return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending);
}
function nextClusterBreak(str, pos, includeExtending) {
  if (pos == str.length)
    return pos;
  if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1)))
    pos--;
  let prev = codePointAt(str, pos);
  pos += codePointSize(prev);
  while (pos < str.length) {
    let next = codePointAt(str, pos);
    if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) {
      pos += codePointSize(next);
      prev = next;
    } else if (isRegionalIndicator(next)) {
      let countBefore = 0, i = pos - 2;
      while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) {
        countBefore++;
        i -= 2;
      }
      if (countBefore % 2 == 0)
        break;
      else
        pos += 2;
    } else {
      break;
    }
  }
  return pos;
}
function prevClusterBreak(str, pos, includeExtending) {
  while (pos > 0) {
    let found = nextClusterBreak(str, pos - 2, includeExtending);
    if (found < pos)
      return found;
    pos--;
  }
  return 0;
}
function surrogateLow(ch) {
  return ch >= 56320 && ch < 57344;
}
function surrogateHigh(ch) {
  return ch >= 55296 && ch < 56320;
}
function codePointAt(str, pos) {
  let code0 = str.charCodeAt(pos);
  if (!surrogateHigh(code0) || pos + 1 == str.length)
    return code0;
  let code1 = str.charCodeAt(pos + 1);
  if (!surrogateLow(code1))
    return code0;
  return (code0 - 55296 << 10) + (code1 - 56320) + 65536;
}
function fromCodePoint(code) {
  if (code <= 65535)
    return String.fromCharCode(code);
  code -= 65536;
  return String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320);
}
function codePointSize(code) {
  return code < 65536 ? 1 : 2;
}
var DefaultSplit = /\r\n?|\n/;
var MapMode = /* @__PURE__ */ function(MapMode2) {
  MapMode2[MapMode2["Simple"] = 0] = "Simple";
  MapMode2[MapMode2["TrackDel"] = 1] = "TrackDel";
  MapMode2[MapMode2["TrackBefore"] = 2] = "TrackBefore";
  MapMode2[MapMode2["TrackAfter"] = 3] = "TrackAfter";
  return MapMode2;
}(MapMode || (MapMode = {}));
var ChangeDesc = class {
  constructor(sections) {
    this.sections = sections;
  }
  get length() {
    let result = 0;
    for (let i = 0; i < this.sections.length; i += 2)
      result += this.sections[i];
    return result;
  }
  get newLength() {
    let result = 0;
    for (let i = 0; i < this.sections.length; i += 2) {
      let ins = this.sections[i + 1];
      result += ins < 0 ? this.sections[i] : ins;
    }
    return result;
  }
  get empty() {
    return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0;
  }
  iterGaps(f) {
    for (let i = 0, posA = 0, posB = 0; i < this.sections.length; ) {
      let len = this.sections[i++], ins = this.sections[i++];
      if (ins < 0) {
        f(posA, posB, len);
        posB += len;
      } else {
        posB += ins;
      }
      posA += len;
    }
  }
  iterChangedRanges(f, individual = false) {
    iterChanges(this, f, individual);
  }
  get invertedDesc() {
    let sections = [];
    for (let i = 0; i < this.sections.length; ) {
      let len = this.sections[i++], ins = this.sections[i++];
      if (ins < 0)
        sections.push(len, ins);
      else
        sections.push(ins, len);
    }
    return new ChangeDesc(sections);
  }
  composeDesc(other) {
    return this.empty ? other : other.empty ? this : composeSets(this, other);
  }
  mapDesc(other, before = false) {
    return other.empty ? this : mapSet(this, other, before);
  }
  mapPos(pos, assoc = -1, mode = MapMode.Simple) {
    let posA = 0, posB = 0;
    for (let i = 0; i < this.sections.length; ) {
      let len = this.sections[i++], ins = this.sections[i++], endA = posA + len;
      if (ins < 0) {
        if (endA > pos)
          return posB + (pos - posA);
        posB += len;
      } else {
        if (mode != MapMode.Simple && endA >= pos && (mode == MapMode.TrackDel && posA < pos && endA > pos || mode == MapMode.TrackBefore && posA < pos || mode == MapMode.TrackAfter && endA > pos))
          return null;
        if (endA > pos || endA == pos && assoc < 0 && !len)
          return pos == posA || assoc < 0 ? posB : posB + ins;
        posB += ins;
      }
      posA = endA;
    }
    if (pos > posA)
      throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);
    return posB;
  }
  touchesRange(from, to = from) {
    for (let i = 0, pos = 0; i < this.sections.length && pos <= to; ) {
      let len = this.sections[i++], ins = this.sections[i++], end = pos + len;
      if (ins >= 0 && pos <= to && end >= from)
        return pos < from && end > to ? "cover" : true;
      pos = end;
    }
    return false;
  }
  toString() {
    let result = "";
    for (let i = 0; i < this.sections.length; ) {
      let len = this.sections[i++], ins = this.sections[i++];
      result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "");
    }
    return result;
  }
  toJSON() {
    return this.sections;
  }
  static fromJSON(json) {
    if (!Array.isArray(json) || json.length % 2 || json.some((a) => typeof a != "number"))
      throw new RangeError("Invalid JSON representation of ChangeDesc");
    return new ChangeDesc(json);
  }
  static create(sections) {
    return new ChangeDesc(sections);
  }
};
var ChangeSet = class extends ChangeDesc {
  constructor(sections, inserted) {
    super(sections);
    this.inserted = inserted;
  }
  apply(doc2) {
    if (this.length != doc2.length)
      throw new RangeError("Applying change set to a document with the wrong length");
    iterChanges(this, (fromA, toA, fromB, _toB, text2) => doc2 = doc2.replace(fromB, fromB + (toA - fromA), text2), false);
    return doc2;
  }
  mapDesc(other, before = false) {
    return mapSet(this, other, before, true);
  }
  invert(doc2) {
    let sections = this.sections.slice(), inserted = [];
    for (let i = 0, pos = 0; i < sections.length; i += 2) {
      let len = sections[i], ins = sections[i + 1];
      if (ins >= 0) {
        sections[i] = ins;
        sections[i + 1] = len;
        let index2 = i >> 1;
        while (inserted.length < index2)
          inserted.push(Text.empty);
        inserted.push(len ? doc2.slice(pos, pos + len) : Text.empty);
      }
      pos += len;
    }
    return new ChangeSet(sections, inserted);
  }
  compose(other) {
    return this.empty ? other : other.empty ? this : composeSets(this, other, true);
  }
  map(other, before = false) {
    return other.empty ? this : mapSet(this, other, before, true);
  }
  iterChanges(f, individual = false) {
    iterChanges(this, f, individual);
  }
  get desc() {
    return ChangeDesc.create(this.sections);
  }
  filter(ranges) {
    let resultSections = [], resultInserted = [], filteredSections = [];
    let iter = new SectionIter(this);
    done:
      for (let i = 0, pos = 0; ; ) {
        let next = i == ranges.length ? 1e9 : ranges[i++];
        while (pos < next || pos == next && iter.len == 0) {
          if (iter.done)
            break done;
          let len = Math.min(iter.len, next - pos);
          addSection(filteredSections, len, -1);
          let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;
          addSection(resultSections, len, ins);
          if (ins > 0)
            addInsert(resultInserted, resultSections, iter.text);
          iter.forward(len);
          pos += len;
        }
        let end = ranges[i++];
        while (pos < end) {
          if (iter.done)
            break done;
          let len = Math.min(iter.len, end - pos);
          addSection(resultSections, len, -1);
          addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);
          iter.forward(len);
          pos += len;
        }
      }
    return {
      changes: new ChangeSet(resultSections, resultInserted),
      filtered: ChangeDesc.create(filteredSections)
    };
  }
  toJSON() {
    let parts = [];
    for (let i = 0; i < this.sections.length; i += 2) {
      let len = this.sections[i], ins = this.sections[i + 1];
      if (ins < 0)
        parts.push(len);
      else if (ins == 0)
        parts.push([len]);
      else
        parts.push([len].concat(this.inserted[i >> 1].toJSON()));
    }
    return parts;
  }
  static of(changes, length, lineSep) {
    let sections = [], inserted = [], pos = 0;
    let total = null;
    function flush2(force = false) {
      if (!force && !sections.length)
        return;
      if (pos < length)
        addSection(sections, length - pos, -1);
      let set = new ChangeSet(sections, inserted);
      total = total ? total.compose(set.map(total)) : set;
      sections = [];
      inserted = [];
      pos = 0;
    }
    function process(spec) {
      if (Array.isArray(spec)) {
        for (let sub of spec)
          process(sub);
      } else if (spec instanceof ChangeSet) {
        if (spec.length != length)
          throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);
        flush2();
        total = total ? total.compose(spec.map(total)) : spec;
      } else {
        let { from, to = from, insert: insert3 } = spec;
        if (from > to || from < 0 || to > length)
          throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);
        let insText = !insert3 ? Text.empty : typeof insert3 == "string" ? Text.of(insert3.split(lineSep || DefaultSplit)) : insert3;
        let insLen = insText.length;
        if (from == to && insLen == 0)
          return;
        if (from < pos)
          flush2();
        if (from > pos)
          addSection(sections, from - pos, -1);
        addSection(sections, to - from, insLen);
        addInsert(inserted, sections, insText);
        pos = to;
      }
    }
    process(changes);
    flush2(!total);
    return total;
  }
  static empty(length) {
    return new ChangeSet(length ? [length, -1] : [], []);
  }
  static fromJSON(json) {
    if (!Array.isArray(json))
      throw new RangeError("Invalid JSON representation of ChangeSet");
    let sections = [], inserted = [];
    for (let i = 0; i < json.length; i++) {
      let part = json[i];
      if (typeof part == "number") {
        sections.push(part, -1);
      } else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e3, i2) => i2 && typeof e3 != "string")) {
        throw new RangeError("Invalid JSON representation of ChangeSet");
      } else if (part.length == 1) {
        sections.push(part[0], 0);
      } else {
        while (inserted.length < i)
          inserted.push(Text.empty);
        inserted[i] = Text.of(part.slice(1));
        sections.push(part[0], inserted[i].length);
      }
    }
    return new ChangeSet(sections, inserted);
  }
  static createSet(sections, inserted) {
    return new ChangeSet(sections, inserted);
  }
};
function addSection(sections, len, ins, forceJoin = false) {
  if (len == 0 && ins <= 0)
    return;
  let last = sections.length - 2;
  if (last >= 0 && ins <= 0 && ins == sections[last + 1])
    sections[last] += len;
  else if (len == 0 && sections[last] == 0)
    sections[last + 1] += ins;
  else if (forceJoin) {
    sections[last] += len;
    sections[last + 1] += ins;
  } else
    sections.push(len, ins);
}
function addInsert(values, sections, value) {
  if (value.length == 0)
    return;
  let index2 = sections.length - 2 >> 1;
  if (index2 < values.length) {
    values[values.length - 1] = values[values.length - 1].append(value);
  } else {
    while (values.length < index2)
      values.push(Text.empty);
    values.push(value);
  }
}
function iterChanges(desc, f, individual) {
  let inserted = desc.inserted;
  for (let posA = 0, posB = 0, i = 0; i < desc.sections.length; ) {
    let len = desc.sections[i++], ins = desc.sections[i++];
    if (ins < 0) {
      posA += len;
      posB += len;
    } else {
      let endA = posA, endB = posB, text2 = Text.empty;
      for (; ; ) {
        endA += len;
        endB += ins;
        if (ins && inserted)
          text2 = text2.append(inserted[i - 2 >> 1]);
        if (individual || i == desc.sections.length || desc.sections[i + 1] < 0)
          break;
        len = desc.sections[i++];
        ins = desc.sections[i++];
      }
      f(posA, endA, posB, endB, text2);
      posA = endA;
      posB = endB;
    }
  }
}
function mapSet(setA, setB, before, mkSet = false) {
  let sections = [], insert3 = mkSet ? [] : null;
  let a = new SectionIter(setA), b = new SectionIter(setB);
  for (let inserted = -1; ; ) {
    if (a.ins == -1 && b.ins == -1) {
      let len = Math.min(a.len, b.len);
      addSection(sections, len, -1);
      a.forward(len);
      b.forward(len);
    } else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) {
      let len = b.len;
      addSection(sections, b.ins, -1);
      while (len) {
        let piece = Math.min(a.len, len);
        if (a.ins >= 0 && inserted < a.i && a.len <= piece) {
          addSection(sections, 0, a.ins);
          if (insert3)
            addInsert(insert3, sections, a.text);
          inserted = a.i;
        }
        a.forward(piece);
        len -= piece;
      }
      b.next();
    } else if (a.ins >= 0) {
      let len = 0, left2 = a.len;
      while (left2) {
        if (b.ins == -1) {
          let piece = Math.min(left2, b.len);
          len += piece;
          left2 -= piece;
          b.forward(piece);
        } else if (b.ins == 0 && b.len < left2) {
          left2 -= b.len;
          b.next();
        } else {
          break;
        }
      }
      addSection(sections, len, inserted < a.i ? a.ins : 0);
      if (insert3 && inserted < a.i)
        addInsert(insert3, sections, a.text);
      inserted = a.i;
      a.forward(a.len - left2);
    } else if (a.done && b.done) {
      return insert3 ? ChangeSet.createSet(sections, insert3) : ChangeDesc.create(sections);
    } else {
      throw new Error("Mismatched change set lengths");
    }
  }
}
function composeSets(setA, setB, mkSet = false) {
  let sections = [];
  let insert3 = mkSet ? [] : null;
  let a = new SectionIter(setA), b = new SectionIter(setB);
  for (let open = false; ; ) {
    if (a.done && b.done) {
      return insert3 ? ChangeSet.createSet(sections, insert3) : ChangeDesc.create(sections);
    } else if (a.ins == 0) {
      addSection(sections, a.len, 0, open);
      a.next();
    } else if (b.len == 0 && !b.done) {
      addSection(sections, 0, b.ins, open);
      if (insert3)
        addInsert(insert3, sections, b.text);
      b.next();
    } else if (a.done || b.done) {
      throw new Error("Mismatched change set lengths");
    } else {
      let len = Math.min(a.len2, b.len), sectionLen = sections.length;
      if (a.ins == -1) {
        let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins;
        addSection(sections, len, insB, open);
        if (insert3 && insB)
          addInsert(insert3, sections, b.text);
      } else if (b.ins == -1) {
        addSection(sections, a.off ? 0 : a.len, len, open);
        if (insert3)
          addInsert(insert3, sections, a.textBit(len));
      } else {
        addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open);
        if (insert3 && !b.off)
          addInsert(insert3, sections, b.text);
      }
      open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);
      a.forward2(len);
      b.forward(len);
    }
  }
}
var SectionIter = class {
  constructor(set) {
    this.set = set;
    this.i = 0;
    this.next();
  }
  next() {
    let { sections } = this.set;
    if (this.i < sections.length) {
      this.len = sections[this.i++];
      this.ins = sections[this.i++];
    } else {
      this.len = 0;
      this.ins = -2;
    }
    this.off = 0;
  }
  get done() {
    return this.ins == -2;
  }
  get len2() {
    return this.ins < 0 ? this.len : this.ins;
  }
  get text() {
    let { inserted } = this.set, index2 = this.i - 2 >> 1;
    return index2 >= inserted.length ? Text.empty : inserted[index2];
  }
  textBit(len) {
    let { inserted } = this.set, index2 = this.i - 2 >> 1;
    return index2 >= inserted.length && !len ? Text.empty : inserted[index2].slice(this.off, len == null ? void 0 : this.off + len);
  }
  forward(len) {
    if (len == this.len)
      this.next();
    else {
      this.len -= len;
      this.off += len;
    }
  }
  forward2(len) {
    if (this.ins == -1)
      this.forward(len);
    else if (len == this.ins)
      this.next();
    else {
      this.ins -= len;
      this.off += len;
    }
  }
};
var SelectionRange = class {
  constructor(from, to, flags) {
    this.from = from;
    this.to = to;
    this.flags = flags;
  }
  get anchor() {
    return this.flags & 16 ? this.to : this.from;
  }
  get head() {
    return this.flags & 16 ? this.from : this.to;
  }
  get empty() {
    return this.from == this.to;
  }
  get assoc() {
    return this.flags & 4 ? -1 : this.flags & 8 ? 1 : 0;
  }
  get bidiLevel() {
    let level = this.flags & 3;
    return level == 3 ? null : level;
  }
  get goalColumn() {
    let value = this.flags >> 5;
    return value == 33554431 ? void 0 : value;
  }
  map(change, assoc = -1) {
    let from, to;
    if (this.empty) {
      from = to = change.mapPos(this.from, assoc);
    } else {
      from = change.mapPos(this.from, 1);
      to = change.mapPos(this.to, -1);
    }
    return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags);
  }
  extend(from, to = from) {
    if (from <= this.anchor && to >= this.anchor)
      return EditorSelection.range(from, to);
    let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;
    return EditorSelection.range(this.anchor, head);
  }
  eq(other) {
    return this.anchor == other.anchor && this.head == other.head;
  }
  toJSON() {
    return { anchor: this.anchor, head: this.head };
  }
  static fromJSON(json) {
    if (!json || typeof json.anchor != "number" || typeof json.head != "number")
      throw new RangeError("Invalid JSON representation for SelectionRange");
    return EditorSelection.range(json.anchor, json.head);
  }
  static create(from, to, flags) {
    return new SelectionRange(from, to, flags);
  }
};
var EditorSelection = class {
  constructor(ranges, mainIndex) {
    this.ranges = ranges;
    this.mainIndex = mainIndex;
  }
  map(change, assoc = -1) {
    if (change.empty)
      return this;
    return EditorSelection.create(this.ranges.map((r) => r.map(change, assoc)), this.mainIndex);
  }
  eq(other) {
    if (this.ranges.length != other.ranges.length || this.mainIndex != other.mainIndex)
      return false;
    for (let i = 0; i < this.ranges.length; i++)
      if (!this.ranges[i].eq(other.ranges[i]))
        return false;
    return true;
  }
  get main() {
    return this.ranges[this.mainIndex];
  }
  asSingle() {
    return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0);
  }
  addRange(range2, main = true) {
    return EditorSelection.create([range2].concat(this.ranges), main ? 0 : this.mainIndex + 1);
  }
  replaceRange(range2, which = this.mainIndex) {
    let ranges = this.ranges.slice();
    ranges[which] = range2;
    return EditorSelection.create(ranges, this.mainIndex);
  }
  toJSON() {
    return { ranges: this.ranges.map((r) => r.toJSON()), main: this.mainIndex };
  }
  static fromJSON(json) {
    if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length)
      throw new RangeError("Invalid JSON representation for EditorSelection");
    return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main);
  }
  static single(anchor, head = anchor) {
    return new EditorSelection([EditorSelection.range(anchor, head)], 0);
  }
  static create(ranges, mainIndex = 0) {
    if (ranges.length == 0)
      throw new RangeError("A selection needs at least one range");
    for (let pos = 0, i = 0; i < ranges.length; i++) {
      let range2 = ranges[i];
      if (range2.empty ? range2.from <= pos : range2.from < pos)
        return EditorSelection.normalized(ranges.slice(), mainIndex);
      pos = range2.to;
    }
    return new EditorSelection(ranges, mainIndex);
  }
  static cursor(pos, assoc = 0, bidiLevel, goalColumn) {
    return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 4 : 8) | (bidiLevel == null ? 3 : Math.min(2, bidiLevel)) | (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431) << 5);
  }
  static range(anchor, head, goalColumn) {
    let goal = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431) << 5;
    return head < anchor ? SelectionRange.create(head, anchor, 16 | goal | 8) : SelectionRange.create(anchor, head, goal | (head > anchor ? 4 : 0));
  }
  static normalized(ranges, mainIndex = 0) {
    let main = ranges[mainIndex];
    ranges.sort((a, b) => a.from - b.from);
    mainIndex = ranges.indexOf(main);
    for (let i = 1; i < ranges.length; i++) {
      let range2 = ranges[i], prev = ranges[i - 1];
      if (range2.empty ? range2.from <= prev.to : range2.from < prev.to) {
        let from = prev.from, to = Math.max(range2.to, prev.to);
        if (i <= mainIndex)
          mainIndex--;
        ranges.splice(--i, 2, range2.anchor > range2.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to));
      }
    }
    return new EditorSelection(ranges, mainIndex);
  }
};
function checkSelection(selection2, docLength) {
  for (let range2 of selection2.ranges)
    if (range2.to > docLength)
      throw new RangeError("Selection points outside of document");
}
var nextID = 0;
var Facet = class {
  constructor(combine, compareInput, compare2, isStatic, enables) {
    this.combine = combine;
    this.compareInput = compareInput;
    this.compare = compare2;
    this.isStatic = isStatic;
    this.id = nextID++;
    this.default = combine([]);
    this.extensions = typeof enables == "function" ? enables(this) : enables;
  }
  static define(config2 = {}) {
    return new Facet(config2.combine || ((a) => a), config2.compareInput || ((a, b) => a === b), config2.compare || (!config2.combine ? sameArray : (a, b) => a === b), !!config2.static, config2.enables);
  }
  of(value) {
    return new FacetProvider([], this, 0, value);
  }
  compute(deps, get2) {
    if (this.isStatic)
      throw new Error("Can't compute a static facet");
    return new FacetProvider(deps, this, 1, get2);
  }
  computeN(deps, get2) {
    if (this.isStatic)
      throw new Error("Can't compute a static facet");
    return new FacetProvider(deps, this, 2, get2);
  }
  from(field, get2) {
    if (!get2)
      get2 = (x2) => x2;
    return this.compute([field], (state) => get2(state.field(field)));
  }
};
function sameArray(a, b) {
  return a == b || a.length == b.length && a.every((e3, i) => e3 === b[i]);
}
var FacetProvider = class {
  constructor(dependencies, facet, type, value) {
    this.dependencies = dependencies;
    this.facet = facet;
    this.type = type;
    this.value = value;
    this.id = nextID++;
  }
  dynamicSlot(addresses) {
    var _a2;
    let getter = this.value;
    let compare2 = this.facet.compareInput;
    let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2;
    let depDoc = false, depSel = false, depAddrs = [];
    for (let dep of this.dependencies) {
      if (dep == "doc")
        depDoc = true;
      else if (dep == "selection")
        depSel = true;
      else if ((((_a2 = addresses[dep.id]) !== null && _a2 !== void 0 ? _a2 : 1) & 1) == 0)
        depAddrs.push(addresses[dep.id]);
    }
    return {
      create(state) {
        state.values[idx] = getter(state);
        return 1;
      },
      update(state, tr) {
        if (depDoc && tr.docChanged || depSel && (tr.docChanged || tr.selection) || ensureAll(state, depAddrs)) {
          let newVal = getter(state);
          if (multi ? !compareArray(newVal, state.values[idx], compare2) : !compare2(newVal, state.values[idx])) {
            state.values[idx] = newVal;
            return 1;
          }
        }
        return 0;
      },
      reconfigure: (state, oldState) => {
        let newVal = getter(state);
        let oldAddr = oldState.config.address[id];
        if (oldAddr != null) {
          let oldVal = getAddr(oldState, oldAddr);
          if (this.dependencies.every((dep) => {
            return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) : dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true;
          }) || (multi ? compareArray(newVal, oldVal, compare2) : compare2(newVal, oldVal))) {
            state.values[idx] = oldVal;
            return 0;
          }
        }
        state.values[idx] = newVal;
        return 1;
      }
    };
  }
};
function compareArray(a, b, compare2) {
  if (a.length != b.length)
    return false;
  for (let i = 0; i < a.length; i++)
    if (!compare2(a[i], b[i]))
      return false;
  return true;
}
function ensureAll(state, addrs) {
  let changed = false;
  for (let addr of addrs)
    if (ensureAddr(state, addr) & 1)
      changed = true;
  return changed;
}
function dynamicFacetSlot(addresses, facet, providers) {
  let providerAddrs = providers.map((p) => addresses[p.id]);
  let providerTypes = providers.map((p) => p.type);
  let dynamic = providerAddrs.filter((p) => !(p & 1));
  let idx = addresses[facet.id] >> 1;
  function get2(state) {
    let values = [];
    for (let i = 0; i < providerAddrs.length; i++) {
      let value = getAddr(state, providerAddrs[i]);
      if (providerTypes[i] == 2)
        for (let val of value)
          values.push(val);
      else
        values.push(value);
    }
    return facet.combine(values);
  }
  return {
    create(state) {
      for (let addr of providerAddrs)
        ensureAddr(state, addr);
      state.values[idx] = get2(state);
      return 1;
    },
    update(state, tr) {
      if (!ensureAll(state, dynamic))
        return 0;
      let value = get2(state);
      if (facet.compare(value, state.values[idx]))
        return 0;
      state.values[idx] = value;
      return 1;
    },
    reconfigure(state, oldState) {
      let depChanged = ensureAll(state, providerAddrs);
      let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);
      if (oldProviders && !depChanged && sameArray(providers, oldProviders)) {
        state.values[idx] = oldValue;
        return 0;
      }
      let value = get2(state);
      if (facet.compare(value, oldValue)) {
        state.values[idx] = oldValue;
        return 0;
      }
      state.values[idx] = value;
      return 1;
    }
  };
}
var initField = /* @__PURE__ */ Facet.define({ static: true });
var StateField = class {
  constructor(id, createF, updateF, compareF, spec) {
    this.id = id;
    this.createF = createF;
    this.updateF = updateF;
    this.compareF = compareF;
    this.spec = spec;
    this.provides = void 0;
  }
  static define(config2) {
    let field = new StateField(nextID++, config2.create, config2.update, config2.compare || ((a, b) => a === b), config2);
    if (config2.provide)
      field.provides = config2.provide(field);
    return field;
  }
  create(state) {
    let init3 = state.facet(initField).find((i) => i.field == this);
    return ((init3 === null || init3 === void 0 ? void 0 : init3.create) || this.createF)(state);
  }
  slot(addresses) {
    let idx = addresses[this.id] >> 1;
    return {
      create: (state) => {
        state.values[idx] = this.create(state);
        return 1;
      },
      update: (state, tr) => {
        let oldVal = state.values[idx];
        let value = this.updateF(oldVal, tr);
        if (this.compareF(oldVal, value))
          return 0;
        state.values[idx] = value;
        return 1;
      },
      reconfigure: (state, oldState) => {
        if (oldState.config.address[this.id] != null) {
          state.values[idx] = oldState.field(this);
          return 0;
        }
        state.values[idx] = this.create(state);
        return 1;
      }
    };
  }
  init(create2) {
    return [this, initField.of({ field: this, create: create2 })];
  }
  get extension() {
    return this;
  }
};
var Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 };
function prec(value) {
  return (ext2) => new PrecExtension(ext2, value);
}
var Prec = {
  highest: /* @__PURE__ */ prec(Prec_.highest),
  high: /* @__PURE__ */ prec(Prec_.high),
  default: /* @__PURE__ */ prec(Prec_.default),
  low: /* @__PURE__ */ prec(Prec_.low),
  lowest: /* @__PURE__ */ prec(Prec_.lowest)
};
var PrecExtension = class {
  constructor(inner, prec2) {
    this.inner = inner;
    this.prec = prec2;
  }
};
var Compartment = class {
  of(ext2) {
    return new CompartmentInstance(this, ext2);
  }
  reconfigure(content2) {
    return Compartment.reconfigure.of({ compartment: this, extension: content2 });
  }
  get(state) {
    return state.config.compartments.get(this);
  }
};
var CompartmentInstance = class {
  constructor(compartment, inner) {
    this.compartment = compartment;
    this.inner = inner;
  }
};
var Configuration = class {
  constructor(base2, compartments, dynamicSlots, address, staticValues, facets) {
    this.base = base2;
    this.compartments = compartments;
    this.dynamicSlots = dynamicSlots;
    this.address = address;
    this.staticValues = staticValues;
    this.facets = facets;
    this.statusTemplate = [];
    while (this.statusTemplate.length < dynamicSlots.length)
      this.statusTemplate.push(0);
  }
  staticFacet(facet) {
    let addr = this.address[facet.id];
    return addr == null ? facet.default : this.staticValues[addr >> 1];
  }
  static resolve(base2, compartments, oldState) {
    let fields = [];
    let facets = /* @__PURE__ */ Object.create(null);
    let newCompartments = /* @__PURE__ */ new Map();
    for (let ext2 of flatten2(base2, compartments, newCompartments)) {
      if (ext2 instanceof StateField)
        fields.push(ext2);
      else
        (facets[ext2.facet.id] || (facets[ext2.facet.id] = [])).push(ext2);
    }
    let address = /* @__PURE__ */ Object.create(null);
    let staticValues = [];
    let dynamicSlots = [];
    for (let field of fields) {
      address[field.id] = dynamicSlots.length << 1;
      dynamicSlots.push((a) => field.slot(a));
    }
    let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;
    for (let id in facets) {
      let providers = facets[id], facet = providers[0].facet;
      let oldProviders = oldFacets && oldFacets[id] || [];
      if (providers.every((p) => p.type == 0)) {
        address[facet.id] = staticValues.length << 1 | 1;
        if (sameArray(oldProviders, providers)) {
          staticValues.push(oldState.facet(facet));
        } else {
          let value = facet.combine(providers.map((p) => p.value));
          staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);
        }
      } else {
        for (let p of providers) {
          if (p.type == 0) {
            address[p.id] = staticValues.length << 1 | 1;
            staticValues.push(p.value);
          } else {
            address[p.id] = dynamicSlots.length << 1;
            dynamicSlots.push((a) => p.dynamicSlot(a));
          }
        }
        address[facet.id] = dynamicSlots.length << 1;
        dynamicSlots.push((a) => dynamicFacetSlot(a, facet, providers));
      }
    }
    let dynamic = dynamicSlots.map((f) => f(address));
    return new Configuration(base2, newCompartments, dynamic, address, staticValues, facets);
  }
};
function flatten2(extension, compartments, newCompartments) {
  let result = [[], [], [], [], []];
  let seen = /* @__PURE__ */ new Map();
  function inner(ext2, prec2) {
    let known = seen.get(ext2);
    if (known != null) {
      if (known <= prec2)
        return;
      let found = result[known].indexOf(ext2);
      if (found > -1)
        result[known].splice(found, 1);
      if (ext2 instanceof CompartmentInstance)
        newCompartments.delete(ext2.compartment);
    }
    seen.set(ext2, prec2);
    if (Array.isArray(ext2)) {
      for (let e3 of ext2)
        inner(e3, prec2);
    } else if (ext2 instanceof CompartmentInstance) {
      if (newCompartments.has(ext2.compartment))
        throw new RangeError(`Duplicate use of compartment in extensions`);
      let content2 = compartments.get(ext2.compartment) || ext2.inner;
      newCompartments.set(ext2.compartment, content2);
      inner(content2, prec2);
    } else if (ext2 instanceof PrecExtension) {
      inner(ext2.inner, ext2.prec);
    } else if (ext2 instanceof StateField) {
      result[prec2].push(ext2);
      if (ext2.provides)
        inner(ext2.provides, prec2);
    } else if (ext2 instanceof FacetProvider) {
      result[prec2].push(ext2);
      if (ext2.facet.extensions)
        inner(ext2.facet.extensions, Prec_.default);
    } else {
      let content2 = ext2.extension;
      if (!content2)
        throw new Error(`Unrecognized extension value in extension set (${ext2}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
      inner(content2, prec2);
    }
  }
  inner(extension, Prec_.default);
  return result.reduce((a, b) => a.concat(b));
}
function ensureAddr(state, addr) {
  if (addr & 1)
    return 2;
  let idx = addr >> 1;
  let status = state.status[idx];
  if (status == 4)
    throw new Error("Cyclic dependency between fields and/or facets");
  if (status & 2)
    return status;
  state.status[idx] = 4;
  let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);
  return state.status[idx] = 2 | changed;
}
function getAddr(state, addr) {
  return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
}
var languageData = /* @__PURE__ */ Facet.define();
var allowMultipleSelections = /* @__PURE__ */ Facet.define({
  combine: (values) => values.some((v) => v),
  static: true
});
var lineSeparator = /* @__PURE__ */ Facet.define({
  combine: (values) => values.length ? values[0] : void 0,
  static: true
});
var changeFilter = /* @__PURE__ */ Facet.define();
var transactionFilter = /* @__PURE__ */ Facet.define();
var transactionExtender = /* @__PURE__ */ Facet.define();
var readOnly = /* @__PURE__ */ Facet.define({
  combine: (values) => values.length ? values[0] : false
});
var Annotation = class {
  constructor(type, value) {
    this.type = type;
    this.value = value;
  }
  static define() {
    return new AnnotationType();
  }
};
var AnnotationType = class {
  of(value) {
    return new Annotation(this, value);
  }
};
var StateEffectType = class {
  constructor(map2) {
    this.map = map2;
  }
  of(value) {
    return new StateEffect(this, value);
  }
};
var StateEffect = class {
  constructor(type, value) {
    this.type = type;
    this.value = value;
  }
  map(mapping) {
    let mapped = this.type.map(this.value, mapping);
    return mapped === void 0 ? void 0 : mapped == this.value ? this : new StateEffect(this.type, mapped);
  }
  is(type) {
    return this.type == type;
  }
  static define(spec = {}) {
    return new StateEffectType(spec.map || ((v) => v));
  }
  static mapEffects(effects, mapping) {
    if (!effects.length)
      return effects;
    let result = [];
    for (let effect of effects) {
      let mapped = effect.map(mapping);
      if (mapped)
        result.push(mapped);
    }
    return result;
  }
};
StateEffect.reconfigure = /* @__PURE__ */ StateEffect.define();
StateEffect.appendConfig = /* @__PURE__ */ StateEffect.define();
var Transaction2 = class {
  constructor(startState, changes, selection2, effects, annotations, scrollIntoView3) {
    this.startState = startState;
    this.changes = changes;
    this.selection = selection2;
    this.effects = effects;
    this.annotations = annotations;
    this.scrollIntoView = scrollIntoView3;
    this._doc = null;
    this._state = null;
    if (selection2)
      checkSelection(selection2, changes.newLength);
    if (!annotations.some((a) => a.type == Transaction2.time))
      this.annotations = annotations.concat(Transaction2.time.of(Date.now()));
  }
  static create(startState, changes, selection2, effects, annotations, scrollIntoView3) {
    return new Transaction2(startState, changes, selection2, effects, annotations, scrollIntoView3);
  }
  get newDoc() {
    return this._doc || (this._doc = this.changes.apply(this.startState.doc));
  }
  get newSelection() {
    return this.selection || this.startState.selection.map(this.changes);
  }
  get state() {
    if (!this._state)
      this.startState.applyTransaction(this);
    return this._state;
  }
  annotation(type) {
    for (let ann of this.annotations)
      if (ann.type == type)
        return ann.value;
    return void 0;
  }
  get docChanged() {
    return !this.changes.empty;
  }
  get reconfigured() {
    return this.startState.config != this.state.config;
  }
  isUserEvent(event) {
    let e3 = this.annotation(Transaction2.userEvent);
    return !!(e3 && (e3 == event || e3.length > event.length && e3.slice(0, event.length) == event && e3[event.length] == "."));
  }
};
Transaction2.time = /* @__PURE__ */ Annotation.define();
Transaction2.userEvent = /* @__PURE__ */ Annotation.define();
Transaction2.addToHistory = /* @__PURE__ */ Annotation.define();
Transaction2.remote = /* @__PURE__ */ Annotation.define();
function joinRanges(a, b) {
  let result = [];
  for (let iA = 0, iB = 0; ; ) {
    let from, to;
    if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {
      from = a[iA++];
      to = a[iA++];
    } else if (iB < b.length) {
      from = b[iB++];
      to = b[iB++];
    } else
      return result;
    if (!result.length || result[result.length - 1] < from)
      result.push(from, to);
    else if (result[result.length - 1] < to)
      result[result.length - 1] = to;
  }
}
function mergeTransaction(a, b, sequential) {
  var _a2;
  let mapForA, mapForB, changes;
  if (sequential) {
    mapForA = b.changes;
    mapForB = ChangeSet.empty(b.changes.length);
    changes = a.changes.compose(b.changes);
  } else {
    mapForA = b.changes.map(a.changes);
    mapForB = a.changes.mapDesc(b.changes, true);
    changes = a.changes.compose(mapForA);
  }
  return {
    changes,
    selection: b.selection ? b.selection.map(mapForB) : (_a2 = a.selection) === null || _a2 === void 0 ? void 0 : _a2.map(mapForA),
    effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)),
    annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,
    scrollIntoView: a.scrollIntoView || b.scrollIntoView
  };
}
function resolveTransactionInner(state, spec, docSize) {
  let sel = spec.selection, annotations = asArray(spec.annotations);
  if (spec.userEvent)
    annotations = annotations.concat(Transaction2.userEvent.of(spec.userEvent));
  return {
    changes: spec.changes instanceof ChangeSet ? spec.changes : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)),
    selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),
    effects: asArray(spec.effects),
    annotations,
    scrollIntoView: !!spec.scrollIntoView
  };
}
function resolveTransaction(state, specs, filter2) {
  let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);
  if (specs.length && specs[0].filter === false)
    filter2 = false;
  for (let i = 1; i < specs.length; i++) {
    if (specs[i].filter === false)
      filter2 = false;
    let seq = !!specs[i].sequential;
    s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq);
  }
  let tr = Transaction2.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);
  return extendTransaction(filter2 ? filterTransaction(tr) : tr);
}
function filterTransaction(tr) {
  let state = tr.startState;
  let result = true;
  for (let filter2 of state.facet(changeFilter)) {
    let value = filter2(tr);
    if (value === false) {
      result = false;
      break;
    }
    if (Array.isArray(value))
      result = result === true ? value : joinRanges(result, value);
  }
  if (result !== true) {
    let changes, back;
    if (result === false) {
      back = tr.changes.invertedDesc;
      changes = ChangeSet.empty(state.doc.length);
    } else {
      let filtered = tr.changes.filter(result);
      changes = filtered.changes;
      back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;
    }
    tr = Transaction2.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);
  }
  let filters = state.facet(transactionFilter);
  for (let i = filters.length - 1; i >= 0; i--) {
    let filtered = filters[i](tr);
    if (filtered instanceof Transaction2)
      tr = filtered;
    else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction2)
      tr = filtered[0];
    else
      tr = resolveTransaction(state, asArray(filtered), false);
  }
  return tr;
}
function extendTransaction(tr) {
  let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr;
  for (let i = extenders.length - 1; i >= 0; i--) {
    let extension = extenders[i](tr);
    if (extension && Object.keys(extension).length)
      spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true);
  }
  return spec == tr ? tr : Transaction2.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);
}
var none = [];
function asArray(value) {
  return value == null ? none : Array.isArray(value) ? value : [value];
}
var CharCategory = /* @__PURE__ */ function(CharCategory2) {
  CharCategory2[CharCategory2["Word"] = 0] = "Word";
  CharCategory2[CharCategory2["Space"] = 1] = "Space";
  CharCategory2[CharCategory2["Other"] = 2] = "Other";
  return CharCategory2;
}(CharCategory || (CharCategory = {}));
var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
var wordChar;
try {
  wordChar = /* @__PURE__ */ new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
} catch (_2) {
}
function hasWordChar(str) {
  if (wordChar)
    return wordChar.test(str);
  for (let i = 0; i < str.length; i++) {
    let ch = str[i];
    if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))
      return true;
  }
  return false;
}
function makeCategorizer(wordChars) {
  return (char) => {
    if (!/\S/.test(char))
      return CharCategory.Space;
    if (hasWordChar(char))
      return CharCategory.Word;
    for (let i = 0; i < wordChars.length; i++)
      if (char.indexOf(wordChars[i]) > -1)
        return CharCategory.Word;
    return CharCategory.Other;
  };
}
var EditorState = class {
  constructor(config2, doc2, selection2, values, computeSlot, tr) {
    this.config = config2;
    this.doc = doc2;
    this.selection = selection2;
    this.values = values;
    this.status = config2.statusTemplate.slice();
    this.computeSlot = computeSlot;
    if (tr)
      tr._state = this;
    for (let i = 0; i < this.config.dynamicSlots.length; i++)
      ensureAddr(this, i << 1);
    this.computeSlot = null;
  }
  field(field, require2 = true) {
    let addr = this.config.address[field.id];
    if (addr == null) {
      if (require2)
        throw new RangeError("Field is not present in this state");
      return void 0;
    }
    ensureAddr(this, addr);
    return getAddr(this, addr);
  }
  update(...specs) {
    return resolveTransaction(this, specs, true);
  }
  applyTransaction(tr) {
    let conf = this.config, { base: base2, compartments } = conf;
    for (let effect of tr.effects) {
      if (effect.is(Compartment.reconfigure)) {
        if (conf) {
          compartments = /* @__PURE__ */ new Map();
          conf.compartments.forEach((val, key) => compartments.set(key, val));
          conf = null;
        }
        compartments.set(effect.value.compartment, effect.value.extension);
      } else if (effect.is(StateEffect.reconfigure)) {
        conf = null;
        base2 = effect.value;
      } else if (effect.is(StateEffect.appendConfig)) {
        conf = null;
        base2 = asArray(base2).concat(effect.value);
      }
    }
    let startValues;
    if (!conf) {
      conf = Configuration.resolve(base2, compartments, this);
      let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null);
      startValues = intermediateState.values;
    } else {
      startValues = tr.startState.values.slice();
    }
    new EditorState(conf, tr.newDoc, tr.newSelection, startValues, (state, slot) => slot.update(state, tr), tr);
  }
  replaceSelection(text2) {
    if (typeof text2 == "string")
      text2 = this.toText(text2);
    return this.changeByRange((range2) => ({
      changes: { from: range2.from, to: range2.to, insert: text2 },
      range: EditorSelection.cursor(range2.from + text2.length)
    }));
  }
  changeByRange(f) {
    let sel = this.selection;
    let result1 = f(sel.ranges[0]);
    let changes = this.changes(result1.changes), ranges = [result1.range];
    let effects = asArray(result1.effects);
    for (let i = 1; i < sel.ranges.length; i++) {
      let result = f(sel.ranges[i]);
      let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);
      for (let j = 0; j < i; j++)
        ranges[j] = ranges[j].map(newMapped);
      let mapBy = changes.mapDesc(newChanges, true);
      ranges.push(result.range.map(mapBy));
      changes = changes.compose(newMapped);
      effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result.effects), mapBy));
    }
    return {
      changes,
      selection: EditorSelection.create(ranges, sel.mainIndex),
      effects
    };
  }
  changes(spec = []) {
    if (spec instanceof ChangeSet)
      return spec;
    return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator));
  }
  toText(string5) {
    return Text.of(string5.split(this.facet(EditorState.lineSeparator) || DefaultSplit));
  }
  sliceDoc(from = 0, to = this.doc.length) {
    return this.doc.sliceString(from, to, this.lineBreak);
  }
  facet(facet) {
    let addr = this.config.address[facet.id];
    if (addr == null)
      return facet.default;
    ensureAddr(this, addr);
    return getAddr(this, addr);
  }
  toJSON(fields) {
    let result = {
      doc: this.sliceDoc(),
      selection: this.selection.toJSON()
    };
    if (fields)
      for (let prop in fields) {
        let value = fields[prop];
        if (value instanceof StateField && this.config.address[value.id] != null)
          result[prop] = value.spec.toJSON(this.field(fields[prop]), this);
      }
    return result;
  }
  static fromJSON(json, config2 = {}, fields) {
    if (!json || typeof json.doc != "string")
      throw new RangeError("Invalid JSON representation for EditorState");
    let fieldInit = [];
    if (fields)
      for (let prop in fields) {
        if (Object.prototype.hasOwnProperty.call(json, prop)) {
          let field = fields[prop], value = json[prop];
          fieldInit.push(field.init((state) => field.spec.fromJSON(value, state)));
        }
      }
    return EditorState.create({
      doc: json.doc,
      selection: EditorSelection.fromJSON(json.selection),
      extensions: config2.extensions ? fieldInit.concat([config2.extensions]) : fieldInit
    });
  }
  static create(config2 = {}) {
    let configuration = Configuration.resolve(config2.extensions || [], /* @__PURE__ */ new Map());
    let doc2 = config2.doc instanceof Text ? config2.doc : Text.of((config2.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit));
    let selection2 = !config2.selection ? EditorSelection.single(0) : config2.selection instanceof EditorSelection ? config2.selection : EditorSelection.single(config2.selection.anchor, config2.selection.head);
    checkSelection(selection2, doc2.length);
    if (!configuration.staticFacet(allowMultipleSelections))
      selection2 = selection2.asSingle();
    return new EditorState(configuration, doc2, selection2, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);
  }
  get tabSize() {
    return this.facet(EditorState.tabSize);
  }
  get lineBreak() {
    return this.facet(EditorState.lineSeparator) || "\n";
  }
  get readOnly() {
    return this.facet(readOnly);
  }
  phrase(phrase2, ...insert3) {
    for (let map2 of this.facet(EditorState.phrases))
      if (Object.prototype.hasOwnProperty.call(map2, phrase2)) {
        phrase2 = map2[phrase2];
        break;
      }
    if (insert3.length)
      phrase2 = phrase2.replace(/\$(\$|\d*)/g, (m, i) => {
        if (i == "$")
          return "$";
        let n = +(i || 1);
        return !n || n > insert3.length ? m : insert3[n - 1];
      });
    return phrase2;
  }
  languageDataAt(name2, pos, side = -1) {
    let values = [];
    for (let provider of this.facet(languageData)) {
      for (let result of provider(this, pos, side)) {
        if (Object.prototype.hasOwnProperty.call(result, name2))
          values.push(result[name2]);
      }
    }
    return values;
  }
  charCategorizer(at) {
    return makeCategorizer(this.languageDataAt("wordChars", at).join(""));
  }
  wordAt(pos) {
    let { text: text2, from, length } = this.doc.lineAt(pos);
    let cat = this.charCategorizer(pos);
    let start = pos - from, end = pos - from;
    while (start > 0) {
      let prev = findClusterBreak(text2, start, false);
      if (cat(text2.slice(prev, start)) != CharCategory.Word)
        break;
      start = prev;
    }
    while (end < length) {
      let next = findClusterBreak(text2, end);
      if (cat(text2.slice(end, next)) != CharCategory.Word)
        break;
      end = next;
    }
    return start == end ? null : EditorSelection.range(start + from, end + from);
  }
};
EditorState.allowMultipleSelections = allowMultipleSelections;
EditorState.tabSize = /* @__PURE__ */ Facet.define({
  combine: (values) => values.length ? values[0] : 4
});
EditorState.lineSeparator = lineSeparator;
EditorState.readOnly = readOnly;
EditorState.phrases = /* @__PURE__ */ Facet.define({
  compare(a, b) {
    let kA = Object.keys(a), kB = Object.keys(b);
    return kA.length == kB.length && kA.every((k) => a[k] == b[k]);
  }
});
EditorState.languageData = languageData;
EditorState.changeFilter = changeFilter;
EditorState.transactionFilter = transactionFilter;
EditorState.transactionExtender = transactionExtender;
Compartment.reconfigure = /* @__PURE__ */ StateEffect.define();
function combineConfig(configs, defaults3, combine = {}) {
  let result = {};
  for (let config2 of configs)
    for (let key of Object.keys(config2)) {
      let value = config2[key], current = result[key];
      if (current === void 0)
        result[key] = value;
      else if (current === value || value === void 0)
        ;
      else if (Object.hasOwnProperty.call(combine, key))
        result[key] = combine[key](current, value);
      else
        throw new Error("Config merge conflict for field " + key);
    }
  for (let key in defaults3)
    if (result[key] === void 0)
      result[key] = defaults3[key];
  return result;
}
var RangeValue = class {
  eq(other) {
    return this == other;
  }
  range(from, to = from) {
    return Range.create(from, to, this);
  }
};
RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
RangeValue.prototype.point = false;
RangeValue.prototype.mapMode = MapMode.TrackDel;
var Range = class {
  constructor(from, to, value) {
    this.from = from;
    this.to = to;
    this.value = value;
  }
  static create(from, to, value) {
    return new Range(from, to, value);
  }
};
function cmpRange(a, b) {
  return a.from - b.from || a.value.startSide - b.value.startSide;
}
var Chunk = class {
  constructor(from, to, value, maxPoint) {
    this.from = from;
    this.to = to;
    this.value = value;
    this.maxPoint = maxPoint;
  }
  get length() {
    return this.to[this.to.length - 1];
  }
  findIndex(pos, side, end, startAt = 0) {
    let arr = end ? this.to : this.from;
    for (let lo = startAt, hi = arr.length; ; ) {
      if (lo == hi)
        return lo;
      let mid = lo + hi >> 1;
      let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;
      if (mid == lo)
        return diff >= 0 ? lo : hi;
      if (diff >= 0)
        hi = mid;
      else
        lo = mid + 1;
    }
  }
  between(offset, from, to, f) {
    for (let i = this.findIndex(from, -1e9, true), e3 = this.findIndex(to, 1e9, false, i); i < e3; i++)
      if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false)
        return false;
  }
  map(offset, changes) {
    let value = [], from = [], to = [], newPos = -1, maxPoint = -1;
    for (let i = 0; i < this.value.length; i++) {
      let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo;
      if (curFrom == curTo) {
        let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);
        if (mapped == null)
          continue;
        newFrom = newTo = mapped;
        if (val.startSide != val.endSide) {
          newTo = changes.mapPos(curFrom, val.endSide);
          if (newTo < newFrom)
            continue;
        }
      } else {
        newFrom = changes.mapPos(curFrom, val.startSide);
        newTo = changes.mapPos(curTo, val.endSide);
        if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0)
          continue;
      }
      if ((newTo - newFrom || val.endSide - val.startSide) < 0)
        continue;
      if (newPos < 0)
        newPos = newFrom;
      if (val.point)
        maxPoint = Math.max(maxPoint, newTo - newFrom);
      value.push(val);
      from.push(newFrom - newPos);
      to.push(newTo - newPos);
    }
    return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos };
  }
};
var RangeSet = class {
  constructor(chunkPos, chunk, nextLayer, maxPoint) {
    this.chunkPos = chunkPos;
    this.chunk = chunk;
    this.nextLayer = nextLayer;
    this.maxPoint = maxPoint;
  }
  static create(chunkPos, chunk, nextLayer, maxPoint) {
    return new RangeSet(chunkPos, chunk, nextLayer, maxPoint);
  }
  get length() {
    let last = this.chunk.length - 1;
    return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);
  }
  get size() {
    if (this.isEmpty)
      return 0;
    let size = this.nextLayer.size;
    for (let chunk of this.chunk)
      size += chunk.value.length;
    return size;
  }
  chunkEnd(index2) {
    return this.chunkPos[index2] + this.chunk[index2].length;
  }
  update(updateSpec) {
    let { add: add3 = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec;
    let filter2 = updateSpec.filter;
    if (add3.length == 0 && !filter2)
      return this;
    if (sort)
      add3 = add3.slice().sort(cmpRange);
    if (this.isEmpty)
      return add3.length ? RangeSet.of(add3) : this;
    let cur2 = new LayerCursor(this, null, -1).goto(0), i = 0, spill = [];
    let builder = new RangeSetBuilder();
    while (cur2.value || i < add3.length) {
      if (i < add3.length && (cur2.from - add3[i].from || cur2.startSide - add3[i].value.startSide) >= 0) {
        let range2 = add3[i++];
        if (!builder.addInner(range2.from, range2.to, range2.value))
          spill.push(range2);
      } else if (cur2.rangeIndex == 1 && cur2.chunkIndex < this.chunk.length && (i == add3.length || this.chunkEnd(cur2.chunkIndex) < add3[i].from) && (!filter2 || filterFrom > this.chunkEnd(cur2.chunkIndex) || filterTo < this.chunkPos[cur2.chunkIndex]) && builder.addChunk(this.chunkPos[cur2.chunkIndex], this.chunk[cur2.chunkIndex])) {
        cur2.nextChunk();
      } else {
        if (!filter2 || filterFrom > cur2.to || filterTo < cur2.from || filter2(cur2.from, cur2.to, cur2.value)) {
          if (!builder.addInner(cur2.from, cur2.to, cur2.value))
            spill.push(Range.create(cur2.from, cur2.to, cur2.value));
        }
        cur2.next();
      }
    }
    return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty : this.nextLayer.update({ add: spill, filter: filter2, filterFrom, filterTo }));
  }
  map(changes) {
    if (changes.empty || this.isEmpty)
      return this;
    let chunks = [], chunkPos = [], maxPoint = -1;
    for (let i = 0; i < this.chunk.length; i++) {
      let start = this.chunkPos[i], chunk = this.chunk[i];
      let touch = changes.touchesRange(start, start + chunk.length);
      if (touch === false) {
        maxPoint = Math.max(maxPoint, chunk.maxPoint);
        chunks.push(chunk);
        chunkPos.push(changes.mapPos(start));
      } else if (touch === true) {
        let { mapped, pos } = chunk.map(start, changes);
        if (mapped) {
          maxPoint = Math.max(maxPoint, mapped.maxPoint);
          chunks.push(mapped);
          chunkPos.push(pos);
        }
      }
    }
    let next = this.nextLayer.map(changes);
    return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint);
  }
  between(from, to, f) {
    if (this.isEmpty)
      return;
    for (let i = 0; i < this.chunk.length; i++) {
      let start = this.chunkPos[i], chunk = this.chunk[i];
      if (to >= start && from <= start + chunk.length && chunk.between(start, from - start, to - start, f) === false)
        return;
    }
    this.nextLayer.between(from, to, f);
  }
  iter(from = 0) {
    return HeapCursor.from([this]).goto(from);
  }
  get isEmpty() {
    return this.nextLayer == this;
  }
  static iter(sets, from = 0) {
    return HeapCursor.from(sets).goto(from);
  }
  static compare(oldSets, newSets, textDiff, comparator, minPointSize = -1) {
    let a = oldSets.filter((set) => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
    let b = newSets.filter((set) => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
    let sharedChunks = findSharedChunks(a, b, textDiff);
    let sideA = new SpanCursor(a, sharedChunks, minPointSize);
    let sideB = new SpanCursor(b, sharedChunks, minPointSize);
    textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));
    if (textDiff.empty && textDiff.length == 0)
      compare(sideA, 0, sideB, 0, 0, comparator);
  }
  static eq(oldSets, newSets, from = 0, to) {
    if (to == null)
      to = 1e9;
    let a = oldSets.filter((set) => !set.isEmpty && newSets.indexOf(set) < 0);
    let b = newSets.filter((set) => !set.isEmpty && oldSets.indexOf(set) < 0);
    if (a.length != b.length)
      return false;
    if (!a.length)
      return true;
    let sharedChunks = findSharedChunks(a, b);
    let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from);
    for (; ; ) {
      if (sideA.to != sideB.to || !sameValues(sideA.active, sideB.active) || sideA.point && (!sideB.point || !sideA.point.eq(sideB.point)))
        return false;
      if (sideA.to > to)
        return true;
      sideA.next();
      sideB.next();
    }
  }
  static spans(sets, from, to, iterator, minPointSize = -1) {
    let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from;
    let open = cursor.openStart;
    for (; ; ) {
      let curTo = Math.min(cursor.to, to);
      if (cursor.point) {
        iterator.point(pos, curTo, cursor.point, cursor.activeForPoint(cursor.to), open, cursor.pointRank);
        open = cursor.openEnd(curTo) + (cursor.to > curTo ? 1 : 0);
      } else if (curTo > pos) {
        iterator.span(pos, curTo, cursor.active, open);
        open = cursor.openEnd(curTo);
      }
      if (cursor.to > to)
        break;
      pos = cursor.to;
      cursor.next();
    }
    return open;
  }
  static of(ranges, sort = false) {
    let build = new RangeSetBuilder();
    for (let range2 of ranges instanceof Range ? [ranges] : sort ? lazySort(ranges) : ranges)
      build.add(range2.from, range2.to, range2.value);
    return build.finish();
  }
};
RangeSet.empty = /* @__PURE__ */ new RangeSet([], [], null, -1);
function lazySort(ranges) {
  if (ranges.length > 1)
    for (let prev = ranges[0], i = 1; i < ranges.length; i++) {
      let cur2 = ranges[i];
      if (cmpRange(prev, cur2) > 0)
        return ranges.slice().sort(cmpRange);
      prev = cur2;
    }
  return ranges;
}
RangeSet.empty.nextLayer = RangeSet.empty;
var RangeSetBuilder = class {
  constructor() {
    this.chunks = [];
    this.chunkPos = [];
    this.chunkStart = -1;
    this.last = null;
    this.lastFrom = -1e9;
    this.lastTo = -1e9;
    this.from = [];
    this.to = [];
    this.value = [];
    this.maxPoint = -1;
    this.setMaxPoint = -1;
    this.nextLayer = null;
  }
  finishChunk(newArrays) {
    this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint));
    this.chunkPos.push(this.chunkStart);
    this.chunkStart = -1;
    this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);
    this.maxPoint = -1;
    if (newArrays) {
      this.from = [];
      this.to = [];
      this.value = [];
    }
  }
  add(from, to, value) {
    if (!this.addInner(from, to, value))
      (this.nextLayer || (this.nextLayer = new RangeSetBuilder())).add(from, to, value);
  }
  addInner(from, to, value) {
    let diff = from - this.lastTo || value.startSide - this.last.endSide;
    if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0)
      throw new Error("Ranges must be added sorted by `from` position and `startSide`");
    if (diff < 0)
      return false;
    if (this.from.length == 250)
      this.finishChunk(true);
    if (this.chunkStart < 0)
      this.chunkStart = from;
    this.from.push(from - this.chunkStart);
    this.to.push(to - this.chunkStart);
    this.last = value;
    this.lastFrom = from;
    this.lastTo = to;
    this.value.push(value);
    if (value.point)
      this.maxPoint = Math.max(this.maxPoint, to - from);
    return true;
  }
  addChunk(from, chunk) {
    if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0)
      return false;
    if (this.from.length)
      this.finishChunk(true);
    this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);
    this.chunks.push(chunk);
    this.chunkPos.push(from);
    let last = chunk.value.length - 1;
    this.last = chunk.value[last];
    this.lastFrom = chunk.from[last] + from;
    this.lastTo = chunk.to[last] + from;
    return true;
  }
  finish() {
    return this.finishInner(RangeSet.empty);
  }
  finishInner(next) {
    if (this.from.length)
      this.finishChunk(false);
    if (this.chunks.length == 0)
      return next;
    let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);
    this.from = null;
    return result;
  }
};
function findSharedChunks(a, b, textDiff) {
  let inA = /* @__PURE__ */ new Map();
  for (let set of a)
    for (let i = 0; i < set.chunk.length; i++)
      if (set.chunk[i].maxPoint <= 0)
        inA.set(set.chunk[i], set.chunkPos[i]);
  let shared = /* @__PURE__ */ new Set();
  for (let set of b)
    for (let i = 0; i < set.chunk.length; i++) {
      let known = inA.get(set.chunk[i]);
      if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] && !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length)))
        shared.add(set.chunk[i]);
    }
  return shared;
}
var LayerCursor = class {
  constructor(layer, skip, minPoint, rank = 0) {
    this.layer = layer;
    this.skip = skip;
    this.minPoint = minPoint;
    this.rank = rank;
  }
  get startSide() {
    return this.value ? this.value.startSide : 0;
  }
  get endSide() {
    return this.value ? this.value.endSide : 0;
  }
  goto(pos, side = -1e9) {
    this.chunkIndex = this.rangeIndex = 0;
    this.gotoInner(pos, side, false);
    return this;
  }
  gotoInner(pos, side, forward) {
    while (this.chunkIndex < this.layer.chunk.length) {
      let next = this.layer.chunk[this.chunkIndex];
      if (!(this.skip && this.skip.has(next) || this.layer.chunkEnd(this.chunkIndex) < pos || next.maxPoint < this.minPoint))
        break;
      this.chunkIndex++;
      forward = false;
    }
    if (this.chunkIndex < this.layer.chunk.length) {
      let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true);
      if (!forward || this.rangeIndex < rangeIndex)
        this.setRangeIndex(rangeIndex);
    }
    this.next();
  }
  forward(pos, side) {
    if ((this.to - pos || this.endSide - side) < 0)
      this.gotoInner(pos, side, true);
  }
  next() {
    for (; ; ) {
      if (this.chunkIndex == this.layer.chunk.length) {
        this.from = this.to = 1e9;
        this.value = null;
        break;
      } else {
        let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex];
        let from = chunkPos + chunk.from[this.rangeIndex];
        this.from = from;
        this.to = chunkPos + chunk.to[this.rangeIndex];
        this.value = chunk.value[this.rangeIndex];
        this.setRangeIndex(this.rangeIndex + 1);
        if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint)
          break;
      }
    }
  }
  setRangeIndex(index2) {
    if (index2 == this.layer.chunk[this.chunkIndex].value.length) {
      this.chunkIndex++;
      if (this.skip) {
        while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]))
          this.chunkIndex++;
      }
      this.rangeIndex = 0;
    } else {
      this.rangeIndex = index2;
    }
  }
  nextChunk() {
    this.chunkIndex++;
    this.rangeIndex = 0;
    this.next();
  }
  compare(other) {
    return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || this.to - other.to || this.endSide - other.endSide;
  }
};
var HeapCursor = class {
  constructor(heap) {
    this.heap = heap;
  }
  static from(sets, skip = null, minPoint = -1) {
    let heap = [];
    for (let i = 0; i < sets.length; i++) {
      for (let cur2 = sets[i]; !cur2.isEmpty; cur2 = cur2.nextLayer) {
        if (cur2.maxPoint >= minPoint)
          heap.push(new LayerCursor(cur2, skip, minPoint, i));
      }
    }
    return heap.length == 1 ? heap[0] : new HeapCursor(heap);
  }
  get startSide() {
    return this.value ? this.value.startSide : 0;
  }
  goto(pos, side = -1e9) {
    for (let cur2 of this.heap)
      cur2.goto(pos, side);
    for (let i = this.heap.length >> 1; i >= 0; i--)
      heapBubble(this.heap, i);
    this.next();
    return this;
  }
  forward(pos, side) {
    for (let cur2 of this.heap)
      cur2.forward(pos, side);
    for (let i = this.heap.length >> 1; i >= 0; i--)
      heapBubble(this.heap, i);
    if ((this.to - pos || this.value.endSide - side) < 0)
      this.next();
  }
  next() {
    if (this.heap.length == 0) {
      this.from = this.to = 1e9;
      this.value = null;
      this.rank = -1;
    } else {
      let top3 = this.heap[0];
      this.from = top3.from;
      this.to = top3.to;
      this.value = top3.value;
      this.rank = top3.rank;
      if (top3.value)
        top3.next();
      heapBubble(this.heap, 0);
    }
  }
};
function heapBubble(heap, index2) {
  for (let cur2 = heap[index2]; ; ) {
    let childIndex = (index2 << 1) + 1;
    if (childIndex >= heap.length)
      break;
    let child = heap[childIndex];
    if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) {
      child = heap[childIndex + 1];
      childIndex++;
    }
    if (cur2.compare(child) < 0)
      break;
    heap[childIndex] = cur2;
    heap[index2] = child;
    index2 = childIndex;
  }
}
var SpanCursor = class {
  constructor(sets, skip, minPoint) {
    this.minPoint = minPoint;
    this.active = [];
    this.activeTo = [];
    this.activeRank = [];
    this.minActive = -1;
    this.point = null;
    this.pointFrom = 0;
    this.pointRank = 0;
    this.to = -1e9;
    this.endSide = 0;
    this.openStart = -1;
    this.cursor = HeapCursor.from(sets, skip, minPoint);
  }
  goto(pos, side = -1e9) {
    this.cursor.goto(pos, side);
    this.active.length = this.activeTo.length = this.activeRank.length = 0;
    this.minActive = -1;
    this.to = pos;
    this.endSide = side;
    this.openStart = -1;
    this.next();
    return this;
  }
  forward(pos, side) {
    while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0)
      this.removeActive(this.minActive);
    this.cursor.forward(pos, side);
  }
  removeActive(index2) {
    remove(this.active, index2);
    remove(this.activeTo, index2);
    remove(this.activeRank, index2);
    this.minActive = findMinIndex(this.active, this.activeTo);
  }
  addActive(trackOpen) {
    let i = 0, { value, to, rank } = this.cursor;
    while (i < this.activeRank.length && this.activeRank[i] <= rank)
      i++;
    insert2(this.active, i, value);
    insert2(this.activeTo, i, to);
    insert2(this.activeRank, i, rank);
    if (trackOpen)
      insert2(trackOpen, i, this.cursor.from);
    this.minActive = findMinIndex(this.active, this.activeTo);
  }
  next() {
    let from = this.to, wasPoint = this.point;
    this.point = null;
    let trackOpen = this.openStart < 0 ? [] : null, trackExtra = 0;
    for (; ; ) {
      let a = this.minActive;
      if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {
        if (this.activeTo[a] > from) {
          this.to = this.activeTo[a];
          this.endSide = this.active[a].endSide;
          break;
        }
        this.removeActive(a);
        if (trackOpen)
          remove(trackOpen, a);
      } else if (!this.cursor.value) {
        this.to = this.endSide = 1e9;
        break;
      } else if (this.cursor.from > from) {
        this.to = this.cursor.from;
        this.endSide = this.cursor.startSide;
        break;
      } else {
        let nextVal = this.cursor.value;
        if (!nextVal.point) {
          this.addActive(trackOpen);
          if (this.cursor.from < from && this.cursor.to > from)
            trackExtra++;
          this.cursor.next();
        } else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) {
          this.cursor.next();
        } else {
          this.point = nextVal;
          this.pointFrom = this.cursor.from;
          this.pointRank = this.cursor.rank;
          this.to = this.cursor.to;
          this.endSide = nextVal.endSide;
          if (this.cursor.from < from)
            trackExtra = 1;
          this.cursor.next();
          this.forward(this.to, this.endSide);
          break;
        }
      }
    }
    if (trackOpen) {
      let openStart = 0;
      while (openStart < trackOpen.length && trackOpen[openStart] < from)
        openStart++;
      this.openStart = openStart + trackExtra;
    }
  }
  activeForPoint(to) {
    if (!this.active.length)
      return this.active;
    let active = [];
    for (let i = this.active.length - 1; i >= 0; i--) {
      if (this.activeRank[i] < this.pointRank)
        break;
      if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide)
        active.push(this.active[i]);
    }
    return active.reverse();
  }
  openEnd(to) {
    let open = 0;
    for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--)
      open++;
    return open;
  }
};
function compare(a, startA, b, startB, length, comparator) {
  a.goto(startA);
  b.goto(startB);
  let endB = startB + length;
  let pos = startB, dPos = startB - startA;
  for (; ; ) {
    let diff = a.to + dPos - b.to || a.endSide - b.endSide;
    let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB);
    if (a.point || b.point) {
      if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) && sameValues(a.activeForPoint(a.to + dPos), b.activeForPoint(b.to))))
        comparator.comparePoint(pos, clipEnd, a.point, b.point);
    } else {
      if (clipEnd > pos && !sameValues(a.active, b.active))
        comparator.compareRange(pos, clipEnd, a.active, b.active);
    }
    if (end > endB)
      break;
    pos = end;
    if (diff <= 0)
      a.next();
    if (diff >= 0)
      b.next();
  }
}
function sameValues(a, b) {
  if (a.length != b.length)
    return false;
  for (let i = 0; i < a.length; i++)
    if (a[i] != b[i] && !a[i].eq(b[i]))
      return false;
  return true;
}
function remove(array3, index2) {
  for (let i = index2, e3 = array3.length - 1; i < e3; i++)
    array3[i] = array3[i + 1];
  array3.pop();
}
function insert2(array3, index2, value) {
  for (let i = array3.length - 1; i >= index2; i--)
    array3[i + 1] = array3[i];
  array3[index2] = value;
}
function findMinIndex(value, array3) {
  let found = -1, foundPos = 1e9;
  for (let i = 0; i < array3.length; i++)
    if ((array3[i] - foundPos || value[i].endSide - value[found].endSide) < 0) {
      found = i;
      foundPos = array3[i];
    }
  return found;
}
function countColumn(string5, tabSize, to = string5.length) {
  let n = 0;
  for (let i = 0; i < to; ) {
    if (string5.charCodeAt(i) == 9) {
      n += tabSize - n % tabSize;
      i++;
    } else {
      n++;
      i = findClusterBreak(string5, i);
    }
  }
  return n;
}
function findColumn(string5, col, tabSize, strict) {
  for (let i = 0, n = 0; ; ) {
    if (n >= col)
      return i;
    if (i == string5.length)
      break;
    n += string5.charCodeAt(i) == 9 ? tabSize - n % tabSize : 1;
    i = findClusterBreak(string5, i);
  }
  return strict === true ? -1 : string5.length;
}

// node_modules/style-mod/src/style-mod.js
var C = "\u037C";
var COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C);
var SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet");
var top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {};
var StyleModule = class {
  constructor(spec, options2) {
    this.rules = [];
    let { finish } = options2 || {};
    function splitSelector(selector) {
      return /^@/.test(selector) ? [selector] : selector.split(/,\s*/);
    }
    function render(selectors, spec2, target, isKeyframes) {
      let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes";
      if (isAt && spec2 == null)
        return target.push(selectors[0] + ";");
      for (let prop in spec2) {
        let value = spec2[prop];
        if (/&/.test(prop)) {
          render(
            prop.split(/,\s*/).map((part) => selectors.map((sel) => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)),
            value,
            target
          );
        } else if (value && typeof value == "object") {
          if (!isAt)
            throw new RangeError("The value of a property (" + prop + ") should be a primitive value.");
          render(splitSelector(prop), value, local, keyframes);
        } else if (value != null) {
          local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, (l) => "-" + l.toLowerCase()) + ": " + value + ";");
        }
      }
      if (local.length || keyframes) {
        target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") + " {" + local.join(" ") + "}");
      }
    }
    for (let prop in spec)
      render(splitSelector(prop), spec[prop], this.rules);
  }
  getRules() {
    return this.rules.join("\n");
  }
  static newName() {
    let id = top[COUNT] || 1;
    top[COUNT] = id + 1;
    return C + id.toString(36);
  }
  static mount(root2, modules) {
    (root2[SET] || new StyleSet(root2)).mount(Array.isArray(modules) ? modules : [modules]);
  }
};
var adoptedSet = null;
var StyleSet = class {
  constructor(root2) {
    if (!root2.head && root2.adoptedStyleSheets && typeof CSSStyleSheet != "undefined") {
      if (adoptedSet) {
        root2.adoptedStyleSheets = [adoptedSet.sheet].concat(root2.adoptedStyleSheets);
        return root2[SET] = adoptedSet;
      }
      this.sheet = new CSSStyleSheet();
      root2.adoptedStyleSheets = [this.sheet].concat(root2.adoptedStyleSheets);
      adoptedSet = this;
    } else {
      this.styleTag = (root2.ownerDocument || root2).createElement("style");
      let target = root2.head || root2;
      target.insertBefore(this.styleTag, target.firstChild);
    }
    this.modules = [];
    root2[SET] = this;
  }
  mount(modules) {
    let sheet = this.sheet;
    let pos = 0, j = 0;
    for (let i = 0; i < modules.length; i++) {
      let mod = modules[i], index2 = this.modules.indexOf(mod);
      if (index2 < j && index2 > -1) {
        this.modules.splice(index2, 1);
        j--;
        index2 = -1;
      }
      if (index2 == -1) {
        this.modules.splice(j++, 0, mod);
        if (sheet)
          for (let k = 0; k < mod.rules.length; k++)
            sheet.insertRule(mod.rules[k], pos++);
      } else {
        while (j < index2)
          pos += this.modules[j++].rules.length;
        pos += mod.rules.length;
        j++;
      }
    }
    if (!sheet) {
      let text2 = "";
      for (let i = 0; i < this.modules.length; i++)
        text2 += this.modules[i].getRules() + "\n";
      this.styleTag.textContent = text2;
    }
  }
};

// node_modules/w3c-keyname/index.es.js
var base = {
  8: "Backspace",
  9: "Tab",
  10: "Enter",
  12: "NumLock",
  13: "Enter",
  16: "Shift",
  17: "Control",
  18: "Alt",
  20: "CapsLock",
  27: "Escape",
  32: " ",
  33: "PageUp",
  34: "PageDown",
  35: "End",
  36: "Home",
  37: "ArrowLeft",
  38: "ArrowUp",
  39: "ArrowRight",
  40: "ArrowDown",
  44: "PrintScreen",
  45: "Insert",
  46: "Delete",
  59: ";",
  61: "=",
  91: "Meta",
  92: "Meta",
  106: "*",
  107: "+",
  108: ",",
  109: "-",
  110: ".",
  111: "/",
  144: "NumLock",
  145: "ScrollLock",
  160: "Shift",
  161: "Shift",
  162: "Control",
  163: "Control",
  164: "Alt",
  165: "Alt",
  173: "-",
  186: ";",
  187: "=",
  188: ",",
  189: "-",
  190: ".",
  191: "/",
  192: "`",
  219: "[",
  220: "\\",
  221: "]",
  222: "'"
};
var shift = {
  48: ")",
  49: "!",
  50: "@",
  51: "#",
  52: "$",
  53: "%",
  54: "^",
  55: "&",
  56: "*",
  57: "(",
  59: ":",
  61: "+",
  173: "_",
  186: ":",
  187: "+",
  188: "<",
  189: "_",
  190: ">",
  191: "?",
  192: "~",
  219: "{",
  220: "|",
  221: "}",
  222: '"'
};
var chrome = typeof navigator != "undefined" && /Chrome\/(\d+)/.exec(navigator.userAgent);
var gecko = typeof navigator != "undefined" && /Gecko\/\d+/.test(navigator.userAgent);
var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
var ie = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
var brokenModifierNames = mac || chrome && +chrome[1] < 57;
for (i = 0; i < 10; i++)
  base[48 + i] = base[96 + i] = String(i);
var i;
for (i = 1; i <= 24; i++)
  base[i + 111] = "F" + i;
var i;
for (i = 65; i <= 90; i++) {
  base[i] = String.fromCharCode(i + 32);
  shift[i] = String.fromCharCode(i);
}
var i;
for (code in base)
  if (!shift.hasOwnProperty(code))
    shift[code] = base[code];
var code;
function keyName(event) {
  var ignoreKey = brokenModifierNames && (event.ctrlKey || event.altKey || event.metaKey) || ie && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified";
  var name2 = !ignoreKey && event.key || (event.shiftKey ? shift : base)[event.keyCode] || event.key || "Unidentified";
  if (name2 == "Esc")
    name2 = "Escape";
  if (name2 == "Del")
    name2 = "Delete";
  if (name2 == "Left")
    name2 = "ArrowLeft";
  if (name2 == "Up")
    name2 = "ArrowUp";
  if (name2 == "Right")
    name2 = "ArrowRight";
  if (name2 == "Down")
    name2 = "ArrowDown";
  return name2;
}

// node_modules/@codemirror/view/dist/index.js
function getSelection(root2) {
  let target;
  if (root2.nodeType == 11) {
    target = root2.getSelection ? root2 : root2.ownerDocument;
  } else {
    target = root2;
  }
  return target.getSelection();
}
function contains(dom, node) {
  return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false;
}
function deepActiveElement(doc2) {
  let elt = doc2.activeElement;
  while (elt && elt.shadowRoot)
    elt = elt.shadowRoot.activeElement;
  return elt;
}
function hasSelection(dom, selection2) {
  if (!selection2.anchorNode)
    return false;
  try {
    return contains(dom, selection2.anchorNode);
  } catch (_2) {
    return false;
  }
}
function clientRectsFor(dom) {
  if (dom.nodeType == 3)
    return textRange(dom, 0, dom.nodeValue.length).getClientRects();
  else if (dom.nodeType == 1)
    return dom.getClientRects();
  else
    return [];
}
function isEquivalentPosition(node, off, targetNode, targetOff) {
  return targetNode ? scanFor(node, off, targetNode, targetOff, -1) || scanFor(node, off, targetNode, targetOff, 1) : false;
}
function domIndex(node) {
  for (var index2 = 0; ; index2++) {
    node = node.previousSibling;
    if (!node)
      return index2;
  }
}
function scanFor(node, off, targetNode, targetOff, dir) {
  for (; ; ) {
    if (node == targetNode && off == targetOff)
      return true;
    if (off == (dir < 0 ? 0 : maxOffset(node))) {
      if (node.nodeName == "DIV")
        return false;
      let parent2 = node.parentNode;
      if (!parent2 || parent2.nodeType != 1)
        return false;
      off = domIndex(node) + (dir < 0 ? 0 : 1);
      node = parent2;
    } else if (node.nodeType == 1) {
      node = node.childNodes[off + (dir < 0 ? -1 : 0)];
      if (node.nodeType == 1 && node.contentEditable == "false")
        return false;
      off = dir < 0 ? maxOffset(node) : 0;
    } else {
      return false;
    }
  }
}
function maxOffset(node) {
  return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
}
var Rect0 = { left: 0, right: 0, top: 0, bottom: 0 };
function flattenRect(rect, left2) {
  let x2 = left2 ? rect.left : rect.right;
  return { left: x2, right: x2, top: rect.top, bottom: rect.bottom };
}
function windowRect(win) {
  return {
    left: 0,
    right: win.innerWidth,
    top: 0,
    bottom: win.innerHeight
  };
}
function scrollRectIntoView(dom, rect, side, x2, y2, xMargin, yMargin, ltr) {
  let doc2 = dom.ownerDocument, win = doc2.defaultView || window;
  for (let cur2 = dom; cur2; ) {
    if (cur2.nodeType == 1) {
      let bounding, top3 = cur2 == doc2.body;
      if (top3) {
        bounding = windowRect(win);
      } else {
        if (cur2.scrollHeight <= cur2.clientHeight && cur2.scrollWidth <= cur2.clientWidth) {
          cur2 = cur2.assignedSlot || cur2.parentNode;
          continue;
        }
        let rect2 = cur2.getBoundingClientRect();
        bounding = {
          left: rect2.left,
          right: rect2.left + cur2.clientWidth,
          top: rect2.top,
          bottom: rect2.top + cur2.clientHeight
        };
      }
      let moveX = 0, moveY = 0;
      if (y2 == "nearest") {
        if (rect.top < bounding.top) {
          moveY = -(bounding.top - rect.top + yMargin);
          if (side > 0 && rect.bottom > bounding.bottom + moveY)
            moveY = rect.bottom - bounding.bottom + moveY + yMargin;
        } else if (rect.bottom > bounding.bottom) {
          moveY = rect.bottom - bounding.bottom + yMargin;
          if (side < 0 && rect.top - moveY < bounding.top)
            moveY = -(bounding.top + moveY - rect.top + yMargin);
        }
      } else {
        let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top;
        let targetTop = y2 == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 : y2 == "start" || y2 == "center" && side < 0 ? rect.top - yMargin : rect.bottom - boundingHeight + yMargin;
        moveY = targetTop - bounding.top;
      }
      if (x2 == "nearest") {
        if (rect.left < bounding.left) {
          moveX = -(bounding.left - rect.left + xMargin);
          if (side > 0 && rect.right > bounding.right + moveX)
            moveX = rect.right - bounding.right + moveX + xMargin;
        } else if (rect.right > bounding.right) {
          moveX = rect.right - bounding.right + xMargin;
          if (side < 0 && rect.left < bounding.left + moveX)
            moveX = -(bounding.left + moveX - rect.left + xMargin);
        }
      } else {
        let targetLeft = x2 == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 : x2 == "start" == ltr ? rect.left - xMargin : rect.right - (bounding.right - bounding.left) + xMargin;
        moveX = targetLeft - bounding.left;
      }
      if (moveX || moveY) {
        if (top3) {
          win.scrollBy(moveX, moveY);
        } else {
          let movedX = 0, movedY = 0;
          if (moveY) {
            let start = cur2.scrollTop;
            cur2.scrollTop += moveY;
            movedY = cur2.scrollTop - start;
          }
          if (moveX) {
            let start = cur2.scrollLeft;
            cur2.scrollLeft += moveX;
            movedX = cur2.scrollLeft - start;
          }
          rect = {
            left: rect.left - movedX,
            top: rect.top - movedY,
            right: rect.right - movedX,
            bottom: rect.bottom - movedY
          };
          if (movedX && Math.abs(movedX - moveX) < 1)
            x2 = "nearest";
          if (movedY && Math.abs(movedY - moveY) < 1)
            y2 = "nearest";
        }
      }
      if (top3)
        break;
      cur2 = cur2.assignedSlot || cur2.parentNode;
    } else if (cur2.nodeType == 11) {
      cur2 = cur2.host;
    } else {
      break;
    }
  }
}
var DOMSelectionState = class {
  constructor() {
    this.anchorNode = null;
    this.anchorOffset = 0;
    this.focusNode = null;
    this.focusOffset = 0;
  }
  eq(domSel) {
    return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset && this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset;
  }
  setRange(range2) {
    this.set(range2.anchorNode, range2.anchorOffset, range2.focusNode, range2.focusOffset);
  }
  set(anchorNode, anchorOffset, focusNode, focusOffset) {
    this.anchorNode = anchorNode;
    this.anchorOffset = anchorOffset;
    this.focusNode = focusNode;
    this.focusOffset = focusOffset;
  }
};
var preventScrollSupported = null;
function focusPreventScroll(dom) {
  if (dom.setActive)
    return dom.setActive();
  if (preventScrollSupported)
    return dom.focus(preventScrollSupported);
  let stack = [];
  for (let cur2 = dom; cur2; cur2 = cur2.parentNode) {
    stack.push(cur2, cur2.scrollTop, cur2.scrollLeft);
    if (cur2 == cur2.ownerDocument)
      break;
  }
  dom.focus(preventScrollSupported == null ? {
    get preventScroll() {
      preventScrollSupported = { preventScroll: true };
      return true;
    }
  } : void 0);
  if (!preventScrollSupported) {
    preventScrollSupported = false;
    for (let i = 0; i < stack.length; ) {
      let elt = stack[i++], top3 = stack[i++], left2 = stack[i++];
      if (elt.scrollTop != top3)
        elt.scrollTop = top3;
      if (elt.scrollLeft != left2)
        elt.scrollLeft = left2;
    }
  }
}
var scratchRange;
function textRange(node, from, to = from) {
  let range2 = scratchRange || (scratchRange = document.createRange());
  range2.setEnd(node, to);
  range2.setStart(node, from);
  return range2;
}
function dispatchKey(elt, name2, code) {
  let options2 = { key: name2, code: name2, keyCode: code, which: code, cancelable: true };
  let down = new KeyboardEvent("keydown", options2);
  down.synthetic = true;
  elt.dispatchEvent(down);
  let up = new KeyboardEvent("keyup", options2);
  up.synthetic = true;
  elt.dispatchEvent(up);
  return down.defaultPrevented || up.defaultPrevented;
}
function getRoot(node) {
  while (node) {
    if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host))
      return node;
    node = node.assignedSlot || node.parentNode;
  }
  return null;
}
function clearAttributes(node) {
  while (node.attributes.length)
    node.removeAttributeNode(node.attributes[0]);
}
function atElementStart(doc2, selection2) {
  let node = selection2.focusNode, offset = selection2.focusOffset;
  if (!node || selection2.anchorNode != node || selection2.anchorOffset != offset)
    return false;
  for (; ; ) {
    if (offset) {
      if (node.nodeType != 1)
        return false;
      let prev = node.childNodes[offset - 1];
      if (prev.contentEditable == "false")
        offset--;
      else {
        node = prev;
        offset = maxOffset(node);
      }
    } else if (node == doc2) {
      return true;
    } else {
      offset = domIndex(node);
      node = node.parentNode;
    }
  }
}
var DOMPos = class {
  constructor(node, offset, precise = true) {
    this.node = node;
    this.offset = offset;
    this.precise = precise;
  }
  static before(dom, precise) {
    return new DOMPos(dom.parentNode, domIndex(dom), precise);
  }
  static after(dom, precise) {
    return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise);
  }
};
var noChildren = [];
var ContentView = class {
  constructor() {
    this.parent = null;
    this.dom = null;
    this.dirty = 2;
  }
  get editorView() {
    if (!this.parent)
      throw new Error("Accessing view in orphan content view");
    return this.parent.editorView;
  }
  get overrideDOMText() {
    return null;
  }
  get posAtStart() {
    return this.parent ? this.parent.posBefore(this) : 0;
  }
  get posAtEnd() {
    return this.posAtStart + this.length;
  }
  posBefore(view) {
    let pos = this.posAtStart;
    for (let child of this.children) {
      if (child == view)
        return pos;
      pos += child.length + child.breakAfter;
    }
    throw new RangeError("Invalid child in posBefore");
  }
  posAfter(view) {
    return this.posBefore(view) + view.length;
  }
  coordsAt(_pos, _side) {
    return null;
  }
  sync(track) {
    if (this.dirty & 2) {
      let parent2 = this.dom;
      let prev = null, next;
      for (let child of this.children) {
        if (child.dirty) {
          if (!child.dom && (next = prev ? prev.nextSibling : parent2.firstChild)) {
            let contentView = ContentView.get(next);
            if (!contentView || !contentView.parent && contentView.canReuseDOM(child))
              child.reuseDOM(next);
          }
          child.sync(track);
          child.dirty = 0;
        }
        next = prev ? prev.nextSibling : parent2.firstChild;
        if (track && !track.written && track.node == parent2 && next != child.dom)
          track.written = true;
        if (child.dom.parentNode == parent2) {
          while (next && next != child.dom)
            next = rm$1(next);
        } else {
          parent2.insertBefore(child.dom, next);
        }
        prev = child.dom;
      }
      next = prev ? prev.nextSibling : parent2.firstChild;
      if (next && track && track.node == parent2)
        track.written = true;
      while (next)
        next = rm$1(next);
    } else if (this.dirty & 1) {
      for (let child of this.children)
        if (child.dirty) {
          child.sync(track);
          child.dirty = 0;
        }
    }
  }
  reuseDOM(_dom) {
  }
  localPosFromDOM(node, offset) {
    let after;
    if (node == this.dom) {
      after = this.dom.childNodes[offset];
    } else {
      let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1;
      for (; ; ) {
        let parent2 = node.parentNode;
        if (parent2 == this.dom)
          break;
        if (bias == 0 && parent2.firstChild != parent2.lastChild) {
          if (node == parent2.firstChild)
            bias = -1;
          else
            bias = 1;
        }
        node = parent2;
      }
      if (bias < 0)
        after = node;
      else
        after = node.nextSibling;
    }
    if (after == this.dom.firstChild)
      return 0;
    while (after && !ContentView.get(after))
      after = after.nextSibling;
    if (!after)
      return this.length;
    for (let i = 0, pos = 0; ; i++) {
      let child = this.children[i];
      if (child.dom == after)
        return pos;
      pos += child.length + child.breakAfter;
    }
  }
  domBoundsAround(from, to, offset = 0) {
    let fromI = -1, fromStart = -1, toI = -1, toEnd = -1;
    for (let i = 0, pos = offset, prevEnd = offset; i < this.children.length; i++) {
      let child = this.children[i], end = pos + child.length;
      if (pos < from && end > to)
        return child.domBoundsAround(from, to, pos);
      if (end >= from && fromI == -1) {
        fromI = i;
        fromStart = pos;
      }
      if (pos > to && child.dom.parentNode == this.dom) {
        toI = i;
        toEnd = prevEnd;
        break;
      }
      prevEnd = end;
      pos = end + child.breakAfter;
    }
    return {
      from: fromStart,
      to: toEnd < 0 ? offset + this.length : toEnd,
      startDOM: (fromI ? this.children[fromI - 1].dom.nextSibling : null) || this.dom.firstChild,
      endDOM: toI < this.children.length && toI >= 0 ? this.children[toI].dom : null
    };
  }
  markDirty(andParent = false) {
    this.dirty |= 2;
    this.markParentsDirty(andParent);
  }
  markParentsDirty(childList) {
    for (let parent2 = this.parent; parent2; parent2 = parent2.parent) {
      if (childList)
        parent2.dirty |= 2;
      if (parent2.dirty & 1)
        return;
      parent2.dirty |= 1;
      childList = false;
    }
  }
  setParent(parent2) {
    if (this.parent != parent2) {
      this.parent = parent2;
      if (this.dirty)
        this.markParentsDirty(true);
    }
  }
  setDOM(dom) {
    if (this.dom)
      this.dom.cmView = null;
    this.dom = dom;
    dom.cmView = this;
  }
  get rootView() {
    for (let v = this; ; ) {
      let parent2 = v.parent;
      if (!parent2)
        return v;
      v = parent2;
    }
  }
  replaceChildren(from, to, children3 = noChildren) {
    this.markDirty();
    for (let i = from; i < to; i++) {
      let child = this.children[i];
      if (child.parent == this)
        child.destroy();
    }
    this.children.splice(from, to - from, ...children3);
    for (let i = 0; i < children3.length; i++)
      children3[i].setParent(this);
  }
  ignoreMutation(_rec) {
    return false;
  }
  ignoreEvent(_event) {
    return false;
  }
  childCursor(pos = this.length) {
    return new ChildCursor(this.children, pos, this.children.length);
  }
  childPos(pos, bias = 1) {
    return this.childCursor().findPos(pos, bias);
  }
  toString() {
    let name2 = this.constructor.name.replace("View", "");
    return name2 + (this.children.length ? "(" + this.children.join() + ")" : this.length ? "[" + (name2 == "Text" ? this.text : this.length) + "]" : "") + (this.breakAfter ? "#" : "");
  }
  static get(node) {
    return node.cmView;
  }
  get isEditable() {
    return true;
  }
  merge(from, to, source, hasStart, openStart, openEnd) {
    return false;
  }
  become(other) {
    return false;
  }
  canReuseDOM(other) {
    return other.constructor == this.constructor;
  }
  getSide() {
    return 0;
  }
  destroy() {
    this.parent = null;
  }
};
ContentView.prototype.breakAfter = 0;
function rm$1(dom) {
  let next = dom.nextSibling;
  dom.parentNode.removeChild(dom);
  return next;
}
var ChildCursor = class {
  constructor(children3, pos, i) {
    this.children = children3;
    this.pos = pos;
    this.i = i;
    this.off = 0;
  }
  findPos(pos, bias = 1) {
    for (; ; ) {
      if (pos > this.pos || pos == this.pos && (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) {
        this.off = pos - this.pos;
        return this;
      }
      let next = this.children[--this.i];
      this.pos -= next.length + next.breakAfter;
    }
  }
};
function replaceRange(parent2, fromI, fromOff, toI, toOff, insert3, breakAtStart, openStart, openEnd) {
  let { children: children3 } = parent2;
  let before = children3.length ? children3[fromI] : null;
  let last = insert3.length ? insert3[insert3.length - 1] : null;
  let breakAtEnd = last ? last.breakAfter : breakAtStart;
  if (fromI == toI && before && !breakAtStart && !breakAtEnd && insert3.length < 2 && before.merge(fromOff, toOff, insert3.length ? last : null, fromOff == 0, openStart, openEnd))
    return;
  if (toI < children3.length) {
    let after = children3[toI];
    if (after && toOff < after.length) {
      if (fromI == toI) {
        after = after.split(toOff);
        toOff = 0;
      }
      if (!breakAtEnd && last && after.merge(0, toOff, last, true, 0, openEnd)) {
        insert3[insert3.length - 1] = after;
      } else {
        if (toOff)
          after.merge(0, toOff, null, false, 0, openEnd);
        insert3.push(after);
      }
    } else if (after === null || after === void 0 ? void 0 : after.breakAfter) {
      if (last)
        last.breakAfter = 1;
      else
        breakAtStart = 1;
    }
    toI++;
  }
  if (before) {
    before.breakAfter = breakAtStart;
    if (fromOff > 0) {
      if (!breakAtStart && insert3.length && before.merge(fromOff, before.length, insert3[0], false, openStart, 0)) {
        before.breakAfter = insert3.shift().breakAfter;
      } else if (fromOff < before.length || before.children.length && before.children[before.children.length - 1].length == 0) {
        before.merge(fromOff, before.length, null, false, openStart, 0);
      }
      fromI++;
    }
  }
  while (fromI < toI && insert3.length) {
    if (children3[toI - 1].become(insert3[insert3.length - 1])) {
      toI--;
      insert3.pop();
      openEnd = insert3.length ? 0 : openStart;
    } else if (children3[fromI].become(insert3[0])) {
      fromI++;
      insert3.shift();
      openStart = insert3.length ? 0 : openEnd;
    } else {
      break;
    }
  }
  if (!insert3.length && fromI && toI < children3.length && !children3[fromI - 1].breakAfter && children3[toI].merge(0, 0, children3[fromI - 1], false, openStart, openEnd))
    fromI--;
  if (fromI < toI || insert3.length)
    parent2.replaceChildren(fromI, toI, insert3);
}
function mergeChildrenInto(parent2, from, to, insert3, openStart, openEnd) {
  let cur2 = parent2.childCursor();
  let { i: toI, off: toOff } = cur2.findPos(to, 1);
  let { i: fromI, off: fromOff } = cur2.findPos(from, -1);
  let dLen = from - to;
  for (let view of insert3)
    dLen += view.length;
  parent2.length += dLen;
  replaceRange(parent2, fromI, fromOff, toI, toOff, insert3, 0, openStart, openEnd);
}
var nav = typeof navigator != "undefined" ? navigator : { userAgent: "", vendor: "", platform: "" };
var doc = typeof document != "undefined" ? document : { documentElement: { style: {} } };
var ie_edge = /* @__PURE__ */ /Edge\/(\d+)/.exec(nav.userAgent);
var ie_upto10 = /* @__PURE__ */ /MSIE \d/.test(nav.userAgent);
var ie_11up = /* @__PURE__ */ /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent);
var ie2 = !!(ie_upto10 || ie_11up || ie_edge);
var gecko2 = !ie2 && /* @__PURE__ */ /gecko\/(\d+)/i.test(nav.userAgent);
var chrome2 = !ie2 && /* @__PURE__ */ /Chrome\/(\d+)/.exec(nav.userAgent);
var webkit = "webkitFontSmoothing" in doc.documentElement.style;
var safari = !ie2 && /* @__PURE__ */ /Apple Computer/.test(nav.vendor);
var ios = safari && (/* @__PURE__ */ /Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2);
var browser = {
  mac: ios || /* @__PURE__ */ /Mac/.test(nav.platform),
  windows: /* @__PURE__ */ /Win/.test(nav.platform),
  linux: /* @__PURE__ */ /Linux|X11/.test(nav.platform),
  ie: ie2,
  ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0,
  gecko: gecko2,
  gecko_version: gecko2 ? +(/* @__PURE__ */ /Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
  chrome: !!chrome2,
  chrome_version: chrome2 ? +chrome2[1] : 0,
  ios,
  android: /* @__PURE__ */ /Android\b/.test(nav.userAgent),
  webkit,
  safari,
  webkit_version: webkit ? +(/* @__PURE__ */ /\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0,
  tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size"
};
var MaxJoinLen = 256;
var TextView = class extends ContentView {
  constructor(text2) {
    super();
    this.text = text2;
  }
  get length() {
    return this.text.length;
  }
  createDOM(textDOM) {
    this.setDOM(textDOM || document.createTextNode(this.text));
  }
  sync(track) {
    if (!this.dom)
      this.createDOM();
    if (this.dom.nodeValue != this.text) {
      if (track && track.node == this.dom)
        track.written = true;
      this.dom.nodeValue = this.text;
    }
  }
  reuseDOM(dom) {
    if (dom.nodeType == 3)
      this.createDOM(dom);
  }
  merge(from, to, source) {
    if (source && (!(source instanceof TextView) || this.length - (to - from) + source.length > MaxJoinLen))
      return false;
    this.text = this.text.slice(0, from) + (source ? source.text : "") + this.text.slice(to);
    this.markDirty();
    return true;
  }
  split(from) {
    let result = new TextView(this.text.slice(from));
    this.text = this.text.slice(0, from);
    this.markDirty();
    return result;
  }
  localPosFromDOM(node, offset) {
    return node == this.dom ? offset : offset ? this.text.length : 0;
  }
  domAtPos(pos) {
    return new DOMPos(this.dom, pos);
  }
  domBoundsAround(_from, _to, offset) {
    return { from: offset, to: offset + this.length, startDOM: this.dom, endDOM: this.dom.nextSibling };
  }
  coordsAt(pos, side) {
    return textCoords(this.dom, pos, side);
  }
};
var MarkView = class extends ContentView {
  constructor(mark, children3 = [], length = 0) {
    super();
    this.mark = mark;
    this.children = children3;
    this.length = length;
    for (let ch of children3)
      ch.setParent(this);
  }
  setAttrs(dom) {
    clearAttributes(dom);
    if (this.mark.class)
      dom.className = this.mark.class;
    if (this.mark.attrs)
      for (let name2 in this.mark.attrs)
        dom.setAttribute(name2, this.mark.attrs[name2]);
    return dom;
  }
  reuseDOM(node) {
    if (node.nodeName == this.mark.tagName.toUpperCase()) {
      this.setDOM(node);
      this.dirty |= 4 | 2;
    }
  }
  sync(track) {
    if (!this.dom)
      this.setDOM(this.setAttrs(document.createElement(this.mark.tagName)));
    else if (this.dirty & 4)
      this.setAttrs(this.dom);
    super.sync(track);
  }
  merge(from, to, source, _hasStart, openStart, openEnd) {
    if (source && (!(source instanceof MarkView && source.mark.eq(this.mark)) || from && openStart <= 0 || to < this.length && openEnd <= 0))
      return false;
    mergeChildrenInto(this, from, to, source ? source.children : [], openStart - 1, openEnd - 1);
    this.markDirty();
    return true;
  }
  split(from) {
    let result = [], off = 0, detachFrom = -1, i = 0;
    for (let elt of this.children) {
      let end = off + elt.length;
      if (end > from)
        result.push(off < from ? elt.split(from - off) : elt);
      if (detachFrom < 0 && off >= from)
        detachFrom = i;
      off = end;
      i++;
    }
    let length = this.length - from;
    this.length = from;
    if (detachFrom > -1) {
      this.children.length = detachFrom;
      this.markDirty();
    }
    return new MarkView(this.mark, result, length);
  }
  domAtPos(pos) {
    return inlineDOMAtPos(this, pos);
  }
  coordsAt(pos, side) {
    return coordsInChildren(this, pos, side);
  }
};
function textCoords(text2, pos, side) {
  let length = text2.nodeValue.length;
  if (pos > length)
    pos = length;
  let from = pos, to = pos, flatten3 = 0;
  if (pos == 0 && side < 0 || pos == length && side >= 0) {
    if (!(browser.chrome || browser.gecko)) {
      if (pos) {
        from--;
        flatten3 = 1;
      } else if (to < length) {
        to++;
        flatten3 = -1;
      }
    }
  } else {
    if (side < 0)
      from--;
    else if (to < length)
      to++;
  }
  let rects = textRange(text2, from, to).getClientRects();
  if (!rects.length)
    return Rect0;
  let rect = rects[(flatten3 ? flatten3 < 0 : side >= 0) ? 0 : rects.length - 1];
  if (browser.safari && !flatten3 && rect.width == 0)
    rect = Array.prototype.find.call(rects, (r) => r.width) || rect;
  return flatten3 ? flattenRect(rect, flatten3 < 0) : rect || null;
}
var WidgetView = class extends ContentView {
  constructor(widget, length, side) {
    super();
    this.widget = widget;
    this.length = length;
    this.side = side;
    this.prevWidget = null;
  }
  static create(widget, length, side) {
    return new (widget.customView || WidgetView)(widget, length, side);
  }
  split(from) {
    let result = WidgetView.create(this.widget, this.length - from, this.side);
    this.length -= from;
    return result;
  }
  sync() {
    if (!this.dom || !this.widget.updateDOM(this.dom)) {
      if (this.dom && this.prevWidget)
        this.prevWidget.destroy(this.dom);
      this.prevWidget = null;
      this.setDOM(this.widget.toDOM(this.editorView));
      this.dom.contentEditable = "false";
    }
  }
  getSide() {
    return this.side;
  }
  merge(from, to, source, hasStart, openStart, openEnd) {
    if (source && (!(source instanceof WidgetView) || !this.widget.compare(source.widget) || from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))
      return false;
    this.length = from + (source ? source.length : 0) + (this.length - to);
    return true;
  }
  become(other) {
    if (other.length == this.length && other instanceof WidgetView && other.side == this.side) {
      if (this.widget.constructor == other.widget.constructor) {
        if (!this.widget.eq(other.widget))
          this.markDirty(true);
        if (this.dom && !this.prevWidget)
          this.prevWidget = this.widget;
        this.widget = other.widget;
        return true;
      }
    }
    return false;
  }
  ignoreMutation() {
    return true;
  }
  ignoreEvent(event) {
    return this.widget.ignoreEvent(event);
  }
  get overrideDOMText() {
    if (this.length == 0)
      return Text.empty;
    let top3 = this;
    while (top3.parent)
      top3 = top3.parent;
    let view = top3.editorView, text2 = view && view.state.doc, start = this.posAtStart;
    return text2 ? text2.slice(start, start + this.length) : Text.empty;
  }
  domAtPos(pos) {
    return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length);
  }
  domBoundsAround() {
    return null;
  }
  coordsAt(pos, side) {
    let rects = this.dom.getClientRects(), rect = null;
    if (!rects.length)
      return Rect0;
    for (let i = pos > 0 ? rects.length - 1 : 0; ; i += pos > 0 ? -1 : 1) {
      rect = rects[i];
      if (pos > 0 ? i == 0 : i == rects.length - 1 || rect.top < rect.bottom)
        break;
    }
    return flattenRect(rect, this.side > 0);
  }
  get isEditable() {
    return false;
  }
  destroy() {
    super.destroy();
    if (this.dom)
      this.widget.destroy(this.dom);
  }
};
var CompositionView = class extends WidgetView {
  domAtPos(pos) {
    let { topView, text: text2 } = this.widget;
    if (!topView)
      return new DOMPos(text2, Math.min(pos, text2.nodeValue.length));
    return scanCompositionTree(pos, 0, topView, text2, (v, p) => v.domAtPos(p), (p) => new DOMPos(text2, Math.min(p, text2.nodeValue.length)));
  }
  sync() {
    this.setDOM(this.widget.toDOM());
  }
  localPosFromDOM(node, offset) {
    let { topView, text: text2 } = this.widget;
    if (!topView)
      return Math.min(offset, this.length);
    return posFromDOMInCompositionTree(node, offset, topView, text2);
  }
  ignoreMutation() {
    return false;
  }
  get overrideDOMText() {
    return null;
  }
  coordsAt(pos, side) {
    let { topView, text: text2 } = this.widget;
    if (!topView)
      return textCoords(text2, pos, side);
    return scanCompositionTree(pos, side, topView, text2, (v, pos2, side2) => v.coordsAt(pos2, side2), (pos2, side2) => textCoords(text2, pos2, side2));
  }
  destroy() {
    var _a2;
    super.destroy();
    (_a2 = this.widget.topView) === null || _a2 === void 0 ? void 0 : _a2.destroy();
  }
  get isEditable() {
    return true;
  }
  canReuseDOM() {
    return true;
  }
};
function scanCompositionTree(pos, side, view, text2, enterView, fromText) {
  if (view instanceof MarkView) {
    for (let child = view.dom.firstChild; child; child = child.nextSibling) {
      let desc = ContentView.get(child);
      if (!desc)
        return fromText(pos, side);
      let hasComp = contains(child, text2);
      let len = desc.length + (hasComp ? text2.nodeValue.length : 0);
      if (pos < len || pos == len && desc.getSide() <= 0)
        return hasComp ? scanCompositionTree(pos, side, desc, text2, enterView, fromText) : enterView(desc, pos, side);
      pos -= len;
    }
    return enterView(view, view.length, -1);
  } else if (view.dom == text2) {
    return fromText(pos, side);
  } else {
    return enterView(view, pos, side);
  }
}
function posFromDOMInCompositionTree(node, offset, view, text2) {
  if (view instanceof MarkView) {
    for (let child of view.children) {
      let pos = 0, hasComp = contains(child.dom, text2);
      if (contains(child.dom, node))
        return pos + (hasComp ? posFromDOMInCompositionTree(node, offset, child, text2) : child.localPosFromDOM(node, offset));
      pos += hasComp ? text2.nodeValue.length : child.length;
    }
  } else if (view.dom == text2) {
    return Math.min(offset, text2.nodeValue.length);
  }
  return view.localPosFromDOM(node, offset);
}
var WidgetBufferView = class extends ContentView {
  constructor(side) {
    super();
    this.side = side;
  }
  get length() {
    return 0;
  }
  merge() {
    return false;
  }
  become(other) {
    return other instanceof WidgetBufferView && other.side == this.side;
  }
  split() {
    return new WidgetBufferView(this.side);
  }
  sync() {
    if (!this.dom) {
      let dom = document.createElement("img");
      dom.className = "cm-widgetBuffer";
      dom.setAttribute("aria-hidden", "true");
      this.setDOM(dom);
    }
  }
  getSide() {
    return this.side;
  }
  domAtPos(pos) {
    return DOMPos.before(this.dom);
  }
  localPosFromDOM() {
    return 0;
  }
  domBoundsAround() {
    return null;
  }
  coordsAt(pos) {
    let imgRect = this.dom.getBoundingClientRect();
    let siblingRect = inlineSiblingRect(this, this.side > 0 ? -1 : 1);
    return siblingRect && siblingRect.top < imgRect.bottom && siblingRect.bottom > imgRect.top ? { left: imgRect.left, right: imgRect.right, top: siblingRect.top, bottom: siblingRect.bottom } : imgRect;
  }
  get overrideDOMText() {
    return Text.empty;
  }
};
TextView.prototype.children = WidgetView.prototype.children = WidgetBufferView.prototype.children = noChildren;
function inlineSiblingRect(view, side) {
  let parent2 = view.parent, index2 = parent2 ? parent2.children.indexOf(view) : -1;
  while (parent2 && index2 >= 0) {
    if (side < 0 ? index2 > 0 : index2 < parent2.children.length) {
      let next = parent2.children[index2 + side];
      if (next instanceof TextView) {
        let nextRect = next.coordsAt(side < 0 ? next.length : 0, side);
        if (nextRect)
          return nextRect;
      }
      index2 += side;
    } else if (parent2 instanceof MarkView && parent2.parent) {
      index2 = parent2.parent.children.indexOf(parent2) + (side < 0 ? 0 : 1);
      parent2 = parent2.parent;
    } else {
      let last = parent2.dom.lastChild;
      if (last && last.nodeName == "BR")
        return last.getClientRects()[0];
      break;
    }
  }
  return void 0;
}
function inlineDOMAtPos(parent2, pos) {
  let dom = parent2.dom, { children: children3 } = parent2, i = 0;
  for (let off = 0; i < children3.length; i++) {
    let child = children3[i], end = off + child.length;
    if (end == off && child.getSide() <= 0)
      continue;
    if (pos > off && pos < end && child.dom.parentNode == dom)
      return child.domAtPos(pos - off);
    if (pos <= off)
      break;
    off = end;
  }
  for (let j = i; j > 0; j--) {
    let prev = children3[j - 1];
    if (prev.dom.parentNode == dom)
      return prev.domAtPos(prev.length);
  }
  for (let j = i; j < children3.length; j++) {
    let next = children3[j];
    if (next.dom.parentNode == dom)
      return next.domAtPos(0);
  }
  return new DOMPos(dom, 0);
}
function joinInlineInto(parent2, view, open) {
  let last, { children: children3 } = parent2;
  if (open > 0 && view instanceof MarkView && children3.length && (last = children3[children3.length - 1]) instanceof MarkView && last.mark.eq(view.mark)) {
    joinInlineInto(last, view.children[0], open - 1);
  } else {
    children3.push(view);
    view.setParent(parent2);
  }
  parent2.length += view.length;
}
function coordsInChildren(view, pos, side) {
  let before = null, beforePos = -1, after = null, afterPos = -1;
  function scan(view2, pos2) {
    for (let i = 0, off = 0; i < view2.children.length && off <= pos2; i++) {
      let child = view2.children[i], end = off + child.length;
      if (end >= pos2) {
        if (child.children.length) {
          scan(child, pos2 - off);
        } else if (!after && (end > pos2 || off == end && child.getSide() > 0)) {
          after = child;
          afterPos = pos2 - off;
        } else if (off < pos2 || off == end && child.getSide() < 0) {
          before = child;
          beforePos = pos2 - off;
        }
      }
      off = end;
    }
  }
  scan(view, pos);
  let target = (side < 0 ? before : after) || before || after;
  if (target)
    return target.coordsAt(Math.max(0, target == before ? beforePos : afterPos), side);
  return fallbackRect(view);
}
function fallbackRect(view) {
  let last = view.dom.lastChild;
  if (!last)
    return view.dom.getBoundingClientRect();
  let rects = clientRectsFor(last);
  return rects[rects.length - 1] || null;
}
function combineAttrs(source, target) {
  for (let name2 in source) {
    if (name2 == "class" && target.class)
      target.class += " " + source.class;
    else if (name2 == "style" && target.style)
      target.style += ";" + source.style;
    else
      target[name2] = source[name2];
  }
  return target;
}
function attrsEq(a, b) {
  if (a == b)
    return true;
  if (!a || !b)
    return false;
  let keysA = Object.keys(a), keysB = Object.keys(b);
  if (keysA.length != keysB.length)
    return false;
  for (let key of keysA) {
    if (keysB.indexOf(key) == -1 || a[key] !== b[key])
      return false;
  }
  return true;
}
function updateAttrs(dom, prev, attrs) {
  let changed = null;
  if (prev) {
    for (let name2 in prev)
      if (!(attrs && name2 in attrs))
        dom.removeAttribute(changed = name2);
  }
  if (attrs) {
    for (let name2 in attrs)
      if (!(prev && prev[name2] == attrs[name2]))
        dom.setAttribute(changed = name2, attrs[name2]);
  }
  return !!changed;
}
var WidgetType = class {
  eq(widget) {
    return false;
  }
  updateDOM(dom) {
    return false;
  }
  compare(other) {
    return this == other || this.constructor == other.constructor && this.eq(other);
  }
  get estimatedHeight() {
    return -1;
  }
  ignoreEvent(event) {
    return true;
  }
  get customView() {
    return null;
  }
  destroy(dom) {
  }
};
var BlockType = /* @__PURE__ */ function(BlockType2) {
  BlockType2[BlockType2["Text"] = 0] = "Text";
  BlockType2[BlockType2["WidgetBefore"] = 1] = "WidgetBefore";
  BlockType2[BlockType2["WidgetAfter"] = 2] = "WidgetAfter";
  BlockType2[BlockType2["WidgetRange"] = 3] = "WidgetRange";
  return BlockType2;
}(BlockType || (BlockType = {}));
var Decoration = class extends RangeValue {
  constructor(startSide, endSide, widget, spec) {
    super();
    this.startSide = startSide;
    this.endSide = endSide;
    this.widget = widget;
    this.spec = spec;
  }
  get heightRelevant() {
    return false;
  }
  static mark(spec) {
    return new MarkDecoration(spec);
  }
  static widget(spec) {
    let side = spec.side || 0, block = !!spec.block;
    side += block ? side > 0 ? 3e8 : -4e8 : side > 0 ? 1e8 : -1e8;
    return new PointDecoration(spec, side, side, block, spec.widget || null, false);
  }
  static replace(spec) {
    let block = !!spec.block, startSide, endSide;
    if (spec.isBlockGap) {
      startSide = -5e8;
      endSide = 4e8;
    } else {
      let { start, end } = getInclusive(spec, block);
      startSide = (start ? block ? -3e8 : -1 : 5e8) - 1;
      endSide = (end ? block ? 2e8 : 1 : -6e8) + 1;
    }
    return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true);
  }
  static line(spec) {
    return new LineDecoration(spec);
  }
  static set(of, sort = false) {
    return RangeSet.of(of, sort);
  }
  hasHeight() {
    return this.widget ? this.widget.estimatedHeight > -1 : false;
  }
};
Decoration.none = RangeSet.empty;
var MarkDecoration = class extends Decoration {
  constructor(spec) {
    let { start, end } = getInclusive(spec);
    super(start ? -1 : 5e8, end ? 1 : -6e8, null, spec);
    this.tagName = spec.tagName || "span";
    this.class = spec.class || "";
    this.attrs = spec.attributes || null;
  }
  eq(other) {
    return this == other || other instanceof MarkDecoration && this.tagName == other.tagName && this.class == other.class && attrsEq(this.attrs, other.attrs);
  }
  range(from, to = from) {
    if (from >= to)
      throw new RangeError("Mark decorations may not be empty");
    return super.range(from, to);
  }
};
MarkDecoration.prototype.point = false;
var LineDecoration = class extends Decoration {
  constructor(spec) {
    super(-2e8, -2e8, null, spec);
  }
  eq(other) {
    return other instanceof LineDecoration && attrsEq(this.spec.attributes, other.spec.attributes);
  }
  range(from, to = from) {
    if (to != from)
      throw new RangeError("Line decoration ranges must be zero-length");
    return super.range(from, to);
  }
};
LineDecoration.prototype.mapMode = MapMode.TrackBefore;
LineDecoration.prototype.point = true;
var PointDecoration = class extends Decoration {
  constructor(spec, startSide, endSide, block, widget, isReplace) {
    super(startSide, endSide, widget, spec);
    this.block = block;
    this.isReplace = isReplace;
    this.mapMode = !block ? MapMode.TrackDel : startSide <= 0 ? MapMode.TrackBefore : MapMode.TrackAfter;
  }
  get type() {
    return this.startSide < this.endSide ? BlockType.WidgetRange : this.startSide <= 0 ? BlockType.WidgetBefore : BlockType.WidgetAfter;
  }
  get heightRelevant() {
    return this.block || !!this.widget && this.widget.estimatedHeight >= 5;
  }
  eq(other) {
    return other instanceof PointDecoration && widgetsEq(this.widget, other.widget) && this.block == other.block && this.startSide == other.startSide && this.endSide == other.endSide;
  }
  range(from, to = from) {
    if (this.isReplace && (from > to || from == to && this.startSide > 0 && this.endSide <= 0))
      throw new RangeError("Invalid range for replacement decoration");
    if (!this.isReplace && to != from)
      throw new RangeError("Widget decorations can only have zero-length ranges");
    return super.range(from, to);
  }
};
PointDecoration.prototype.point = true;
function getInclusive(spec, block = false) {
  let { inclusiveStart: start, inclusiveEnd: end } = spec;
  if (start == null)
    start = spec.inclusive;
  if (end == null)
    end = spec.inclusive;
  return { start: start !== null && start !== void 0 ? start : block, end: end !== null && end !== void 0 ? end : block };
}
function widgetsEq(a, b) {
  return a == b || !!(a && b && a.compare(b));
}
function addRange(from, to, ranges, margin = 0) {
  let last = ranges.length - 1;
  if (last >= 0 && ranges[last] + margin >= from)
    ranges[last] = Math.max(ranges[last], to);
  else
    ranges.push(from, to);
}
var LineView = class extends ContentView {
  constructor() {
    super(...arguments);
    this.children = [];
    this.length = 0;
    this.prevAttrs = void 0;
    this.attrs = null;
    this.breakAfter = 0;
  }
  merge(from, to, source, hasStart, openStart, openEnd) {
    if (source) {
      if (!(source instanceof LineView))
        return false;
      if (!this.dom)
        source.transferDOM(this);
    }
    if (hasStart)
      this.setDeco(source ? source.attrs : null);
    mergeChildrenInto(this, from, to, source ? source.children : [], openStart, openEnd);
    return true;
  }
  split(at) {
    let end = new LineView();
    end.breakAfter = this.breakAfter;
    if (this.length == 0)
      return end;
    let { i, off } = this.childPos(at);
    if (off) {
      end.append(this.children[i].split(off), 0);
      this.children[i].merge(off, this.children[i].length, null, false, 0, 0);
      i++;
    }
    for (let j = i; j < this.children.length; j++)
      end.append(this.children[j], 0);
    while (i > 0 && this.children[i - 1].length == 0)
      this.children[--i].destroy();
    this.children.length = i;
    this.markDirty();
    this.length = at;
    return end;
  }
  transferDOM(other) {
    if (!this.dom)
      return;
    this.markDirty();
    other.setDOM(this.dom);
    other.prevAttrs = this.prevAttrs === void 0 ? this.attrs : this.prevAttrs;
    this.prevAttrs = void 0;
    this.dom = null;
  }
  setDeco(attrs) {
    if (!attrsEq(this.attrs, attrs)) {
      if (this.dom) {
        this.prevAttrs = this.attrs;
        this.markDirty();
      }
      this.attrs = attrs;
    }
  }
  append(child, openStart) {
    joinInlineInto(this, child, openStart);
  }
  addLineDeco(deco) {
    let attrs = deco.spec.attributes, cls = deco.spec.class;
    if (attrs)
      this.attrs = combineAttrs(attrs, this.attrs || {});
    if (cls)
      this.attrs = combineAttrs({ class: cls }, this.attrs || {});
  }
  domAtPos(pos) {
    return inlineDOMAtPos(this, pos);
  }
  reuseDOM(node) {
    if (node.nodeName == "DIV") {
      this.setDOM(node);
      this.dirty |= 4 | 2;
    }
  }
  sync(track) {
    var _a2;
    if (!this.dom) {
      this.setDOM(document.createElement("div"));
      this.dom.className = "cm-line";
      this.prevAttrs = this.attrs ? null : void 0;
    } else if (this.dirty & 4) {
      clearAttributes(this.dom);
      this.dom.className = "cm-line";
      this.prevAttrs = this.attrs ? null : void 0;
    }
    if (this.prevAttrs !== void 0) {
      updateAttrs(this.dom, this.prevAttrs, this.attrs);
      this.dom.classList.add("cm-line");
      this.prevAttrs = void 0;
    }
    super.sync(track);
    let last = this.dom.lastChild;
    while (last && ContentView.get(last) instanceof MarkView)
      last = last.lastChild;
    if (!last || !this.length || last.nodeName != "BR" && ((_a2 = ContentView.get(last)) === null || _a2 === void 0 ? void 0 : _a2.isEditable) == false && (!browser.ios || !this.children.some((ch) => ch instanceof TextView))) {
      let hack = document.createElement("BR");
      hack.cmIgnore = true;
      this.dom.appendChild(hack);
    }
  }
  measureTextSize() {
    if (this.children.length == 0 || this.length > 20)
      return null;
    let totalWidth = 0;
    for (let child of this.children) {
      if (!(child instanceof TextView) || /[^ -~]/.test(child.text))
        return null;
      let rects = clientRectsFor(child.dom);
      if (rects.length != 1)
        return null;
      totalWidth += rects[0].width;
    }
    return !totalWidth ? null : {
      lineHeight: this.dom.getBoundingClientRect().height,
      charWidth: totalWidth / this.length
    };
  }
  coordsAt(pos, side) {
    return coordsInChildren(this, pos, side);
  }
  become(_other) {
    return false;
  }
  get type() {
    return BlockType.Text;
  }
  static find(docView, pos) {
    for (let i = 0, off = 0; i < docView.children.length; i++) {
      let block = docView.children[i], end = off + block.length;
      if (end >= pos) {
        if (block instanceof LineView)
          return block;
        if (end > pos)
          break;
      }
      off = end + block.breakAfter;
    }
    return null;
  }
};
var BlockWidgetView = class extends ContentView {
  constructor(widget, length, type) {
    super();
    this.widget = widget;
    this.length = length;
    this.type = type;
    this.breakAfter = 0;
    this.prevWidget = null;
  }
  merge(from, to, source, _takeDeco, openStart, openEnd) {
    if (source && (!(source instanceof BlockWidgetView) || !this.widget.compare(source.widget) || from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))
      return false;
    this.length = from + (source ? source.length : 0) + (this.length - to);
    return true;
  }
  domAtPos(pos) {
    return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length);
  }
  split(at) {
    let len = this.length - at;
    this.length = at;
    let end = new BlockWidgetView(this.widget, len, this.type);
    end.breakAfter = this.breakAfter;
    return end;
  }
  get children() {
    return noChildren;
  }
  sync() {
    if (!this.dom || !this.widget.updateDOM(this.dom)) {
      if (this.dom && this.prevWidget)
        this.prevWidget.destroy(this.dom);
      this.prevWidget = null;
      this.setDOM(this.widget.toDOM(this.editorView));
      this.dom.contentEditable = "false";
    }
  }
  get overrideDOMText() {
    return this.parent ? this.parent.view.state.doc.slice(this.posAtStart, this.posAtEnd) : Text.empty;
  }
  domBoundsAround() {
    return null;
  }
  become(other) {
    if (other instanceof BlockWidgetView && other.type == this.type && other.widget.constructor == this.widget.constructor) {
      if (!other.widget.eq(this.widget))
        this.markDirty(true);
      if (this.dom && !this.prevWidget)
        this.prevWidget = this.widget;
      this.widget = other.widget;
      this.length = other.length;
      this.breakAfter = other.breakAfter;
      return true;
    }
    return false;
  }
  ignoreMutation() {
    return true;
  }
  ignoreEvent(event) {
    return this.widget.ignoreEvent(event);
  }
  destroy() {
    super.destroy();
    if (this.dom)
      this.widget.destroy(this.dom);
  }
};
var ContentBuilder = class {
  constructor(doc2, pos, end, disallowBlockEffectsFor) {
    this.doc = doc2;
    this.pos = pos;
    this.end = end;
    this.disallowBlockEffectsFor = disallowBlockEffectsFor;
    this.content = [];
    this.curLine = null;
    this.breakAtStart = 0;
    this.pendingBuffer = 0;
    this.atCursorPos = true;
    this.openStart = -1;
    this.openEnd = -1;
    this.text = "";
    this.textOff = 0;
    this.cursor = doc2.iter();
    this.skip = pos;
  }
  posCovered() {
    if (this.content.length == 0)
      return !this.breakAtStart && this.doc.lineAt(this.pos).from != this.pos;
    let last = this.content[this.content.length - 1];
    return !last.breakAfter && !(last instanceof BlockWidgetView && last.type == BlockType.WidgetBefore);
  }
  getLine() {
    if (!this.curLine) {
      this.content.push(this.curLine = new LineView());
      this.atCursorPos = true;
    }
    return this.curLine;
  }
  flushBuffer(active) {
    if (this.pendingBuffer) {
      this.curLine.append(wrapMarks(new WidgetBufferView(-1), active), active.length);
      this.pendingBuffer = 0;
    }
  }
  addBlockWidget(view) {
    this.flushBuffer([]);
    this.curLine = null;
    this.content.push(view);
  }
  finish(openEnd) {
    if (!openEnd)
      this.flushBuffer([]);
    else
      this.pendingBuffer = 0;
    if (!this.posCovered())
      this.getLine();
  }
  buildText(length, active, openStart) {
    while (length > 0) {
      if (this.textOff == this.text.length) {
        let { value, lineBreak, done } = this.cursor.next(this.skip);
        this.skip = 0;
        if (done)
          throw new Error("Ran out of text content when drawing inline views");
        if (lineBreak) {
          if (!this.posCovered())
            this.getLine();
          if (this.content.length)
            this.content[this.content.length - 1].breakAfter = 1;
          else
            this.breakAtStart = 1;
          this.flushBuffer([]);
          this.curLine = null;
          length--;
          continue;
        } else {
          this.text = value;
          this.textOff = 0;
        }
      }
      let take = Math.min(this.text.length - this.textOff, length, 512);
      this.flushBuffer(active.slice(0, openStart));
      this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff, this.textOff + take)), active), openStart);
      this.atCursorPos = true;
      this.textOff += take;
      length -= take;
      openStart = 0;
    }
  }
  span(from, to, active, openStart) {
    this.buildText(to - from, active, openStart);
    this.pos = to;
    if (this.openStart < 0)
      this.openStart = openStart;
  }
  point(from, to, deco, active, openStart, index2) {
    if (this.disallowBlockEffectsFor[index2] && deco instanceof PointDecoration) {
      if (deco.block)
        throw new RangeError("Block decorations may not be specified via plugins");
      if (to > this.doc.lineAt(this.pos).to)
        throw new RangeError("Decorations that replace line breaks may not be specified via plugins");
    }
    let len = to - from;
    if (deco instanceof PointDecoration) {
      if (deco.block) {
        let { type } = deco;
        if (type == BlockType.WidgetAfter && !this.posCovered())
          this.getLine();
        this.addBlockWidget(new BlockWidgetView(deco.widget || new NullWidget("div"), len, type));
      } else {
        let view = WidgetView.create(deco.widget || new NullWidget("span"), len, len ? 0 : deco.startSide);
        let cursorBefore = this.atCursorPos && !view.isEditable && openStart <= active.length && (from < to || deco.startSide > 0);
        let cursorAfter = !view.isEditable && (from < to || deco.startSide <= 0);
        let line = this.getLine();
        if (this.pendingBuffer == 2 && !cursorBefore)
          this.pendingBuffer = 0;
        this.flushBuffer(active);
        if (cursorBefore) {
          line.append(wrapMarks(new WidgetBufferView(1), active), openStart);
          openStart = active.length + Math.max(0, openStart - active.length);
        }
        line.append(wrapMarks(view, active), openStart);
        this.atCursorPos = cursorAfter;
        this.pendingBuffer = !cursorAfter ? 0 : from < to ? 1 : 2;
      }
    } else if (this.doc.lineAt(this.pos).from == this.pos) {
      this.getLine().addLineDeco(deco);
    }
    if (len) {
      if (this.textOff + len <= this.text.length) {
        this.textOff += len;
      } else {
        this.skip += len - (this.text.length - this.textOff);
        this.text = "";
        this.textOff = 0;
      }
      this.pos = to;
    }
    if (this.openStart < 0)
      this.openStart = openStart;
  }
  static build(text2, from, to, decorations2, dynamicDecorationMap) {
    let builder = new ContentBuilder(text2, from, to, dynamicDecorationMap);
    builder.openEnd = RangeSet.spans(decorations2, from, to, builder);
    if (builder.openStart < 0)
      builder.openStart = builder.openEnd;
    builder.finish(builder.openEnd);
    return builder;
  }
};
function wrapMarks(view, active) {
  for (let mark of active)
    view = new MarkView(mark, [view], view.length);
  return view;
}
var NullWidget = class extends WidgetType {
  constructor(tag2) {
    super();
    this.tag = tag2;
  }
  eq(other) {
    return other.tag == this.tag;
  }
  toDOM() {
    return document.createElement(this.tag);
  }
  updateDOM(elt) {
    return elt.nodeName.toLowerCase() == this.tag;
  }
};
var clickAddsSelectionRange = /* @__PURE__ */ Facet.define();
var dragMovesSelection$1 = /* @__PURE__ */ Facet.define();
var mouseSelectionStyle = /* @__PURE__ */ Facet.define();
var exceptionSink = /* @__PURE__ */ Facet.define();
var updateListener = /* @__PURE__ */ Facet.define();
var inputHandler = /* @__PURE__ */ Facet.define();
var perLineTextDirection = /* @__PURE__ */ Facet.define({
  combine: (values) => values.some((x2) => x2)
});
var ScrollTarget = class {
  constructor(range2, y2 = "nearest", x2 = "nearest", yMargin = 5, xMargin = 5) {
    this.range = range2;
    this.y = y2;
    this.x = x2;
    this.yMargin = yMargin;
    this.xMargin = xMargin;
  }
  map(changes) {
    return changes.empty ? this : new ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin);
  }
};
var scrollIntoView = /* @__PURE__ */ StateEffect.define({ map: (t4, ch) => t4.map(ch) });
function logException(state, exception, context) {
  let handler = state.facet(exceptionSink);
  if (handler.length)
    handler[0](exception);
  else if (window.onerror)
    window.onerror(String(exception), context, void 0, void 0, exception);
  else if (context)
    console.error(context + ":", exception);
  else
    console.error(exception);
}
var editable = /* @__PURE__ */ Facet.define({ combine: (values) => values.length ? values[0] : true });
var nextPluginID = 0;
var viewPlugin = /* @__PURE__ */ Facet.define();
var ViewPlugin = class {
  constructor(id, create2, domEventHandlers, buildExtensions) {
    this.id = id;
    this.create = create2;
    this.domEventHandlers = domEventHandlers;
    this.extension = buildExtensions(this);
  }
  static define(create2, spec) {
    const { eventHandlers, provide, decorations: deco } = spec || {};
    return new ViewPlugin(nextPluginID++, create2, eventHandlers, (plugin) => {
      let ext2 = [viewPlugin.of(plugin)];
      if (deco)
        ext2.push(decorations.of((view) => {
          let pluginInst = view.plugin(plugin);
          return pluginInst ? deco(pluginInst) : Decoration.none;
        }));
      if (provide)
        ext2.push(provide(plugin));
      return ext2;
    });
  }
  static fromClass(cls, spec) {
    return ViewPlugin.define((view) => new cls(view), spec);
  }
};
var PluginInstance = class {
  constructor(spec) {
    this.spec = spec;
    this.mustUpdate = null;
    this.value = null;
  }
  update(view) {
    if (!this.value) {
      if (this.spec) {
        try {
          this.value = this.spec.create(view);
        } catch (e3) {
          logException(view.state, e3, "CodeMirror plugin crashed");
          this.deactivate();
        }
      }
    } else if (this.mustUpdate) {
      let update2 = this.mustUpdate;
      this.mustUpdate = null;
      if (this.value.update) {
        try {
          this.value.update(update2);
        } catch (e3) {
          logException(update2.state, e3, "CodeMirror plugin crashed");
          if (this.value.destroy)
            try {
              this.value.destroy();
            } catch (_2) {
            }
          this.deactivate();
        }
      }
    }
    return this;
  }
  destroy(view) {
    var _a2;
    if ((_a2 = this.value) === null || _a2 === void 0 ? void 0 : _a2.destroy) {
      try {
        this.value.destroy();
      } catch (e3) {
        logException(view.state, e3, "CodeMirror plugin crashed");
      }
    }
  }
  deactivate() {
    this.spec = this.value = null;
  }
};
var editorAttributes = /* @__PURE__ */ Facet.define();
var contentAttributes = /* @__PURE__ */ Facet.define();
var decorations = /* @__PURE__ */ Facet.define();
var atomicRanges = /* @__PURE__ */ Facet.define();
var scrollMargins = /* @__PURE__ */ Facet.define();
var styleModule = /* @__PURE__ */ Facet.define();
var ChangedRange = class {
  constructor(fromA, toA, fromB, toB) {
    this.fromA = fromA;
    this.toA = toA;
    this.fromB = fromB;
    this.toB = toB;
  }
  join(other) {
    return new ChangedRange(Math.min(this.fromA, other.fromA), Math.max(this.toA, other.toA), Math.min(this.fromB, other.fromB), Math.max(this.toB, other.toB));
  }
  addToSet(set) {
    let i = set.length, me = this;
    for (; i > 0; i--) {
      let range2 = set[i - 1];
      if (range2.fromA > me.toA)
        continue;
      if (range2.toA < me.fromA)
        break;
      me = me.join(range2);
      set.splice(i - 1, 1);
    }
    set.splice(i, 0, me);
    return set;
  }
  static extendWithRanges(diff, ranges) {
    if (ranges.length == 0)
      return diff;
    let result = [];
    for (let dI = 0, rI = 0, posA = 0, posB = 0; ; dI++) {
      let next = dI == diff.length ? null : diff[dI], off = posA - posB;
      let end = next ? next.fromB : 1e9;
      while (rI < ranges.length && ranges[rI] < end) {
        let from = ranges[rI], to = ranges[rI + 1];
        let fromB = Math.max(posB, from), toB = Math.min(end, to);
        if (fromB <= toB)
          new ChangedRange(fromB + off, toB + off, fromB, toB).addToSet(result);
        if (to > end)
          break;
        else
          rI += 2;
      }
      if (!next)
        return result;
      new ChangedRange(next.fromA, next.toA, next.fromB, next.toB).addToSet(result);
      posA = next.toA;
      posB = next.toB;
    }
  }
};
var ViewUpdate = class {
  constructor(view, state, transactions) {
    this.view = view;
    this.state = state;
    this.transactions = transactions;
    this.flags = 0;
    this.startState = view.state;
    this.changes = ChangeSet.empty(this.startState.doc.length);
    for (let tr of transactions)
      this.changes = this.changes.compose(tr.changes);
    let changedRanges = [];
    this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB)));
    this.changedRanges = changedRanges;
    let focus = view.hasFocus;
    if (focus != view.inputState.notifiedFocused) {
      view.inputState.notifiedFocused = focus;
      this.flags |= 1;
    }
  }
  static create(view, state, transactions) {
    return new ViewUpdate(view, state, transactions);
  }
  get viewportChanged() {
    return (this.flags & 4) > 0;
  }
  get heightChanged() {
    return (this.flags & 2) > 0;
  }
  get geometryChanged() {
    return this.docChanged || (this.flags & (8 | 2)) > 0;
  }
  get focusChanged() {
    return (this.flags & 1) > 0;
  }
  get docChanged() {
    return !this.changes.empty;
  }
  get selectionSet() {
    return this.transactions.some((tr) => tr.selection);
  }
  get empty() {
    return this.flags == 0 && this.transactions.length == 0;
  }
};
var Direction = /* @__PURE__ */ function(Direction2) {
  Direction2[Direction2["LTR"] = 0] = "LTR";
  Direction2[Direction2["RTL"] = 1] = "RTL";
  return Direction2;
}(Direction || (Direction = {}));
var LTR = Direction.LTR;
var RTL = Direction.RTL;
function dec(str) {
  let result = [];
  for (let i = 0; i < str.length; i++)
    result.push(1 << +str[i]);
  return result;
}
var LowTypes = /* @__PURE__ */ dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008");
var ArabicTypes = /* @__PURE__ */ dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333");
var Brackets = /* @__PURE__ */ Object.create(null);
var BracketStack = [];
for (let p of ["()", "[]", "{}"]) {
  let l = /* @__PURE__ */ p.charCodeAt(0), r = /* @__PURE__ */ p.charCodeAt(1);
  Brackets[l] = r;
  Brackets[r] = -l;
}
function charType(ch) {
  return ch <= 247 ? LowTypes[ch] : 1424 <= ch && ch <= 1524 ? 2 : 1536 <= ch && ch <= 1785 ? ArabicTypes[ch - 1536] : 1774 <= ch && ch <= 2220 ? 4 : 8192 <= ch && ch <= 8203 ? 256 : 64336 <= ch && ch <= 65023 ? 4 : ch == 8204 ? 256 : 1;
}
var BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/;
var BidiSpan = class {
  constructor(from, to, level) {
    this.from = from;
    this.to = to;
    this.level = level;
  }
  get dir() {
    return this.level % 2 ? RTL : LTR;
  }
  side(end, dir) {
    return this.dir == dir == end ? this.to : this.from;
  }
  static find(order, index2, level, assoc) {
    let maybe = -1;
    for (let i = 0; i < order.length; i++) {
      let span = order[i];
      if (span.from <= index2 && span.to >= index2) {
        if (span.level == level)
          return i;
        if (maybe < 0 || (assoc != 0 ? assoc < 0 ? span.from < index2 : span.to > index2 : order[maybe].level > span.level))
          maybe = i;
      }
    }
    if (maybe < 0)
      throw new RangeError("Index out of range");
    return maybe;
  }
};
var types = [];
function computeOrder(line, direction) {
  let len = line.length, outerType = direction == LTR ? 1 : 2, oppositeType = direction == LTR ? 2 : 1;
  if (!line || outerType == 1 && !BidiRE.test(line))
    return trivialOrder(len);
  for (let i = 0, prev = outerType, prevStrong = outerType; i < len; i++) {
    let type = charType(line.charCodeAt(i));
    if (type == 512)
      type = prev;
    else if (type == 8 && prevStrong == 4)
      type = 16;
    types[i] = type == 4 ? 2 : type;
    if (type & 7)
      prevStrong = type;
    prev = type;
  }
  for (let i = 0, prev = outerType, prevStrong = outerType; i < len; i++) {
    let type = types[i];
    if (type == 128) {
      if (i < len - 1 && prev == types[i + 1] && prev & 24)
        type = types[i] = prev;
      else
        types[i] = 256;
    } else if (type == 64) {
      let end = i + 1;
      while (end < len && types[end] == 64)
        end++;
      let replace = i && prev == 8 || end < len && types[end] == 8 ? prevStrong == 1 ? 1 : 8 : 256;
      for (let j = i; j < end; j++)
        types[j] = replace;
      i = end - 1;
    } else if (type == 8 && prevStrong == 1) {
      types[i] = 1;
    }
    prev = type;
    if (type & 7)
      prevStrong = type;
  }
  for (let i = 0, sI = 0, context = 0, ch, br, type; i < len; i++) {
    if (br = Brackets[ch = line.charCodeAt(i)]) {
      if (br < 0) {
        for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
          if (BracketStack[sJ + 1] == -br) {
            let flags = BracketStack[sJ + 2];
            let type2 = flags & 2 ? outerType : !(flags & 4) ? 0 : flags & 1 ? oppositeType : outerType;
            if (type2)
              types[i] = types[BracketStack[sJ]] = type2;
            sI = sJ;
            break;
          }
        }
      } else if (BracketStack.length == 189) {
        break;
      } else {
        BracketStack[sI++] = i;
        BracketStack[sI++] = ch;
        BracketStack[sI++] = context;
      }
    } else if ((type = types[i]) == 2 || type == 1) {
      let embed = type == outerType;
      context = embed ? 0 : 1;
      for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
        let cur2 = BracketStack[sJ + 2];
        if (cur2 & 2)
          break;
        if (embed) {
          BracketStack[sJ + 2] |= 2;
        } else {
          if (cur2 & 4)
            break;
          BracketStack[sJ + 2] |= 4;
        }
      }
    }
  }
  for (let i = 0; i < len; i++) {
    if (types[i] == 256) {
      let end = i + 1;
      while (end < len && types[end] == 256)
        end++;
      let beforeL = (i ? types[i - 1] : outerType) == 1;
      let afterL = (end < len ? types[end] : outerType) == 1;
      let replace = beforeL == afterL ? beforeL ? 1 : 2 : outerType;
      for (let j = i; j < end; j++)
        types[j] = replace;
      i = end - 1;
    }
  }
  let order = [];
  if (outerType == 1) {
    for (let i = 0; i < len; ) {
      let start = i, rtl = types[i++] != 1;
      while (i < len && rtl == (types[i] != 1))
        i++;
      if (rtl) {
        for (let j = i; j > start; ) {
          let end = j, l = types[--j] != 2;
          while (j > start && l == (types[j - 1] != 2))
            j--;
          order.push(new BidiSpan(j, end, l ? 2 : 1));
        }
      } else {
        order.push(new BidiSpan(start, i, 0));
      }
    }
  } else {
    for (let i = 0; i < len; ) {
      let start = i, rtl = types[i++] == 2;
      while (i < len && rtl == (types[i] == 2))
        i++;
      order.push(new BidiSpan(start, i, rtl ? 1 : 2));
    }
  }
  return order;
}
function trivialOrder(length) {
  return [new BidiSpan(0, length, 0)];
}
var movedOver = "";
function moveVisually(line, order, dir, start, forward) {
  var _a2;
  let startIndex = start.head - line.from, spanI = -1;
  if (startIndex == 0) {
    if (!forward || !line.length)
      return null;
    if (order[0].level != dir) {
      startIndex = order[0].side(false, dir);
      spanI = 0;
    }
  } else if (startIndex == line.length) {
    if (forward)
      return null;
    let last = order[order.length - 1];
    if (last.level != dir) {
      startIndex = last.side(true, dir);
      spanI = order.length - 1;
    }
  }
  if (spanI < 0)
    spanI = BidiSpan.find(order, startIndex, (_a2 = start.bidiLevel) !== null && _a2 !== void 0 ? _a2 : -1, start.assoc);
  let span = order[spanI];
  if (startIndex == span.side(forward, dir)) {
    span = order[spanI += forward ? 1 : -1];
    startIndex = span.side(!forward, dir);
  }
  let indexForward = forward == (span.dir == dir);
  let nextIndex = findClusterBreak(line.text, startIndex, indexForward);
  movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex));
  if (nextIndex != span.side(forward, dir))
    return EditorSelection.cursor(nextIndex + line.from, indexForward ? -1 : 1, span.level);
  let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)];
  if (!nextSpan && span.level != dir)
    return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1, dir);
  if (nextSpan && nextSpan.level < span.level)
    return EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, forward ? 1 : -1, nextSpan.level);
  return EditorSelection.cursor(nextIndex + line.from, forward ? -1 : 1, span.level);
}
var LineBreakPlaceholder = "\uFFFF";
var DOMReader = class {
  constructor(points, state) {
    this.points = points;
    this.text = "";
    this.lineSeparator = state.facet(EditorState.lineSeparator);
  }
  append(text2) {
    this.text += text2;
  }
  lineBreak() {
    this.text += LineBreakPlaceholder;
  }
  readRange(start, end) {
    if (!start)
      return this;
    let parent2 = start.parentNode;
    for (let cur2 = start; ; ) {
      this.findPointBefore(parent2, cur2);
      this.readNode(cur2);
      let next = cur2.nextSibling;
      if (next == end)
        break;
      let view = ContentView.get(cur2), nextView = ContentView.get(next);
      if (view && nextView ? view.breakAfter : (view ? view.breakAfter : isBlockElement(cur2)) || isBlockElement(next) && (cur2.nodeName != "BR" || cur2.cmIgnore))
        this.lineBreak();
      cur2 = next;
    }
    this.findPointBefore(parent2, end);
    return this;
  }
  readTextNode(node) {
    let text2 = node.nodeValue;
    for (let point2 of this.points)
      if (point2.node == node)
        point2.pos = this.text.length + Math.min(point2.offset, text2.length);
    for (let off = 0, re2 = this.lineSeparator ? null : /\r\n?|\n/g; ; ) {
      let nextBreak = -1, breakSize = 1, m;
      if (this.lineSeparator) {
        nextBreak = text2.indexOf(this.lineSeparator, off);
        breakSize = this.lineSeparator.length;
      } else if (m = re2.exec(text2)) {
        nextBreak = m.index;
        breakSize = m[0].length;
      }
      this.append(text2.slice(off, nextBreak < 0 ? text2.length : nextBreak));
      if (nextBreak < 0)
        break;
      this.lineBreak();
      if (breakSize > 1) {
        for (let point2 of this.points)
          if (point2.node == node && point2.pos > this.text.length)
            point2.pos -= breakSize - 1;
      }
      off = nextBreak + breakSize;
    }
  }
  readNode(node) {
    if (node.cmIgnore)
      return;
    let view = ContentView.get(node);
    let fromView = view && view.overrideDOMText;
    if (fromView != null) {
      this.findPointInside(node, fromView.length);
      for (let i = fromView.iter(); !i.next().done; ) {
        if (i.lineBreak)
          this.lineBreak();
        else
          this.append(i.value);
      }
    } else if (node.nodeType == 3) {
      this.readTextNode(node);
    } else if (node.nodeName == "BR") {
      if (node.nextSibling)
        this.lineBreak();
    } else if (node.nodeType == 1) {
      this.readRange(node.firstChild, null);
    }
  }
  findPointBefore(node, next) {
    for (let point2 of this.points)
      if (point2.node == node && node.childNodes[point2.offset] == next)
        point2.pos = this.text.length;
  }
  findPointInside(node, maxLen) {
    for (let point2 of this.points)
      if (node.nodeType == 3 ? point2.node == node : node.contains(point2.node))
        point2.pos = this.text.length + Math.min(maxLen, point2.offset);
  }
};
function isBlockElement(node) {
  return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName);
}
var DOMPoint = class {
  constructor(node, offset) {
    this.node = node;
    this.offset = offset;
    this.pos = -1;
  }
};
var DocView = class extends ContentView {
  constructor(view) {
    super();
    this.view = view;
    this.compositionDeco = Decoration.none;
    this.decorations = [];
    this.dynamicDecorationMap = [];
    this.minWidth = 0;
    this.minWidthFrom = 0;
    this.minWidthTo = 0;
    this.impreciseAnchor = null;
    this.impreciseHead = null;
    this.forceSelection = false;
    this.lastUpdate = Date.now();
    this.setDOM(view.contentDOM);
    this.children = [new LineView()];
    this.children[0].setParent(this);
    this.updateDeco();
    this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], 0);
  }
  get editorView() {
    return this.view;
  }
  get length() {
    return this.view.state.doc.length;
  }
  update(update2) {
    let changedRanges = update2.changedRanges;
    if (this.minWidth > 0 && changedRanges.length) {
      if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) {
        this.minWidth = this.minWidthFrom = this.minWidthTo = 0;
      } else {
        this.minWidthFrom = update2.changes.mapPos(this.minWidthFrom, 1);
        this.minWidthTo = update2.changes.mapPos(this.minWidthTo, 1);
      }
    }
    if (this.view.inputState.composing < 0)
      this.compositionDeco = Decoration.none;
    else if (update2.transactions.length || this.dirty)
      this.compositionDeco = computeCompositionDeco(this.view, update2.changes);
    if ((browser.ie || browser.chrome) && !this.compositionDeco.size && update2 && update2.state.doc.lines != update2.startState.doc.lines)
      this.forceSelection = true;
    let prevDeco = this.decorations, deco = this.updateDeco();
    let decoDiff = findChangedDeco(prevDeco, deco, update2.changes);
    changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff);
    if (this.dirty == 0 && changedRanges.length == 0) {
      return false;
    } else {
      this.updateInner(changedRanges, update2.startState.doc.length);
      if (update2.transactions.length)
        this.lastUpdate = Date.now();
      return true;
    }
  }
  updateInner(changes, oldLength) {
    this.view.viewState.mustMeasureContent = true;
    this.updateChildren(changes, oldLength);
    let { observer } = this.view;
    observer.ignore(() => {
      this.dom.style.height = this.view.viewState.contentHeight + "px";
      this.dom.style.flexBasis = this.minWidth ? this.minWidth + "px" : "";
      let track = browser.chrome || browser.ios ? { node: observer.selectionRange.focusNode, written: false } : void 0;
      this.sync(track);
      this.dirty = 0;
      if (track && (track.written || observer.selectionRange.focusNode != track.node))
        this.forceSelection = true;
      this.dom.style.height = "";
    });
    let gaps = [];
    if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length) {
      for (let child of this.children)
        if (child instanceof BlockWidgetView && child.widget instanceof BlockGapWidget)
          gaps.push(child.dom);
    }
    observer.updateGaps(gaps);
  }
  updateChildren(changes, oldLength) {
    let cursor = this.childCursor(oldLength);
    for (let i = changes.length - 1; ; i--) {
      let next = i >= 0 ? changes[i] : null;
      if (!next)
        break;
      let { fromA, toA, fromB, toB } = next;
      let { content: content2, breakAtStart, openStart, openEnd } = ContentBuilder.build(this.view.state.doc, fromB, toB, this.decorations, this.dynamicDecorationMap);
      let { i: toI, off: toOff } = cursor.findPos(toA, 1);
      let { i: fromI, off: fromOff } = cursor.findPos(fromA, -1);
      replaceRange(this, fromI, fromOff, toI, toOff, content2, breakAtStart, openStart, openEnd);
    }
  }
  updateSelection(mustRead = false, fromPointer = false) {
    if (mustRead || !this.view.observer.selectionRange.focusNode)
      this.view.observer.readSelectionRange();
    if (!(fromPointer || this.mayControlSelection()))
      return;
    let force = this.forceSelection;
    this.forceSelection = false;
    let main = this.view.state.selection.main;
    let anchor = this.domAtPos(main.anchor);
    let head = main.empty ? anchor : this.domAtPos(main.head);
    if (browser.gecko && main.empty && betweenUneditable(anchor)) {
      let dummy = document.createTextNode("");
      this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null));
      anchor = head = new DOMPos(dummy, 0);
      force = true;
    }
    let domSel = this.view.observer.selectionRange;
    if (force || !domSel.focusNode || !isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) || !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) {
      this.view.observer.ignore(() => {
        if (browser.android && browser.chrome && this.dom.contains(domSel.focusNode) && inUneditable(domSel.focusNode, this.dom)) {
          this.dom.blur();
          this.dom.focus({ preventScroll: true });
        }
        let rawSel = getSelection(this.view.root);
        if (!rawSel)
          ;
        else if (main.empty) {
          if (browser.gecko) {
            let nextTo = nextToUneditable(anchor.node, anchor.offset);
            if (nextTo && nextTo != (1 | 2)) {
              let text2 = nearbyTextNode(anchor.node, anchor.offset, nextTo == 1 ? 1 : -1);
              if (text2)
                anchor = new DOMPos(text2, nextTo == 1 ? 0 : text2.nodeValue.length);
            }
          }
          rawSel.collapse(anchor.node, anchor.offset);
          if (main.bidiLevel != null && domSel.cursorBidiLevel != null)
            domSel.cursorBidiLevel = main.bidiLevel;
        } else if (rawSel.extend) {
          rawSel.collapse(anchor.node, anchor.offset);
          try {
            rawSel.extend(head.node, head.offset);
          } catch (_2) {
          }
        } else {
          let range2 = document.createRange();
          if (main.anchor > main.head)
            [anchor, head] = [head, anchor];
          range2.setEnd(head.node, head.offset);
          range2.setStart(anchor.node, anchor.offset);
          rawSel.removeAllRanges();
          rawSel.addRange(range2);
        }
      });
      this.view.observer.setSelectionRange(anchor, head);
    }
    this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset);
    this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset);
  }
  enforceCursorAssoc() {
    if (this.compositionDeco.size)
      return;
    let cursor = this.view.state.selection.main;
    let sel = getSelection(this.view.root);
    if (!sel || !cursor.empty || !cursor.assoc || !sel.modify)
      return;
    let line = LineView.find(this, cursor.head);
    if (!line)
      return;
    let lineStart = line.posAtStart;
    if (cursor.head == lineStart || cursor.head == lineStart + line.length)
      return;
    let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1);
    if (!before || !after || before.bottom > after.top)
      return;
    let dom = this.domAtPos(cursor.head + cursor.assoc);
    sel.collapse(dom.node, dom.offset);
    sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary");
  }
  mayControlSelection() {
    let active = this.view.root.activeElement;
    return active == this.dom || hasSelection(this.dom, this.view.observer.selectionRange) && !(active && this.dom.contains(active));
  }
  nearest(dom) {
    for (let cur2 = dom; cur2; ) {
      let domView = ContentView.get(cur2);
      if (domView && domView.rootView == this)
        return domView;
      cur2 = cur2.parentNode;
    }
    return null;
  }
  posFromDOM(node, offset) {
    let view = this.nearest(node);
    if (!view)
      throw new RangeError("Trying to find position for a DOM position outside of the document");
    return view.localPosFromDOM(node, offset) + view.posAtStart;
  }
  domAtPos(pos) {
    let { i, off } = this.childCursor().findPos(pos, -1);
    for (; i < this.children.length - 1; ) {
      let child = this.children[i];
      if (off < child.length || child instanceof LineView)
        break;
      i++;
      off = 0;
    }
    return this.children[i].domAtPos(off);
  }
  coordsAt(pos, side) {
    for (let off = this.length, i = this.children.length - 1; ; i--) {
      let child = this.children[i], start = off - child.breakAfter - child.length;
      if (pos > start || pos == start && child.type != BlockType.WidgetBefore && child.type != BlockType.WidgetAfter && (!i || side == 2 || this.children[i - 1].breakAfter || this.children[i - 1].type == BlockType.WidgetBefore && side > -2))
        return child.coordsAt(pos - start, side);
      off = start;
    }
  }
  measureVisibleLineHeights(viewport) {
    let result = [], { from, to } = viewport;
    let contentWidth = this.view.contentDOM.clientWidth;
    let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1;
    let widest = -1, ltr = this.view.textDirection == Direction.LTR;
    for (let pos = 0, i = 0; i < this.children.length; i++) {
      let child = this.children[i], end = pos + child.length;
      if (end > to)
        break;
      if (pos >= from) {
        let childRect = child.dom.getBoundingClientRect();
        result.push(childRect.height);
        if (isWider) {
          let last = child.dom.lastChild;
          let rects = last ? clientRectsFor(last) : [];
          if (rects.length) {
            let rect = rects[rects.length - 1];
            let width = ltr ? rect.right - childRect.left : childRect.right - rect.left;
            if (width > widest) {
              widest = width;
              this.minWidth = contentWidth;
              this.minWidthFrom = pos;
              this.minWidthTo = end;
            }
          }
        }
      }
      pos = end + child.breakAfter;
    }
    return result;
  }
  textDirectionAt(pos) {
    let { i } = this.childPos(pos, 1);
    return getComputedStyle(this.children[i].dom).direction == "rtl" ? Direction.RTL : Direction.LTR;
  }
  measureTextSize() {
    for (let child of this.children) {
      if (child instanceof LineView) {
        let measure = child.measureTextSize();
        if (measure)
          return measure;
      }
    }
    let dummy = document.createElement("div"), lineHeight, charWidth;
    dummy.className = "cm-line";
    dummy.style.width = "99999px";
    dummy.textContent = "abc def ghi jkl mno pqr stu";
    this.view.observer.ignore(() => {
      this.dom.appendChild(dummy);
      let rect = clientRectsFor(dummy.firstChild)[0];
      lineHeight = dummy.getBoundingClientRect().height;
      charWidth = rect ? rect.width / 27 : 7;
      dummy.remove();
    });
    return { lineHeight, charWidth };
  }
  childCursor(pos = this.length) {
    let i = this.children.length;
    if (i)
      pos -= this.children[--i].length;
    return new ChildCursor(this.children, pos, i);
  }
  computeBlockGapDeco() {
    let deco = [], vs = this.view.viewState;
    for (let pos = 0, i = 0; ; i++) {
      let next = i == vs.viewports.length ? null : vs.viewports[i];
      let end = next ? next.from - 1 : this.length;
      if (end > pos) {
        let height4 = vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top;
        deco.push(Decoration.replace({
          widget: new BlockGapWidget(height4),
          block: true,
          inclusive: true,
          isBlockGap: true
        }).range(pos, end));
      }
      if (!next)
        break;
      pos = next.to + 1;
    }
    return Decoration.set(deco);
  }
  updateDeco() {
    let allDeco = this.view.state.facet(decorations).map((d, i) => {
      let dynamic = this.dynamicDecorationMap[i] = typeof d == "function";
      return dynamic ? d(this.view) : d;
    });
    for (let i = allDeco.length; i < allDeco.length + 3; i++)
      this.dynamicDecorationMap[i] = false;
    return this.decorations = [
      ...allDeco,
      this.compositionDeco,
      this.computeBlockGapDeco(),
      this.view.viewState.lineGapDeco
    ];
  }
  scrollIntoView(target) {
    let { range: range2 } = target;
    let rect = this.coordsAt(range2.head, range2.empty ? range2.assoc : range2.head > range2.anchor ? -1 : 1), other;
    if (!rect)
      return;
    if (!range2.empty && (other = this.coordsAt(range2.anchor, range2.anchor > range2.head ? -1 : 1)))
      rect = {
        left: Math.min(rect.left, other.left),
        top: Math.min(rect.top, other.top),
        right: Math.max(rect.right, other.right),
        bottom: Math.max(rect.bottom, other.bottom)
      };
    let mLeft = 0, mRight = 0, mTop = 0, mBottom = 0;
    for (let margins of this.view.state.facet(scrollMargins).map((f) => f(this.view)))
      if (margins) {
        let { left: left2, right: right2, top: top3, bottom: bottom2 } = margins;
        if (left2 != null)
          mLeft = Math.max(mLeft, left2);
        if (right2 != null)
          mRight = Math.max(mRight, right2);
        if (top3 != null)
          mTop = Math.max(mTop, top3);
        if (bottom2 != null)
          mBottom = Math.max(mBottom, bottom2);
      }
    let targetRect = {
      left: rect.left - mLeft,
      top: rect.top - mTop,
      right: rect.right + mRight,
      bottom: rect.bottom + mBottom
    };
    scrollRectIntoView(this.view.scrollDOM, targetRect, range2.head < range2.anchor ? -1 : 1, target.x, target.y, target.xMargin, target.yMargin, this.view.textDirection == Direction.LTR);
  }
};
function betweenUneditable(pos) {
  return pos.node.nodeType == 1 && pos.node.firstChild && (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") && (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == "false");
}
var BlockGapWidget = class extends WidgetType {
  constructor(height4) {
    super();
    this.height = height4;
  }
  toDOM() {
    let elt = document.createElement("div");
    this.updateDOM(elt);
    return elt;
  }
  eq(other) {
    return other.height == this.height;
  }
  updateDOM(elt) {
    elt.style.height = this.height + "px";
    return true;
  }
  get estimatedHeight() {
    return this.height;
  }
};
function compositionSurroundingNode(view) {
  let sel = view.observer.selectionRange;
  let textNode = sel.focusNode && nearbyTextNode(sel.focusNode, sel.focusOffset, 0);
  if (!textNode)
    return null;
  let cView = view.docView.nearest(textNode);
  if (!cView)
    return null;
  if (cView instanceof LineView) {
    let topNode = textNode;
    while (topNode.parentNode != cView.dom)
      topNode = topNode.parentNode;
    let prev = topNode.previousSibling;
    while (prev && !ContentView.get(prev))
      prev = prev.previousSibling;
    let pos = prev ? ContentView.get(prev).posAtEnd : cView.posAtStart;
    return { from: pos, to: pos, node: topNode, text: textNode };
  } else {
    for (; ; ) {
      let { parent: parent2 } = cView;
      if (!parent2)
        return null;
      if (parent2 instanceof LineView)
        break;
      cView = parent2;
    }
    let from = cView.posAtStart;
    return { from, to: from + cView.length, node: cView.dom, text: textNode };
  }
}
function computeCompositionDeco(view, changes) {
  let surrounding = compositionSurroundingNode(view);
  if (!surrounding)
    return Decoration.none;
  let { from, to, node, text: textNode } = surrounding;
  let newFrom = changes.mapPos(from, 1), newTo = Math.max(newFrom, changes.mapPos(to, -1));
  let { state } = view, text2 = node.nodeType == 3 ? node.nodeValue : new DOMReader([], state).readRange(node.firstChild, null).text;
  if (newTo - newFrom < text2.length) {
    if (state.doc.sliceString(newFrom, Math.min(state.doc.length, newFrom + text2.length), LineBreakPlaceholder) == text2)
      newTo = newFrom + text2.length;
    else if (state.doc.sliceString(Math.max(0, newTo - text2.length), newTo, LineBreakPlaceholder) == text2)
      newFrom = newTo - text2.length;
    else
      return Decoration.none;
  } else if (state.doc.sliceString(newFrom, newTo, LineBreakPlaceholder) != text2) {
    return Decoration.none;
  }
  let topView = ContentView.get(node);
  if (topView instanceof CompositionView)
    topView = topView.widget.topView;
  else if (topView)
    topView.parent = null;
  return Decoration.set(Decoration.replace({ widget: new CompositionWidget(node, textNode, topView), inclusive: true }).range(newFrom, newTo));
}
var CompositionWidget = class extends WidgetType {
  constructor(top3, text2, topView) {
    super();
    this.top = top3;
    this.text = text2;
    this.topView = topView;
  }
  eq(other) {
    return this.top == other.top && this.text == other.text;
  }
  toDOM() {
    return this.top;
  }
  ignoreEvent() {
    return false;
  }
  get customView() {
    return CompositionView;
  }
};
function nearbyTextNode(node, offset, side) {
  for (; ; ) {
    if (node.nodeType == 3)
      return node;
    if (node.nodeType == 1 && offset > 0 && side <= 0) {
      node = node.childNodes[offset - 1];
      offset = maxOffset(node);
    } else if (node.nodeType == 1 && offset < node.childNodes.length && side >= 0) {
      node = node.childNodes[offset];
      offset = 0;
    } else {
      return null;
    }
  }
}
function nextToUneditable(node, offset) {
  if (node.nodeType != 1)
    return 0;
  return (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 : 0) | (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 : 0);
}
var DecorationComparator$1 = class {
  constructor() {
    this.changes = [];
  }
  compareRange(from, to) {
    addRange(from, to, this.changes);
  }
  comparePoint(from, to) {
    addRange(from, to, this.changes);
  }
};
function findChangedDeco(a, b, diff) {
  let comp = new DecorationComparator$1();
  RangeSet.compare(a, b, diff, comp);
  return comp.changes;
}
function inUneditable(node, inside2) {
  for (let cur2 = node; cur2 && cur2 != inside2; cur2 = cur2.assignedSlot || cur2.parentNode) {
    if (cur2.nodeType == 1 && cur2.contentEditable == "false") {
      return true;
    }
  }
  return false;
}
function groupAt(state, pos, bias = 1) {
  let categorize = state.charCategorizer(pos);
  let line = state.doc.lineAt(pos), linePos = pos - line.from;
  if (line.length == 0)
    return EditorSelection.cursor(pos);
  if (linePos == 0)
    bias = 1;
  else if (linePos == line.length)
    bias = -1;
  let from = linePos, to = linePos;
  if (bias < 0)
    from = findClusterBreak(line.text, linePos, false);
  else
    to = findClusterBreak(line.text, linePos);
  let cat = categorize(line.text.slice(from, to));
  while (from > 0) {
    let prev = findClusterBreak(line.text, from, false);
    if (categorize(line.text.slice(prev, from)) != cat)
      break;
    from = prev;
  }
  while (to < line.length) {
    let next = findClusterBreak(line.text, to);
    if (categorize(line.text.slice(to, next)) != cat)
      break;
    to = next;
  }
  return EditorSelection.range(from + line.from, to + line.from);
}
function getdx(x2, rect) {
  return rect.left > x2 ? rect.left - x2 : Math.max(0, x2 - rect.right);
}
function getdy(y2, rect) {
  return rect.top > y2 ? rect.top - y2 : Math.max(0, y2 - rect.bottom);
}
function yOverlap(a, b) {
  return a.top < b.bottom - 1 && a.bottom > b.top + 1;
}
function upTop(rect, top3) {
  return top3 < rect.top ? { top: top3, left: rect.left, right: rect.right, bottom: rect.bottom } : rect;
}
function upBot(rect, bottom2) {
  return bottom2 > rect.bottom ? { top: rect.top, left: rect.left, right: rect.right, bottom: bottom2 } : rect;
}
function domPosAtCoords(parent2, x2, y2) {
  let closest, closestRect, closestX, closestY, closestOverlap = false;
  let above, below, aboveRect, belowRect;
  for (let child = parent2.firstChild; child; child = child.nextSibling) {
    let rects = clientRectsFor(child);
    for (let i = 0; i < rects.length; i++) {
      let rect = rects[i];
      if (closestRect && yOverlap(closestRect, rect))
        rect = upTop(upBot(rect, closestRect.bottom), closestRect.top);
      let dx = getdx(x2, rect), dy = getdy(y2, rect);
      if (dx == 0 && dy == 0)
        return child.nodeType == 3 ? domPosInText(child, x2, y2) : domPosAtCoords(child, x2, y2);
      if (!closest || closestY > dy || closestY == dy && closestX > dx) {
        closest = child;
        closestRect = rect;
        closestX = dx;
        closestY = dy;
        closestOverlap = !dx || (dx > 0 ? i < rects.length - 1 : i > 0);
      }
      if (dx == 0) {
        if (y2 > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) {
          above = child;
          aboveRect = rect;
        } else if (y2 < rect.top && (!belowRect || belowRect.top > rect.top)) {
          below = child;
          belowRect = rect;
        }
      } else if (aboveRect && yOverlap(aboveRect, rect)) {
        aboveRect = upBot(aboveRect, rect.bottom);
      } else if (belowRect && yOverlap(belowRect, rect)) {
        belowRect = upTop(belowRect, rect.top);
      }
    }
  }
  if (aboveRect && aboveRect.bottom >= y2) {
    closest = above;
    closestRect = aboveRect;
  } else if (belowRect && belowRect.top <= y2) {
    closest = below;
    closestRect = belowRect;
  }
  if (!closest)
    return { node: parent2, offset: 0 };
  let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x2));
  if (closest.nodeType == 3)
    return domPosInText(closest, clipX, y2);
  if (closestOverlap && closest.contentEditable != "false")
    return domPosAtCoords(closest, clipX, y2);
  let offset = Array.prototype.indexOf.call(parent2.childNodes, closest) + (x2 >= (closestRect.left + closestRect.right) / 2 ? 1 : 0);
  return { node: parent2, offset };
}
function domPosInText(node, x2, y2) {
  let len = node.nodeValue.length;
  let closestOffset = -1, closestDY = 1e9, generalSide = 0;
  for (let i = 0; i < len; i++) {
    let rects = textRange(node, i, i + 1).getClientRects();
    for (let j = 0; j < rects.length; j++) {
      let rect = rects[j];
      if (rect.top == rect.bottom)
        continue;
      if (!generalSide)
        generalSide = x2 - rect.left;
      let dy = (rect.top > y2 ? rect.top - y2 : y2 - rect.bottom) - 1;
      if (rect.left - 1 <= x2 && rect.right + 1 >= x2 && dy < closestDY) {
        let right2 = x2 >= (rect.left + rect.right) / 2, after = right2;
        if (browser.chrome || browser.gecko) {
          let rectBefore = textRange(node, i).getBoundingClientRect();
          if (rectBefore.left == rect.right)
            after = !right2;
        }
        if (dy <= 0)
          return { node, offset: i + (after ? 1 : 0) };
        closestOffset = i + (after ? 1 : 0);
        closestDY = dy;
      }
    }
  }
  return { node, offset: closestOffset > -1 ? closestOffset : generalSide > 0 ? node.nodeValue.length : 0 };
}
function posAtCoords(view, { x: x2, y: y2 }, precise, bias = -1) {
  var _a2;
  let content2 = view.contentDOM.getBoundingClientRect(), docTop = content2.top + view.viewState.paddingTop;
  let block, { docHeight } = view.viewState;
  let yOffset = y2 - docTop;
  if (yOffset < 0)
    return 0;
  if (yOffset > docHeight)
    return view.state.doc.length;
  for (let halfLine = view.defaultLineHeight / 2, bounced = false; ; ) {
    block = view.elementAtHeight(yOffset);
    if (block.type == BlockType.Text)
      break;
    for (; ; ) {
      yOffset = bias > 0 ? block.bottom + halfLine : block.top - halfLine;
      if (yOffset >= 0 && yOffset <= docHeight)
        break;
      if (bounced)
        return precise ? null : 0;
      bounced = true;
      bias = -bias;
    }
  }
  y2 = docTop + yOffset;
  let lineStart = block.from;
  if (lineStart < view.viewport.from)
    return view.viewport.from == 0 ? 0 : precise ? null : posAtCoordsImprecise(view, content2, block, x2, y2);
  if (lineStart > view.viewport.to)
    return view.viewport.to == view.state.doc.length ? view.state.doc.length : precise ? null : posAtCoordsImprecise(view, content2, block, x2, y2);
  let doc2 = view.dom.ownerDocument;
  let root2 = view.root.elementFromPoint ? view.root : doc2;
  let element2 = root2.elementFromPoint(x2, y2);
  if (element2 && !view.contentDOM.contains(element2))
    element2 = null;
  if (!element2) {
    x2 = Math.max(content2.left + 1, Math.min(content2.right - 1, x2));
    element2 = root2.elementFromPoint(x2, y2);
    if (element2 && !view.contentDOM.contains(element2))
      element2 = null;
  }
  let node, offset = -1;
  if (element2 && ((_a2 = view.docView.nearest(element2)) === null || _a2 === void 0 ? void 0 : _a2.isEditable) != false) {
    if (doc2.caretPositionFromPoint) {
      let pos = doc2.caretPositionFromPoint(x2, y2);
      if (pos)
        ({ offsetNode: node, offset } = pos);
    } else if (doc2.caretRangeFromPoint) {
      let range2 = doc2.caretRangeFromPoint(x2, y2);
      if (range2) {
        ({ startContainer: node, startOffset: offset } = range2);
        if (!view.contentDOM.contains(node) || browser.safari && isSuspiciousSafariCaretResult(node, offset, x2) || browser.chrome && isSuspiciousChromeCaretResult(node, offset, x2))
          node = void 0;
      }
    }
  }
  if (!node || !view.docView.dom.contains(node)) {
    let line = LineView.find(view.docView, lineStart);
    if (!line)
      return yOffset > block.top + block.height / 2 ? block.to : block.from;
    ({ node, offset } = domPosAtCoords(line.dom, x2, y2));
  }
  return view.docView.posFromDOM(node, offset);
}
function posAtCoordsImprecise(view, contentRect, block, x2, y2) {
  let into = Math.round((x2 - contentRect.left) * view.defaultCharacterWidth);
  if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) {
    let line = Math.floor((y2 - block.top) / view.defaultLineHeight);
    into += line * view.viewState.heightOracle.lineLength;
  }
  let content2 = view.state.sliceDoc(block.from, block.to);
  return block.from + findColumn(content2, into, view.state.tabSize);
}
function isSuspiciousSafariCaretResult(node, offset, x2) {
  let len;
  if (node.nodeType != 3 || offset != (len = node.nodeValue.length))
    return false;
  for (let next = node.nextSibling; next; next = next.nextSibling)
    if (next.nodeType != 1 || next.nodeName != "BR")
      return false;
  return textRange(node, len - 1, len).getBoundingClientRect().left > x2;
}
function isSuspiciousChromeCaretResult(node, offset, x2) {
  if (offset != 0)
    return false;
  for (let cur2 = node; ; ) {
    let parent2 = cur2.parentNode;
    if (!parent2 || parent2.nodeType != 1 || parent2.firstChild != cur2)
      return false;
    if (parent2.classList.contains("cm-line"))
      break;
    cur2 = parent2;
  }
  let rect = node.nodeType == 1 ? node.getBoundingClientRect() : textRange(node, 0, Math.max(node.nodeValue.length, 1)).getBoundingClientRect();
  return x2 - rect.left > 5;
}
function moveToLineBoundary(view, start, forward, includeWrap) {
  let line = view.state.doc.lineAt(start.head);
  let coords = !includeWrap || !view.lineWrapping ? null : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head);
  if (coords) {
    let editorRect = view.dom.getBoundingClientRect();
    let direction = view.textDirectionAt(line.from);
    let pos = view.posAtCoords({
      x: forward == (direction == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1,
      y: (coords.top + coords.bottom) / 2
    });
    if (pos != null)
      return EditorSelection.cursor(pos, forward ? -1 : 1);
  }
  let lineView = LineView.find(view.docView, start.head);
  let end = lineView ? forward ? lineView.posAtEnd : lineView.posAtStart : forward ? line.to : line.from;
  return EditorSelection.cursor(end, forward ? -1 : 1);
}
function moveByChar(view, start, forward, by) {
  let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line);
  let direction = view.textDirectionAt(line.from);
  for (let cur2 = start, check = null; ; ) {
    let next = moveVisually(line, spans, direction, cur2, forward), char = movedOver;
    if (!next) {
      if (line.number == (forward ? view.state.doc.lines : 1))
        return cur2;
      char = "\n";
      line = view.state.doc.line(line.number + (forward ? 1 : -1));
      spans = view.bidiSpans(line);
      next = EditorSelection.cursor(forward ? line.from : line.to);
    }
    if (!check) {
      if (!by)
        return next;
      check = by(char);
    } else if (!check(char)) {
      return cur2;
    }
    cur2 = next;
  }
}
function byGroup(view, pos, start) {
  let categorize = view.state.charCategorizer(pos);
  let cat = categorize(start);
  return (next) => {
    let nextCat = categorize(next);
    if (cat == CharCategory.Space)
      cat = nextCat;
    return cat == nextCat;
  };
}
function moveVertically(view, start, forward, distance) {
  let startPos = start.head, dir = forward ? 1 : -1;
  if (startPos == (forward ? view.state.doc.length : 0))
    return EditorSelection.cursor(startPos, start.assoc);
  let goal = start.goalColumn, startY;
  let rect = view.contentDOM.getBoundingClientRect();
  let startCoords = view.coordsAtPos(startPos), docTop = view.documentTop;
  if (startCoords) {
    if (goal == null)
      goal = startCoords.left - rect.left;
    startY = dir < 0 ? startCoords.top : startCoords.bottom;
  } else {
    let line = view.viewState.lineBlockAt(startPos);
    if (goal == null)
      goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from));
    startY = (dir < 0 ? line.top : line.bottom) + docTop;
  }
  let resolvedGoal = rect.left + goal;
  let dist = distance !== null && distance !== void 0 ? distance : view.defaultLineHeight >> 1;
  for (let extra = 0; ; extra += 10) {
    let curY = startY + (dist + extra) * dir;
    let pos = posAtCoords(view, { x: resolvedGoal, y: curY }, false, dir);
    if (curY < rect.top || curY > rect.bottom || (dir < 0 ? pos < startPos : pos > startPos))
      return EditorSelection.cursor(pos, start.assoc, void 0, goal);
  }
}
function skipAtoms(view, oldPos, pos) {
  let atoms = view.state.facet(atomicRanges).map((f) => f(view));
  for (; ; ) {
    let moved = false;
    for (let set of atoms) {
      set.between(pos.from - 1, pos.from + 1, (from, to, value) => {
        if (pos.from > from && pos.from < to) {
          pos = oldPos.head > pos.from ? EditorSelection.cursor(from, 1) : EditorSelection.cursor(to, -1);
          moved = true;
        }
      });
    }
    if (!moved)
      return pos;
  }
}
var InputState = class {
  constructor(view) {
    this.lastKeyCode = 0;
    this.lastKeyTime = 0;
    this.lastTouchTime = 0;
    this.lastFocusTime = 0;
    this.lastScrollTop = 0;
    this.lastScrollLeft = 0;
    this.chromeScrollHack = -1;
    this.pendingIOSKey = void 0;
    this.lastSelectionOrigin = null;
    this.lastSelectionTime = 0;
    this.lastEscPress = 0;
    this.lastContextMenu = 0;
    this.scrollHandlers = [];
    this.registeredEvents = [];
    this.customHandlers = [];
    this.composing = -1;
    this.compositionFirstChange = null;
    this.compositionEndedAt = 0;
    this.mouseSelection = null;
    for (let type in handlers) {
      let handler = handlers[type];
      view.contentDOM.addEventListener(type, (event) => {
        if (!eventBelongsToEditor(view, event) || this.ignoreDuringComposition(event))
          return;
        if (type == "keydown" && this.keydown(view, event))
          return;
        if (this.mustFlushObserver(event))
          view.observer.forceFlush();
        if (this.runCustomHandlers(type, view, event))
          event.preventDefault();
        else
          handler(view, event);
      }, handlerOptions[type]);
      this.registeredEvents.push(type);
    }
    if (browser.chrome && browser.chrome_version == 102) {
      view.scrollDOM.addEventListener("wheel", () => {
        if (this.chromeScrollHack < 0)
          view.contentDOM.style.pointerEvents = "none";
        else
          window.clearTimeout(this.chromeScrollHack);
        this.chromeScrollHack = setTimeout(() => {
          this.chromeScrollHack = -1;
          view.contentDOM.style.pointerEvents = "";
        }, 100);
      }, { passive: true });
    }
    this.notifiedFocused = view.hasFocus;
    if (browser.safari)
      view.contentDOM.addEventListener("input", () => null);
  }
  setSelectionOrigin(origin) {
    this.lastSelectionOrigin = origin;
    this.lastSelectionTime = Date.now();
  }
  ensureHandlers(view, plugins) {
    var _a2;
    let handlers2;
    this.customHandlers = [];
    for (let plugin of plugins)
      if (handlers2 = (_a2 = plugin.update(view).spec) === null || _a2 === void 0 ? void 0 : _a2.domEventHandlers) {
        this.customHandlers.push({ plugin: plugin.value, handlers: handlers2 });
        for (let type in handlers2)
          if (this.registeredEvents.indexOf(type) < 0 && type != "scroll") {
            this.registeredEvents.push(type);
            view.contentDOM.addEventListener(type, (event) => {
              if (!eventBelongsToEditor(view, event))
                return;
              if (this.runCustomHandlers(type, view, event))
                event.preventDefault();
            });
          }
      }
  }
  runCustomHandlers(type, view, event) {
    for (let set of this.customHandlers) {
      let handler = set.handlers[type];
      if (handler) {
        try {
          if (handler.call(set.plugin, event, view) || event.defaultPrevented)
            return true;
        } catch (e3) {
          logException(view.state, e3);
        }
      }
    }
    return false;
  }
  runScrollHandlers(view, event) {
    this.lastScrollTop = view.scrollDOM.scrollTop;
    this.lastScrollLeft = view.scrollDOM.scrollLeft;
    for (let set of this.customHandlers) {
      let handler = set.handlers.scroll;
      if (handler) {
        try {
          handler.call(set.plugin, event, view);
        } catch (e3) {
          logException(view.state, e3);
        }
      }
    }
  }
  keydown(view, event) {
    this.lastKeyCode = event.keyCode;
    this.lastKeyTime = Date.now();
    if (event.keyCode == 9 && Date.now() < this.lastEscPress + 2e3)
      return true;
    if (browser.android && browser.chrome && !event.synthetic && (event.keyCode == 13 || event.keyCode == 8)) {
      view.observer.delayAndroidKey(event.key, event.keyCode);
      return true;
    }
    let pending;
    if (browser.ios && !event.synthetic && !event.altKey && !event.metaKey && ((pending = PendingKeys.find((key) => key.keyCode == event.keyCode)) && !event.ctrlKey || EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey && !event.shiftKey)) {
      this.pendingIOSKey = pending || event;
      setTimeout(() => this.flushIOSKey(view), 250);
      return true;
    }
    return false;
  }
  flushIOSKey(view) {
    let key = this.pendingIOSKey;
    if (!key)
      return false;
    this.pendingIOSKey = void 0;
    return dispatchKey(view.contentDOM, key.key, key.keyCode);
  }
  ignoreDuringComposition(event) {
    if (!/^key/.test(event.type))
      return false;
    if (this.composing > 0)
      return true;
    if (browser.safari && !browser.ios && Date.now() - this.compositionEndedAt < 100) {
      this.compositionEndedAt = 0;
      return true;
    }
    return false;
  }
  mustFlushObserver(event) {
    return event.type == "keydown" && event.keyCode != 229;
  }
  startMouseSelection(mouseSelection) {
    if (this.mouseSelection)
      this.mouseSelection.destroy();
    this.mouseSelection = mouseSelection;
  }
  update(update2) {
    if (this.mouseSelection)
      this.mouseSelection.update(update2);
    if (update2.transactions.length)
      this.lastKeyCode = this.lastSelectionTime = 0;
  }
  destroy() {
    if (this.mouseSelection)
      this.mouseSelection.destroy();
  }
};
var PendingKeys = [
  { key: "Backspace", keyCode: 8, inputType: "deleteContentBackward" },
  { key: "Enter", keyCode: 13, inputType: "insertParagraph" },
  { key: "Delete", keyCode: 46, inputType: "deleteContentForward" }
];
var EmacsyPendingKeys = "dthko";
var modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225];
var MouseSelection = class {
  constructor(view, startEvent, style, mustSelect) {
    this.view = view;
    this.style = style;
    this.mustSelect = mustSelect;
    this.lastEvent = startEvent;
    let doc2 = view.contentDOM.ownerDocument;
    doc2.addEventListener("mousemove", this.move = this.move.bind(this));
    doc2.addEventListener("mouseup", this.up = this.up.bind(this));
    this.extend = startEvent.shiftKey;
    this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent);
    this.dragMove = dragMovesSelection(view, startEvent);
    this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false;
    if (this.dragging === false) {
      startEvent.preventDefault();
      this.select(startEvent);
    }
  }
  move(event) {
    if (event.buttons == 0)
      return this.destroy();
    if (this.dragging !== false)
      return;
    this.select(this.lastEvent = event);
  }
  up(event) {
    if (this.dragging == null)
      this.select(this.lastEvent);
    if (!this.dragging)
      event.preventDefault();
    this.destroy();
  }
  destroy() {
    let doc2 = this.view.contentDOM.ownerDocument;
    doc2.removeEventListener("mousemove", this.move);
    doc2.removeEventListener("mouseup", this.up);
    this.view.inputState.mouseSelection = null;
  }
  select(event) {
    let selection2 = this.style.get(event, this.extend, this.multiple);
    if (this.mustSelect || !selection2.eq(this.view.state.selection) || selection2.main.assoc != this.view.state.selection.main.assoc)
      this.view.dispatch({
        selection: selection2,
        userEvent: "select.pointer",
        scrollIntoView: true
      });
    this.mustSelect = false;
  }
  update(update2) {
    if (update2.docChanged && this.dragging)
      this.dragging = this.dragging.map(update2.changes);
    if (this.style.update(update2))
      setTimeout(() => this.select(this.lastEvent), 20);
  }
};
function addsSelectionRange(view, event) {
  let facet = view.state.facet(clickAddsSelectionRange);
  return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey;
}
function dragMovesSelection(view, event) {
  let facet = view.state.facet(dragMovesSelection$1);
  return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey;
}
function isInPrimarySelection(view, event) {
  let { main } = view.state.selection;
  if (main.empty)
    return false;
  let sel = getSelection(view.root);
  if (!sel || sel.rangeCount == 0)
    return true;
  let rects = sel.getRangeAt(0).getClientRects();
  for (let i = 0; i < rects.length; i++) {
    let rect = rects[i];
    if (rect.left <= event.clientX && rect.right >= event.clientX && rect.top <= event.clientY && rect.bottom >= event.clientY)
      return true;
  }
  return false;
}
function eventBelongsToEditor(view, event) {
  if (!event.bubbles)
    return true;
  if (event.defaultPrevented)
    return false;
  for (let node = event.target, cView; node != view.contentDOM; node = node.parentNode)
    if (!node || node.nodeType == 11 || (cView = ContentView.get(node)) && cView.ignoreEvent(event))
      return false;
  return true;
}
var handlers = /* @__PURE__ */ Object.create(null);
var handlerOptions = /* @__PURE__ */ Object.create(null);
var brokenClipboardAPI = browser.ie && browser.ie_version < 15 || browser.ios && browser.webkit_version < 604;
function capturePaste(view) {
  let parent2 = view.dom.parentNode;
  if (!parent2)
    return;
  let target = parent2.appendChild(document.createElement("textarea"));
  target.style.cssText = "position: fixed; left: -10000px; top: 10px";
  target.focus();
  setTimeout(() => {
    view.focus();
    target.remove();
    doPaste(view, target.value);
  }, 50);
}
function doPaste(view, input) {
  let { state } = view, changes, i = 1, text2 = state.toText(input);
  let byLine = text2.lines == state.selection.ranges.length;
  let linewise = lastLinewiseCopy != null && state.selection.ranges.every((r) => r.empty) && lastLinewiseCopy == text2.toString();
  if (linewise) {
    let lastLine = -1;
    changes = state.changeByRange((range2) => {
      let line = state.doc.lineAt(range2.from);
      if (line.from == lastLine)
        return { range: range2 };
      lastLine = line.from;
      let insert3 = state.toText((byLine ? text2.line(i++).text : input) + state.lineBreak);
      return {
        changes: { from: line.from, insert: insert3 },
        range: EditorSelection.cursor(range2.from + insert3.length)
      };
    });
  } else if (byLine) {
    changes = state.changeByRange((range2) => {
      let line = text2.line(i++);
      return {
        changes: { from: range2.from, to: range2.to, insert: line.text },
        range: EditorSelection.cursor(range2.from + line.length)
      };
    });
  } else {
    changes = state.replaceSelection(text2);
  }
  view.dispatch(changes, {
    userEvent: "input.paste",
    scrollIntoView: true
  });
}
handlers.keydown = (view, event) => {
  view.inputState.setSelectionOrigin("select");
  if (event.keyCode == 27)
    view.inputState.lastEscPress = Date.now();
  else if (modifierCodes.indexOf(event.keyCode) < 0)
    view.inputState.lastEscPress = 0;
};
handlers.touchstart = (view, e3) => {
  view.inputState.lastTouchTime = Date.now();
  view.inputState.setSelectionOrigin("select.pointer");
};
handlers.touchmove = (view) => {
  view.inputState.setSelectionOrigin("select.pointer");
};
handlerOptions.touchstart = handlerOptions.touchmove = { passive: true };
handlers.mousedown = (view, event) => {
  view.observer.flush();
  if (view.inputState.lastTouchTime > Date.now() - 2e3)
    return;
  let style = null;
  for (let makeStyle of view.state.facet(mouseSelectionStyle)) {
    style = makeStyle(view, event);
    if (style)
      break;
  }
  if (!style && event.button == 0)
    style = basicMouseSelection(view, event);
  if (style) {
    let mustFocus = view.root.activeElement != view.contentDOM;
    if (mustFocus)
      view.observer.ignore(() => focusPreventScroll(view.contentDOM));
    view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus));
  }
};
function rangeForClick(view, pos, bias, type) {
  if (type == 1) {
    return EditorSelection.cursor(pos, bias);
  } else if (type == 2) {
    return groupAt(view.state, pos, bias);
  } else {
    let visual = LineView.find(view.docView, pos), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos);
    let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to;
    if (to < view.state.doc.length && to == line.to)
      to++;
    return EditorSelection.range(from, to);
  }
}
var insideY = (y2, rect) => y2 >= rect.top && y2 <= rect.bottom;
var inside = (x2, y2, rect) => insideY(y2, rect) && x2 >= rect.left && x2 <= rect.right;
function findPositionSide(view, pos, x2, y2) {
  let line = LineView.find(view.docView, pos);
  if (!line)
    return 1;
  let off = pos - line.posAtStart;
  if (off == 0)
    return 1;
  if (off == line.length)
    return -1;
  let before = line.coordsAt(off, -1);
  if (before && inside(x2, y2, before))
    return -1;
  let after = line.coordsAt(off, 1);
  if (after && inside(x2, y2, after))
    return 1;
  return before && insideY(y2, before) ? -1 : 1;
}
function queryPos(view, event) {
  let pos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
  return { pos, bias: findPositionSide(view, pos, event.clientX, event.clientY) };
}
var BadMouseDetail = browser.ie && browser.ie_version <= 11;
var lastMouseDown = null;
var lastMouseDownCount = 0;
var lastMouseDownTime = 0;
function getClickType(event) {
  if (!BadMouseDetail)
    return event.detail;
  let last = lastMouseDown, lastTime = lastMouseDownTime;
  lastMouseDown = event;
  lastMouseDownTime = Date.now();
  return lastMouseDownCount = !last || lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 && Math.abs(last.clientY - event.clientY) < 2 ? (lastMouseDownCount + 1) % 3 : 1;
}
function basicMouseSelection(view, event) {
  let start = queryPos(view, event), type = getClickType(event);
  let startSel = view.state.selection;
  let last = start, lastEvent = event;
  return {
    update(update2) {
      if (update2.docChanged) {
        start.pos = update2.changes.mapPos(start.pos);
        startSel = startSel.map(update2.changes);
        lastEvent = null;
      }
    },
    get(event2, extend3, multiple) {
      let cur2;
      if (lastEvent && event2.clientX == lastEvent.clientX && event2.clientY == lastEvent.clientY)
        cur2 = last;
      else {
        cur2 = last = queryPos(view, event2);
        lastEvent = event2;
      }
      let range2 = rangeForClick(view, cur2.pos, cur2.bias, type);
      if (start.pos != cur2.pos && !extend3) {
        let startRange = rangeForClick(view, start.pos, start.bias, type);
        let from = Math.min(startRange.from, range2.from), to = Math.max(startRange.to, range2.to);
        range2 = from < range2.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from);
      }
      if (extend3)
        return startSel.replaceRange(startSel.main.extend(range2.from, range2.to));
      else if (multiple && startSel.ranges.length > 1 && startSel.ranges.some((r) => r.eq(range2)))
        return removeRange(startSel, range2);
      else if (multiple)
        return startSel.addRange(range2);
      else
        return EditorSelection.create([range2]);
    }
  };
}
function removeRange(sel, range2) {
  for (let i = 0; ; i++) {
    if (sel.ranges[i].eq(range2))
      return EditorSelection.create(sel.ranges.slice(0, i).concat(sel.ranges.slice(i + 1)), sel.mainIndex == i ? 0 : sel.mainIndex - (sel.mainIndex > i ? 1 : 0));
  }
}
handlers.dragstart = (view, event) => {
  let { selection: { main } } = view.state;
  let { mouseSelection } = view.inputState;
  if (mouseSelection)
    mouseSelection.dragging = main;
  if (event.dataTransfer) {
    event.dataTransfer.setData("Text", view.state.sliceDoc(main.from, main.to));
    event.dataTransfer.effectAllowed = "copyMove";
  }
};
function dropText(view, event, text2, direct) {
  if (!text2)
    return;
  let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
  event.preventDefault();
  let { mouseSelection } = view.inputState;
  let del = direct && mouseSelection && mouseSelection.dragging && mouseSelection.dragMove ? { from: mouseSelection.dragging.from, to: mouseSelection.dragging.to } : null;
  let ins = { from: dropPos, insert: text2 };
  let changes = view.state.changes(del ? [del, ins] : ins);
  view.focus();
  view.dispatch({
    changes,
    selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) },
    userEvent: del ? "move.drop" : "input.drop"
  });
}
handlers.drop = (view, event) => {
  if (!event.dataTransfer)
    return;
  if (view.state.readOnly)
    return event.preventDefault();
  let files2 = event.dataTransfer.files;
  if (files2 && files2.length) {
    event.preventDefault();
    let text2 = Array(files2.length), read = 0;
    let finishFile = () => {
      if (++read == files2.length)
        dropText(view, event, text2.filter((s) => s != null).join(view.state.lineBreak), false);
    };
    for (let i = 0; i < files2.length; i++) {
      let reader = new FileReader();
      reader.onerror = finishFile;
      reader.onload = () => {
        if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result))
          text2[i] = reader.result;
        finishFile();
      };
      reader.readAsText(files2[i]);
    }
  } else {
    dropText(view, event, event.dataTransfer.getData("Text"), true);
  }
};
handlers.paste = (view, event) => {
  if (view.state.readOnly)
    return event.preventDefault();
  view.observer.flush();
  let data = brokenClipboardAPI ? null : event.clipboardData;
  if (data) {
    doPaste(view, data.getData("text/plain"));
    event.preventDefault();
  } else {
    capturePaste(view);
  }
};
function captureCopy(view, text2) {
  let parent2 = view.dom.parentNode;
  if (!parent2)
    return;
  let target = parent2.appendChild(document.createElement("textarea"));
  target.style.cssText = "position: fixed; left: -10000px; top: 10px";
  target.value = text2;
  target.focus();
  target.selectionEnd = text2.length;
  target.selectionStart = 0;
  setTimeout(() => {
    target.remove();
    view.focus();
  }, 50);
}
function copiedRange(state) {
  let content2 = [], ranges = [], linewise = false;
  for (let range2 of state.selection.ranges)
    if (!range2.empty) {
      content2.push(state.sliceDoc(range2.from, range2.to));
      ranges.push(range2);
    }
  if (!content2.length) {
    let upto = -1;
    for (let { from } of state.selection.ranges) {
      let line = state.doc.lineAt(from);
      if (line.number > upto) {
        content2.push(line.text);
        ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) });
      }
      upto = line.number;
    }
    linewise = true;
  }
  return { text: content2.join(state.lineBreak), ranges, linewise };
}
var lastLinewiseCopy = null;
handlers.copy = handlers.cut = (view, event) => {
  let { text: text2, ranges, linewise } = copiedRange(view.state);
  if (!text2 && !linewise)
    return;
  lastLinewiseCopy = linewise ? text2 : null;
  let data = brokenClipboardAPI ? null : event.clipboardData;
  if (data) {
    event.preventDefault();
    data.clearData();
    data.setData("text/plain", text2);
  } else {
    captureCopy(view, text2);
  }
  if (event.type == "cut" && !view.state.readOnly)
    view.dispatch({
      changes: ranges,
      scrollIntoView: true,
      userEvent: "delete.cut"
    });
};
function updateForFocusChange(view) {
  setTimeout(() => {
    if (view.hasFocus != view.inputState.notifiedFocused)
      view.update([]);
  }, 10);
}
handlers.focus = (view) => {
  view.inputState.lastFocusTime = Date.now();
  if (!view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft)) {
    view.scrollDOM.scrollTop = view.inputState.lastScrollTop;
    view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft;
  }
  updateForFocusChange(view);
};
handlers.blur = (view) => {
  view.observer.clearSelectionRange();
  updateForFocusChange(view);
};
handlers.compositionstart = handlers.compositionupdate = (view) => {
  if (view.inputState.compositionFirstChange == null)
    view.inputState.compositionFirstChange = true;
  if (view.inputState.composing < 0) {
    view.inputState.composing = 0;
  }
};
handlers.compositionend = (view) => {
  view.inputState.composing = -1;
  view.inputState.compositionEndedAt = Date.now();
  view.inputState.compositionFirstChange = null;
  if (browser.chrome && browser.android)
    view.observer.flushSoon();
  setTimeout(() => {
    if (view.inputState.composing < 0 && view.docView.compositionDeco.size)
      view.update([]);
  }, 50);
};
handlers.contextmenu = (view) => {
  view.inputState.lastContextMenu = Date.now();
};
handlers.beforeinput = (view, event) => {
  var _a2;
  let pending;
  if (browser.chrome && browser.android && (pending = PendingKeys.find((key) => key.inputType == event.inputType))) {
    view.observer.delayAndroidKey(pending.key, pending.keyCode);
    if (pending.key == "Backspace" || pending.key == "Delete") {
      let startViewHeight = ((_a2 = window.visualViewport) === null || _a2 === void 0 ? void 0 : _a2.height) || 0;
      setTimeout(() => {
        var _a3;
        if ((((_a3 = window.visualViewport) === null || _a3 === void 0 ? void 0 : _a3.height) || 0) > startViewHeight + 10 && view.hasFocus) {
          view.contentDOM.blur();
          view.focus();
        }
      }, 100);
    }
  }
};
var wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"];
var HeightOracle = class {
  constructor() {
    this.doc = Text.empty;
    this.lineWrapping = false;
    this.heightSamples = {};
    this.lineHeight = 14;
    this.charWidth = 7;
    this.lineLength = 30;
    this.heightChanged = false;
  }
  heightForGap(from, to) {
    let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1;
    if (this.lineWrapping)
      lines += Math.ceil((to - from - lines * this.lineLength * 0.5) / this.lineLength);
    return this.lineHeight * lines;
  }
  heightForLine(length) {
    if (!this.lineWrapping)
      return this.lineHeight;
    let lines = 1 + Math.max(0, Math.ceil((length - this.lineLength) / (this.lineLength - 5)));
    return lines * this.lineHeight;
  }
  setDoc(doc2) {
    this.doc = doc2;
    return this;
  }
  mustRefreshForWrapping(whiteSpace) {
    return wrappingWhiteSpace.indexOf(whiteSpace) > -1 != this.lineWrapping;
  }
  mustRefreshForHeights(lineHeights) {
    let newHeight = false;
    for (let i = 0; i < lineHeights.length; i++) {
      let h = lineHeights[i];
      if (h < 0) {
        i++;
      } else if (!this.heightSamples[Math.floor(h * 10)]) {
        newHeight = true;
        this.heightSamples[Math.floor(h * 10)] = true;
      }
    }
    return newHeight;
  }
  refresh(whiteSpace, lineHeight, charWidth, lineLength, knownHeights) {
    let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1;
    let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || this.lineWrapping != lineWrapping;
    this.lineWrapping = lineWrapping;
    this.lineHeight = lineHeight;
    this.charWidth = charWidth;
    this.lineLength = lineLength;
    if (changed) {
      this.heightSamples = {};
      for (let i = 0; i < knownHeights.length; i++) {
        let h = knownHeights[i];
        if (h < 0)
          i++;
        else
          this.heightSamples[Math.floor(h * 10)] = true;
      }
    }
    return changed;
  }
};
var MeasuredHeights = class {
  constructor(from, heights) {
    this.from = from;
    this.heights = heights;
    this.index = 0;
  }
  get more() {
    return this.index < this.heights.length;
  }
};
var BlockInfo = class {
  constructor(from, length, top3, height4, type) {
    this.from = from;
    this.length = length;
    this.top = top3;
    this.height = height4;
    this.type = type;
  }
  get to() {
    return this.from + this.length;
  }
  get bottom() {
    return this.top + this.height;
  }
  join(other) {
    let detail = (Array.isArray(this.type) ? this.type : [this]).concat(Array.isArray(other.type) ? other.type : [other]);
    return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, detail);
  }
};
var QueryType = /* @__PURE__ */ function(QueryType3) {
  QueryType3[QueryType3["ByPos"] = 0] = "ByPos";
  QueryType3[QueryType3["ByHeight"] = 1] = "ByHeight";
  QueryType3[QueryType3["ByPosNoHeight"] = 2] = "ByPosNoHeight";
  return QueryType3;
}(QueryType || (QueryType = {}));
var Epsilon = 1e-3;
var HeightMap = class {
  constructor(length, height4, flags = 2) {
    this.length = length;
    this.height = height4;
    this.flags = flags;
  }
  get outdated() {
    return (this.flags & 2) > 0;
  }
  set outdated(value) {
    this.flags = (value ? 2 : 0) | this.flags & ~2;
  }
  setHeight(oracle, height4) {
    if (this.height != height4) {
      if (Math.abs(this.height - height4) > Epsilon)
        oracle.heightChanged = true;
      this.height = height4;
    }
  }
  replace(_from, _to, nodes) {
    return HeightMap.of(nodes);
  }
  decomposeLeft(_to, result) {
    result.push(this);
  }
  decomposeRight(_from, result) {
    result.push(this);
  }
  applyChanges(decorations2, oldDoc, oracle, changes) {
    let me = this;
    for (let i = changes.length - 1; i >= 0; i--) {
      let { fromA, toA, fromB, toB } = changes[i];
      let start = me.lineAt(fromA, QueryType.ByPosNoHeight, oldDoc, 0, 0);
      let end = start.to >= toA ? start : me.lineAt(toA, QueryType.ByPosNoHeight, oldDoc, 0, 0);
      toB += end.to - toA;
      toA = end.to;
      while (i > 0 && start.from <= changes[i - 1].toA) {
        fromA = changes[i - 1].fromA;
        fromB = changes[i - 1].fromB;
        i--;
        if (fromA < start.from)
          start = me.lineAt(fromA, QueryType.ByPosNoHeight, oldDoc, 0, 0);
      }
      fromB += start.from - fromA;
      fromA = start.from;
      let nodes = NodeBuilder.build(oracle, decorations2, fromB, toB);
      me = me.replace(fromA, toA, nodes);
    }
    return me.updateHeight(oracle, 0);
  }
  static empty() {
    return new HeightMapText(0, 0);
  }
  static of(nodes) {
    if (nodes.length == 1)
      return nodes[0];
    let i = 0, j = nodes.length, before = 0, after = 0;
    for (; ; ) {
      if (i == j) {
        if (before > after * 2) {
          let split = nodes[i - 1];
          if (split.break)
            nodes.splice(--i, 1, split.left, null, split.right);
          else
            nodes.splice(--i, 1, split.left, split.right);
          j += 1 + split.break;
          before -= split.size;
        } else if (after > before * 2) {
          let split = nodes[j];
          if (split.break)
            nodes.splice(j, 1, split.left, null, split.right);
          else
            nodes.splice(j, 1, split.left, split.right);
          j += 2 + split.break;
          after -= split.size;
        } else {
          break;
        }
      } else if (before < after) {
        let next = nodes[i++];
        if (next)
          before += next.size;
      } else {
        let next = nodes[--j];
        if (next)
          after += next.size;
      }
    }
    let brk = 0;
    if (nodes[i - 1] == null) {
      brk = 1;
      i--;
    } else if (nodes[i] == null) {
      brk = 1;
      j++;
    }
    return new HeightMapBranch(HeightMap.of(nodes.slice(0, i)), brk, HeightMap.of(nodes.slice(j)));
  }
};
HeightMap.prototype.size = 1;
var HeightMapBlock = class extends HeightMap {
  constructor(length, height4, type) {
    super(length, height4);
    this.type = type;
  }
  blockAt(_height, _doc, top3, offset) {
    return new BlockInfo(offset, this.length, top3, this.height, this.type);
  }
  lineAt(_value, _type, doc2, top3, offset) {
    return this.blockAt(0, doc2, top3, offset);
  }
  forEachLine(from, to, doc2, top3, offset, f) {
    if (from <= offset + this.length && to >= offset)
      f(this.blockAt(0, doc2, top3, offset));
  }
  updateHeight(oracle, offset = 0, _force = false, measured) {
    if (measured && measured.from <= offset && measured.more)
      this.setHeight(oracle, measured.heights[measured.index++]);
    this.outdated = false;
    return this;
  }
  toString() {
    return `block(${this.length})`;
  }
};
var HeightMapText = class extends HeightMapBlock {
  constructor(length, height4) {
    super(length, height4, BlockType.Text);
    this.collapsed = 0;
    this.widgetHeight = 0;
  }
  replace(_from, _to, nodes) {
    let node = nodes[0];
    if (nodes.length == 1 && (node instanceof HeightMapText || node instanceof HeightMapGap && node.flags & 4) && Math.abs(this.length - node.length) < 10) {
      if (node instanceof HeightMapGap)
        node = new HeightMapText(node.length, this.height);
      else
        node.height = this.height;
      if (!this.outdated)
        node.outdated = false;
      return node;
    } else {
      return HeightMap.of(nodes);
    }
  }
  updateHeight(oracle, offset = 0, force = false, measured) {
    if (measured && measured.from <= offset && measured.more)
      this.setHeight(oracle, measured.heights[measured.index++]);
    else if (force || this.outdated)
      this.setHeight(oracle, Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed)));
    this.outdated = false;
    return this;
  }
  toString() {
    return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`;
  }
};
var HeightMapGap = class extends HeightMap {
  constructor(length) {
    super(length, 0);
  }
  lines(doc2, offset) {
    let firstLine = doc2.lineAt(offset).number, lastLine = doc2.lineAt(offset + this.length).number;
    return { firstLine, lastLine, lineHeight: this.height / (lastLine - firstLine + 1) };
  }
  blockAt(height4, doc2, top3, offset) {
    let { firstLine, lastLine, lineHeight } = this.lines(doc2, offset);
    let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height4 - top3) / lineHeight)));
    let { from, length } = doc2.line(firstLine + line);
    return new BlockInfo(from, length, top3 + lineHeight * line, lineHeight, BlockType.Text);
  }
  lineAt(value, type, doc2, top3, offset) {
    if (type == QueryType.ByHeight)
      return this.blockAt(value, doc2, top3, offset);
    if (type == QueryType.ByPosNoHeight) {
      let { from: from2, to } = doc2.lineAt(value);
      return new BlockInfo(from2, to - from2, 0, 0, BlockType.Text);
    }
    let { firstLine, lineHeight } = this.lines(doc2, offset);
    let { from, length, number: number8 } = doc2.lineAt(value);
    return new BlockInfo(from, length, top3 + lineHeight * (number8 - firstLine), lineHeight, BlockType.Text);
  }
  forEachLine(from, to, doc2, top3, offset, f) {
    let { firstLine, lineHeight } = this.lines(doc2, offset);
    for (let pos = Math.max(from, offset), end = Math.min(offset + this.length, to); pos <= end; ) {
      let line = doc2.lineAt(pos);
      if (pos == from)
        top3 += lineHeight * (line.number - firstLine);
      f(new BlockInfo(line.from, line.length, top3, lineHeight, BlockType.Text));
      top3 += lineHeight;
      pos = line.to + 1;
    }
  }
  replace(from, to, nodes) {
    let after = this.length - to;
    if (after > 0) {
      let last = nodes[nodes.length - 1];
      if (last instanceof HeightMapGap)
        nodes[nodes.length - 1] = new HeightMapGap(last.length + after);
      else
        nodes.push(null, new HeightMapGap(after - 1));
    }
    if (from > 0) {
      let first = nodes[0];
      if (first instanceof HeightMapGap)
        nodes[0] = new HeightMapGap(from + first.length);
      else
        nodes.unshift(new HeightMapGap(from - 1), null);
    }
    return HeightMap.of(nodes);
  }
  decomposeLeft(to, result) {
    result.push(new HeightMapGap(to - 1), null);
  }
  decomposeRight(from, result) {
    result.push(null, new HeightMapGap(this.length - from - 1));
  }
  updateHeight(oracle, offset = 0, force = false, measured) {
    let end = offset + this.length;
    if (measured && measured.from <= offset + this.length && measured.more) {
      let nodes = [], pos = Math.max(offset, measured.from), singleHeight = -1;
      let wasChanged = oracle.heightChanged;
      if (measured.from > offset)
        nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset));
      while (pos <= end && measured.more) {
        let len = oracle.doc.lineAt(pos).length;
        if (nodes.length)
          nodes.push(null);
        let height4 = measured.heights[measured.index++];
        if (singleHeight == -1)
          singleHeight = height4;
        else if (Math.abs(height4 - singleHeight) >= Epsilon)
          singleHeight = -2;
        let line = new HeightMapText(len, height4);
        line.outdated = false;
        nodes.push(line);
        pos += len + 1;
      }
      if (pos <= end)
        nodes.push(null, new HeightMapGap(end - pos).updateHeight(oracle, pos));
      let result = HeightMap.of(nodes);
      oracle.heightChanged = wasChanged || singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon || Math.abs(singleHeight - this.lines(oracle.doc, offset).lineHeight) >= Epsilon;
      return result;
    } else if (force || this.outdated) {
      this.setHeight(oracle, oracle.heightForGap(offset, offset + this.length));
      this.outdated = false;
    }
    return this;
  }
  toString() {
    return `gap(${this.length})`;
  }
};
var HeightMapBranch = class extends HeightMap {
  constructor(left2, brk, right2) {
    super(left2.length + brk + right2.length, left2.height + right2.height, brk | (left2.outdated || right2.outdated ? 2 : 0));
    this.left = left2;
    this.right = right2;
    this.size = left2.size + right2.size;
  }
  get break() {
    return this.flags & 1;
  }
  blockAt(height4, doc2, top3, offset) {
    let mid = top3 + this.left.height;
    return height4 < mid ? this.left.blockAt(height4, doc2, top3, offset) : this.right.blockAt(height4, doc2, mid, offset + this.left.length + this.break);
  }
  lineAt(value, type, doc2, top3, offset) {
    let rightTop = top3 + this.left.height, rightOffset = offset + this.left.length + this.break;
    let left2 = type == QueryType.ByHeight ? value < rightTop : value < rightOffset;
    let base2 = left2 ? this.left.lineAt(value, type, doc2, top3, offset) : this.right.lineAt(value, type, doc2, rightTop, rightOffset);
    if (this.break || (left2 ? base2.to < rightOffset : base2.from > rightOffset))
      return base2;
    let subQuery = type == QueryType.ByPosNoHeight ? QueryType.ByPosNoHeight : QueryType.ByPos;
    if (left2)
      return base2.join(this.right.lineAt(rightOffset, subQuery, doc2, rightTop, rightOffset));
    else
      return this.left.lineAt(rightOffset, subQuery, doc2, top3, offset).join(base2);
  }
  forEachLine(from, to, doc2, top3, offset, f) {
    let rightTop = top3 + this.left.height, rightOffset = offset + this.left.length + this.break;
    if (this.break) {
      if (from < rightOffset)
        this.left.forEachLine(from, to, doc2, top3, offset, f);
      if (to >= rightOffset)
        this.right.forEachLine(from, to, doc2, rightTop, rightOffset, f);
    } else {
      let mid = this.lineAt(rightOffset, QueryType.ByPos, doc2, top3, offset);
      if (from < mid.from)
        this.left.forEachLine(from, mid.from - 1, doc2, top3, offset, f);
      if (mid.to >= from && mid.from <= to)
        f(mid);
      if (to > mid.to)
        this.right.forEachLine(mid.to + 1, to, doc2, rightTop, rightOffset, f);
    }
  }
  replace(from, to, nodes) {
    let rightStart = this.left.length + this.break;
    if (to < rightStart)
      return this.balanced(this.left.replace(from, to, nodes), this.right);
    if (from > this.left.length)
      return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes));
    let result = [];
    if (from > 0)
      this.decomposeLeft(from, result);
    let left2 = result.length;
    for (let node of nodes)
      result.push(node);
    if (from > 0)
      mergeGaps(result, left2 - 1);
    if (to < this.length) {
      let right2 = result.length;
      this.decomposeRight(to, result);
      mergeGaps(result, right2);
    }
    return HeightMap.of(result);
  }
  decomposeLeft(to, result) {
    let left2 = this.left.length;
    if (to <= left2)
      return this.left.decomposeLeft(to, result);
    result.push(this.left);
    if (this.break) {
      left2++;
      if (to >= left2)
        result.push(null);
    }
    if (to > left2)
      this.right.decomposeLeft(to - left2, result);
  }
  decomposeRight(from, result) {
    let left2 = this.left.length, right2 = left2 + this.break;
    if (from >= right2)
      return this.right.decomposeRight(from - right2, result);
    if (from < left2)
      this.left.decomposeRight(from, result);
    if (this.break && from < right2)
      result.push(null);
    result.push(this.right);
  }
  balanced(left2, right2) {
    if (left2.size > 2 * right2.size || right2.size > 2 * left2.size)
      return HeightMap.of(this.break ? [left2, null, right2] : [left2, right2]);
    this.left = left2;
    this.right = right2;
    this.height = left2.height + right2.height;
    this.outdated = left2.outdated || right2.outdated;
    this.size = left2.size + right2.size;
    this.length = left2.length + this.break + right2.length;
    return this;
  }
  updateHeight(oracle, offset = 0, force = false, measured) {
    let { left: left2, right: right2 } = this, rightStart = offset + left2.length + this.break, rebalance = null;
    if (measured && measured.from <= offset + left2.length && measured.more)
      rebalance = left2 = left2.updateHeight(oracle, offset, force, measured);
    else
      left2.updateHeight(oracle, offset, force);
    if (measured && measured.from <= rightStart + right2.length && measured.more)
      rebalance = right2 = right2.updateHeight(oracle, rightStart, force, measured);
    else
      right2.updateHeight(oracle, rightStart, force);
    if (rebalance)
      return this.balanced(left2, right2);
    this.height = this.left.height + this.right.height;
    this.outdated = false;
    return this;
  }
  toString() {
    return this.left + (this.break ? " " : "-") + this.right;
  }
};
function mergeGaps(nodes, around) {
  let before, after;
  if (nodes[around] == null && (before = nodes[around - 1]) instanceof HeightMapGap && (after = nodes[around + 1]) instanceof HeightMapGap)
    nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length));
}
var relevantWidgetHeight = 5;
var NodeBuilder = class {
  constructor(pos, oracle) {
    this.pos = pos;
    this.oracle = oracle;
    this.nodes = [];
    this.lineStart = -1;
    this.lineEnd = -1;
    this.covering = null;
    this.writtenTo = pos;
  }
  get isCovered() {
    return this.covering && this.nodes[this.nodes.length - 1] == this.covering;
  }
  span(_from, to) {
    if (this.lineStart > -1) {
      let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1];
      if (last instanceof HeightMapText)
        last.length += end - this.pos;
      else if (end > this.pos || !this.isCovered)
        this.nodes.push(new HeightMapText(end - this.pos, -1));
      this.writtenTo = end;
      if (to > end) {
        this.nodes.push(null);
        this.writtenTo++;
        this.lineStart = -1;
      }
    }
    this.pos = to;
  }
  point(from, to, deco) {
    if (from < to || deco.heightRelevant) {
      let height4 = deco.widget ? deco.widget.estimatedHeight : 0;
      if (height4 < 0)
        height4 = this.oracle.lineHeight;
      let len = to - from;
      if (deco.block) {
        this.addBlock(new HeightMapBlock(len, height4, deco.type));
      } else if (len || height4 >= relevantWidgetHeight) {
        this.addLineDeco(height4, len);
      }
    } else if (to > from) {
      this.span(from, to);
    }
    if (this.lineEnd > -1 && this.lineEnd < this.pos)
      this.lineEnd = this.oracle.doc.lineAt(this.pos).to;
  }
  enterLine() {
    if (this.lineStart > -1)
      return;
    let { from, to } = this.oracle.doc.lineAt(this.pos);
    this.lineStart = from;
    this.lineEnd = to;
    if (this.writtenTo < from) {
      if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null)
        this.nodes.push(this.blankContent(this.writtenTo, from - 1));
      this.nodes.push(null);
    }
    if (this.pos > from)
      this.nodes.push(new HeightMapText(this.pos - from, -1));
    this.writtenTo = this.pos;
  }
  blankContent(from, to) {
    let gap = new HeightMapGap(to - from);
    if (this.oracle.doc.lineAt(from).to == to)
      gap.flags |= 4;
    return gap;
  }
  ensureLine() {
    this.enterLine();
    let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null;
    if (last instanceof HeightMapText)
      return last;
    let line = new HeightMapText(0, -1);
    this.nodes.push(line);
    return line;
  }
  addBlock(block) {
    this.enterLine();
    if (block.type == BlockType.WidgetAfter && !this.isCovered)
      this.ensureLine();
    this.nodes.push(block);
    this.writtenTo = this.pos = this.pos + block.length;
    if (block.type != BlockType.WidgetBefore)
      this.covering = block;
  }
  addLineDeco(height4, length) {
    let line = this.ensureLine();
    line.length += length;
    line.collapsed += length;
    line.widgetHeight = Math.max(line.widgetHeight, height4);
    this.writtenTo = this.pos = this.pos + length;
  }
  finish(from) {
    let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1];
    if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered)
      this.nodes.push(new HeightMapText(0, -1));
    else if (this.writtenTo < this.pos || last == null)
      this.nodes.push(this.blankContent(this.writtenTo, this.pos));
    let pos = from;
    for (let node of this.nodes) {
      if (node instanceof HeightMapText)
        node.updateHeight(this.oracle, pos);
      pos += node ? node.length : 1;
    }
    return this.nodes;
  }
  static build(oracle, decorations2, from, to) {
    let builder = new NodeBuilder(from, oracle);
    RangeSet.spans(decorations2, from, to, builder, 0);
    return builder.finish(from);
  }
};
function heightRelevantDecoChanges(a, b, diff) {
  let comp = new DecorationComparator();
  RangeSet.compare(a, b, diff, comp, 0);
  return comp.changes;
}
var DecorationComparator = class {
  constructor() {
    this.changes = [];
  }
  compareRange() {
  }
  comparePoint(from, to, a, b) {
    if (from < to || a && a.heightRelevant || b && b.heightRelevant)
      addRange(from, to, this.changes, 5);
  }
};
function visiblePixelRange(dom, paddingTop) {
  let rect = dom.getBoundingClientRect();
  let doc2 = dom.ownerDocument, win = doc2.defaultView || window;
  let left2 = Math.max(0, rect.left), right2 = Math.min(win.innerWidth, rect.right);
  let top3 = Math.max(0, rect.top), bottom2 = Math.min(win.innerHeight, rect.bottom);
  for (let parent2 = dom.parentNode; parent2 && parent2 != doc2.body; ) {
    if (parent2.nodeType == 1) {
      let elt = parent2;
      let style = window.getComputedStyle(elt);
      if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) && style.overflow != "visible") {
        let parentRect = elt.getBoundingClientRect();
        left2 = Math.max(left2, parentRect.left);
        right2 = Math.min(right2, parentRect.right);
        top3 = Math.max(top3, parentRect.top);
        bottom2 = parent2 == dom.parentNode ? parentRect.bottom : Math.min(bottom2, parentRect.bottom);
      }
      parent2 = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode;
    } else if (parent2.nodeType == 11) {
      parent2 = parent2.host;
    } else {
      break;
    }
  }
  return {
    left: left2 - rect.left,
    right: Math.max(left2, right2) - rect.left,
    top: top3 - (rect.top + paddingTop),
    bottom: Math.max(top3, bottom2) - (rect.top + paddingTop)
  };
}
function fullPixelRange(dom, paddingTop) {
  let rect = dom.getBoundingClientRect();
  return {
    left: 0,
    right: rect.right - rect.left,
    top: paddingTop,
    bottom: rect.bottom - (rect.top + paddingTop)
  };
}
var LineGap = class {
  constructor(from, to, size) {
    this.from = from;
    this.to = to;
    this.size = size;
  }
  static same(a, b) {
    if (a.length != b.length)
      return false;
    for (let i = 0; i < a.length; i++) {
      let gA = a[i], gB = b[i];
      if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size)
        return false;
    }
    return true;
  }
  draw(wrapping) {
    return Decoration.replace({ widget: new LineGapWidget(this.size, wrapping) }).range(this.from, this.to);
  }
};
var LineGapWidget = class extends WidgetType {
  constructor(size, vertical) {
    super();
    this.size = size;
    this.vertical = vertical;
  }
  eq(other) {
    return other.size == this.size && other.vertical == this.vertical;
  }
  toDOM() {
    let elt = document.createElement("div");
    if (this.vertical) {
      elt.style.height = this.size + "px";
    } else {
      elt.style.width = this.size + "px";
      elt.style.height = "2px";
      elt.style.display = "inline-block";
    }
    return elt;
  }
  get estimatedHeight() {
    return this.vertical ? this.size : -1;
  }
};
var ViewState = class {
  constructor(state) {
    this.state = state;
    this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 };
    this.inView = true;
    this.paddingTop = 0;
    this.paddingBottom = 0;
    this.contentDOMWidth = 0;
    this.contentDOMHeight = 0;
    this.editorHeight = 0;
    this.editorWidth = 0;
    this.heightOracle = new HeightOracle();
    this.scaler = IdScaler;
    this.scrollTarget = null;
    this.printing = false;
    this.mustMeasureContent = true;
    this.defaultTextDirection = Direction.RTL;
    this.visibleRanges = [];
    this.mustEnforceCursorAssoc = false;
    this.stateDeco = state.facet(decorations).filter((d) => typeof d != "function");
    this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]);
    this.viewport = this.getViewport(0, null);
    this.updateViewportLines();
    this.updateForViewport();
    this.lineGaps = this.ensureLineGaps([]);
    this.lineGapDeco = Decoration.set(this.lineGaps.map((gap) => gap.draw(false)));
    this.computeVisibleRanges();
  }
  updateForViewport() {
    let viewports = [this.viewport], { main } = this.state.selection;
    for (let i = 0; i <= 1; i++) {
      let pos = i ? main.head : main.anchor;
      if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) {
        let { from, to } = this.lineBlockAt(pos);
        viewports.push(new Viewport(from, to));
      }
    }
    this.viewports = viewports.sort((a, b) => a.from - b.from);
    this.scaler = this.heightMap.height <= 7e6 ? IdScaler : new BigScaler(this.heightOracle.doc, this.heightMap, this.viewports);
  }
  updateViewportLines() {
    this.viewportLines = [];
    this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.state.doc, 0, 0, (block) => {
      this.viewportLines.push(this.scaler.scale == 1 ? block : scaleBlock(block, this.scaler));
    });
  }
  update(update2, scrollTarget = null) {
    this.state = update2.state;
    let prevDeco = this.stateDeco;
    this.stateDeco = this.state.facet(decorations).filter((d) => typeof d != "function");
    let contentChanges = update2.changedRanges;
    let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update2 ? update2.changes : ChangeSet.empty(this.state.doc.length)));
    let prevHeight = this.heightMap.height;
    this.heightMap = this.heightMap.applyChanges(this.stateDeco, update2.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges);
    if (this.heightMap.height != prevHeight)
      update2.flags |= 2;
    let viewport = heightChanges.length ? this.mapViewport(this.viewport, update2.changes) : this.viewport;
    if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) || !this.viewportIsAppropriate(viewport))
      viewport = this.getViewport(0, scrollTarget);
    let updateLines = !update2.changes.empty || update2.flags & 2 || viewport.from != this.viewport.from || viewport.to != this.viewport.to;
    this.viewport = viewport;
    this.updateForViewport();
    if (updateLines)
      this.updateViewportLines();
    if (this.lineGaps.length || this.viewport.to - this.viewport.from > 2e3 << 1)
      this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update2.changes)));
    update2.flags |= this.computeVisibleRanges();
    if (scrollTarget)
      this.scrollTarget = scrollTarget;
    if (!this.mustEnforceCursorAssoc && update2.selectionSet && update2.view.lineWrapping && update2.state.selection.main.empty && update2.state.selection.main.assoc)
      this.mustEnforceCursorAssoc = true;
  }
  measure(view) {
    let dom = view.contentDOM, style = window.getComputedStyle(dom);
    let oracle = this.heightOracle;
    let whiteSpace = style.whiteSpace;
    this.defaultTextDirection = style.direction == "rtl" ? Direction.RTL : Direction.LTR;
    let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace);
    let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != dom.clientHeight;
    this.contentDOMHeight = dom.clientHeight;
    this.mustMeasureContent = false;
    let result = 0, bias = 0;
    let paddingTop = parseInt(style.paddingTop) || 0, paddingBottom = parseInt(style.paddingBottom) || 0;
    if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) {
      this.paddingTop = paddingTop;
      this.paddingBottom = paddingBottom;
      result |= 8 | 2;
    }
    if (this.editorWidth != view.scrollDOM.clientWidth) {
      if (oracle.lineWrapping)
        measureContent = true;
      this.editorWidth = view.scrollDOM.clientWidth;
      result |= 8;
    }
    let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop);
    let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom;
    this.pixelViewport = pixelViewport;
    let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left;
    if (inView != this.inView) {
      this.inView = inView;
      if (inView)
        measureContent = true;
    }
    if (!this.inView && !this.scrollTarget)
      return 0;
    let contentWidth = dom.clientWidth;
    if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) {
      this.contentDOMWidth = contentWidth;
      this.editorHeight = view.scrollDOM.clientHeight;
      result |= 8;
    }
    if (measureContent) {
      let lineHeights = view.docView.measureVisibleLineHeights(this.viewport);
      if (oracle.mustRefreshForHeights(lineHeights))
        refresh = true;
      if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) {
        let { lineHeight, charWidth } = view.docView.measureTextSize();
        refresh = lineHeight > 0 && oracle.refresh(whiteSpace, lineHeight, charWidth, contentWidth / charWidth, lineHeights);
        if (refresh) {
          view.docView.minWidth = 0;
          result |= 8;
        }
      }
      if (dTop > 0 && dBottom > 0)
        bias = Math.max(dTop, dBottom);
      else if (dTop < 0 && dBottom < 0)
        bias = Math.min(dTop, dBottom);
      oracle.heightChanged = false;
      for (let vp of this.viewports) {
        let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp);
        this.heightMap = this.heightMap.updateHeight(oracle, 0, refresh, new MeasuredHeights(vp.from, heights));
      }
      if (oracle.heightChanged)
        result |= 2;
    }
    let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) || this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from || this.scrollTarget.range.head > this.viewport.to);
    if (viewportChange)
      this.viewport = this.getViewport(bias, this.scrollTarget);
    this.updateForViewport();
    if (result & 2 || viewportChange)
      this.updateViewportLines();
    if (this.lineGaps.length || this.viewport.to - this.viewport.from > 2e3 << 1)
      this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view));
    result |= this.computeVisibleRanges();
    if (this.mustEnforceCursorAssoc) {
      this.mustEnforceCursorAssoc = false;
      view.docView.enforceCursorAssoc();
    }
    return result;
  }
  get visibleTop() {
    return this.scaler.fromDOM(this.pixelViewport.top);
  }
  get visibleBottom() {
    return this.scaler.fromDOM(this.pixelViewport.bottom);
  }
  getViewport(bias, scrollTarget) {
    let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1e3 / 2));
    let map2 = this.heightMap, doc2 = this.state.doc, { visibleTop, visibleBottom } = this;
    let viewport = new Viewport(map2.lineAt(visibleTop - marginTop * 1e3, QueryType.ByHeight, doc2, 0, 0).from, map2.lineAt(visibleBottom + (1 - marginTop) * 1e3, QueryType.ByHeight, doc2, 0, 0).to);
    if (scrollTarget) {
      let { head } = scrollTarget.range;
      if (head < viewport.from || head > viewport.to) {
        let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top);
        let block = map2.lineAt(head, QueryType.ByPos, doc2, 0, 0), topPos;
        if (scrollTarget.y == "center")
          topPos = (block.top + block.bottom) / 2 - viewHeight / 2;
        else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from)
          topPos = block.top;
        else
          topPos = block.bottom - viewHeight;
        viewport = new Viewport(map2.lineAt(topPos - 1e3 / 2, QueryType.ByHeight, doc2, 0, 0).from, map2.lineAt(topPos + viewHeight + 1e3 / 2, QueryType.ByHeight, doc2, 0, 0).to);
      }
    }
    return viewport;
  }
  mapViewport(viewport, changes) {
    let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1);
    return new Viewport(this.heightMap.lineAt(from, QueryType.ByPos, this.state.doc, 0, 0).from, this.heightMap.lineAt(to, QueryType.ByPos, this.state.doc, 0, 0).to);
  }
  viewportIsAppropriate({ from, to }, bias = 0) {
    if (!this.inView)
      return true;
    let { top: top3 } = this.heightMap.lineAt(from, QueryType.ByPos, this.state.doc, 0, 0);
    let { bottom: bottom2 } = this.heightMap.lineAt(to, QueryType.ByPos, this.state.doc, 0, 0);
    let { visibleTop, visibleBottom } = this;
    return (from == 0 || top3 <= visibleTop - Math.max(10, Math.min(-bias, 250))) && (to == this.state.doc.length || bottom2 >= visibleBottom + Math.max(10, Math.min(bias, 250))) && (top3 > visibleTop - 2 * 1e3 && bottom2 < visibleBottom + 2 * 1e3);
  }
  mapLineGaps(gaps, changes) {
    if (!gaps.length || changes.empty)
      return gaps;
    let mapped = [];
    for (let gap of gaps)
      if (!changes.touchesRange(gap.from, gap.to))
        mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size));
    return mapped;
  }
  ensureLineGaps(current, mayMeasure) {
    let wrapping = this.heightOracle.lineWrapping;
    let margin = wrapping ? 1e4 : 2e3, halfMargin = margin >> 1, doubleMargin = margin << 1;
    if (this.defaultTextDirection != Direction.LTR && !wrapping)
      return [];
    let gaps = [];
    let addGap = (from, to, line, structure) => {
      if (to - from < halfMargin)
        return;
      let sel = this.state.selection.main, avoid = [sel.from];
      if (!sel.empty)
        avoid.push(sel.to);
      for (let pos of avoid) {
        if (pos > from && pos < to) {
          addGap(from, pos - 10, line, structure);
          addGap(pos + 10, to, line, structure);
          return;
        }
      }
      let gap = find(current, (gap2) => gap2.from >= line.from && gap2.to <= line.to && Math.abs(gap2.from - from) < halfMargin && Math.abs(gap2.to - to) < halfMargin && !avoid.some((pos) => gap2.from < pos && gap2.to > pos));
      if (!gap) {
        if (to < line.to && mayMeasure && wrapping && mayMeasure.visibleRanges.some((r) => r.from <= to && r.to >= to)) {
          let lineStart = mayMeasure.moveToLineBoundary(EditorSelection.cursor(to), false, true).head;
          if (lineStart > from)
            to = lineStart;
        }
        gap = new LineGap(from, to, this.gapSize(line, from, to, structure));
      }
      gaps.push(gap);
    };
    for (let line of this.viewportLines) {
      if (line.length < doubleMargin)
        continue;
      let structure = lineStructure(line.from, line.to, this.stateDeco);
      if (structure.total < doubleMargin)
        continue;
      let target = this.scrollTarget ? this.scrollTarget.range.head : null;
      let viewFrom, viewTo;
      if (wrapping) {
        let marginHeight = margin / this.heightOracle.lineLength * this.heightOracle.lineHeight;
        let top3, bot;
        if (target != null) {
          let targetFrac = findFraction(structure, target);
          let spaceFrac = ((this.visibleBottom - this.visibleTop) / 2 + marginHeight) / line.height;
          top3 = targetFrac - spaceFrac;
          bot = targetFrac + spaceFrac;
        } else {
          top3 = (this.visibleTop - line.top - marginHeight) / line.height;
          bot = (this.visibleBottom - line.top + marginHeight) / line.height;
        }
        viewFrom = findPosition(structure, top3);
        viewTo = findPosition(structure, bot);
      } else {
        let totalWidth = structure.total * this.heightOracle.charWidth;
        let marginWidth = margin * this.heightOracle.charWidth;
        let left2, right2;
        if (target != null) {
          let targetFrac = findFraction(structure, target);
          let spaceFrac = ((this.pixelViewport.right - this.pixelViewport.left) / 2 + marginWidth) / totalWidth;
          left2 = targetFrac - spaceFrac;
          right2 = targetFrac + spaceFrac;
        } else {
          left2 = (this.pixelViewport.left - marginWidth) / totalWidth;
          right2 = (this.pixelViewport.right + marginWidth) / totalWidth;
        }
        viewFrom = findPosition(structure, left2);
        viewTo = findPosition(structure, right2);
      }
      if (viewFrom > line.from)
        addGap(line.from, viewFrom, line, structure);
      if (viewTo < line.to)
        addGap(viewTo, line.to, line, structure);
    }
    return gaps;
  }
  gapSize(line, from, to, structure) {
    let fraction = findFraction(structure, to) - findFraction(structure, from);
    if (this.heightOracle.lineWrapping) {
      return line.height * fraction;
    } else {
      return structure.total * this.heightOracle.charWidth * fraction;
    }
  }
  updateLineGaps(gaps) {
    if (!LineGap.same(gaps, this.lineGaps)) {
      this.lineGaps = gaps;
      this.lineGapDeco = Decoration.set(gaps.map((gap) => gap.draw(this.heightOracle.lineWrapping)));
    }
  }
  computeVisibleRanges() {
    let deco = this.stateDeco;
    if (this.lineGaps.length)
      deco = deco.concat(this.lineGapDeco);
    let ranges = [];
    RangeSet.spans(deco, this.viewport.from, this.viewport.to, {
      span(from, to) {
        ranges.push({ from, to });
      },
      point() {
      }
    }, 20);
    let changed = ranges.length != this.visibleRanges.length || this.visibleRanges.some((r, i) => r.from != ranges[i].from || r.to != ranges[i].to);
    this.visibleRanges = ranges;
    return changed ? 4 : 0;
  }
  lineBlockAt(pos) {
    return pos >= this.viewport.from && pos <= this.viewport.to && this.viewportLines.find((b) => b.from <= pos && b.to >= pos) || scaleBlock(this.heightMap.lineAt(pos, QueryType.ByPos, this.state.doc, 0, 0), this.scaler);
  }
  lineBlockAtHeight(height4) {
    return scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height4), QueryType.ByHeight, this.state.doc, 0, 0), this.scaler);
  }
  elementAtHeight(height4) {
    return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height4), this.state.doc, 0, 0), this.scaler);
  }
  get docHeight() {
    return this.scaler.toDOM(this.heightMap.height);
  }
  get contentHeight() {
    return this.docHeight + this.paddingTop + this.paddingBottom;
  }
};
var Viewport = class {
  constructor(from, to) {
    this.from = from;
    this.to = to;
  }
};
function lineStructure(from, to, stateDeco) {
  let ranges = [], pos = from, total = 0;
  RangeSet.spans(stateDeco, from, to, {
    span() {
    },
    point(from2, to2) {
      if (from2 > pos) {
        ranges.push({ from: pos, to: from2 });
        total += from2 - pos;
      }
      pos = to2;
    }
  }, 20);
  if (pos < to) {
    ranges.push({ from: pos, to });
    total += to - pos;
  }
  return { total, ranges };
}
function findPosition({ total, ranges }, ratio) {
  if (ratio <= 0)
    return ranges[0].from;
  if (ratio >= 1)
    return ranges[ranges.length - 1].to;
  let dist = Math.floor(total * ratio);
  for (let i = 0; ; i++) {
    let { from, to } = ranges[i], size = to - from;
    if (dist <= size)
      return from + dist;
    dist -= size;
  }
}
function findFraction(structure, pos) {
  let counted = 0;
  for (let { from, to } of structure.ranges) {
    if (pos <= to) {
      counted += pos - from;
      break;
    }
    counted += to - from;
  }
  return counted / structure.total;
}
function find(array3, f) {
  for (let val of array3)
    if (f(val))
      return val;
  return void 0;
}
var IdScaler = {
  toDOM(n) {
    return n;
  },
  fromDOM(n) {
    return n;
  },
  scale: 1
};
var BigScaler = class {
  constructor(doc2, heightMap, viewports) {
    let vpHeight = 0, base2 = 0, domBase = 0;
    this.viewports = viewports.map(({ from, to }) => {
      let top3 = heightMap.lineAt(from, QueryType.ByPos, doc2, 0, 0).top;
      let bottom2 = heightMap.lineAt(to, QueryType.ByPos, doc2, 0, 0).bottom;
      vpHeight += bottom2 - top3;
      return { from, to, top: top3, bottom: bottom2, domTop: 0, domBottom: 0 };
    });
    this.scale = (7e6 - vpHeight) / (heightMap.height - vpHeight);
    for (let obj of this.viewports) {
      obj.domTop = domBase + (obj.top - base2) * this.scale;
      domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top);
      base2 = obj.bottom;
    }
  }
  toDOM(n) {
    for (let i = 0, base2 = 0, domBase = 0; ; i++) {
      let vp = i < this.viewports.length ? this.viewports[i] : null;
      if (!vp || n < vp.top)
        return domBase + (n - base2) * this.scale;
      if (n <= vp.bottom)
        return vp.domTop + (n - vp.top);
      base2 = vp.bottom;
      domBase = vp.domBottom;
    }
  }
  fromDOM(n) {
    for (let i = 0, base2 = 0, domBase = 0; ; i++) {
      let vp = i < this.viewports.length ? this.viewports[i] : null;
      if (!vp || n < vp.domTop)
        return base2 + (n - domBase) / this.scale;
      if (n <= vp.domBottom)
        return vp.top + (n - vp.domTop);
      base2 = vp.bottom;
      domBase = vp.domBottom;
    }
  }
};
function scaleBlock(block, scaler) {
  if (scaler.scale == 1)
    return block;
  let bTop = scaler.toDOM(block.top), bBottom = scaler.toDOM(block.bottom);
  return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block.type) ? block.type.map((b) => scaleBlock(b, scaler)) : block.type);
}
var theme = /* @__PURE__ */ Facet.define({ combine: (strs) => strs.join(" ") });
var darkTheme = /* @__PURE__ */ Facet.define({ combine: (values) => values.indexOf(true) > -1 });
var baseThemeID = /* @__PURE__ */ StyleModule.newName();
var baseLightID = /* @__PURE__ */ StyleModule.newName();
var baseDarkID = /* @__PURE__ */ StyleModule.newName();
var lightDarkIDs = { "&light": "." + baseLightID, "&dark": "." + baseDarkID };
function buildTheme(main, spec, scopes) {
  return new StyleModule(spec, {
    finish(sel) {
      return /&/.test(sel) ? sel.replace(/&\w*/, (m) => {
        if (m == "&")
          return main;
        if (!scopes || !scopes[m])
          throw new RangeError(`Unsupported selector: ${m}`);
        return scopes[m];
      }) : main + " " + sel;
    }
  });
}
var baseTheme$1 = /* @__PURE__ */ buildTheme("." + baseThemeID, {
  "&.cm-editor": {
    position: "relative !important",
    boxSizing: "border-box",
    "&.cm-focused": {
      outline: "1px dotted #212121"
    },
    display: "flex !important",
    flexDirection: "column"
  },
  ".cm-scroller": {
    display: "flex !important",
    alignItems: "flex-start !important",
    fontFamily: "monospace",
    lineHeight: 1.4,
    height: "100%",
    overflowX: "auto",
    position: "relative",
    zIndex: 0
  },
  ".cm-content": {
    margin: 0,
    flexGrow: 2,
    flexShrink: 0,
    minHeight: "100%",
    display: "block",
    whiteSpace: "pre",
    wordWrap: "normal",
    boxSizing: "border-box",
    padding: "4px 0",
    outline: "none",
    "&[contenteditable=true]": {
      WebkitUserModify: "read-write-plaintext-only"
    }
  },
  ".cm-lineWrapping": {
    whiteSpace_fallback: "pre-wrap",
    whiteSpace: "break-spaces",
    wordBreak: "break-word",
    overflowWrap: "anywhere",
    flexShrink: 1
  },
  "&light .cm-content": { caretColor: "black" },
  "&dark .cm-content": { caretColor: "white" },
  ".cm-line": {
    display: "block",
    padding: "0 2px 0 4px"
  },
  ".cm-selectionLayer": {
    zIndex: -1,
    contain: "size style"
  },
  ".cm-selectionBackground": {
    position: "absolute"
  },
  "&light .cm-selectionBackground": {
    background: "#d9d9d9"
  },
  "&dark .cm-selectionBackground": {
    background: "#222"
  },
  "&light.cm-focused .cm-selectionBackground": {
    background: "#d7d4f0"
  },
  "&dark.cm-focused .cm-selectionBackground": {
    background: "#233"
  },
  ".cm-cursorLayer": {
    zIndex: 100,
    contain: "size style",
    pointerEvents: "none"
  },
  "&.cm-focused .cm-cursorLayer": {
    animation: "steps(1) cm-blink 1.2s infinite"
  },
  "@keyframes cm-blink": { "0%": {}, "50%": { opacity: 0 }, "100%": {} },
  "@keyframes cm-blink2": { "0%": {}, "50%": { opacity: 0 }, "100%": {} },
  ".cm-cursor, .cm-dropCursor": {
    position: "absolute",
    borderLeft: "1.2px solid black",
    marginLeft: "-0.6px",
    pointerEvents: "none"
  },
  ".cm-cursor": {
    display: "none"
  },
  "&dark .cm-cursor": {
    borderLeftColor: "#444"
  },
  "&.cm-focused .cm-cursor": {
    display: "block"
  },
  "&light .cm-activeLine": { backgroundColor: "#cceeff44" },
  "&dark .cm-activeLine": { backgroundColor: "#99eeff33" },
  "&light .cm-specialChar": { color: "red" },
  "&dark .cm-specialChar": { color: "#f78" },
  ".cm-gutters": {
    flexShrink: 0,
    display: "flex",
    height: "100%",
    boxSizing: "border-box",
    left: 0,
    zIndex: 200
  },
  "&light .cm-gutters": {
    backgroundColor: "#f5f5f5",
    color: "#6c6c6c",
    borderRight: "1px solid #ddd"
  },
  "&dark .cm-gutters": {
    backgroundColor: "#333338",
    color: "#ccc"
  },
  ".cm-gutter": {
    display: "flex !important",
    flexDirection: "column",
    flexShrink: 0,
    boxSizing: "border-box",
    minHeight: "100%",
    overflow: "hidden"
  },
  ".cm-gutterElement": {
    boxSizing: "border-box"
  },
  ".cm-lineNumbers .cm-gutterElement": {
    padding: "0 3px 0 5px",
    minWidth: "20px",
    textAlign: "right",
    whiteSpace: "nowrap"
  },
  "&light .cm-activeLineGutter": {
    backgroundColor: "#e2f2ff"
  },
  "&dark .cm-activeLineGutter": {
    backgroundColor: "#222227"
  },
  ".cm-panels": {
    boxSizing: "border-box",
    position: "sticky",
    left: 0,
    right: 0
  },
  "&light .cm-panels": {
    backgroundColor: "#f5f5f5",
    color: "black"
  },
  "&light .cm-panels-top": {
    borderBottom: "1px solid #ddd"
  },
  "&light .cm-panels-bottom": {
    borderTop: "1px solid #ddd"
  },
  "&dark .cm-panels": {
    backgroundColor: "#333338",
    color: "white"
  },
  ".cm-tab": {
    display: "inline-block",
    overflow: "hidden",
    verticalAlign: "bottom"
  },
  ".cm-widgetBuffer": {
    verticalAlign: "text-top",
    height: "1em",
    width: 0,
    display: "inline"
  },
  ".cm-placeholder": {
    color: "#888",
    display: "inline-block",
    verticalAlign: "top"
  },
  ".cm-button": {
    verticalAlign: "middle",
    color: "inherit",
    fontSize: "70%",
    padding: ".2em 1em",
    borderRadius: "1px"
  },
  "&light .cm-button": {
    backgroundImage: "linear-gradient(#eff1f5, #d9d9df)",
    border: "1px solid #888",
    "&:active": {
      backgroundImage: "linear-gradient(#b4b4b4, #d0d3d6)"
    }
  },
  "&dark .cm-button": {
    backgroundImage: "linear-gradient(#393939, #111)",
    border: "1px solid #888",
    "&:active": {
      backgroundImage: "linear-gradient(#111, #333)"
    }
  },
  ".cm-textfield": {
    verticalAlign: "middle",
    color: "inherit",
    fontSize: "70%",
    border: "1px solid silver",
    padding: ".2em .5em"
  },
  "&light .cm-textfield": {
    backgroundColor: "white"
  },
  "&dark .cm-textfield": {
    border: "1px solid #555",
    backgroundColor: "inherit"
  }
}, lightDarkIDs);
var DOMChange = class {
  constructor(view, start, end, typeOver) {
    this.typeOver = typeOver;
    this.bounds = null;
    this.text = "";
    let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView;
    if (start > -1 && !view.state.readOnly && (this.bounds = view.docView.domBoundsAround(start, end, 0))) {
      let selPoints = iHead || iAnchor ? [] : selectionPoints(view);
      let reader = new DOMReader(selPoints, view.state);
      reader.readRange(this.bounds.startDOM, this.bounds.endDOM);
      this.text = reader.text;
      this.newSel = selectionFromPoints(selPoints, this.bounds.from);
    } else {
      let domSel = view.observer.selectionRange;
      let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset || !contains(view.contentDOM, domSel.focusNode) ? view.state.selection.main.head : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);
      let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset || !contains(view.contentDOM, domSel.anchorNode) ? view.state.selection.main.anchor : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset);
      this.newSel = EditorSelection.single(anchor, head);
    }
  }
};
function applyDOMChange(view, domChange) {
  let change;
  let { newSel } = domChange, sel = view.state.selection.main;
  if (domChange.bounds) {
    let { from, to } = domChange.bounds;
    let preferredPos = sel.from, preferredSide = null;
    if (view.inputState.lastKeyCode === 8 && view.inputState.lastKeyTime > Date.now() - 100 || browser.android && domChange.text.length < to - from) {
      preferredPos = sel.to;
      preferredSide = "end";
    }
    let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), domChange.text, preferredPos - from, preferredSide);
    if (diff) {
      if (browser.chrome && view.inputState.lastKeyCode == 13 && diff.toB == diff.from + 2 && domChange.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder)
        diff.toB--;
      change = {
        from: from + diff.from,
        to: from + diff.toA,
        insert: Text.of(domChange.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder))
      };
    }
  } else if (newSel && (!view.hasFocus || !view.state.facet(editable) || newSel.main.eq(sel))) {
    newSel = null;
  }
  if (!change && !newSel)
    return false;
  if (!change && domChange.typeOver && !sel.empty && newSel && newSel.main.empty) {
    change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) };
  } else if (change && change.from >= sel.from && change.to <= sel.to && (change.from != sel.from || change.to != sel.to) && sel.to - sel.from - (change.to - change.from) <= 4) {
    change = {
      from: sel.from,
      to: sel.to,
      insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to))
    };
  } else if ((browser.mac || browser.android) && change && change.from == change.to && change.from == sel.head - 1 && /^\. ?$/.test(change.insert.toString())) {
    if (newSel && change.insert.length == 2)
      newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
    change = { from: sel.from, to: sel.to, insert: Text.of([" "]) };
  } else if (browser.chrome && change && change.from == change.to && change.from == sel.head && change.insert.toString() == "\n " && view.lineWrapping) {
    if (newSel)
      newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
    change = { from: sel.from, to: sel.to, insert: Text.of([" "]) };
  }
  if (change) {
    let startState = view.state;
    if (browser.ios && view.inputState.flushIOSKey(view))
      return true;
    if (browser.android && (change.from == sel.from && change.to == sel.to && change.insert.length == 1 && change.insert.lines == 2 && dispatchKey(view.contentDOM, "Enter", 13) || change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 && dispatchKey(view.contentDOM, "Backspace", 8) || change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 && dispatchKey(view.contentDOM, "Delete", 46)))
      return true;
    let text2 = change.insert.toString();
    if (view.state.facet(inputHandler).some((h) => h(view, change.from, change.to, text2)))
      return true;
    if (view.inputState.composing >= 0)
      view.inputState.composing++;
    let tr;
    if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 && (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) && view.inputState.composing < 0) {
      let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : "";
      let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : "";
      tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, void 0, view.state.lineBreak) + after));
    } else {
      let changes = startState.changes(change);
      let mainSel = newSel && !startState.selection.main.eq(newSel.main) && newSel.main.to <= changes.newLength ? newSel.main : void 0;
      if (startState.selection.ranges.length > 1 && view.inputState.composing >= 0 && change.to <= sel.to && change.to >= sel.to - 10) {
        let replaced = view.state.sliceDoc(change.from, change.to);
        let compositionRange = compositionSurroundingNode(view) || view.state.doc.lineAt(sel.head);
        let offset = sel.to - change.to, size = sel.to - sel.from;
        tr = startState.changeByRange((range2) => {
          if (range2.from == sel.from && range2.to == sel.to)
            return { changes, range: mainSel || range2.map(changes) };
          let to = range2.to - offset, from = to - replaced.length;
          if (range2.to - range2.from != size || view.state.sliceDoc(from, to) != replaced || compositionRange && range2.to >= compositionRange.from && range2.from <= compositionRange.to)
            return { range: range2 };
          let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range2.to - sel.to;
          return {
            changes: rangeChanges,
            range: !mainSel ? range2.map(rangeChanges) : EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff))
          };
        });
      } else {
        tr = {
          changes,
          selection: mainSel && startState.selection.replaceRange(mainSel)
        };
      }
    }
    let userEvent = "input.type";
    if (view.composing) {
      userEvent += ".compose";
      if (view.inputState.compositionFirstChange) {
        userEvent += ".start";
        view.inputState.compositionFirstChange = false;
      }
    }
    view.dispatch(tr, { scrollIntoView: true, userEvent });
    return true;
  } else if (newSel && !newSel.main.eq(sel)) {
    let scrollIntoView3 = false, userEvent = "select";
    if (view.inputState.lastSelectionTime > Date.now() - 50) {
      if (view.inputState.lastSelectionOrigin == "select")
        scrollIntoView3 = true;
      userEvent = view.inputState.lastSelectionOrigin;
    }
    view.dispatch({ selection: newSel, scrollIntoView: scrollIntoView3, userEvent });
    return true;
  } else {
    return false;
  }
}
function findDiff(a, b, preferredPos, preferredSide) {
  let minLen = Math.min(a.length, b.length);
  let from = 0;
  while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from))
    from++;
  if (from == minLen && a.length == b.length)
    return null;
  let toA = a.length, toB = b.length;
  while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) {
    toA--;
    toB--;
  }
  if (preferredSide == "end") {
    let adjust = Math.max(0, from - Math.min(toA, toB));
    preferredPos -= toA + adjust - from;
  }
  if (toA < from && a.length < b.length) {
    let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0;
    from -= move;
    toB = from + (toB - toA);
    toA = from;
  } else if (toB < from) {
    let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0;
    from -= move;
    toA = from + (toA - toB);
    toB = from;
  }
  return { from, toA, toB };
}
function selectionPoints(view) {
  let result = [];
  if (view.root.activeElement != view.contentDOM)
    return result;
  let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange;
  if (anchorNode) {
    result.push(new DOMPoint(anchorNode, anchorOffset));
    if (focusNode != anchorNode || focusOffset != anchorOffset)
      result.push(new DOMPoint(focusNode, focusOffset));
  }
  return result;
}
function selectionFromPoints(points, base2) {
  if (points.length == 0)
    return null;
  let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor;
  return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base2, head + base2) : null;
}
var observeOptions = {
  childList: true,
  characterData: true,
  subtree: true,
  attributes: true,
  characterDataOldValue: true
};
var useCharData = browser.ie && browser.ie_version <= 11;
var DOMObserver = class {
  constructor(view) {
    this.view = view;
    this.active = false;
    this.selectionRange = new DOMSelectionState();
    this.selectionChanged = false;
    this.delayedFlush = -1;
    this.resizeTimeout = -1;
    this.queue = [];
    this.delayedAndroidKey = null;
    this.flushingAndroidKey = -1;
    this.lastChange = 0;
    this.scrollTargets = [];
    this.intersection = null;
    this.resize = null;
    this.intersecting = false;
    this.gapIntersection = null;
    this.gaps = [];
    this.parentCheck = -1;
    this.dom = view.contentDOM;
    this.observer = new MutationObserver((mutations) => {
      for (let mut of mutations)
        this.queue.push(mut);
      if ((browser.ie && browser.ie_version <= 11 || browser.ios && view.composing) && mutations.some((m) => m.type == "childList" && m.removedNodes.length || m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length))
        this.flushSoon();
      else
        this.flush();
    });
    if (useCharData)
      this.onCharData = (event) => {
        this.queue.push({
          target: event.target,
          type: "characterData",
          oldValue: event.prevValue
        });
        this.flushSoon();
      };
    this.onSelectionChange = this.onSelectionChange.bind(this);
    this.onResize = this.onResize.bind(this);
    this.onPrint = this.onPrint.bind(this);
    this.onScroll = this.onScroll.bind(this);
    if (typeof ResizeObserver == "function") {
      this.resize = new ResizeObserver(() => {
        if (this.view.docView.lastUpdate < Date.now() - 75)
          this.onResize();
      });
      this.resize.observe(view.scrollDOM);
    }
    this.addWindowListeners(this.win = view.win);
    this.start();
    if (typeof IntersectionObserver == "function") {
      this.intersection = new IntersectionObserver((entries) => {
        if (this.parentCheck < 0)
          this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1e3);
        if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0 != this.intersecting) {
          this.intersecting = !this.intersecting;
          if (this.intersecting != this.view.inView)
            this.onScrollChanged(document.createEvent("Event"));
        }
      }, {});
      this.intersection.observe(this.dom);
      this.gapIntersection = new IntersectionObserver((entries) => {
        if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0)
          this.onScrollChanged(document.createEvent("Event"));
      }, {});
    }
    this.listenForScroll();
    this.readSelectionRange();
  }
  onScrollChanged(e3) {
    this.view.inputState.runScrollHandlers(this.view, e3);
    if (this.intersecting)
      this.view.measure();
  }
  onScroll(e3) {
    if (this.intersecting)
      this.flush(false);
    this.onScrollChanged(e3);
  }
  onResize() {
    if (this.resizeTimeout < 0)
      this.resizeTimeout = setTimeout(() => {
        this.resizeTimeout = -1;
        this.view.requestMeasure();
      }, 50);
  }
  onPrint() {
    this.view.viewState.printing = true;
    this.view.measure();
    setTimeout(() => {
      this.view.viewState.printing = false;
      this.view.requestMeasure();
    }, 500);
  }
  updateGaps(gaps) {
    if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i) => g != gaps[i]))) {
      this.gapIntersection.disconnect();
      for (let gap of gaps)
        this.gapIntersection.observe(gap);
      this.gaps = gaps;
    }
  }
  onSelectionChange(event) {
    let wasChanged = this.selectionChanged;
    if (!this.readSelectionRange() || this.delayedAndroidKey)
      return;
    let { view } = this, sel = this.selectionRange;
    if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(view.dom, sel))
      return;
    let context = sel.anchorNode && view.docView.nearest(sel.anchorNode);
    if (context && context.ignoreEvent(event)) {
      if (!wasChanged)
        this.selectionChanged = false;
      return;
    }
    if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty && sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))
      this.flushSoon();
    else
      this.flush(false);
  }
  readSelectionRange() {
    let { view } = this;
    let range2 = browser.safari && view.root.nodeType == 11 && deepActiveElement(this.dom.ownerDocument) == this.dom && safariSelectionRangeHack(this.view) || getSelection(view.root);
    if (!range2 || this.selectionRange.eq(range2))
      return false;
    let local = hasSelection(this.dom, range2);
    if (local && !this.selectionChanged && view.inputState.lastFocusTime > Date.now() - 200 && view.inputState.lastTouchTime < Date.now() - 300 && atElementStart(this.dom, range2)) {
      this.view.inputState.lastFocusTime = 0;
      view.docView.updateSelection();
      return false;
    }
    this.selectionRange.setRange(range2);
    if (local)
      this.selectionChanged = true;
    return true;
  }
  setSelectionRange(anchor, head) {
    this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset);
    this.selectionChanged = false;
  }
  clearSelectionRange() {
    this.selectionRange.set(null, 0, null, 0);
  }
  listenForScroll() {
    this.parentCheck = -1;
    let i = 0, changed = null;
    for (let dom = this.dom; dom; ) {
      if (dom.nodeType == 1) {
        if (!changed && i < this.scrollTargets.length && this.scrollTargets[i] == dom)
          i++;
        else if (!changed)
          changed = this.scrollTargets.slice(0, i);
        if (changed)
          changed.push(dom);
        dom = dom.assignedSlot || dom.parentNode;
      } else if (dom.nodeType == 11) {
        dom = dom.host;
      } else {
        break;
      }
    }
    if (i < this.scrollTargets.length && !changed)
      changed = this.scrollTargets.slice(0, i);
    if (changed) {
      for (let dom of this.scrollTargets)
        dom.removeEventListener("scroll", this.onScroll);
      for (let dom of this.scrollTargets = changed)
        dom.addEventListener("scroll", this.onScroll);
    }
  }
  ignore(f) {
    if (!this.active)
      return f();
    try {
      this.stop();
      return f();
    } finally {
      this.start();
      this.clear();
    }
  }
  start() {
    if (this.active)
      return;
    this.observer.observe(this.dom, observeOptions);
    if (useCharData)
      this.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
    this.active = true;
  }
  stop() {
    if (!this.active)
      return;
    this.active = false;
    this.observer.disconnect();
    if (useCharData)
      this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
  }
  clear() {
    this.processRecords();
    this.queue.length = 0;
    this.selectionChanged = false;
  }
  delayAndroidKey(key, keyCode) {
    var _a2;
    if (!this.delayedAndroidKey) {
      let flush2 = () => {
        let key2 = this.delayedAndroidKey;
        if (key2) {
          this.clearDelayedAndroidKey();
          if (!this.flush() && key2.force)
            dispatchKey(this.dom, key2.key, key2.keyCode);
        }
      };
      this.flushingAndroidKey = this.view.win.requestAnimationFrame(flush2);
    }
    if (!this.delayedAndroidKey || key == "Enter")
      this.delayedAndroidKey = {
        key,
        keyCode,
        force: this.lastChange < Date.now() - 50 || !!((_a2 = this.delayedAndroidKey) === null || _a2 === void 0 ? void 0 : _a2.force)
      };
  }
  clearDelayedAndroidKey() {
    this.win.cancelAnimationFrame(this.flushingAndroidKey);
    this.delayedAndroidKey = null;
    this.flushingAndroidKey = -1;
  }
  flushSoon() {
    if (this.delayedFlush < 0)
      this.delayedFlush = this.view.win.requestAnimationFrame(() => {
        this.delayedFlush = -1;
        this.flush();
      });
  }
  forceFlush() {
    if (this.delayedFlush >= 0) {
      this.view.win.cancelAnimationFrame(this.delayedFlush);
      this.delayedFlush = -1;
    }
    this.flush();
  }
  processRecords() {
    let records = this.queue;
    for (let mut of this.observer.takeRecords())
      records.push(mut);
    if (records.length)
      this.queue = [];
    let from = -1, to = -1, typeOver = false;
    for (let record2 of records) {
      let range2 = this.readMutation(record2);
      if (!range2)
        continue;
      if (range2.typeOver)
        typeOver = true;
      if (from == -1) {
        ({ from, to } = range2);
      } else {
        from = Math.min(range2.from, from);
        to = Math.max(range2.to, to);
      }
    }
    return { from, to, typeOver };
  }
  readChange() {
    let { from, to, typeOver } = this.processRecords();
    let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange);
    if (from < 0 && !newSel)
      return null;
    if (from > -1)
      this.lastChange = Date.now();
    this.view.inputState.lastFocusTime = 0;
    this.selectionChanged = false;
    return new DOMChange(this.view, from, to, typeOver);
  }
  flush(readSelection = true) {
    if (this.delayedFlush >= 0 || this.delayedAndroidKey)
      return false;
    if (readSelection)
      this.readSelectionRange();
    let domChange = this.readChange();
    if (!domChange)
      return false;
    let startState = this.view.state;
    let handled = applyDOMChange(this.view, domChange);
    if (this.view.state == startState)
      this.view.update([]);
    return handled;
  }
  readMutation(rec) {
    let cView = this.view.docView.nearest(rec.target);
    if (!cView || cView.ignoreMutation(rec))
      return null;
    cView.markDirty(rec.type == "attributes");
    if (rec.type == "attributes")
      cView.dirty |= 4;
    if (rec.type == "childList") {
      let childBefore = findChild(cView, rec.previousSibling || rec.target.previousSibling, -1);
      let childAfter = findChild(cView, rec.nextSibling || rec.target.nextSibling, 1);
      return {
        from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart,
        to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd,
        typeOver: false
      };
    } else if (rec.type == "characterData") {
      return { from: cView.posAtStart, to: cView.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue };
    } else {
      return null;
    }
  }
  setWindow(win) {
    if (win != this.win) {
      this.removeWindowListeners(this.win);
      this.win = win;
      this.addWindowListeners(this.win);
    }
  }
  addWindowListeners(win) {
    win.addEventListener("resize", this.onResize);
    win.addEventListener("beforeprint", this.onPrint);
    win.addEventListener("scroll", this.onScroll);
    win.document.addEventListener("selectionchange", this.onSelectionChange);
  }
  removeWindowListeners(win) {
    win.removeEventListener("scroll", this.onScroll);
    win.removeEventListener("resize", this.onResize);
    win.removeEventListener("beforeprint", this.onPrint);
    win.document.removeEventListener("selectionchange", this.onSelectionChange);
  }
  destroy() {
    var _a2, _b, _c;
    this.stop();
    (_a2 = this.intersection) === null || _a2 === void 0 ? void 0 : _a2.disconnect();
    (_b = this.gapIntersection) === null || _b === void 0 ? void 0 : _b.disconnect();
    (_c = this.resize) === null || _c === void 0 ? void 0 : _c.disconnect();
    for (let dom of this.scrollTargets)
      dom.removeEventListener("scroll", this.onScroll);
    this.removeWindowListeners(this.win);
    clearTimeout(this.parentCheck);
    clearTimeout(this.resizeTimeout);
    this.win.cancelAnimationFrame(this.delayedFlush);
    this.win.cancelAnimationFrame(this.flushingAndroidKey);
  }
};
function findChild(cView, dom, dir) {
  while (dom) {
    let curView = ContentView.get(dom);
    if (curView && curView.parent == cView)
      return curView;
    let parent2 = dom.parentNode;
    dom = parent2 != cView.dom ? parent2 : dir > 0 ? dom.nextSibling : dom.previousSibling;
  }
  return null;
}
function safariSelectionRangeHack(view) {
  let found = null;
  function read(event) {
    event.preventDefault();
    event.stopImmediatePropagation();
    found = event.getTargetRanges()[0];
  }
  view.contentDOM.addEventListener("beforeinput", read, true);
  view.dom.ownerDocument.execCommand("indent");
  view.contentDOM.removeEventListener("beforeinput", read, true);
  if (!found)
    return null;
  let anchorNode = found.startContainer, anchorOffset = found.startOffset;
  let focusNode = found.endContainer, focusOffset = found.endOffset;
  let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor);
  if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset))
    [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];
  return { anchorNode, anchorOffset, focusNode, focusOffset };
}
var EditorView = class {
  constructor(config2 = {}) {
    this.plugins = [];
    this.pluginMap = /* @__PURE__ */ new Map();
    this.editorAttrs = {};
    this.contentAttrs = {};
    this.bidiCache = [];
    this.destroyed = false;
    this.updateState = 2;
    this.measureScheduled = -1;
    this.measureRequests = [];
    this.contentDOM = document.createElement("div");
    this.scrollDOM = document.createElement("div");
    this.scrollDOM.tabIndex = -1;
    this.scrollDOM.className = "cm-scroller";
    this.scrollDOM.appendChild(this.contentDOM);
    this.announceDOM = document.createElement("div");
    this.announceDOM.style.cssText = "position: absolute; top: -10000px";
    this.announceDOM.setAttribute("aria-live", "polite");
    this.dom = document.createElement("div");
    this.dom.appendChild(this.announceDOM);
    this.dom.appendChild(this.scrollDOM);
    this._dispatch = config2.dispatch || ((tr) => this.update([tr]));
    this.dispatch = this.dispatch.bind(this);
    this._root = config2.root || getRoot(config2.parent) || document;
    this.viewState = new ViewState(config2.state || EditorState.create(config2));
    this.plugins = this.state.facet(viewPlugin).map((spec) => new PluginInstance(spec));
    for (let plugin of this.plugins)
      plugin.update(this);
    this.observer = new DOMObserver(this);
    this.inputState = new InputState(this);
    this.inputState.ensureHandlers(this, this.plugins);
    this.docView = new DocView(this);
    this.mountStyles();
    this.updateAttrs();
    this.updateState = 0;
    this.requestMeasure();
    if (config2.parent)
      config2.parent.appendChild(this.dom);
  }
  get state() {
    return this.viewState.state;
  }
  get viewport() {
    return this.viewState.viewport;
  }
  get visibleRanges() {
    return this.viewState.visibleRanges;
  }
  get inView() {
    return this.viewState.inView;
  }
  get composing() {
    return this.inputState.composing > 0;
  }
  get compositionStarted() {
    return this.inputState.composing >= 0;
  }
  get root() {
    return this._root;
  }
  get win() {
    return this.dom.ownerDocument.defaultView || window;
  }
  dispatch(...input) {
    this._dispatch(input.length == 1 && input[0] instanceof Transaction2 ? input[0] : this.state.update(...input));
  }
  update(transactions) {
    if (this.updateState != 0)
      throw new Error("Calls to EditorView.update are not allowed while an update is in progress");
    let redrawn = false, attrsChanged = false, update2;
    let state = this.state;
    for (let tr of transactions) {
      if (tr.startState != state)
        throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");
      state = tr.state;
    }
    if (this.destroyed) {
      this.viewState.state = state;
      return;
    }
    let pendingKey = this.observer.delayedAndroidKey, domChange = null;
    if (pendingKey) {
      this.observer.clearDelayedAndroidKey();
      domChange = this.observer.readChange();
      if (domChange && !this.state.doc.eq(state.doc) || !this.state.selection.eq(state.selection))
        domChange = null;
    } else {
      this.observer.clear();
    }
    if (state.facet(EditorState.phrases) != this.state.facet(EditorState.phrases))
      return this.setState(state);
    update2 = ViewUpdate.create(this, state, transactions);
    let scrollTarget = this.viewState.scrollTarget;
    try {
      this.updateState = 2;
      for (let tr of transactions) {
        if (scrollTarget)
          scrollTarget = scrollTarget.map(tr.changes);
        if (tr.scrollIntoView) {
          let { main } = tr.state.selection;
          scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1));
        }
        for (let e3 of tr.effects)
          if (e3.is(scrollIntoView))
            scrollTarget = e3.value;
      }
      this.viewState.update(update2, scrollTarget);
      this.bidiCache = CachedOrder.update(this.bidiCache, update2.changes);
      if (!update2.empty) {
        this.updatePlugins(update2);
        this.inputState.update(update2);
      }
      redrawn = this.docView.update(update2);
      if (this.state.facet(styleModule) != this.styleModules)
        this.mountStyles();
      attrsChanged = this.updateAttrs();
      this.showAnnouncements(transactions);
      this.docView.updateSelection(redrawn, transactions.some((tr) => tr.isUserEvent("select.pointer")));
    } finally {
      this.updateState = 0;
    }
    if (update2.startState.facet(theme) != update2.state.facet(theme))
      this.viewState.mustMeasureContent = true;
    if (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent)
      this.requestMeasure();
    if (!update2.empty)
      for (let listener of this.state.facet(updateListener))
        listener(update2);
    if (domChange) {
      if (!applyDOMChange(this, domChange) && pendingKey.force)
        dispatchKey(this.contentDOM, pendingKey.key, pendingKey.keyCode);
    }
  }
  setState(newState) {
    if (this.updateState != 0)
      throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");
    if (this.destroyed) {
      this.viewState.state = newState;
      return;
    }
    this.updateState = 2;
    let hadFocus = this.hasFocus;
    try {
      for (let plugin of this.plugins)
        plugin.destroy(this);
      this.viewState = new ViewState(newState);
      this.plugins = newState.facet(viewPlugin).map((spec) => new PluginInstance(spec));
      this.pluginMap.clear();
      for (let plugin of this.plugins)
        plugin.update(this);
      this.docView = new DocView(this);
      this.inputState.ensureHandlers(this, this.plugins);
      this.mountStyles();
      this.updateAttrs();
      this.bidiCache = [];
    } finally {
      this.updateState = 0;
    }
    if (hadFocus)
      this.focus();
    this.requestMeasure();
  }
  updatePlugins(update2) {
    let prevSpecs = update2.startState.facet(viewPlugin), specs = update2.state.facet(viewPlugin);
    if (prevSpecs != specs) {
      let newPlugins = [];
      for (let spec of specs) {
        let found = prevSpecs.indexOf(spec);
        if (found < 0) {
          newPlugins.push(new PluginInstance(spec));
        } else {
          let plugin = this.plugins[found];
          plugin.mustUpdate = update2;
          newPlugins.push(plugin);
        }
      }
      for (let plugin of this.plugins)
        if (plugin.mustUpdate != update2)
          plugin.destroy(this);
      this.plugins = newPlugins;
      this.pluginMap.clear();
      this.inputState.ensureHandlers(this, this.plugins);
    } else {
      for (let p of this.plugins)
        p.mustUpdate = update2;
    }
    for (let i = 0; i < this.plugins.length; i++)
      this.plugins[i].update(this);
  }
  measure(flush2 = true) {
    if (this.destroyed)
      return;
    if (this.measureScheduled > -1)
      cancelAnimationFrame(this.measureScheduled);
    this.measureScheduled = 0;
    if (flush2)
      this.observer.forceFlush();
    let updated = null;
    let { scrollHeight, scrollTop, clientHeight } = this.scrollDOM;
    let refHeight = scrollTop > scrollHeight - clientHeight - 4 ? scrollHeight : scrollTop;
    try {
      for (let i = 0; ; i++) {
        this.updateState = 1;
        let oldViewport = this.viewport;
        let refBlock = this.viewState.lineBlockAtHeight(refHeight);
        let changed = this.viewState.measure(this);
        if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null)
          break;
        if (i > 5) {
          console.warn(this.measureRequests.length ? "Measure loop restarted more than 5 times" : "Viewport failed to stabilize");
          break;
        }
        let measuring = [];
        if (!(changed & 4))
          [this.measureRequests, measuring] = [measuring, this.measureRequests];
        let measured = measuring.map((m) => {
          try {
            return m.read(this);
          } catch (e3) {
            logException(this.state, e3);
            return BadMeasure;
          }
        });
        let update2 = ViewUpdate.create(this, this.state, []), redrawn = false, scrolled = false;
        update2.flags |= changed;
        if (!updated)
          updated = update2;
        else
          updated.flags |= changed;
        this.updateState = 2;
        if (!update2.empty) {
          this.updatePlugins(update2);
          this.inputState.update(update2);
          this.updateAttrs();
          redrawn = this.docView.update(update2);
        }
        for (let i2 = 0; i2 < measuring.length; i2++)
          if (measured[i2] != BadMeasure) {
            try {
              let m = measuring[i2];
              if (m.write)
                m.write(measured[i2], this);
            } catch (e3) {
              logException(this.state, e3);
            }
          }
        if (this.viewState.editorHeight) {
          if (this.viewState.scrollTarget) {
            this.docView.scrollIntoView(this.viewState.scrollTarget);
            this.viewState.scrollTarget = null;
            scrolled = true;
          } else {
            let diff = this.viewState.lineBlockAt(refBlock.from).top - refBlock.top;
            if (diff > 1 || diff < -1) {
              this.scrollDOM.scrollTop += diff;
              scrolled = true;
            }
          }
        }
        if (redrawn)
          this.docView.updateSelection(true);
        if (this.viewport.from == oldViewport.from && this.viewport.to == oldViewport.to && !scrolled && this.measureRequests.length == 0)
          break;
      }
    } finally {
      this.updateState = 0;
      this.measureScheduled = -1;
    }
    if (updated && !updated.empty)
      for (let listener of this.state.facet(updateListener))
        listener(updated);
  }
  get themeClasses() {
    return baseThemeID + " " + (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + " " + this.state.facet(theme);
  }
  updateAttrs() {
    let editorAttrs = attrsFromFacet(this, editorAttributes, {
      class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses
    });
    let contentAttrs = {
      spellcheck: "false",
      autocorrect: "off",
      autocapitalize: "off",
      translate: "no",
      contenteditable: !this.state.facet(editable) ? "false" : "true",
      class: "cm-content",
      style: `${browser.tabSize}: ${this.state.tabSize}`,
      role: "textbox",
      "aria-multiline": "true"
    };
    if (this.state.readOnly)
      contentAttrs["aria-readonly"] = "true";
    attrsFromFacet(this, contentAttributes, contentAttrs);
    let changed = this.observer.ignore(() => {
      let changedContent = updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs);
      let changedEditor = updateAttrs(this.dom, this.editorAttrs, editorAttrs);
      return changedContent || changedEditor;
    });
    this.editorAttrs = editorAttrs;
    this.contentAttrs = contentAttrs;
    return changed;
  }
  showAnnouncements(trs) {
    let first = true;
    for (let tr of trs)
      for (let effect of tr.effects)
        if (effect.is(EditorView.announce)) {
          if (first)
            this.announceDOM.textContent = "";
          first = false;
          let div = this.announceDOM.appendChild(document.createElement("div"));
          div.textContent = effect.value;
        }
  }
  mountStyles() {
    this.styleModules = this.state.facet(styleModule);
    StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1).reverse());
  }
  readMeasured() {
    if (this.updateState == 2)
      throw new Error("Reading the editor layout isn't allowed during an update");
    if (this.updateState == 0 && this.measureScheduled > -1)
      this.measure(false);
  }
  requestMeasure(request) {
    if (this.measureScheduled < 0)
      this.measureScheduled = this.win.requestAnimationFrame(() => this.measure());
    if (request) {
      if (request.key != null)
        for (let i = 0; i < this.measureRequests.length; i++) {
          if (this.measureRequests[i].key === request.key) {
            this.measureRequests[i] = request;
            return;
          }
        }
      this.measureRequests.push(request);
    }
  }
  plugin(plugin) {
    let known = this.pluginMap.get(plugin);
    if (known === void 0 || known && known.spec != plugin)
      this.pluginMap.set(plugin, known = this.plugins.find((p) => p.spec == plugin) || null);
    return known && known.update(this).value;
  }
  get documentTop() {
    return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop;
  }
  get documentPadding() {
    return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom };
  }
  elementAtHeight(height4) {
    this.readMeasured();
    return this.viewState.elementAtHeight(height4);
  }
  lineBlockAtHeight(height4) {
    this.readMeasured();
    return this.viewState.lineBlockAtHeight(height4);
  }
  get viewportLineBlocks() {
    return this.viewState.viewportLines;
  }
  lineBlockAt(pos) {
    return this.viewState.lineBlockAt(pos);
  }
  get contentHeight() {
    return this.viewState.contentHeight;
  }
  moveByChar(start, forward, by) {
    return skipAtoms(this, start, moveByChar(this, start, forward, by));
  }
  moveByGroup(start, forward) {
    return skipAtoms(this, start, moveByChar(this, start, forward, (initial) => byGroup(this, start.head, initial)));
  }
  moveToLineBoundary(start, forward, includeWrap = true) {
    return moveToLineBoundary(this, start, forward, includeWrap);
  }
  moveVertically(start, forward, distance) {
    return skipAtoms(this, start, moveVertically(this, start, forward, distance));
  }
  domAtPos(pos) {
    return this.docView.domAtPos(pos);
  }
  posAtDOM(node, offset = 0) {
    return this.docView.posFromDOM(node, offset);
  }
  posAtCoords(coords, precise = true) {
    this.readMeasured();
    return posAtCoords(this, coords, precise);
  }
  coordsAtPos(pos, side = 1) {
    this.readMeasured();
    let rect = this.docView.coordsAt(pos, side);
    if (!rect || rect.left == rect.right)
      return rect;
    let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line);
    let span = order[BidiSpan.find(order, pos - line.from, -1, side)];
    return flattenRect(rect, span.dir == Direction.LTR == side > 0);
  }
  get defaultCharacterWidth() {
    return this.viewState.heightOracle.charWidth;
  }
  get defaultLineHeight() {
    return this.viewState.heightOracle.lineHeight;
  }
  get textDirection() {
    return this.viewState.defaultTextDirection;
  }
  textDirectionAt(pos) {
    let perLine = this.state.facet(perLineTextDirection);
    if (!perLine || pos < this.viewport.from || pos > this.viewport.to)
      return this.textDirection;
    this.readMeasured();
    return this.docView.textDirectionAt(pos);
  }
  get lineWrapping() {
    return this.viewState.heightOracle.lineWrapping;
  }
  bidiSpans(line) {
    if (line.length > MaxBidiLine)
      return trivialOrder(line.length);
    let dir = this.textDirectionAt(line.from);
    for (let entry of this.bidiCache)
      if (entry.from == line.from && entry.dir == dir)
        return entry.order;
    let order = computeOrder(line.text, dir);
    this.bidiCache.push(new CachedOrder(line.from, line.to, dir, order));
    return order;
  }
  get hasFocus() {
    var _a2;
    return (this.dom.ownerDocument.hasFocus() || browser.safari && ((_a2 = this.inputState) === null || _a2 === void 0 ? void 0 : _a2.lastContextMenu) > Date.now() - 3e4) && this.root.activeElement == this.contentDOM;
  }
  focus() {
    this.observer.ignore(() => {
      focusPreventScroll(this.contentDOM);
      this.docView.updateSelection();
    });
  }
  setRoot(root2) {
    if (this._root != root2) {
      this._root = root2;
      this.observer.setWindow((root2.nodeType == 9 ? root2 : root2.ownerDocument).defaultView || window);
      this.mountStyles();
    }
  }
  destroy() {
    for (let plugin of this.plugins)
      plugin.destroy(this);
    this.plugins = [];
    this.inputState.destroy();
    this.dom.remove();
    this.observer.destroy();
    if (this.measureScheduled > -1)
      cancelAnimationFrame(this.measureScheduled);
    this.destroyed = true;
  }
  static scrollIntoView(pos, options2 = {}) {
    return scrollIntoView.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options2.y, options2.x, options2.yMargin, options2.xMargin));
  }
  static domEventHandlers(handlers2) {
    return ViewPlugin.define(() => ({}), { eventHandlers: handlers2 });
  }
  static theme(spec, options2) {
    let prefix = StyleModule.newName();
    let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))];
    if (options2 && options2.dark)
      result.push(darkTheme.of(true));
    return result;
  }
  static baseTheme(spec) {
    return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs)));
  }
  static findFromDOM(dom) {
    var _a2;
    let content2 = dom.querySelector(".cm-content");
    let cView = content2 && ContentView.get(content2) || ContentView.get(dom);
    return ((_a2 = cView === null || cView === void 0 ? void 0 : cView.rootView) === null || _a2 === void 0 ? void 0 : _a2.view) || null;
  }
};
EditorView.styleModule = styleModule;
EditorView.inputHandler = inputHandler;
EditorView.perLineTextDirection = perLineTextDirection;
EditorView.exceptionSink = exceptionSink;
EditorView.updateListener = updateListener;
EditorView.editable = editable;
EditorView.mouseSelectionStyle = mouseSelectionStyle;
EditorView.dragMovesSelection = dragMovesSelection$1;
EditorView.clickAddsSelectionRange = clickAddsSelectionRange;
EditorView.decorations = decorations;
EditorView.atomicRanges = atomicRanges;
EditorView.scrollMargins = scrollMargins;
EditorView.darkTheme = darkTheme;
EditorView.contentAttributes = contentAttributes;
EditorView.editorAttributes = editorAttributes;
EditorView.lineWrapping = /* @__PURE__ */ EditorView.contentAttributes.of({ "class": "cm-lineWrapping" });
EditorView.announce = /* @__PURE__ */ StateEffect.define();
var MaxBidiLine = 4096;
var BadMeasure = {};
var CachedOrder = class {
  constructor(from, to, dir, order) {
    this.from = from;
    this.to = to;
    this.dir = dir;
    this.order = order;
  }
  static update(cache, changes) {
    if (changes.empty)
      return cache;
    let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : Direction.LTR;
    for (let i = Math.max(0, cache.length - 10); i < cache.length; i++) {
      let entry = cache[i];
      if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to))
        result.push(new CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.order));
    }
    return result;
  }
};
function attrsFromFacet(view, facet, base2) {
  for (let sources = view.state.facet(facet), i = sources.length - 1; i >= 0; i--) {
    let source = sources[i], value = typeof source == "function" ? source(view) : source;
    if (value)
      combineAttrs(value, base2);
  }
  return base2;
}
var currentPlatform = browser.mac ? "mac" : browser.windows ? "win" : browser.linux ? "linux" : "key";
function normalizeKeyName(name2, platform) {
  const parts = name2.split(/-(?!$)/);
  let result = parts[parts.length - 1];
  if (result == "Space")
    result = " ";
  let alt, ctrl, shift2, meta3;
  for (let i = 0; i < parts.length - 1; ++i) {
    const mod = parts[i];
    if (/^(cmd|meta|m)$/i.test(mod))
      meta3 = true;
    else if (/^a(lt)?$/i.test(mod))
      alt = true;
    else if (/^(c|ctrl|control)$/i.test(mod))
      ctrl = true;
    else if (/^s(hift)?$/i.test(mod))
      shift2 = true;
    else if (/^mod$/i.test(mod)) {
      if (platform == "mac")
        meta3 = true;
      else
        ctrl = true;
    } else
      throw new Error("Unrecognized modifier name: " + mod);
  }
  if (alt)
    result = "Alt-" + result;
  if (ctrl)
    result = "Ctrl-" + result;
  if (meta3)
    result = "Meta-" + result;
  if (shift2)
    result = "Shift-" + result;
  return result;
}
function modifiers(name2, event, shift2) {
  if (event.altKey)
    name2 = "Alt-" + name2;
  if (event.ctrlKey)
    name2 = "Ctrl-" + name2;
  if (event.metaKey)
    name2 = "Meta-" + name2;
  if (shift2 !== false && event.shiftKey)
    name2 = "Shift-" + name2;
  return name2;
}
var handleKeyEvents = /* @__PURE__ */ Prec.default(/* @__PURE__ */ EditorView.domEventHandlers({
  keydown(event, view) {
    return runHandlers(getKeymap(view.state), event, view, "editor");
  }
}));
var keymap = /* @__PURE__ */ Facet.define({ enables: handleKeyEvents });
var Keymaps = /* @__PURE__ */ new WeakMap();
function getKeymap(state) {
  let bindings = state.facet(keymap);
  let map2 = Keymaps.get(bindings);
  if (!map2)
    Keymaps.set(bindings, map2 = buildKeymap(bindings.reduce((a, b) => a.concat(b), [])));
  return map2;
}
function runScopeHandlers(view, event, scope) {
  return runHandlers(getKeymap(view.state), event, view, scope);
}
var storedPrefix = null;
var PrefixTimeout = 4e3;
function buildKeymap(bindings, platform = currentPlatform) {
  let bound = /* @__PURE__ */ Object.create(null);
  let isPrefix = /* @__PURE__ */ Object.create(null);
  let checkPrefix = (name2, is) => {
    let current = isPrefix[name2];
    if (current == null)
      isPrefix[name2] = is;
    else if (current != is)
      throw new Error("Key binding " + name2 + " is used both as a regular binding and as a multi-stroke prefix");
  };
  let add3 = (scope, key, command2, preventDefault) => {
    var _a2, _b;
    let scopeObj = bound[scope] || (bound[scope] = /* @__PURE__ */ Object.create(null));
    let parts = key.split(/ (?!$)/).map((k) => normalizeKeyName(k, platform));
    for (let i = 1; i < parts.length; i++) {
      let prefix = parts.slice(0, i).join(" ");
      checkPrefix(prefix, true);
      if (!scopeObj[prefix])
        scopeObj[prefix] = {
          preventDefault: true,
          run: [(view) => {
            let ourObj = storedPrefix = { view, prefix, scope };
            setTimeout(() => {
              if (storedPrefix == ourObj)
                storedPrefix = null;
            }, PrefixTimeout);
            return true;
          }]
        };
    }
    let full = parts.join(" ");
    checkPrefix(full, false);
    let binding = scopeObj[full] || (scopeObj[full] = { preventDefault: false, run: ((_b = (_a2 = scopeObj._any) === null || _a2 === void 0 ? void 0 : _a2.run) === null || _b === void 0 ? void 0 : _b.slice()) || [] });
    if (command2)
      binding.run.push(command2);
    if (preventDefault)
      binding.preventDefault = true;
  };
  for (let b of bindings) {
    let scopes = b.scope ? b.scope.split(" ") : ["editor"];
    if (b.any)
      for (let scope of scopes) {
        let scopeObj = bound[scope] || (bound[scope] = /* @__PURE__ */ Object.create(null));
        if (!scopeObj._any)
          scopeObj._any = { preventDefault: false, run: [] };
        for (let key in scopeObj)
          scopeObj[key].run.push(b.any);
      }
    let name2 = b[platform] || b.key;
    if (!name2)
      continue;
    for (let scope of scopes) {
      add3(scope, name2, b.run, b.preventDefault);
      if (b.shift)
        add3(scope, "Shift-" + name2, b.shift, b.preventDefault);
    }
  }
  return bound;
}
function runHandlers(map2, event, view, scope) {
  let name2 = keyName(event);
  let charCode = codePointAt(name2, 0), isChar = codePointSize(charCode) == name2.length && name2 != " ";
  let prefix = "", fallthrough = false;
  if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) {
    prefix = storedPrefix.prefix + " ";
    if (fallthrough = modifierCodes.indexOf(event.keyCode) < 0)
      storedPrefix = null;
  }
  let ran = /* @__PURE__ */ new Set();
  let runFor = (binding) => {
    if (binding) {
      for (let cmd2 of binding.run)
        if (!ran.has(cmd2)) {
          ran.add(cmd2);
          if (cmd2(view, event))
            return true;
        }
      if (binding.preventDefault)
        fallthrough = true;
    }
    return false;
  };
  let scopeObj = map2[scope], baseName, shiftName;
  if (scopeObj) {
    if (runFor(scopeObj[prefix + modifiers(name2, event, !isChar)]))
      return true;
    if (isChar && (event.shiftKey || event.altKey || event.metaKey || charCode > 127) && (baseName = base[event.keyCode]) && baseName != name2) {
      if (runFor(scopeObj[prefix + modifiers(baseName, event, true)]))
        return true;
      else if (event.shiftKey && (shiftName = shift[event.keyCode]) != name2 && shiftName != baseName && runFor(scopeObj[prefix + modifiers(shiftName, event, false)]))
        return true;
    } else if (isChar && event.shiftKey) {
      if (runFor(scopeObj[prefix + modifiers(name2, event, true)]))
        return true;
    }
    if (runFor(scopeObj._any))
      return true;
  }
  return fallthrough;
}
var CanHidePrimary = !browser.ios;
var selectionConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      cursorBlinkRate: 1200,
      drawRangeCursor: true
    }, {
      cursorBlinkRate: (a, b) => Math.min(a, b),
      drawRangeCursor: (a, b) => a || b
    });
  }
});
function drawSelection(config2 = {}) {
  return [
    selectionConfig.of(config2),
    drawSelectionPlugin,
    hideNativeSelection
  ];
}
var Piece = class {
  constructor(left2, top3, width, height4, className) {
    this.left = left2;
    this.top = top3;
    this.width = width;
    this.height = height4;
    this.className = className;
  }
  draw() {
    let elt = document.createElement("div");
    elt.className = this.className;
    this.adjust(elt);
    return elt;
  }
  adjust(elt) {
    elt.style.left = this.left + "px";
    elt.style.top = this.top + "px";
    if (this.width >= 0)
      elt.style.width = this.width + "px";
    elt.style.height = this.height + "px";
  }
  eq(p) {
    return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height && this.className == p.className;
  }
};
var drawSelectionPlugin = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.rangePieces = [];
    this.cursors = [];
    this.measureReq = { read: this.readPos.bind(this), write: this.drawSel.bind(this) };
    this.selectionLayer = view.scrollDOM.appendChild(document.createElement("div"));
    this.selectionLayer.className = "cm-selectionLayer";
    this.selectionLayer.setAttribute("aria-hidden", "true");
    this.cursorLayer = view.scrollDOM.appendChild(document.createElement("div"));
    this.cursorLayer.className = "cm-cursorLayer";
    this.cursorLayer.setAttribute("aria-hidden", "true");
    view.requestMeasure(this.measureReq);
    this.setBlinkRate();
  }
  setBlinkRate() {
    this.cursorLayer.style.animationDuration = this.view.state.facet(selectionConfig).cursorBlinkRate + "ms";
  }
  update(update2) {
    let confChanged = update2.startState.facet(selectionConfig) != update2.state.facet(selectionConfig);
    if (confChanged || update2.selectionSet || update2.geometryChanged || update2.viewportChanged)
      this.view.requestMeasure(this.measureReq);
    if (update2.transactions.some((tr) => tr.scrollIntoView))
      this.cursorLayer.style.animationName = this.cursorLayer.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink";
    if (confChanged)
      this.setBlinkRate();
  }
  readPos() {
    let { state } = this.view, conf = state.facet(selectionConfig);
    let rangePieces = state.selection.ranges.map((r) => r.empty ? [] : measureRange(this.view, r)).reduce((a, b) => a.concat(b));
    let cursors = [];
    for (let r of state.selection.ranges) {
      let prim = r == state.selection.main;
      if (r.empty ? !prim || CanHidePrimary : conf.drawRangeCursor) {
        let piece = measureCursor(this.view, r, prim);
        if (piece)
          cursors.push(piece);
      }
    }
    return { rangePieces, cursors };
  }
  drawSel({ rangePieces, cursors }) {
    if (rangePieces.length != this.rangePieces.length || rangePieces.some((p, i) => !p.eq(this.rangePieces[i]))) {
      this.selectionLayer.textContent = "";
      for (let p of rangePieces)
        this.selectionLayer.appendChild(p.draw());
      this.rangePieces = rangePieces;
    }
    if (cursors.length != this.cursors.length || cursors.some((c, i) => !c.eq(this.cursors[i]))) {
      let oldCursors = this.cursorLayer.children;
      if (oldCursors.length !== cursors.length) {
        this.cursorLayer.textContent = "";
        for (const c of cursors)
          this.cursorLayer.appendChild(c.draw());
      } else {
        cursors.forEach((c, idx) => c.adjust(oldCursors[idx]));
      }
      this.cursors = cursors;
    }
  }
  destroy() {
    this.selectionLayer.remove();
    this.cursorLayer.remove();
  }
});
var themeSpec = {
  ".cm-line": {
    "& ::selection": { backgroundColor: "transparent !important" },
    "&::selection": { backgroundColor: "transparent !important" }
  }
};
if (CanHidePrimary)
  themeSpec[".cm-line"].caretColor = "transparent !important";
var hideNativeSelection = /* @__PURE__ */ Prec.highest(/* @__PURE__ */ EditorView.theme(themeSpec));
function getBase(view) {
  let rect = view.scrollDOM.getBoundingClientRect();
  let left2 = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth;
  return { left: left2 - view.scrollDOM.scrollLeft, top: rect.top - view.scrollDOM.scrollTop };
}
function wrappedLine(view, pos, inside2) {
  let range2 = EditorSelection.cursor(pos);
  return {
    from: Math.max(inside2.from, view.moveToLineBoundary(range2, false, true).from),
    to: Math.min(inside2.to, view.moveToLineBoundary(range2, true, true).from),
    type: BlockType.Text
  };
}
function blockAt(view, pos) {
  let line = view.lineBlockAt(pos);
  if (Array.isArray(line.type))
    for (let l of line.type) {
      if (l.to > pos || l.to == pos && (l.to == line.to || l.type == BlockType.Text))
        return l;
    }
  return line;
}
function measureRange(view, range2) {
  if (range2.to <= view.viewport.from || range2.from >= view.viewport.to)
    return [];
  let from = Math.max(range2.from, view.viewport.from), to = Math.min(range2.to, view.viewport.to);
  let ltr = view.textDirection == Direction.LTR;
  let content2 = view.contentDOM, contentRect = content2.getBoundingClientRect(), base2 = getBase(view);
  let lineStyle = window.getComputedStyle(content2.firstChild);
  let leftSide = contentRect.left + parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent));
  let rightSide = contentRect.right - parseInt(lineStyle.paddingRight);
  let startBlock = blockAt(view, from), endBlock = blockAt(view, to);
  let visualStart = startBlock.type == BlockType.Text ? startBlock : null;
  let visualEnd = endBlock.type == BlockType.Text ? endBlock : null;
  if (view.lineWrapping) {
    if (visualStart)
      visualStart = wrappedLine(view, from, visualStart);
    if (visualEnd)
      visualEnd = wrappedLine(view, to, visualEnd);
  }
  if (visualStart && visualEnd && visualStart.from == visualEnd.from) {
    return pieces(drawForLine(range2.from, range2.to, visualStart));
  } else {
    let top3 = visualStart ? drawForLine(range2.from, null, visualStart) : drawForWidget(startBlock, false);
    let bottom2 = visualEnd ? drawForLine(null, range2.to, visualEnd) : drawForWidget(endBlock, true);
    let between = [];
    if ((visualStart || startBlock).to < (visualEnd || endBlock).from - 1)
      between.push(piece(leftSide, top3.bottom, rightSide, bottom2.top));
    else if (top3.bottom < bottom2.top && view.elementAtHeight((top3.bottom + bottom2.top) / 2).type == BlockType.Text)
      top3.bottom = bottom2.top = (top3.bottom + bottom2.top) / 2;
    return pieces(top3).concat(between).concat(pieces(bottom2));
  }
  function piece(left2, top3, right2, bottom2) {
    return new Piece(left2 - base2.left, top3 - base2.top - 0.01, right2 - left2, bottom2 - top3 + 0.01, "cm-selectionBackground");
  }
  function pieces({ top: top3, bottom: bottom2, horizontal }) {
    let pieces2 = [];
    for (let i = 0; i < horizontal.length; i += 2)
      pieces2.push(piece(horizontal[i], top3, horizontal[i + 1], bottom2));
    return pieces2;
  }
  function drawForLine(from2, to2, line) {
    let top3 = 1e9, bottom2 = -1e9, horizontal = [];
    function addSpan(from3, fromOpen, to3, toOpen, dir) {
      let fromCoords = view.coordsAtPos(from3, from3 == line.to ? -2 : 2);
      let toCoords = view.coordsAtPos(to3, to3 == line.from ? 2 : -2);
      top3 = Math.min(fromCoords.top, toCoords.top, top3);
      bottom2 = Math.max(fromCoords.bottom, toCoords.bottom, bottom2);
      if (dir == Direction.LTR)
        horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right);
      else
        horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right);
    }
    let start = from2 !== null && from2 !== void 0 ? from2 : line.from, end = to2 !== null && to2 !== void 0 ? to2 : line.to;
    for (let r of view.visibleRanges)
      if (r.to > start && r.from < end) {
        for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end); ; ) {
          let docLine = view.state.doc.lineAt(pos);
          for (let span of view.bidiSpans(docLine)) {
            let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from;
            if (spanFrom >= endPos)
              break;
            if (spanTo > pos)
              addSpan(Math.max(spanFrom, pos), from2 == null && spanFrom <= start, Math.min(spanTo, endPos), to2 == null && spanTo >= end, span.dir);
          }
          pos = docLine.to + 1;
          if (pos >= endPos)
            break;
        }
      }
    if (horizontal.length == 0)
      addSpan(start, from2 == null, end, to2 == null, view.textDirection);
    return { top: top3, bottom: bottom2, horizontal };
  }
  function drawForWidget(block, top3) {
    let y2 = contentRect.top + (top3 ? block.top : block.bottom);
    return { top: y2, bottom: y2, horizontal: [] };
  }
}
function measureCursor(view, cursor, primary) {
  let pos = view.coordsAtPos(cursor.head, cursor.assoc || 1);
  if (!pos)
    return null;
  let base2 = getBase(view);
  return new Piece(pos.left - base2.left, pos.top - base2.top, -1, pos.bottom - pos.top, primary ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary");
}
function iterMatches(doc2, re2, from, to, f) {
  re2.lastIndex = 0;
  for (let cursor = doc2.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length) {
    if (!cursor.lineBreak)
      while (m = re2.exec(cursor.value))
        f(pos + m.index, m);
  }
}
function matchRanges(view, maxLength) {
  let visible = view.visibleRanges;
  if (visible.length == 1 && visible[0].from == view.viewport.from && visible[0].to == view.viewport.to)
    return visible;
  let result = [];
  for (let { from, to } of visible) {
    from = Math.max(view.state.doc.lineAt(from).from, from - maxLength);
    to = Math.min(view.state.doc.lineAt(to).to, to + maxLength);
    if (result.length && result[result.length - 1].to >= from)
      result[result.length - 1].to = to;
    else
      result.push({ from, to });
  }
  return result;
}
var MatchDecorator = class {
  constructor(config2) {
    const { regexp, decoration, decorate, boundary, maxLength = 1e3 } = config2;
    if (!regexp.global)
      throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");
    this.regexp = regexp;
    if (decorate) {
      this.addMatch = (match, view, from, add3) => decorate(add3, from, from + match[0].length, match, view);
    } else if (typeof decoration == "function") {
      this.addMatch = (match, view, from, add3) => {
        let deco = decoration(match, view, from);
        if (deco)
          add3(from, from + match[0].length, deco);
      };
    } else if (decoration) {
      this.addMatch = (match, _view, from, add3) => add3(from, from + match[0].length, decoration);
    } else {
      throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");
    }
    this.boundary = boundary;
    this.maxLength = maxLength;
  }
  createDeco(view) {
    let build = new RangeSetBuilder(), add3 = build.add.bind(build);
    for (let { from, to } of matchRanges(view, this.maxLength))
      iterMatches(view.state.doc, this.regexp, from, to, (from2, m) => this.addMatch(m, view, from2, add3));
    return build.finish();
  }
  updateDeco(update2, deco) {
    let changeFrom = 1e9, changeTo = -1;
    if (update2.docChanged)
      update2.changes.iterChanges((_f, _t, from, to) => {
        if (to > update2.view.viewport.from && from < update2.view.viewport.to) {
          changeFrom = Math.min(from, changeFrom);
          changeTo = Math.max(to, changeTo);
        }
      });
    if (update2.viewportChanged || changeTo - changeFrom > 1e3)
      return this.createDeco(update2.view);
    if (changeTo > -1)
      return this.updateRange(update2.view, deco.map(update2.changes), changeFrom, changeTo);
    return deco;
  }
  updateRange(view, deco, updateFrom, updateTo) {
    for (let r of view.visibleRanges) {
      let from = Math.max(r.from, updateFrom), to = Math.min(r.to, updateTo);
      if (to > from) {
        let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine;
        let start = Math.max(r.from, fromLine.from), end = Math.min(r.to, toLine.to);
        if (this.boundary) {
          for (; from > fromLine.from; from--)
            if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) {
              start = from;
              break;
            }
          for (; to < toLine.to; to++)
            if (this.boundary.test(toLine.text[to - toLine.from])) {
              end = to;
              break;
            }
        }
        let ranges = [], m;
        let add3 = (from2, to2, deco2) => ranges.push(deco2.range(from2, to2));
        if (fromLine == toLine) {
          this.regexp.lastIndex = start - fromLine.from;
          while ((m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from)
            this.addMatch(m, view, m.index + fromLine.from, add3);
        } else {
          iterMatches(view.state.doc, this.regexp, start, end, (from2, m2) => this.addMatch(m2, view, from2, add3));
        }
        deco = deco.update({ filterFrom: start, filterTo: end, filter: (from2, to2) => from2 < start || to2 > end, add: ranges });
      }
    }
    return deco;
  }
};
var UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g";
var Specials = /* @__PURE__ */ new RegExp("[\0-\b\n-\x7F-\x9F\xAD\u061C\u200B\u200E\u200F\u2028\u2029\u202D\u202E\u2066\u2067\u2069\uFEFF\uFFF9-\uFFFC]", UnicodeRegexpSupport);
var Names = {
  0: "null",
  7: "bell",
  8: "backspace",
  10: "newline",
  11: "vertical tab",
  13: "carriage return",
  27: "escape",
  8203: "zero width space",
  8204: "zero width non-joiner",
  8205: "zero width joiner",
  8206: "left-to-right mark",
  8207: "right-to-left mark",
  8232: "line separator",
  8237: "left-to-right override",
  8238: "right-to-left override",
  8294: "left-to-right isolate",
  8295: "right-to-left isolate",
  8297: "pop directional isolate",
  8233: "paragraph separator",
  65279: "zero width no-break space",
  65532: "object replacement"
};
var _supportsTabSize = null;
function supportsTabSize() {
  var _a2;
  if (_supportsTabSize == null && typeof document != "undefined" && document.body) {
    let styles = document.body.style;
    _supportsTabSize = ((_a2 = styles.tabSize) !== null && _a2 !== void 0 ? _a2 : styles.MozTabSize) != null;
  }
  return _supportsTabSize || false;
}
var specialCharConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    let config2 = combineConfig(configs, {
      render: null,
      specialChars: Specials,
      addSpecialChars: null
    });
    if (config2.replaceTabs = !supportsTabSize())
      config2.specialChars = new RegExp("	|" + config2.specialChars.source, UnicodeRegexpSupport);
    if (config2.addSpecialChars)
      config2.specialChars = new RegExp(config2.specialChars.source + "|" + config2.addSpecialChars.source, UnicodeRegexpSupport);
    return config2;
  }
});
function highlightSpecialChars(config2 = {}) {
  return [specialCharConfig.of(config2), specialCharPlugin()];
}
var _plugin = null;
function specialCharPlugin() {
  return _plugin || (_plugin = ViewPlugin.fromClass(class {
    constructor(view) {
      this.view = view;
      this.decorations = Decoration.none;
      this.decorationCache = /* @__PURE__ */ Object.create(null);
      this.decorator = this.makeDecorator(view.state.facet(specialCharConfig));
      this.decorations = this.decorator.createDeco(view);
    }
    makeDecorator(conf) {
      return new MatchDecorator({
        regexp: conf.specialChars,
        decoration: (m, view, pos) => {
          let { doc: doc2 } = view.state;
          let code = codePointAt(m[0], 0);
          if (code == 9) {
            let line = doc2.lineAt(pos);
            let size = view.state.tabSize, col = countColumn(line.text, size, pos - line.from);
            return Decoration.replace({ widget: new TabWidget((size - col % size) * this.view.defaultCharacterWidth) });
          }
          return this.decorationCache[code] || (this.decorationCache[code] = Decoration.replace({ widget: new SpecialCharWidget(conf, code) }));
        },
        boundary: conf.replaceTabs ? void 0 : /[^]/
      });
    }
    update(update2) {
      let conf = update2.state.facet(specialCharConfig);
      if (update2.startState.facet(specialCharConfig) != conf) {
        this.decorator = this.makeDecorator(conf);
        this.decorations = this.decorator.createDeco(update2.view);
      } else {
        this.decorations = this.decorator.updateDeco(update2, this.decorations);
      }
    }
  }, {
    decorations: (v) => v.decorations
  }));
}
var DefaultPlaceholder = "\u2022";
function placeholder$1(code) {
  if (code >= 32)
    return DefaultPlaceholder;
  if (code == 10)
    return "\u2424";
  return String.fromCharCode(9216 + code);
}
var SpecialCharWidget = class extends WidgetType {
  constructor(options2, code) {
    super();
    this.options = options2;
    this.code = code;
  }
  eq(other) {
    return other.code == this.code;
  }
  toDOM(view) {
    let ph = placeholder$1(this.code);
    let desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16));
    let custom2 = this.options.render && this.options.render(this.code, desc, ph);
    if (custom2)
      return custom2;
    let span = document.createElement("span");
    span.textContent = ph;
    span.title = desc;
    span.setAttribute("aria-label", desc);
    span.className = "cm-specialChar";
    return span;
  }
  ignoreEvent() {
    return false;
  }
};
var TabWidget = class extends WidgetType {
  constructor(width) {
    super();
    this.width = width;
  }
  eq(other) {
    return other.width == this.width;
  }
  toDOM() {
    let span = document.createElement("span");
    span.textContent = "	";
    span.className = "cm-tab";
    span.style.width = this.width + "px";
    return span;
  }
  ignoreEvent() {
    return false;
  }
};
function highlightActiveLine() {
  return activeLineHighlighter;
}
var lineDeco = /* @__PURE__ */ Decoration.line({ class: "cm-activeLine" });
var activeLineHighlighter = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.decorations = this.getDeco(view);
  }
  update(update2) {
    if (update2.docChanged || update2.selectionSet)
      this.decorations = this.getDeco(update2.view);
  }
  getDeco(view) {
    let lastLineStart = -1, deco = [];
    for (let r of view.state.selection.ranges) {
      let line = view.lineBlockAt(r.head);
      if (line.from > lastLineStart) {
        deco.push(lineDeco.range(line.from));
        lastLineStart = line.from;
      }
    }
    return Decoration.set(deco);
  }
}, {
  decorations: (v) => v.decorations
});
var Placeholder = class extends WidgetType {
  constructor(content2) {
    super();
    this.content = content2;
  }
  toDOM() {
    let wrap = document.createElement("span");
    wrap.className = "cm-placeholder";
    wrap.style.pointerEvents = "none";
    wrap.appendChild(typeof this.content == "string" ? document.createTextNode(this.content) : this.content);
    if (typeof this.content == "string")
      wrap.setAttribute("aria-label", "placeholder " + this.content);
    else
      wrap.setAttribute("aria-hidden", "true");
    return wrap;
  }
  ignoreEvent() {
    return false;
  }
};
function placeholder(content2) {
  return ViewPlugin.fromClass(class {
    constructor(view) {
      this.view = view;
      this.placeholder = Decoration.set([Decoration.widget({ widget: new Placeholder(content2), side: 1 }).range(0)]);
    }
    get decorations() {
      return this.view.state.doc.length ? Decoration.none : this.placeholder;
    }
  }, { decorations: (v) => v.decorations });
}
var MaxOff = 2e3;
function rectangleFor(state, a, b) {
  let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line);
  let ranges = [];
  if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) {
    let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off);
    for (let i = startLine; i <= endLine; i++) {
      let line = state.doc.line(i);
      if (line.length <= endOff)
        ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff));
    }
  } else {
    let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col);
    for (let i = startLine; i <= endLine; i++) {
      let line = state.doc.line(i);
      let start = findColumn(line.text, startCol, state.tabSize, true);
      if (start < 0) {
        ranges.push(EditorSelection.cursor(line.to));
      } else {
        let end = findColumn(line.text, endCol, state.tabSize);
        ranges.push(EditorSelection.range(line.from + start, line.from + end));
      }
    }
  }
  return ranges;
}
function absoluteColumn(view, x2) {
  let ref = view.coordsAtPos(view.viewport.from);
  return ref ? Math.round(Math.abs((ref.left - x2) / view.defaultCharacterWidth)) : -1;
}
function getPos(view, event) {
  let offset = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
  let line = view.state.doc.lineAt(offset), off = offset - line.from;
  let col = off > MaxOff ? -1 : off == line.length ? absoluteColumn(view, event.clientX) : countColumn(line.text, view.state.tabSize, offset - line.from);
  return { line: line.number, col, off };
}
function rectangleSelectionStyle(view, event) {
  let start = getPos(view, event), startSel = view.state.selection;
  if (!start)
    return null;
  return {
    update(update2) {
      if (update2.docChanged) {
        let newStart = update2.changes.mapPos(update2.startState.doc.line(start.line).from);
        let newLine = update2.state.doc.lineAt(newStart);
        start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) };
        startSel = startSel.map(update2.changes);
      }
    },
    get(event2, _extend, multiple) {
      let cur2 = getPos(view, event2);
      if (!cur2)
        return startSel;
      let ranges = rectangleFor(view.state, start, cur2);
      if (!ranges.length)
        return startSel;
      if (multiple)
        return EditorSelection.create(ranges.concat(startSel.ranges));
      else
        return EditorSelection.create(ranges);
    }
  };
}
function rectangularSelection(options2) {
  let filter2 = (options2 === null || options2 === void 0 ? void 0 : options2.eventFilter) || ((e3) => e3.altKey && e3.button == 0);
  return EditorView.mouseSelectionStyle.of((view, event) => filter2(event) ? rectangleSelectionStyle(view, event) : null);
}
var Outside = "-10000px";
var TooltipViewManager = class {
  constructor(view, facet, createTooltipView) {
    this.facet = facet;
    this.createTooltipView = createTooltipView;
    this.input = view.state.facet(facet);
    this.tooltips = this.input.filter((t4) => t4);
    this.tooltipViews = this.tooltips.map(createTooltipView);
  }
  update(update2) {
    var _a2;
    let input = update2.state.facet(this.facet);
    let tooltips = input.filter((x2) => x2);
    if (input === this.input) {
      for (let t4 of this.tooltipViews)
        if (t4.update)
          t4.update(update2);
      return false;
    }
    let tooltipViews = [];
    for (let i = 0; i < tooltips.length; i++) {
      let tip = tooltips[i], known = -1;
      if (!tip)
        continue;
      for (let i2 = 0; i2 < this.tooltips.length; i2++) {
        let other = this.tooltips[i2];
        if (other && other.create == tip.create)
          known = i2;
      }
      if (known < 0) {
        tooltipViews[i] = this.createTooltipView(tip);
      } else {
        let tooltipView = tooltipViews[i] = this.tooltipViews[known];
        if (tooltipView.update)
          tooltipView.update(update2);
      }
    }
    for (let t4 of this.tooltipViews)
      if (tooltipViews.indexOf(t4) < 0) {
        t4.dom.remove();
        (_a2 = t4.destroy) === null || _a2 === void 0 ? void 0 : _a2.call(t4);
      }
    this.input = input;
    this.tooltips = tooltips;
    this.tooltipViews = tooltipViews;
    return true;
  }
};
function windowSpace(view) {
  let { win } = view;
  return { top: 0, left: 0, bottom: win.innerHeight, right: win.innerWidth };
}
var tooltipConfig = /* @__PURE__ */ Facet.define({
  combine: (values) => {
    var _a2, _b, _c;
    return {
      position: browser.ios ? "absolute" : ((_a2 = values.find((conf) => conf.position)) === null || _a2 === void 0 ? void 0 : _a2.position) || "fixed",
      parent: ((_b = values.find((conf) => conf.parent)) === null || _b === void 0 ? void 0 : _b.parent) || null,
      tooltipSpace: ((_c = values.find((conf) => conf.tooltipSpace)) === null || _c === void 0 ? void 0 : _c.tooltipSpace) || windowSpace
    };
  }
});
var tooltipPlugin = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.inView = true;
    this.lastTransaction = 0;
    this.measureTimeout = -1;
    let config2 = view.state.facet(tooltipConfig);
    this.position = config2.position;
    this.parent = config2.parent;
    this.classes = view.themeClasses;
    this.createContainer();
    this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this };
    this.manager = new TooltipViewManager(view, showTooltip, (t4) => this.createTooltip(t4));
    this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver((entries) => {
      if (Date.now() > this.lastTransaction - 50 && entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1)
        this.measureSoon();
    }, { threshold: [1] }) : null;
    this.observeIntersection();
    view.win.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this));
    this.maybeMeasure();
  }
  createContainer() {
    if (this.parent) {
      this.container = document.createElement("div");
      this.container.style.position = "relative";
      this.container.className = this.view.themeClasses;
      this.parent.appendChild(this.container);
    } else {
      this.container = this.view.dom;
    }
  }
  observeIntersection() {
    if (this.intersectionObserver) {
      this.intersectionObserver.disconnect();
      for (let tooltip2 of this.manager.tooltipViews)
        this.intersectionObserver.observe(tooltip2.dom);
    }
  }
  measureSoon() {
    if (this.measureTimeout < 0)
      this.measureTimeout = setTimeout(() => {
        this.measureTimeout = -1;
        this.maybeMeasure();
      }, 50);
  }
  update(update2) {
    if (update2.transactions.length)
      this.lastTransaction = Date.now();
    let updated = this.manager.update(update2);
    if (updated)
      this.observeIntersection();
    let shouldMeasure = updated || update2.geometryChanged;
    let newConfig = update2.state.facet(tooltipConfig);
    if (newConfig.position != this.position) {
      this.position = newConfig.position;
      for (let t4 of this.manager.tooltipViews)
        t4.dom.style.position = this.position;
      shouldMeasure = true;
    }
    if (newConfig.parent != this.parent) {
      if (this.parent)
        this.container.remove();
      this.parent = newConfig.parent;
      this.createContainer();
      for (let t4 of this.manager.tooltipViews)
        this.container.appendChild(t4.dom);
      shouldMeasure = true;
    } else if (this.parent && this.view.themeClasses != this.classes) {
      this.classes = this.container.className = this.view.themeClasses;
    }
    if (shouldMeasure)
      this.maybeMeasure();
  }
  createTooltip(tooltip2) {
    let tooltipView = tooltip2.create(this.view);
    tooltipView.dom.classList.add("cm-tooltip");
    if (tooltip2.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) {
      let arrow = document.createElement("div");
      arrow.className = "cm-tooltip-arrow";
      tooltipView.dom.appendChild(arrow);
    }
    tooltipView.dom.style.position = this.position;
    tooltipView.dom.style.top = Outside;
    this.container.appendChild(tooltipView.dom);
    if (tooltipView.mount)
      tooltipView.mount(this.view);
    return tooltipView;
  }
  destroy() {
    var _a2, _b;
    this.view.win.removeEventListener("resize", this.measureSoon);
    for (let tooltipView of this.manager.tooltipViews) {
      tooltipView.dom.remove();
      (_a2 = tooltipView.destroy) === null || _a2 === void 0 ? void 0 : _a2.call(tooltipView);
    }
    (_b = this.intersectionObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
    clearTimeout(this.measureTimeout);
  }
  readMeasure() {
    let editor = this.view.dom.getBoundingClientRect();
    return {
      editor,
      parent: this.parent ? this.container.getBoundingClientRect() : editor,
      pos: this.manager.tooltips.map((t4, i) => {
        let tv = this.manager.tooltipViews[i];
        return tv.getCoords ? tv.getCoords(t4.pos) : this.view.coordsAtPos(t4.pos);
      }),
      size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()),
      space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view)
    };
  }
  writeMeasure(measured) {
    let { editor, space: space2 } = measured;
    let others = [];
    for (let i = 0; i < this.manager.tooltips.length; i++) {
      let tooltip2 = this.manager.tooltips[i], tView = this.manager.tooltipViews[i], { dom } = tView;
      let pos = measured.pos[i], size = measured.size[i];
      if (!pos || pos.bottom <= Math.max(editor.top, space2.top) || pos.top >= Math.min(editor.bottom, space2.bottom) || pos.right < Math.max(editor.left, space2.left) - 0.1 || pos.left > Math.min(editor.right, space2.right) + 0.1) {
        dom.style.top = Outside;
        continue;
      }
      let arrow = tooltip2.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null;
      let arrowHeight = arrow ? 7 : 0;
      let width = size.right - size.left, height4 = size.bottom - size.top;
      let offset = tView.offset || noOffset, ltr = this.view.textDirection == Direction.LTR;
      let left2 = size.width > space2.right - space2.left ? ltr ? space2.left : space2.right - size.width : ltr ? Math.min(pos.left - (arrow ? 14 : 0) + offset.x, space2.right - width) : Math.max(space2.left, pos.left - width + (arrow ? 14 : 0) - offset.x);
      let above = !!tooltip2.above;
      if (!tooltip2.strictSide && (above ? pos.top - (size.bottom - size.top) - offset.y < space2.top : pos.bottom + (size.bottom - size.top) + offset.y > space2.bottom) && above == space2.bottom - pos.bottom > pos.top - space2.top)
        above = !above;
      let top3 = above ? pos.top - height4 - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y;
      let right2 = left2 + width;
      if (tView.overlap !== true) {
        for (let r of others)
          if (r.left < right2 && r.right > left2 && r.top < top3 + height4 && r.bottom > top3)
            top3 = above ? r.top - height4 - 2 - arrowHeight : r.bottom + arrowHeight + 2;
      }
      if (this.position == "absolute") {
        dom.style.top = top3 - measured.parent.top + "px";
        dom.style.left = left2 - measured.parent.left + "px";
      } else {
        dom.style.top = top3 + "px";
        dom.style.left = left2 + "px";
      }
      if (arrow)
        arrow.style.left = `${pos.left + (ltr ? offset.x : -offset.x) - (left2 + 14 - 7)}px`;
      if (tView.overlap !== true)
        others.push({ left: left2, top: top3, right: right2, bottom: top3 + height4 });
      dom.classList.toggle("cm-tooltip-above", above);
      dom.classList.toggle("cm-tooltip-below", !above);
      if (tView.positioned)
        tView.positioned();
    }
  }
  maybeMeasure() {
    if (this.manager.tooltips.length) {
      if (this.view.inView)
        this.view.requestMeasure(this.measureReq);
      if (this.inView != this.view.inView) {
        this.inView = this.view.inView;
        if (!this.inView)
          for (let tv of this.manager.tooltipViews)
            tv.dom.style.top = Outside;
      }
    }
  }
}, {
  eventHandlers: {
    scroll() {
      this.maybeMeasure();
    }
  }
});
var baseTheme = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-tooltip": {
    zIndex: 100
  },
  "&light .cm-tooltip": {
    border: "1px solid #bbb",
    backgroundColor: "#f5f5f5"
  },
  "&light .cm-tooltip-section:not(:first-child)": {
    borderTop: "1px solid #bbb"
  },
  "&dark .cm-tooltip": {
    backgroundColor: "#333338",
    color: "white"
  },
  ".cm-tooltip-arrow": {
    height: `${7}px`,
    width: `${7 * 2}px`,
    position: "absolute",
    zIndex: -1,
    overflow: "hidden",
    "&:before, &:after": {
      content: "''",
      position: "absolute",
      width: 0,
      height: 0,
      borderLeft: `${7}px solid transparent`,
      borderRight: `${7}px solid transparent`
    },
    ".cm-tooltip-above &": {
      bottom: `-${7}px`,
      "&:before": {
        borderTop: `${7}px solid #bbb`
      },
      "&:after": {
        borderTop: `${7}px solid #f5f5f5`,
        bottom: "1px"
      }
    },
    ".cm-tooltip-below &": {
      top: `-${7}px`,
      "&:before": {
        borderBottom: `${7}px solid #bbb`
      },
      "&:after": {
        borderBottom: `${7}px solid #f5f5f5`,
        top: "1px"
      }
    }
  },
  "&dark .cm-tooltip .cm-tooltip-arrow": {
    "&:before": {
      borderTopColor: "#333338",
      borderBottomColor: "#333338"
    },
    "&:after": {
      borderTopColor: "transparent",
      borderBottomColor: "transparent"
    }
  }
});
var noOffset = { x: 0, y: 0 };
var showTooltip = /* @__PURE__ */ Facet.define({
  enables: [tooltipPlugin, baseTheme]
});
var showHoverTooltip = /* @__PURE__ */ Facet.define();
var HoverTooltipHost = class {
  constructor(view) {
    this.view = view;
    this.mounted = false;
    this.dom = document.createElement("div");
    this.dom.classList.add("cm-tooltip-hover");
    this.manager = new TooltipViewManager(view, showHoverTooltip, (t4) => this.createHostedView(t4));
  }
  static create(view) {
    return new HoverTooltipHost(view);
  }
  createHostedView(tooltip2) {
    let hostedView = tooltip2.create(this.view);
    hostedView.dom.classList.add("cm-tooltip-section");
    this.dom.appendChild(hostedView.dom);
    if (this.mounted && hostedView.mount)
      hostedView.mount(this.view);
    return hostedView;
  }
  mount(view) {
    for (let hostedView of this.manager.tooltipViews) {
      if (hostedView.mount)
        hostedView.mount(view);
    }
    this.mounted = true;
  }
  positioned() {
    for (let hostedView of this.manager.tooltipViews) {
      if (hostedView.positioned)
        hostedView.positioned();
    }
  }
  update(update2) {
    this.manager.update(update2);
  }
};
var showHoverTooltipHost = /* @__PURE__ */ showTooltip.compute([showHoverTooltip], (state) => {
  let tooltips = state.facet(showHoverTooltip).filter((t4) => t4);
  if (tooltips.length === 0)
    return null;
  return {
    pos: Math.min(...tooltips.map((t4) => t4.pos)),
    end: Math.max(...tooltips.filter((t4) => t4.end != null).map((t4) => t4.end)),
    create: HoverTooltipHost.create,
    above: tooltips[0].above,
    arrow: tooltips.some((t4) => t4.arrow)
  };
});
var HoverPlugin = class {
  constructor(view, source, field, setHover, hoverTime) {
    this.view = view;
    this.source = source;
    this.field = field;
    this.setHover = setHover;
    this.hoverTime = hoverTime;
    this.hoverTimeout = -1;
    this.restartTimeout = -1;
    this.pending = null;
    this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 };
    this.checkHover = this.checkHover.bind(this);
    view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this));
    view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this));
  }
  update() {
    if (this.pending) {
      this.pending = null;
      clearTimeout(this.restartTimeout);
      this.restartTimeout = setTimeout(() => this.startHover(), 20);
    }
  }
  get active() {
    return this.view.state.field(this.field);
  }
  checkHover() {
    this.hoverTimeout = -1;
    if (this.active)
      return;
    let hovered = Date.now() - this.lastMove.time;
    if (hovered < this.hoverTime)
      this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered);
    else
      this.startHover();
  }
  startHover() {
    clearTimeout(this.restartTimeout);
    let { lastMove } = this;
    let pos = this.view.contentDOM.contains(lastMove.target) ? this.view.posAtCoords(lastMove) : null;
    if (pos == null)
      return;
    let posCoords = this.view.coordsAtPos(pos);
    if (posCoords == null || lastMove.y < posCoords.top || lastMove.y > posCoords.bottom || lastMove.x < posCoords.left - this.view.defaultCharacterWidth || lastMove.x > posCoords.right + this.view.defaultCharacterWidth)
      return;
    let bidi = this.view.bidiSpans(this.view.state.doc.lineAt(pos)).find((s) => s.from <= pos && s.to >= pos);
    let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1;
    let open = this.source(this.view, pos, lastMove.x < posCoords.left ? -rtl : rtl);
    if (open === null || open === void 0 ? void 0 : open.then) {
      let pending = this.pending = { pos };
      open.then((result) => {
        if (this.pending == pending) {
          this.pending = null;
          if (result)
            this.view.dispatch({ effects: this.setHover.of(result) });
        }
      }, (e3) => logException(this.view.state, e3, "hover tooltip"));
    } else if (open) {
      this.view.dispatch({ effects: this.setHover.of(open) });
    }
  }
  mousemove(event) {
    var _a2;
    this.lastMove = { x: event.clientX, y: event.clientY, target: event.target, time: Date.now() };
    if (this.hoverTimeout < 0)
      this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime);
    let tooltip2 = this.active;
    if (tooltip2 && !isInTooltip(this.lastMove.target) || this.pending) {
      let { pos } = tooltip2 || this.pending, end = (_a2 = tooltip2 === null || tooltip2 === void 0 ? void 0 : tooltip2.end) !== null && _a2 !== void 0 ? _a2 : pos;
      if (pos == end ? this.view.posAtCoords(this.lastMove) != pos : !isOverRange(this.view, pos, end, event.clientX, event.clientY, 6)) {
        this.view.dispatch({ effects: this.setHover.of(null) });
        this.pending = null;
      }
    }
  }
  mouseleave() {
    clearTimeout(this.hoverTimeout);
    this.hoverTimeout = -1;
    if (this.active)
      this.view.dispatch({ effects: this.setHover.of(null) });
  }
  destroy() {
    clearTimeout(this.hoverTimeout);
    this.view.dom.removeEventListener("mouseleave", this.mouseleave);
    this.view.dom.removeEventListener("mousemove", this.mousemove);
  }
};
function isInTooltip(elt) {
  for (let cur2 = elt; cur2; cur2 = cur2.parentNode)
    if (cur2.nodeType == 1 && cur2.classList.contains("cm-tooltip"))
      return true;
  return false;
}
function isOverRange(view, from, to, x2, y2, margin) {
  let range2 = document.createRange();
  let fromDOM = view.domAtPos(from), toDOM = view.domAtPos(to);
  range2.setEnd(toDOM.node, toDOM.offset);
  range2.setStart(fromDOM.node, fromDOM.offset);
  let rects = range2.getClientRects();
  range2.detach();
  for (let i = 0; i < rects.length; i++) {
    let rect = rects[i];
    let dist = Math.max(rect.top - y2, y2 - rect.bottom, rect.left - x2, x2 - rect.right);
    if (dist <= margin)
      return true;
  }
  return false;
}
function hoverTooltip(source, options2 = {}) {
  let setHover = StateEffect.define();
  let hoverState = StateField.define({
    create() {
      return null;
    },
    update(value, tr) {
      if (value && (options2.hideOnChange && (tr.docChanged || tr.selection) || options2.hideOn && options2.hideOn(tr, value)))
        return null;
      if (value && tr.docChanged) {
        let newPos = tr.changes.mapPos(value.pos, -1, MapMode.TrackDel);
        if (newPos == null)
          return null;
        let copy2 = Object.assign(/* @__PURE__ */ Object.create(null), value);
        copy2.pos = newPos;
        if (value.end != null)
          copy2.end = tr.changes.mapPos(value.end);
        value = copy2;
      }
      for (let effect of tr.effects) {
        if (effect.is(setHover))
          value = effect.value;
        if (effect.is(closeHoverTooltipEffect))
          value = null;
      }
      return value;
    },
    provide: (f) => showHoverTooltip.from(f)
  });
  return [
    hoverState,
    ViewPlugin.define((view) => new HoverPlugin(view, source, hoverState, setHover, options2.hoverTime || 300)),
    showHoverTooltipHost
  ];
}
function getTooltip(view, tooltip2) {
  let plugin = view.plugin(tooltipPlugin);
  if (!plugin)
    return null;
  let found = plugin.manager.tooltips.indexOf(tooltip2);
  return found < 0 ? null : plugin.manager.tooltipViews[found];
}
var closeHoverTooltipEffect = /* @__PURE__ */ StateEffect.define();
var panelConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    let topContainer, bottomContainer;
    for (let c of configs) {
      topContainer = topContainer || c.topContainer;
      bottomContainer = bottomContainer || c.bottomContainer;
    }
    return { topContainer, bottomContainer };
  }
});
function getPanel(view, panel) {
  let plugin = view.plugin(panelPlugin);
  let index2 = plugin ? plugin.specs.indexOf(panel) : -1;
  return index2 > -1 ? plugin.panels[index2] : null;
}
var panelPlugin = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.input = view.state.facet(showPanel);
    this.specs = this.input.filter((s) => s);
    this.panels = this.specs.map((spec) => spec(view));
    let conf = view.state.facet(panelConfig);
    this.top = new PanelGroup(view, true, conf.topContainer);
    this.bottom = new PanelGroup(view, false, conf.bottomContainer);
    this.top.sync(this.panels.filter((p) => p.top));
    this.bottom.sync(this.panels.filter((p) => !p.top));
    for (let p of this.panels) {
      p.dom.classList.add("cm-panel");
      if (p.mount)
        p.mount();
    }
  }
  update(update2) {
    let conf = update2.state.facet(panelConfig);
    if (this.top.container != conf.topContainer) {
      this.top.sync([]);
      this.top = new PanelGroup(update2.view, true, conf.topContainer);
    }
    if (this.bottom.container != conf.bottomContainer) {
      this.bottom.sync([]);
      this.bottom = new PanelGroup(update2.view, false, conf.bottomContainer);
    }
    this.top.syncClasses();
    this.bottom.syncClasses();
    let input = update2.state.facet(showPanel);
    if (input != this.input) {
      let specs = input.filter((x2) => x2);
      let panels = [], top3 = [], bottom2 = [], mount = [];
      for (let spec of specs) {
        let known = this.specs.indexOf(spec), panel;
        if (known < 0) {
          panel = spec(update2.view);
          mount.push(panel);
        } else {
          panel = this.panels[known];
          if (panel.update)
            panel.update(update2);
        }
        panels.push(panel);
        (panel.top ? top3 : bottom2).push(panel);
      }
      this.specs = specs;
      this.panels = panels;
      this.top.sync(top3);
      this.bottom.sync(bottom2);
      for (let p of mount) {
        p.dom.classList.add("cm-panel");
        if (p.mount)
          p.mount();
      }
    } else {
      for (let p of this.panels)
        if (p.update)
          p.update(update2);
    }
  }
  destroy() {
    this.top.sync([]);
    this.bottom.sync([]);
  }
}, {
  provide: (plugin) => EditorView.scrollMargins.of((view) => {
    let value = view.plugin(plugin);
    return value && { top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() };
  })
});
var PanelGroup = class {
  constructor(view, top3, container) {
    this.view = view;
    this.top = top3;
    this.container = container;
    this.dom = void 0;
    this.classes = "";
    this.panels = [];
    this.syncClasses();
  }
  sync(panels) {
    for (let p of this.panels)
      if (p.destroy && panels.indexOf(p) < 0)
        p.destroy();
    this.panels = panels;
    this.syncDOM();
  }
  syncDOM() {
    if (this.panels.length == 0) {
      if (this.dom) {
        this.dom.remove();
        this.dom = void 0;
      }
      return;
    }
    if (!this.dom) {
      this.dom = document.createElement("div");
      this.dom.className = this.top ? "cm-panels cm-panels-top" : "cm-panels cm-panels-bottom";
      this.dom.style[this.top ? "top" : "bottom"] = "0";
      let parent2 = this.container || this.view.dom;
      parent2.insertBefore(this.dom, this.top ? parent2.firstChild : null);
    }
    let curDOM = this.dom.firstChild;
    for (let panel of this.panels) {
      if (panel.dom.parentNode == this.dom) {
        while (curDOM != panel.dom)
          curDOM = rm(curDOM);
        curDOM = curDOM.nextSibling;
      } else {
        this.dom.insertBefore(panel.dom, curDOM);
      }
    }
    while (curDOM)
      curDOM = rm(curDOM);
  }
  scrollMargin() {
    return !this.dom || this.container ? 0 : Math.max(0, this.top ? this.dom.getBoundingClientRect().bottom - Math.max(0, this.view.scrollDOM.getBoundingClientRect().top) : Math.min(innerHeight, this.view.scrollDOM.getBoundingClientRect().bottom) - this.dom.getBoundingClientRect().top);
  }
  syncClasses() {
    if (!this.container || this.classes == this.view.themeClasses)
      return;
    for (let cls of this.classes.split(" "))
      if (cls)
        this.container.classList.remove(cls);
    for (let cls of (this.classes = this.view.themeClasses).split(" "))
      if (cls)
        this.container.classList.add(cls);
  }
};
function rm(node) {
  let next = node.nextSibling;
  node.remove();
  return next;
}
var showPanel = /* @__PURE__ */ Facet.define({
  enables: panelPlugin
});
var GutterMarker = class extends RangeValue {
  compare(other) {
    return this == other || this.constructor == other.constructor && this.eq(other);
  }
  eq(other) {
    return false;
  }
  destroy(dom) {
  }
};
GutterMarker.prototype.elementClass = "";
GutterMarker.prototype.toDOM = void 0;
GutterMarker.prototype.mapMode = MapMode.TrackBefore;
GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1;
GutterMarker.prototype.point = true;
var gutterLineClass = /* @__PURE__ */ Facet.define();
var defaults = {
  class: "",
  renderEmptyElements: false,
  elementStyle: "",
  markers: () => RangeSet.empty,
  lineMarker: () => null,
  lineMarkerChange: null,
  initialSpacer: null,
  updateSpacer: null,
  domEventHandlers: {}
};
var activeGutters = /* @__PURE__ */ Facet.define();
function gutter(config2) {
  return [gutters(), activeGutters.of(Object.assign(Object.assign({}, defaults), config2))];
}
var unfixGutters = /* @__PURE__ */ Facet.define({
  combine: (values) => values.some((x2) => x2)
});
function gutters(config2) {
  let result = [
    gutterView
  ];
  if (config2 && config2.fixed === false)
    result.push(unfixGutters.of(true));
  return result;
}
var gutterView = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.prevViewport = view.viewport;
    this.dom = document.createElement("div");
    this.dom.className = "cm-gutters";
    this.dom.setAttribute("aria-hidden", "true");
    this.dom.style.minHeight = this.view.contentHeight + "px";
    this.gutters = view.state.facet(activeGutters).map((conf) => new SingleGutterView(view, conf));
    for (let gutter2 of this.gutters)
      this.dom.appendChild(gutter2.dom);
    this.fixed = !view.state.facet(unfixGutters);
    if (this.fixed) {
      this.dom.style.position = "sticky";
    }
    this.syncGutters(false);
    view.scrollDOM.insertBefore(this.dom, view.contentDOM);
  }
  update(update2) {
    if (this.updateGutters(update2)) {
      let vpA = this.prevViewport, vpB = update2.view.viewport;
      let vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from);
      this.syncGutters(vpOverlap < (vpB.to - vpB.from) * 0.8);
    }
    if (update2.geometryChanged)
      this.dom.style.minHeight = this.view.contentHeight + "px";
    if (this.view.state.facet(unfixGutters) != !this.fixed) {
      this.fixed = !this.fixed;
      this.dom.style.position = this.fixed ? "sticky" : "";
    }
    this.prevViewport = update2.view.viewport;
  }
  syncGutters(detach2) {
    let after = this.dom.nextSibling;
    if (detach2)
      this.dom.remove();
    let lineClasses = RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from);
    let classSet = [];
    let contexts = this.gutters.map((gutter2) => new UpdateContext(gutter2, this.view.viewport, -this.view.documentPadding.top));
    for (let line of this.view.viewportLineBlocks) {
      let text2;
      if (Array.isArray(line.type)) {
        for (let b of line.type)
          if (b.type == BlockType.Text) {
            text2 = b;
            break;
          }
      } else {
        text2 = line.type == BlockType.Text ? line : void 0;
      }
      if (!text2)
        continue;
      if (classSet.length)
        classSet = [];
      advanceCursor(lineClasses, classSet, line.from);
      for (let cx of contexts)
        cx.line(this.view, text2, classSet);
    }
    for (let cx of contexts)
      cx.finish();
    if (detach2)
      this.view.scrollDOM.insertBefore(this.dom, after);
  }
  updateGutters(update2) {
    let prev = update2.startState.facet(activeGutters), cur2 = update2.state.facet(activeGutters);
    let change = update2.docChanged || update2.heightChanged || update2.viewportChanged || !RangeSet.eq(update2.startState.facet(gutterLineClass), update2.state.facet(gutterLineClass), update2.view.viewport.from, update2.view.viewport.to);
    if (prev == cur2) {
      for (let gutter2 of this.gutters)
        if (gutter2.update(update2))
          change = true;
    } else {
      change = true;
      let gutters2 = [];
      for (let conf of cur2) {
        let known = prev.indexOf(conf);
        if (known < 0) {
          gutters2.push(new SingleGutterView(this.view, conf));
        } else {
          this.gutters[known].update(update2);
          gutters2.push(this.gutters[known]);
        }
      }
      for (let g of this.gutters) {
        g.dom.remove();
        if (gutters2.indexOf(g) < 0)
          g.destroy();
      }
      for (let g of gutters2)
        this.dom.appendChild(g.dom);
      this.gutters = gutters2;
    }
    return change;
  }
  destroy() {
    for (let view of this.gutters)
      view.destroy();
    this.dom.remove();
  }
}, {
  provide: (plugin) => EditorView.scrollMargins.of((view) => {
    let value = view.plugin(plugin);
    if (!value || value.gutters.length == 0 || !value.fixed)
      return null;
    return view.textDirection == Direction.LTR ? { left: value.dom.offsetWidth } : { right: value.dom.offsetWidth };
  })
});
function asArray2(val) {
  return Array.isArray(val) ? val : [val];
}
function advanceCursor(cursor, collect, pos) {
  while (cursor.value && cursor.from <= pos) {
    if (cursor.from == pos)
      collect.push(cursor.value);
    cursor.next();
  }
}
var UpdateContext = class {
  constructor(gutter2, viewport, height4) {
    this.gutter = gutter2;
    this.height = height4;
    this.localMarkers = [];
    this.i = 0;
    this.cursor = RangeSet.iter(gutter2.markers, viewport.from);
  }
  line(view, line, extraMarkers) {
    if (this.localMarkers.length)
      this.localMarkers = [];
    advanceCursor(this.cursor, this.localMarkers, line.from);
    let localMarkers = extraMarkers.length ? this.localMarkers.concat(extraMarkers) : this.localMarkers;
    let forLine = this.gutter.config.lineMarker(view, line, localMarkers);
    if (forLine)
      localMarkers.unshift(forLine);
    let gutter2 = this.gutter;
    if (localMarkers.length == 0 && !gutter2.config.renderEmptyElements)
      return;
    let above = line.top - this.height;
    if (this.i == gutter2.elements.length) {
      let newElt = new GutterElement(view, line.height, above, localMarkers);
      gutter2.elements.push(newElt);
      gutter2.dom.appendChild(newElt.dom);
    } else {
      gutter2.elements[this.i].update(view, line.height, above, localMarkers);
    }
    this.height = line.bottom;
    this.i++;
  }
  finish() {
    let gutter2 = this.gutter;
    while (gutter2.elements.length > this.i) {
      let last = gutter2.elements.pop();
      gutter2.dom.removeChild(last.dom);
      last.destroy();
    }
  }
};
var SingleGutterView = class {
  constructor(view, config2) {
    this.view = view;
    this.config = config2;
    this.elements = [];
    this.spacer = null;
    this.dom = document.createElement("div");
    this.dom.className = "cm-gutter" + (this.config.class ? " " + this.config.class : "");
    for (let prop in config2.domEventHandlers) {
      this.dom.addEventListener(prop, (event) => {
        let line = view.lineBlockAtHeight(event.clientY - view.documentTop);
        if (config2.domEventHandlers[prop](view, line, event))
          event.preventDefault();
      });
    }
    this.markers = asArray2(config2.markers(view));
    if (config2.initialSpacer) {
      this.spacer = new GutterElement(view, 0, 0, [config2.initialSpacer(view)]);
      this.dom.appendChild(this.spacer.dom);
      this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none";
    }
  }
  update(update2) {
    let prevMarkers = this.markers;
    this.markers = asArray2(this.config.markers(update2.view));
    if (this.spacer && this.config.updateSpacer) {
      let updated = this.config.updateSpacer(this.spacer.markers[0], update2);
      if (updated != this.spacer.markers[0])
        this.spacer.update(update2.view, 0, 0, [updated]);
    }
    let vp = update2.view.viewport;
    return !RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) || (this.config.lineMarkerChange ? this.config.lineMarkerChange(update2) : false);
  }
  destroy() {
    for (let elt of this.elements)
      elt.destroy();
  }
};
var GutterElement = class {
  constructor(view, height4, above, markers) {
    this.height = -1;
    this.above = 0;
    this.markers = [];
    this.dom = document.createElement("div");
    this.dom.className = "cm-gutterElement";
    this.update(view, height4, above, markers);
  }
  update(view, height4, above, markers) {
    if (this.height != height4)
      this.dom.style.height = (this.height = height4) + "px";
    if (this.above != above)
      this.dom.style.marginTop = (this.above = above) ? above + "px" : "";
    if (!sameMarkers(this.markers, markers))
      this.setMarkers(view, markers);
  }
  setMarkers(view, markers) {
    let cls = "cm-gutterElement", domPos = this.dom.firstChild;
    for (let iNew = 0, iOld = 0; ; ) {
      let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = false;
      if (marker) {
        let c = marker.elementClass;
        if (c)
          cls += " " + c;
        for (let i = iOld; i < this.markers.length; i++)
          if (this.markers[i].compare(marker)) {
            skipTo = i;
            matched = true;
            break;
          }
      } else {
        skipTo = this.markers.length;
      }
      while (iOld < skipTo) {
        let next = this.markers[iOld++];
        if (next.toDOM) {
          next.destroy(domPos);
          let after = domPos.nextSibling;
          domPos.remove();
          domPos = after;
        }
      }
      if (!marker)
        break;
      if (marker.toDOM) {
        if (matched)
          domPos = domPos.nextSibling;
        else
          this.dom.insertBefore(marker.toDOM(view), domPos);
      }
      if (matched)
        iOld++;
    }
    this.dom.className = cls;
    this.markers = markers;
  }
  destroy() {
    this.setMarkers(null, []);
  }
};
function sameMarkers(a, b) {
  if (a.length != b.length)
    return false;
  for (let i = 0; i < a.length; i++)
    if (!a[i].compare(b[i]))
      return false;
  return true;
}
var lineNumberMarkers = /* @__PURE__ */ Facet.define();
var lineNumberConfig = /* @__PURE__ */ Facet.define({
  combine(values) {
    return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, {
      domEventHandlers(a, b) {
        let result = Object.assign({}, a);
        for (let event in b) {
          let exists = result[event], add3 = b[event];
          result[event] = exists ? (view, line, event2) => exists(view, line, event2) || add3(view, line, event2) : add3;
        }
        return result;
      }
    });
  }
});
var NumberMarker = class extends GutterMarker {
  constructor(number8) {
    super();
    this.number = number8;
  }
  eq(other) {
    return this.number == other.number;
  }
  toDOM() {
    return document.createTextNode(this.number);
  }
};
function formatNumber(view, number8) {
  return view.state.facet(lineNumberConfig).formatNumber(number8, view.state);
}
var lineNumberGutter = /* @__PURE__ */ activeGutters.compute([lineNumberConfig], (state) => ({
  class: "cm-lineNumbers",
  renderEmptyElements: false,
  markers(view) {
    return view.state.facet(lineNumberMarkers);
  },
  lineMarker(view, line, others) {
    if (others.some((m) => m.toDOM))
      return null;
    return new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number));
  },
  lineMarkerChange: (update2) => update2.startState.facet(lineNumberConfig) != update2.state.facet(lineNumberConfig),
  initialSpacer(view) {
    return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines)));
  },
  updateSpacer(spacer, update2) {
    let max3 = formatNumber(update2.view, maxLineNumber(update2.view.state.doc.lines));
    return max3 == spacer.number ? spacer : new NumberMarker(max3);
  },
  domEventHandlers: state.facet(lineNumberConfig).domEventHandlers
}));
function lineNumbers(config2 = {}) {
  return [
    lineNumberConfig.of(config2),
    gutters(),
    lineNumberGutter
  ];
}
function maxLineNumber(lines) {
  let last = 9;
  while (last < lines)
    last = last * 10 + 9;
  return last;
}

// node_modules/@lezer/common/dist/index.js
var DefaultBufferLength = 1024;
var nextPropID = 0;
var Range2 = class {
  constructor(from, to) {
    this.from = from;
    this.to = to;
  }
};
var NodeProp = class {
  constructor(config2 = {}) {
    this.id = nextPropID++;
    this.perNode = !!config2.perNode;
    this.deserialize = config2.deserialize || (() => {
      throw new Error("This node type doesn't define a deserialize function");
    });
  }
  add(match) {
    if (this.perNode)
      throw new RangeError("Can't add per-node props to node types");
    if (typeof match != "function")
      match = NodeType.match(match);
    return (type) => {
      let result = match(type);
      return result === void 0 ? null : [this, result];
    };
  }
};
NodeProp.closedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
NodeProp.openedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
NodeProp.group = new NodeProp({ deserialize: (str) => str.split(" ") });
NodeProp.contextHash = new NodeProp({ perNode: true });
NodeProp.lookAhead = new NodeProp({ perNode: true });
NodeProp.mounted = new NodeProp({ perNode: true });
var noProps = /* @__PURE__ */ Object.create(null);
var NodeType = class {
  constructor(name2, props, id, flags = 0) {
    this.name = name2;
    this.props = props;
    this.id = id;
    this.flags = flags;
  }
  static define(spec) {
    let props = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps;
    let flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0);
    let type = new NodeType(spec.name || "", props, spec.id, flags);
    if (spec.props)
      for (let src of spec.props) {
        if (!Array.isArray(src))
          src = src(type);
        if (src) {
          if (src[0].perNode)
            throw new RangeError("Can't store a per-node prop on a node type");
          props[src[0].id] = src[1];
        }
      }
    return type;
  }
  prop(prop) {
    return this.props[prop.id];
  }
  get isTop() {
    return (this.flags & 1) > 0;
  }
  get isSkipped() {
    return (this.flags & 2) > 0;
  }
  get isError() {
    return (this.flags & 4) > 0;
  }
  get isAnonymous() {
    return (this.flags & 8) > 0;
  }
  is(name2) {
    if (typeof name2 == "string") {
      if (this.name == name2)
        return true;
      let group2 = this.prop(NodeProp.group);
      return group2 ? group2.indexOf(name2) > -1 : false;
    }
    return this.id == name2;
  }
  static match(map2) {
    let direct = /* @__PURE__ */ Object.create(null);
    for (let prop in map2)
      for (let name2 of prop.split(" "))
        direct[name2] = map2[prop];
    return (node) => {
      for (let groups2 = node.prop(NodeProp.group), i = -1; i < (groups2 ? groups2.length : 0); i++) {
        let found = direct[i < 0 ? node.name : groups2[i]];
        if (found)
          return found;
      }
    };
  }
};
NodeType.none = new NodeType("", /* @__PURE__ */ Object.create(null), 0, 8);
var NodeSet = class {
  constructor(types2) {
    this.types = types2;
    for (let i = 0; i < types2.length; i++)
      if (types2[i].id != i)
        throw new RangeError("Node type ids should correspond to array positions when creating a node set");
  }
  extend(...props) {
    let newTypes = [];
    for (let type of this.types) {
      let newProps = null;
      for (let source of props) {
        let add3 = source(type);
        if (add3) {
          if (!newProps)
            newProps = Object.assign({}, type.props);
          newProps[add3[0].id] = add3[1];
        }
      }
      newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
    }
    return new NodeSet(newTypes);
  }
};
var CachedNode = /* @__PURE__ */ new WeakMap();
var CachedInnerNode = /* @__PURE__ */ new WeakMap();
var IterMode;
(function(IterMode2) {
  IterMode2[IterMode2["ExcludeBuffers"] = 1] = "ExcludeBuffers";
  IterMode2[IterMode2["IncludeAnonymous"] = 2] = "IncludeAnonymous";
  IterMode2[IterMode2["IgnoreMounts"] = 4] = "IgnoreMounts";
  IterMode2[IterMode2["IgnoreOverlays"] = 8] = "IgnoreOverlays";
})(IterMode || (IterMode = {}));
var Tree = class {
  constructor(type, children3, positions, length, props) {
    this.type = type;
    this.children = children3;
    this.positions = positions;
    this.length = length;
    this.props = null;
    if (props && props.length) {
      this.props = /* @__PURE__ */ Object.create(null);
      for (let [prop, value] of props)
        this.props[typeof prop == "number" ? prop : prop.id] = value;
    }
  }
  toString() {
    let mounted = this.prop(NodeProp.mounted);
    if (mounted && !mounted.overlay)
      return mounted.tree.toString();
    let children3 = "";
    for (let ch of this.children) {
      let str = ch.toString();
      if (str) {
        if (children3)
          children3 += ",";
        children3 += str;
      }
    }
    return !this.type.name ? children3 : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children3.length ? "(" + children3 + ")" : "");
  }
  cursor(mode = 0) {
    return new TreeCursor(this.topNode, mode);
  }
  cursorAt(pos, side = 0, mode = 0) {
    let scope = CachedNode.get(this) || this.topNode;
    let cursor = new TreeCursor(scope);
    cursor.moveTo(pos, side);
    CachedNode.set(this, cursor._tree);
    return cursor;
  }
  get topNode() {
    return new TreeNode(this, 0, 0, null);
  }
  resolve(pos, side = 0) {
    let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
    CachedNode.set(this, node);
    return node;
  }
  resolveInner(pos, side = 0) {
    let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
    CachedInnerNode.set(this, node);
    return node;
  }
  iterate(spec) {
    let { enter, leave, from = 0, to = this.length } = spec;
    for (let c = this.cursor((spec.mode || 0) | IterMode.IncludeAnonymous); ; ) {
      let entered = false;
      if (c.from <= to && c.to >= from && (c.type.isAnonymous || enter(c) !== false)) {
        if (c.firstChild())
          continue;
        entered = true;
      }
      for (; ; ) {
        if (entered && leave && !c.type.isAnonymous)
          leave(c);
        if (c.nextSibling())
          break;
        if (!c.parent())
          return;
        entered = true;
      }
    }
  }
  prop(prop) {
    return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : void 0;
  }
  get propValues() {
    let result = [];
    if (this.props)
      for (let id in this.props)
        result.push([+id, this.props[id]]);
    return result;
  }
  balance(config2 = {}) {
    return this.children.length <= 8 ? this : balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children3, positions, length) => new Tree(this.type, children3, positions, length, this.propValues), config2.makeTree || ((children3, positions, length) => new Tree(NodeType.none, children3, positions, length)));
  }
  static build(data) {
    return buildTree(data);
  }
};
Tree.empty = new Tree(NodeType.none, [], [], 0);
var FlatBufferCursor = class {
  constructor(buffer, index2) {
    this.buffer = buffer;
    this.index = index2;
  }
  get id() {
    return this.buffer[this.index - 4];
  }
  get start() {
    return this.buffer[this.index - 3];
  }
  get end() {
    return this.buffer[this.index - 2];
  }
  get size() {
    return this.buffer[this.index - 1];
  }
  get pos() {
    return this.index;
  }
  next() {
    this.index -= 4;
  }
  fork() {
    return new FlatBufferCursor(this.buffer, this.index);
  }
};
var TreeBuffer = class {
  constructor(buffer, length, set) {
    this.buffer = buffer;
    this.length = length;
    this.set = set;
  }
  get type() {
    return NodeType.none;
  }
  toString() {
    let result = [];
    for (let index2 = 0; index2 < this.buffer.length; ) {
      result.push(this.childString(index2));
      index2 = this.buffer[index2 + 3];
    }
    return result.join(",");
  }
  childString(index2) {
    let id = this.buffer[index2], endIndex = this.buffer[index2 + 3];
    let type = this.set.types[id], result = type.name;
    if (/\W/.test(result) && !type.isError)
      result = JSON.stringify(result);
    index2 += 4;
    if (endIndex == index2)
      return result;
    let children3 = [];
    while (index2 < endIndex) {
      children3.push(this.childString(index2));
      index2 = this.buffer[index2 + 3];
    }
    return result + "(" + children3.join(",") + ")";
  }
  findChild(startIndex, endIndex, dir, pos, side) {
    let { buffer } = this, pick = -1;
    for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
      if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
        pick = i;
        if (dir > 0)
          break;
      }
    }
    return pick;
  }
  slice(startI, endI, from, to) {
    let b = this.buffer;
    let copy2 = new Uint16Array(endI - startI);
    for (let i = startI, j = 0; i < endI; ) {
      copy2[j++] = b[i++];
      copy2[j++] = b[i++] - from;
      copy2[j++] = b[i++] - from;
      copy2[j++] = b[i++] - startI;
    }
    return new TreeBuffer(copy2, to - from, this.set);
  }
};
function checkSide(side, pos, from, to) {
  switch (side) {
    case -2:
      return from < pos;
    case -1:
      return to >= pos && from < pos;
    case 0:
      return from < pos && to > pos;
    case 1:
      return from <= pos && to > pos;
    case 2:
      return to > pos;
    case 4:
      return true;
  }
}
function enterUnfinishedNodesBefore(node, pos) {
  let scan = node.childBefore(pos);
  while (scan) {
    let last = scan.lastChild;
    if (!last || last.to != scan.to)
      break;
    if (last.type.isError && last.from == last.to) {
      node = scan;
      scan = last.prevSibling;
    } else {
      scan = last;
    }
  }
  return node;
}
function resolveNode(node, pos, side, overlays) {
  var _a2;
  while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) {
    let parent2 = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
    if (!parent2)
      return node;
    node = parent2;
  }
  let mode = overlays ? 0 : IterMode.IgnoreOverlays;
  if (overlays)
    for (let scan = node, parent2 = scan.parent; parent2; scan = parent2, parent2 = scan.parent) {
      if (scan instanceof TreeNode && scan.index < 0 && ((_a2 = parent2.enter(pos, side, mode)) === null || _a2 === void 0 ? void 0 : _a2.from) != scan.from)
        node = parent2;
    }
  for (; ; ) {
    let inner = node.enter(pos, side, mode);
    if (!inner)
      return node;
    node = inner;
  }
}
var TreeNode = class {
  constructor(_tree, from, index2, _parent) {
    this._tree = _tree;
    this.from = from;
    this.index = index2;
    this._parent = _parent;
  }
  get type() {
    return this._tree.type;
  }
  get name() {
    return this._tree.type.name;
  }
  get to() {
    return this.from + this._tree.length;
  }
  nextChild(i, dir, pos, side, mode = 0) {
    for (let parent2 = this; ; ) {
      for (let { children: children3, positions } = parent2._tree, e3 = dir > 0 ? children3.length : -1; i != e3; i += dir) {
        let next = children3[i], start = positions[i] + parent2.from;
        if (!checkSide(side, pos, start, start + next.length))
          continue;
        if (next instanceof TreeBuffer) {
          if (mode & IterMode.ExcludeBuffers)
            continue;
          let index2 = next.findChild(0, next.buffer.length, dir, pos - start, side);
          if (index2 > -1)
            return new BufferNode(new BufferContext(parent2, next, i, start), null, index2);
        } else if (mode & IterMode.IncludeAnonymous || (!next.type.isAnonymous || hasChild(next))) {
          let mounted;
          if (!(mode & IterMode.IgnoreMounts) && next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay)
            return new TreeNode(mounted.tree, start, i, parent2);
          let inner = new TreeNode(next, start, i, parent2);
          return mode & IterMode.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);
        }
      }
      if (mode & IterMode.IncludeAnonymous || !parent2.type.isAnonymous)
        return null;
      if (parent2.index >= 0)
        i = parent2.index + dir;
      else
        i = dir < 0 ? -1 : parent2._parent._tree.children.length;
      parent2 = parent2._parent;
      if (!parent2)
        return null;
    }
  }
  get firstChild() {
    return this.nextChild(0, 1, 0, 4);
  }
  get lastChild() {
    return this.nextChild(this._tree.children.length - 1, -1, 0, 4);
  }
  childAfter(pos) {
    return this.nextChild(0, 1, pos, 2);
  }
  childBefore(pos) {
    return this.nextChild(this._tree.children.length - 1, -1, pos, -2);
  }
  enter(pos, side, mode = 0) {
    let mounted;
    if (!(mode & IterMode.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp.mounted)) && mounted.overlay) {
      let rPos = pos - this.from;
      for (let { from, to } of mounted.overlay) {
        if ((side > 0 ? from <= rPos : from < rPos) && (side < 0 ? to >= rPos : to > rPos))
          return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
      }
    }
    return this.nextChild(0, 1, pos, side, mode);
  }
  nextSignificantParent() {
    let val = this;
    while (val.type.isAnonymous && val._parent)
      val = val._parent;
    return val;
  }
  get parent() {
    return this._parent ? this._parent.nextSignificantParent() : null;
  }
  get nextSibling() {
    return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4) : null;
  }
  get prevSibling() {
    return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4) : null;
  }
  cursor(mode = 0) {
    return new TreeCursor(this, mode);
  }
  get tree() {
    return this._tree;
  }
  toTree() {
    return this._tree;
  }
  resolve(pos, side = 0) {
    return resolveNode(this, pos, side, false);
  }
  resolveInner(pos, side = 0) {
    return resolveNode(this, pos, side, true);
  }
  enterUnfinishedNodesBefore(pos) {
    return enterUnfinishedNodesBefore(this, pos);
  }
  getChild(type, before = null, after = null) {
    let r = getChildren(this, type, before, after);
    return r.length ? r[0] : null;
  }
  getChildren(type, before = null, after = null) {
    return getChildren(this, type, before, after);
  }
  toString() {
    return this._tree.toString();
  }
  get node() {
    return this;
  }
  matchContext(context) {
    return matchNodeContext(this, context);
  }
};
function getChildren(node, type, before, after) {
  let cur2 = node.cursor(), result = [];
  if (!cur2.firstChild())
    return result;
  if (before != null) {
    while (!cur2.type.is(before))
      if (!cur2.nextSibling())
        return result;
  }
  for (; ; ) {
    if (after != null && cur2.type.is(after))
      return result;
    if (cur2.type.is(type))
      result.push(cur2.node);
    if (!cur2.nextSibling())
      return after == null ? result : [];
  }
}
function matchNodeContext(node, context, i = context.length - 1) {
  for (let p = node.parent; i >= 0; p = p.parent) {
    if (!p)
      return false;
    if (!p.type.isAnonymous) {
      if (context[i] && context[i] != p.name)
        return false;
      i--;
    }
  }
  return true;
}
var BufferContext = class {
  constructor(parent2, buffer, index2, start) {
    this.parent = parent2;
    this.buffer = buffer;
    this.index = index2;
    this.start = start;
  }
};
var BufferNode = class {
  constructor(context, _parent, index2) {
    this.context = context;
    this._parent = _parent;
    this.index = index2;
    this.type = context.buffer.set.types[context.buffer.buffer[index2]];
  }
  get name() {
    return this.type.name;
  }
  get from() {
    return this.context.start + this.context.buffer.buffer[this.index + 1];
  }
  get to() {
    return this.context.start + this.context.buffer.buffer[this.index + 2];
  }
  child(dir, pos, side) {
    let { buffer } = this.context;
    let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
    return index2 < 0 ? null : new BufferNode(this.context, this, index2);
  }
  get firstChild() {
    return this.child(1, 0, 4);
  }
  get lastChild() {
    return this.child(-1, 0, 4);
  }
  childAfter(pos) {
    return this.child(1, pos, 2);
  }
  childBefore(pos) {
    return this.child(-1, pos, -2);
  }
  enter(pos, side, mode = 0) {
    if (mode & IterMode.ExcludeBuffers)
      return null;
    let { buffer } = this.context;
    let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
    return index2 < 0 ? null : new BufferNode(this.context, this, index2);
  }
  get parent() {
    return this._parent || this.context.parent.nextSignificantParent();
  }
  externalSibling(dir) {
    return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4);
  }
  get nextSibling() {
    let { buffer } = this.context;
    let after = buffer.buffer[this.index + 3];
    if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
      return new BufferNode(this.context, this._parent, after);
    return this.externalSibling(1);
  }
  get prevSibling() {
    let { buffer } = this.context;
    let parentStart = this._parent ? this._parent.index + 4 : 0;
    if (this.index == parentStart)
      return this.externalSibling(-1);
    return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4));
  }
  cursor(mode = 0) {
    return new TreeCursor(this, mode);
  }
  get tree() {
    return null;
  }
  toTree() {
    let children3 = [], positions = [];
    let { buffer } = this.context;
    let startI = this.index + 4, endI = buffer.buffer[this.index + 3];
    if (endI > startI) {
      let from = buffer.buffer[this.index + 1], to = buffer.buffer[this.index + 2];
      children3.push(buffer.slice(startI, endI, from, to));
      positions.push(0);
    }
    return new Tree(this.type, children3, positions, this.to - this.from);
  }
  resolve(pos, side = 0) {
    return resolveNode(this, pos, side, false);
  }
  resolveInner(pos, side = 0) {
    return resolveNode(this, pos, side, true);
  }
  enterUnfinishedNodesBefore(pos) {
    return enterUnfinishedNodesBefore(this, pos);
  }
  toString() {
    return this.context.buffer.childString(this.index);
  }
  getChild(type, before = null, after = null) {
    let r = getChildren(this, type, before, after);
    return r.length ? r[0] : null;
  }
  getChildren(type, before = null, after = null) {
    return getChildren(this, type, before, after);
  }
  get node() {
    return this;
  }
  matchContext(context) {
    return matchNodeContext(this, context);
  }
};
var TreeCursor = class {
  constructor(node, mode = 0) {
    this.mode = mode;
    this.buffer = null;
    this.stack = [];
    this.index = 0;
    this.bufferNode = null;
    if (node instanceof TreeNode) {
      this.yieldNode(node);
    } else {
      this._tree = node.context.parent;
      this.buffer = node.context;
      for (let n = node._parent; n; n = n._parent)
        this.stack.unshift(n.index);
      this.bufferNode = node;
      this.yieldBuf(node.index);
    }
  }
  get name() {
    return this.type.name;
  }
  yieldNode(node) {
    if (!node)
      return false;
    this._tree = node;
    this.type = node.type;
    this.from = node.from;
    this.to = node.to;
    return true;
  }
  yieldBuf(index2, type) {
    this.index = index2;
    let { start, buffer } = this.buffer;
    this.type = type || buffer.set.types[buffer.buffer[index2]];
    this.from = start + buffer.buffer[index2 + 1];
    this.to = start + buffer.buffer[index2 + 2];
    return true;
  }
  yield(node) {
    if (!node)
      return false;
    if (node instanceof TreeNode) {
      this.buffer = null;
      return this.yieldNode(node);
    }
    this.buffer = node.context;
    return this.yieldBuf(node.index, node.type);
  }
  toString() {
    return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
  }
  enterChild(dir, pos, side) {
    if (!this.buffer)
      return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
    let { buffer } = this.buffer;
    let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
    if (index2 < 0)
      return false;
    this.stack.push(this.index);
    return this.yieldBuf(index2);
  }
  firstChild() {
    return this.enterChild(1, 0, 4);
  }
  lastChild() {
    return this.enterChild(-1, 0, 4);
  }
  childAfter(pos) {
    return this.enterChild(1, pos, 2);
  }
  childBefore(pos) {
    return this.enterChild(-1, pos, -2);
  }
  enter(pos, side, mode = this.mode) {
    if (!this.buffer)
      return this.yield(this._tree.enter(pos, side, mode));
    return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);
  }
  parent() {
    if (!this.buffer)
      return this.yieldNode(this.mode & IterMode.IncludeAnonymous ? this._tree._parent : this._tree.parent);
    if (this.stack.length)
      return this.yieldBuf(this.stack.pop());
    let parent2 = this.mode & IterMode.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
    this.buffer = null;
    return this.yieldNode(parent2);
  }
  sibling(dir) {
    if (!this.buffer)
      return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode));
    let { buffer } = this.buffer, d = this.stack.length - 1;
    if (dir < 0) {
      let parentStart = d < 0 ? 0 : this.stack[d] + 4;
      if (this.index != parentStart)
        return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4));
    } else {
      let after = buffer.buffer[this.index + 3];
      if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
        return this.yieldBuf(after);
    }
    return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false;
  }
  nextSibling() {
    return this.sibling(1);
  }
  prevSibling() {
    return this.sibling(-1);
  }
  atLastNode(dir) {
    let index2, parent2, { buffer } = this;
    if (buffer) {
      if (dir > 0) {
        if (this.index < buffer.buffer.buffer.length)
          return false;
      } else {
        for (let i = 0; i < this.index; i++)
          if (buffer.buffer.buffer[i + 3] < this.index)
            return false;
      }
      ({ index: index2, parent: parent2 } = buffer);
    } else {
      ({ index: index2, _parent: parent2 } = this._tree);
    }
    for (; parent2; { index: index2, _parent: parent2 } = parent2) {
      if (index2 > -1)
        for (let i = index2 + dir, e3 = dir < 0 ? -1 : parent2._tree.children.length; i != e3; i += dir) {
          let child = parent2._tree.children[i];
          if (this.mode & IterMode.IncludeAnonymous || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child))
            return false;
        }
    }
    return true;
  }
  move(dir, enter) {
    if (enter && this.enterChild(dir, 0, 4))
      return true;
    for (; ; ) {
      if (this.sibling(dir))
        return true;
      if (this.atLastNode(dir) || !this.parent())
        return false;
    }
  }
  next(enter = true) {
    return this.move(1, enter);
  }
  prev(enter = true) {
    return this.move(-1, enter);
  }
  moveTo(pos, side = 0) {
    while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos))
      if (!this.parent())
        break;
    while (this.enterChild(1, pos, side)) {
    }
    return this;
  }
  get node() {
    if (!this.buffer)
      return this._tree;
    let cache = this.bufferNode, result = null, depth = 0;
    if (cache && cache.context == this.buffer) {
      scan:
        for (let index2 = this.index, d = this.stack.length; d >= 0; ) {
          for (let c = cache; c; c = c._parent)
            if (c.index == index2) {
              if (index2 == this.index)
                return c;
              result = c;
              depth = d + 1;
              break scan;
            }
          index2 = this.stack[--d];
        }
    }
    for (let i = depth; i < this.stack.length; i++)
      result = new BufferNode(this.buffer, result, this.stack[i]);
    return this.bufferNode = new BufferNode(this.buffer, result, this.index);
  }
  get tree() {
    return this.buffer ? null : this._tree._tree;
  }
  iterate(enter, leave) {
    for (let depth = 0; ; ) {
      let mustLeave = false;
      if (this.type.isAnonymous || enter(this) !== false) {
        if (this.firstChild()) {
          depth++;
          continue;
        }
        if (!this.type.isAnonymous)
          mustLeave = true;
      }
      for (; ; ) {
        if (mustLeave && leave)
          leave(this);
        mustLeave = this.type.isAnonymous;
        if (this.nextSibling())
          break;
        if (!depth)
          return;
        this.parent();
        depth--;
        mustLeave = true;
      }
    }
  }
  matchContext(context) {
    if (!this.buffer)
      return matchNodeContext(this.node, context);
    let { buffer } = this.buffer, { types: types2 } = buffer.set;
    for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {
      if (d < 0)
        return matchNodeContext(this.node, context, i);
      let type = types2[buffer.buffer[this.stack[d]]];
      if (!type.isAnonymous) {
        if (context[i] && context[i] != type.name)
          return false;
        i--;
      }
    }
    return true;
  }
};
function hasChild(tree) {
  return tree.children.some((ch) => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
}
function buildTree(data) {
  var _a2;
  let { buffer, nodeSet: nodeSet2, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet2.types.length } = data;
  let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
  let types2 = nodeSet2.types;
  let contextHash = 0, lookAhead = 0;
  function takeNode(parentStart, minPos, children4, positions2, inRepeat) {
    let { id, start, end, size } = cursor;
    let lookAheadAtStart = lookAhead;
    while (size < 0) {
      cursor.next();
      if (size == -1) {
        let node2 = reused[id];
        children4.push(node2);
        positions2.push(start - parentStart);
        return;
      } else if (size == -3) {
        contextHash = id;
        return;
      } else if (size == -4) {
        lookAhead = id;
        return;
      } else {
        throw new RangeError(`Unrecognized record size: ${size}`);
      }
    }
    let type = types2[id], node, buffer2;
    let startPos = start - parentStart;
    if (end - start <= maxBufferLength && (buffer2 = findBufferSize(cursor.pos - minPos, inRepeat))) {
      let data2 = new Uint16Array(buffer2.size - buffer2.skip);
      let endPos = cursor.pos - buffer2.size, index2 = data2.length;
      while (cursor.pos > endPos)
        index2 = copyToBuffer(buffer2.start, data2, index2);
      node = new TreeBuffer(data2, end - buffer2.start, nodeSet2);
      startPos = buffer2.start - parentStart;
    } else {
      let endPos = cursor.pos - size;
      cursor.next();
      let localChildren = [], localPositions = [];
      let localInRepeat = id >= minRepeatType ? id : -1;
      let lastGroup = 0, lastEnd = end;
      while (cursor.pos > endPos) {
        if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
          if (cursor.end <= lastEnd - maxBufferLength) {
            makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);
            lastGroup = localChildren.length;
            lastEnd = cursor.end;
          }
          cursor.next();
        } else {
          takeNode(start, endPos, localChildren, localPositions, localInRepeat);
        }
      }
      if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
        makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart);
      localChildren.reverse();
      localPositions.reverse();
      if (localInRepeat > -1 && lastGroup > 0) {
        let make = makeBalanced(type);
        node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
      } else {
        node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end);
      }
    }
    children4.push(node);
    positions2.push(startPos);
  }
  function makeBalanced(type) {
    return (children4, positions2, length2) => {
      let lookAhead2 = 0, lastI = children4.length - 1, last, lookAheadProp;
      if (lastI >= 0 && (last = children4[lastI]) instanceof Tree) {
        if (!lastI && last.type == type && last.length == length2)
          return last;
        if (lookAheadProp = last.prop(NodeProp.lookAhead))
          lookAhead2 = positions2[lastI] + last.length + lookAheadProp;
      }
      return makeTree(type, children4, positions2, length2, lookAhead2);
    };
  }
  function makeRepeatLeaf(children4, positions2, base2, i, from, to, type, lookAhead2) {
    let localChildren = [], localPositions = [];
    while (children4.length > i) {
      localChildren.push(children4.pop());
      localPositions.push(positions2.pop() + base2 - from);
    }
    children4.push(makeTree(nodeSet2.types[type], localChildren, localPositions, to - from, lookAhead2 - to));
    positions2.push(from - base2);
  }
  function makeTree(type, children4, positions2, length2, lookAhead2 = 0, props) {
    if (contextHash) {
      let pair = [NodeProp.contextHash, contextHash];
      props = props ? [pair].concat(props) : [pair];
    }
    if (lookAhead2 > 25) {
      let pair = [NodeProp.lookAhead, lookAhead2];
      props = props ? [pair].concat(props) : [pair];
    }
    return new Tree(type, children4, positions2, length2, props);
  }
  function findBufferSize(maxSize, inRepeat) {
    let fork = cursor.fork();
    let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
    let result = { size: 0, start: 0, skip: 0 };
    scan:
      for (let minPos = fork.pos - maxSize; fork.pos > minPos; ) {
        let nodeSize2 = fork.size;
        if (fork.id == inRepeat && nodeSize2 >= 0) {
          result.size = size;
          result.start = start;
          result.skip = skip;
          skip += 4;
          size += 4;
          fork.next();
          continue;
        }
        let startPos = fork.pos - nodeSize2;
        if (nodeSize2 < 0 || startPos < minPos || fork.start < minStart)
          break;
        let localSkipped = fork.id >= minRepeatType ? 4 : 0;
        let nodeStart2 = fork.start;
        fork.next();
        while (fork.pos > startPos) {
          if (fork.size < 0) {
            if (fork.size == -3)
              localSkipped += 4;
            else
              break scan;
          } else if (fork.id >= minRepeatType) {
            localSkipped += 4;
          }
          fork.next();
        }
        start = nodeStart2;
        size += nodeSize2;
        skip += localSkipped;
      }
    if (inRepeat < 0 || size == maxSize) {
      result.size = size;
      result.start = start;
      result.skip = skip;
    }
    return result.size > 4 ? result : void 0;
  }
  function copyToBuffer(bufferStart, buffer2, index2) {
    let { id, start, end, size } = cursor;
    cursor.next();
    if (size >= 0 && id < minRepeatType) {
      let startIndex = index2;
      if (size > 4) {
        let endPos = cursor.pos - (size - 4);
        while (cursor.pos > endPos)
          index2 = copyToBuffer(bufferStart, buffer2, index2);
      }
      buffer2[--index2] = startIndex;
      buffer2[--index2] = end - bufferStart;
      buffer2[--index2] = start - bufferStart;
      buffer2[--index2] = id;
    } else if (size == -3) {
      contextHash = id;
    } else if (size == -4) {
      lookAhead = id;
    }
    return index2;
  }
  let children3 = [], positions = [];
  while (cursor.pos > 0)
    takeNode(data.start || 0, data.bufferStart || 0, children3, positions, -1);
  let length = (_a2 = data.length) !== null && _a2 !== void 0 ? _a2 : children3.length ? positions[0] + children3[0].length : 0;
  return new Tree(types2[data.topID], children3.reverse(), positions.reverse(), length);
}
var nodeSizeCache = /* @__PURE__ */ new WeakMap();
function nodeSize(balanceType, node) {
  if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)
    return 1;
  let size = nodeSizeCache.get(node);
  if (size == null) {
    size = 1;
    for (let child of node.children) {
      if (child.type != balanceType || !(child instanceof Tree)) {
        size = 1;
        break;
      }
      size += nodeSize(balanceType, child);
    }
    nodeSizeCache.set(node, size);
  }
  return size;
}
function balanceRange(balanceType, children3, positions, from, to, start, length, mkTop, mkTree) {
  let total = 0;
  for (let i = from; i < to; i++)
    total += nodeSize(balanceType, children3[i]);
  let maxChild = Math.ceil(total * 1.5 / 8);
  let localChildren = [], localPositions = [];
  function divide(children4, positions2, from2, to2, offset) {
    for (let i = from2; i < to2; ) {
      let groupFrom = i, groupStart = positions2[i], groupSize = nodeSize(balanceType, children4[i]);
      i++;
      for (; i < to2; i++) {
        let nextSize = nodeSize(balanceType, children4[i]);
        if (groupSize + nextSize >= maxChild)
          break;
        groupSize += nextSize;
      }
      if (i == groupFrom + 1) {
        if (groupSize > maxChild) {
          let only = children4[groupFrom];
          divide(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset);
          continue;
        }
        localChildren.push(children4[groupFrom]);
      } else {
        let length2 = positions2[i - 1] + children4[i - 1].length - groupStart;
        localChildren.push(balanceRange(balanceType, children4, positions2, groupFrom, i, groupStart, length2, null, mkTree));
      }
      localPositions.push(groupStart + offset - start);
    }
  }
  divide(children3, positions, from, to, 0);
  return (mkTop || mkTree)(localChildren, localPositions, length);
}
var TreeFragment = class {
  constructor(from, to, tree, offset, openStart = false, openEnd = false) {
    this.from = from;
    this.to = to;
    this.tree = tree;
    this.offset = offset;
    this.open = (openStart ? 1 : 0) | (openEnd ? 2 : 0);
  }
  get openStart() {
    return (this.open & 1) > 0;
  }
  get openEnd() {
    return (this.open & 2) > 0;
  }
  static addTree(tree, fragments = [], partial = false) {
    let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)];
    for (let f of fragments)
      if (f.to > tree.length)
        result.push(f);
    return result;
  }
  static applyChanges(fragments, changes, minGap = 128) {
    if (!changes.length)
      return fragments;
    let result = [];
    let fI = 1, nextF = fragments.length ? fragments[0] : null;
    for (let cI = 0, pos = 0, off = 0; ; cI++) {
      let nextC = cI < changes.length ? changes[cI] : null;
      let nextPos = nextC ? nextC.fromA : 1e9;
      if (nextPos - pos >= minGap)
        while (nextF && nextF.from < nextPos) {
          let cut = nextF;
          if (pos >= cut.from || nextPos <= cut.to || off) {
            let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off;
            cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC);
          }
          if (cut)
            result.push(cut);
          if (nextF.to > nextPos)
            break;
          nextF = fI < fragments.length ? fragments[fI++] : null;
        }
      if (!nextC)
        break;
      pos = nextC.toA;
      off = nextC.toA - nextC.toB;
    }
    return result;
  }
};
var Parser = class {
  startParse(input, fragments, ranges) {
    if (typeof input == "string")
      input = new StringInput(input);
    ranges = !ranges ? [new Range2(0, input.length)] : ranges.length ? ranges.map((r) => new Range2(r.from, r.to)) : [new Range2(0, 0)];
    return this.createParse(input, fragments || [], ranges);
  }
  parse(input, fragments, ranges) {
    let parse = this.startParse(input, fragments, ranges);
    for (; ; ) {
      let done = parse.advance();
      if (done)
        return done;
    }
  }
};
var StringInput = class {
  constructor(string5) {
    this.string = string5;
  }
  get length() {
    return this.string.length;
  }
  chunk(from) {
    return this.string.slice(from);
  }
  get lineChunks() {
    return false;
  }
  read(from, to) {
    return this.string.slice(from, to);
  }
};
var stoppedInner = new NodeProp({ perNode: true });

// node_modules/@lezer/highlight/dist/index.js
var nextTagID = 0;
var Tag = class {
  constructor(set, base2, modified) {
    this.set = set;
    this.base = base2;
    this.modified = modified;
    this.id = nextTagID++;
  }
  static define(parent2) {
    if (parent2 === null || parent2 === void 0 ? void 0 : parent2.base)
      throw new Error("Can not derive from a modified tag");
    let tag2 = new Tag([], null, []);
    tag2.set.push(tag2);
    if (parent2)
      for (let t4 of parent2.set)
        tag2.set.push(t4);
    return tag2;
  }
  static defineModifier() {
    let mod = new Modifier();
    return (tag2) => {
      if (tag2.modified.indexOf(mod) > -1)
        return tag2;
      return Modifier.get(tag2.base || tag2, tag2.modified.concat(mod).sort((a, b) => a.id - b.id));
    };
  }
};
var nextModifierID = 0;
var Modifier = class {
  constructor() {
    this.instances = [];
    this.id = nextModifierID++;
  }
  static get(base2, mods) {
    if (!mods.length)
      return base2;
    let exists = mods[0].instances.find((t4) => t4.base == base2 && sameArray2(mods, t4.modified));
    if (exists)
      return exists;
    let set = [], tag2 = new Tag(set, base2, mods);
    for (let m of mods)
      m.instances.push(tag2);
    let configs = powerSet(mods);
    for (let parent2 of base2.set)
      if (!parent2.modified.length)
        for (let config2 of configs)
          set.push(Modifier.get(parent2, config2));
    return tag2;
  }
};
function sameArray2(a, b) {
  return a.length == b.length && a.every((x2, i) => x2 == b[i]);
}
function powerSet(array3) {
  let sets = [[]];
  for (let i = 0; i < array3.length; i++) {
    for (let j = 0, e3 = sets.length; j < e3; j++) {
      sets.push(sets[j].concat(array3[i]));
    }
  }
  return sets.sort((a, b) => b.length - a.length);
}
function styleTags(spec) {
  let byName = /* @__PURE__ */ Object.create(null);
  for (let prop in spec) {
    let tags3 = spec[prop];
    if (!Array.isArray(tags3))
      tags3 = [tags3];
    for (let part of prop.split(" "))
      if (part) {
        let pieces = [], mode = 2, rest = part;
        for (let pos = 0; ; ) {
          if (rest == "..." && pos > 0 && pos + 3 == part.length) {
            mode = 1;
            break;
          }
          let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);
          if (!m)
            throw new RangeError("Invalid path: " + part);
          pieces.push(m[0] == "*" ? "" : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]);
          pos += m[0].length;
          if (pos == part.length)
            break;
          let next = part[pos++];
          if (pos == part.length && next == "!") {
            mode = 0;
            break;
          }
          if (next != "/")
            throw new RangeError("Invalid path: " + part);
          rest = part.slice(pos);
        }
        let last = pieces.length - 1, inner = pieces[last];
        if (!inner)
          throw new RangeError("Invalid path: " + part);
        let rule = new Rule(tags3, mode, last > 0 ? pieces.slice(0, last) : null);
        byName[inner] = rule.sort(byName[inner]);
      }
  }
  return ruleNodeProp.add(byName);
}
var ruleNodeProp = new NodeProp();
var Rule = class {
  constructor(tags3, mode, context, next) {
    this.tags = tags3;
    this.mode = mode;
    this.context = context;
    this.next = next;
  }
  get opaque() {
    return this.mode == 0;
  }
  get inherit() {
    return this.mode == 1;
  }
  sort(other) {
    if (!other || other.depth < this.depth) {
      this.next = other;
      return this;
    }
    other.next = this.sort(other.next);
    return other;
  }
  get depth() {
    return this.context ? this.context.length : 0;
  }
};
Rule.empty = new Rule([], 2, null);
function tagHighlighter(tags3, options2) {
  let map2 = /* @__PURE__ */ Object.create(null);
  for (let style of tags3) {
    if (!Array.isArray(style.tag))
      map2[style.tag.id] = style.class;
    else
      for (let tag2 of style.tag)
        map2[tag2.id] = style.class;
  }
  let { scope, all = null } = options2 || {};
  return {
    style: (tags4) => {
      let cls = all;
      for (let tag2 of tags4) {
        for (let sub of tag2.set) {
          let tagClass = map2[sub.id];
          if (tagClass) {
            cls = cls ? cls + " " + tagClass : tagClass;
            break;
          }
        }
      }
      return cls;
    },
    scope
  };
}
function highlightTags(highlighters, tags3) {
  let result = null;
  for (let highlighter of highlighters) {
    let value = highlighter.style(tags3);
    if (value)
      result = result ? result + " " + value : value;
  }
  return result;
}
function highlightTree(tree, highlighter, putStyle, from = 0, to = tree.length) {
  let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle);
  builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters);
  builder.flush(to);
}
var HighlightBuilder = class {
  constructor(at, highlighters, span) {
    this.at = at;
    this.highlighters = highlighters;
    this.span = span;
    this.class = "";
  }
  startSpan(at, cls) {
    if (cls != this.class) {
      this.flush(at);
      if (at > this.at)
        this.at = at;
      this.class = cls;
    }
  }
  flush(to) {
    if (to > this.at && this.class)
      this.span(this.at, to, this.class);
  }
  highlightRange(cursor, from, to, inheritedClass, highlighters) {
    let { type, from: start, to: end } = cursor;
    if (start >= to || end <= from)
      return;
    if (type.isTop)
      highlighters = this.highlighters.filter((h) => !h.scope || h.scope(type));
    let cls = inheritedClass;
    let rule = getStyleTags(cursor) || Rule.empty;
    let tagCls = highlightTags(highlighters, rule.tags);
    if (tagCls) {
      if (cls)
        cls += " ";
      cls += tagCls;
      if (rule.mode == 1)
        inheritedClass += (inheritedClass ? " " : "") + tagCls;
    }
    this.startSpan(cursor.from, cls);
    if (rule.opaque)
      return;
    let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted);
    if (mounted && mounted.overlay) {
      let inner = cursor.node.enter(mounted.overlay[0].from + start, 1);
      let innerHighlighters = this.highlighters.filter((h) => !h.scope || h.scope(mounted.tree.type));
      let hasChild2 = cursor.firstChild();
      for (let i = 0, pos = start; ; i++) {
        let next = i < mounted.overlay.length ? mounted.overlay[i] : null;
        let nextPos = next ? next.from + start : end;
        let rangeFrom = Math.max(from, pos), rangeTo = Math.min(to, nextPos);
        if (rangeFrom < rangeTo && hasChild2) {
          while (cursor.from < rangeTo) {
            this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, highlighters);
            this.startSpan(Math.min(to, cursor.to), cls);
            if (cursor.to >= nextPos || !cursor.nextSibling())
              break;
          }
        }
        if (!next || nextPos > to)
          break;
        pos = next.to + start;
        if (pos > from) {
          this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to, pos), inheritedClass, innerHighlighters);
          this.startSpan(pos, cls);
        }
      }
      if (hasChild2)
        cursor.parent();
    } else if (cursor.firstChild()) {
      do {
        if (cursor.to <= from)
          continue;
        if (cursor.from >= to)
          break;
        this.highlightRange(cursor, from, to, inheritedClass, highlighters);
        this.startSpan(Math.min(to, cursor.to), cls);
      } while (cursor.nextSibling());
      cursor.parent();
    }
  }
};
function getStyleTags(node) {
  let rule = node.type.prop(ruleNodeProp);
  while (rule && rule.context && !node.matchContext(rule.context))
    rule = rule.next;
  return rule || null;
}
var t = Tag.define;
var comment = t();
var name = t();
var typeName = t(name);
var propertyName = t(name);
var literal = t();
var string2 = t(literal);
var number3 = t(literal);
var content = t();
var heading = t(content);
var keyword = t();
var operator = t();
var punctuation = t();
var bracket = t(punctuation);
var meta = t();
var tags2 = {
  comment,
  lineComment: t(comment),
  blockComment: t(comment),
  docComment: t(comment),
  name,
  variableName: t(name),
  typeName,
  tagName: t(typeName),
  propertyName,
  attributeName: t(propertyName),
  className: t(name),
  labelName: t(name),
  namespace: t(name),
  macroName: t(name),
  literal,
  string: string2,
  docString: t(string2),
  character: t(string2),
  attributeValue: t(string2),
  number: number3,
  integer: t(number3),
  float: t(number3),
  bool: t(literal),
  regexp: t(literal),
  escape: t(literal),
  color: t(literal),
  url: t(literal),
  keyword,
  self: t(keyword),
  null: t(keyword),
  atom: t(keyword),
  unit: t(keyword),
  modifier: t(keyword),
  operatorKeyword: t(keyword),
  controlKeyword: t(keyword),
  definitionKeyword: t(keyword),
  moduleKeyword: t(keyword),
  operator,
  derefOperator: t(operator),
  arithmeticOperator: t(operator),
  logicOperator: t(operator),
  bitwiseOperator: t(operator),
  compareOperator: t(operator),
  updateOperator: t(operator),
  definitionOperator: t(operator),
  typeOperator: t(operator),
  controlOperator: t(operator),
  punctuation,
  separator: t(punctuation),
  bracket,
  angleBracket: t(bracket),
  squareBracket: t(bracket),
  paren: t(bracket),
  brace: t(bracket),
  content,
  heading,
  heading1: t(heading),
  heading2: t(heading),
  heading3: t(heading),
  heading4: t(heading),
  heading5: t(heading),
  heading6: t(heading),
  contentSeparator: t(content),
  list: t(content),
  quote: t(content),
  emphasis: t(content),
  strong: t(content),
  link: t(content),
  monospace: t(content),
  strikethrough: t(content),
  inserted: t(),
  deleted: t(),
  changed: t(),
  invalid: t(),
  meta,
  documentMeta: t(meta),
  annotation: t(meta),
  processingInstruction: t(meta),
  definition: Tag.defineModifier(),
  constant: Tag.defineModifier(),
  function: Tag.defineModifier(),
  standard: Tag.defineModifier(),
  local: Tag.defineModifier(),
  special: Tag.defineModifier()
};
var classHighlighter = tagHighlighter([
  { tag: tags2.link, class: "tok-link" },
  { tag: tags2.heading, class: "tok-heading" },
  { tag: tags2.emphasis, class: "tok-emphasis" },
  { tag: tags2.strong, class: "tok-strong" },
  { tag: tags2.keyword, class: "tok-keyword" },
  { tag: tags2.atom, class: "tok-atom" },
  { tag: tags2.bool, class: "tok-bool" },
  { tag: tags2.url, class: "tok-url" },
  { tag: tags2.labelName, class: "tok-labelName" },
  { tag: tags2.inserted, class: "tok-inserted" },
  { tag: tags2.deleted, class: "tok-deleted" },
  { tag: tags2.literal, class: "tok-literal" },
  { tag: tags2.string, class: "tok-string" },
  { tag: tags2.number, class: "tok-number" },
  { tag: [tags2.regexp, tags2.escape, tags2.special(tags2.string)], class: "tok-string2" },
  { tag: tags2.variableName, class: "tok-variableName" },
  { tag: tags2.local(tags2.variableName), class: "tok-variableName tok-local" },
  { tag: tags2.definition(tags2.variableName), class: "tok-variableName tok-definition" },
  { tag: tags2.special(tags2.variableName), class: "tok-variableName2" },
  { tag: tags2.definition(tags2.propertyName), class: "tok-propertyName tok-definition" },
  { tag: tags2.typeName, class: "tok-typeName" },
  { tag: tags2.namespace, class: "tok-namespace" },
  { tag: tags2.className, class: "tok-className" },
  { tag: tags2.macroName, class: "tok-macroName" },
  { tag: tags2.propertyName, class: "tok-propertyName" },
  { tag: tags2.operator, class: "tok-operator" },
  { tag: tags2.comment, class: "tok-comment" },
  { tag: tags2.meta, class: "tok-meta" },
  { tag: tags2.invalid, class: "tok-invalid" },
  { tag: tags2.punctuation, class: "tok-punctuation" }
]);

// node_modules/@codemirror/language/dist/index.js
var _a;
var languageDataProp = /* @__PURE__ */ new NodeProp();
function defineLanguageFacet(baseData) {
  return Facet.define({
    combine: baseData ? (values) => values.concat(baseData) : void 0
  });
}
var Language = class {
  constructor(data, parser, extraExtensions = [], name2 = "") {
    this.data = data;
    this.name = name2;
    if (!EditorState.prototype.hasOwnProperty("tree"))
      Object.defineProperty(EditorState.prototype, "tree", { get() {
        return syntaxTree(this);
      } });
    this.parser = parser;
    this.extension = [
      language.of(this),
      EditorState.languageData.of((state, pos, side) => state.facet(languageDataFacetAt(state, pos, side)))
    ].concat(extraExtensions);
  }
  isActiveAt(state, pos, side = -1) {
    return languageDataFacetAt(state, pos, side) == this.data;
  }
  findRegions(state) {
    let lang2 = state.facet(language);
    if ((lang2 === null || lang2 === void 0 ? void 0 : lang2.data) == this.data)
      return [{ from: 0, to: state.doc.length }];
    if (!lang2 || !lang2.allowsNesting)
      return [];
    let result = [];
    let explore = (tree, from) => {
      if (tree.prop(languageDataProp) == this.data) {
        result.push({ from, to: from + tree.length });
        return;
      }
      let mount = tree.prop(NodeProp.mounted);
      if (mount) {
        if (mount.tree.prop(languageDataProp) == this.data) {
          if (mount.overlay)
            for (let r of mount.overlay)
              result.push({ from: r.from + from, to: r.to + from });
          else
            result.push({ from, to: from + tree.length });
          return;
        } else if (mount.overlay) {
          let size = result.length;
          explore(mount.tree, mount.overlay[0].from + from);
          if (result.length > size)
            return;
        }
      }
      for (let i = 0; i < tree.children.length; i++) {
        let ch = tree.children[i];
        if (ch instanceof Tree)
          explore(ch, tree.positions[i] + from);
      }
    };
    explore(syntaxTree(state), 0);
    return result;
  }
  get allowsNesting() {
    return true;
  }
};
Language.setState = /* @__PURE__ */ StateEffect.define();
function languageDataFacetAt(state, pos, side) {
  let topLang = state.facet(language);
  if (!topLang)
    return null;
  let facet = topLang.data;
  if (topLang.allowsNesting) {
    for (let node = syntaxTree(state).topNode; node; node = node.enter(pos, side, IterMode.ExcludeBuffers))
      facet = node.type.prop(languageDataProp) || facet;
  }
  return facet;
}
function syntaxTree(state) {
  let field = state.field(Language.state, false);
  return field ? field.tree : Tree.empty;
}
var DocInput = class {
  constructor(doc2, length = doc2.length) {
    this.doc = doc2;
    this.length = length;
    this.cursorPos = 0;
    this.string = "";
    this.cursor = doc2.iter();
  }
  syncTo(pos) {
    this.string = this.cursor.next(pos - this.cursorPos).value;
    this.cursorPos = pos + this.string.length;
    return this.cursorPos - this.string.length;
  }
  chunk(pos) {
    this.syncTo(pos);
    return this.string;
  }
  get lineChunks() {
    return true;
  }
  read(from, to) {
    let stringStart = this.cursorPos - this.string.length;
    if (from < stringStart || to >= this.cursorPos)
      return this.doc.sliceString(from, to);
    else
      return this.string.slice(from - stringStart, to - stringStart);
  }
};
var currentContext = null;
var ParseContext = class {
  constructor(parser, state, fragments = [], tree, treeLen, viewport, skipped, scheduleOn) {
    this.parser = parser;
    this.state = state;
    this.fragments = fragments;
    this.tree = tree;
    this.treeLen = treeLen;
    this.viewport = viewport;
    this.skipped = skipped;
    this.scheduleOn = scheduleOn;
    this.parse = null;
    this.tempSkipped = [];
  }
  static create(parser, state, viewport) {
    return new ParseContext(parser, state, [], Tree.empty, 0, viewport, [], null);
  }
  startParse() {
    return this.parser.startParse(new DocInput(this.state.doc), this.fragments);
  }
  work(until, upto) {
    if (upto != null && upto >= this.state.doc.length)
      upto = void 0;
    if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) {
      this.takeTree();
      return true;
    }
    return this.withContext(() => {
      var _a2;
      if (typeof until == "number") {
        let endTime = Date.now() + until;
        until = () => Date.now() > endTime;
      }
      if (!this.parse)
        this.parse = this.startParse();
      if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) && upto < this.state.doc.length)
        this.parse.stopAt(upto);
      for (; ; ) {
        let done = this.parse.advance();
        if (done) {
          this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null));
          this.treeLen = (_a2 = this.parse.stoppedAt) !== null && _a2 !== void 0 ? _a2 : this.state.doc.length;
          this.tree = done;
          this.parse = null;
          if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length))
            this.parse = this.startParse();
          else
            return true;
        }
        if (until())
          return false;
      }
    });
  }
  takeTree() {
    let pos, tree;
    if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) {
      if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos)
        this.parse.stopAt(pos);
      this.withContext(() => {
        while (!(tree = this.parse.advance())) {
        }
      });
      this.treeLen = pos;
      this.tree = tree;
      this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true));
      this.parse = null;
    }
  }
  withContext(f) {
    let prev = currentContext;
    currentContext = this;
    try {
      return f();
    } finally {
      currentContext = prev;
    }
  }
  withoutTempSkipped(fragments) {
    for (let r; r = this.tempSkipped.pop(); )
      fragments = cutFragments(fragments, r.from, r.to);
    return fragments;
  }
  changes(changes, newState) {
    let { fragments, tree, treeLen, viewport, skipped } = this;
    this.takeTree();
    if (!changes.empty) {
      let ranges = [];
      changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB }));
      fragments = TreeFragment.applyChanges(fragments, ranges);
      tree = Tree.empty;
      treeLen = 0;
      viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) };
      if (this.skipped.length) {
        skipped = [];
        for (let r of this.skipped) {
          let from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1);
          if (from < to)
            skipped.push({ from, to });
        }
      }
    }
    return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn);
  }
  updateViewport(viewport) {
    if (this.viewport.from == viewport.from && this.viewport.to == viewport.to)
      return false;
    this.viewport = viewport;
    let startLen = this.skipped.length;
    for (let i = 0; i < this.skipped.length; i++) {
      let { from, to } = this.skipped[i];
      if (from < viewport.to && to > viewport.from) {
        this.fragments = cutFragments(this.fragments, from, to);
        this.skipped.splice(i--, 1);
      }
    }
    if (this.skipped.length >= startLen)
      return false;
    this.reset();
    return true;
  }
  reset() {
    if (this.parse) {
      this.takeTree();
      this.parse = null;
    }
  }
  skipUntilInView(from, to) {
    this.skipped.push({ from, to });
  }
  static getSkippingParser(until) {
    return new class extends Parser {
      createParse(input, fragments, ranges) {
        let from = ranges[0].from, to = ranges[ranges.length - 1].to;
        let parser = {
          parsedPos: from,
          advance() {
            let cx = currentContext;
            if (cx) {
              for (let r of ranges)
                cx.tempSkipped.push(r);
              if (until)
                cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until;
            }
            this.parsedPos = to;
            return new Tree(NodeType.none, [], [], to - from);
          },
          stoppedAt: null,
          stopAt() {
          }
        };
        return parser;
      }
    }();
  }
  isDone(upto) {
    upto = Math.min(upto, this.state.doc.length);
    let frags = this.fragments;
    return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto;
  }
  static get() {
    return currentContext;
  }
};
function cutFragments(fragments, from, to) {
  return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]);
}
var LanguageState = class {
  constructor(context) {
    this.context = context;
    this.tree = context.tree;
  }
  apply(tr) {
    if (!tr.docChanged && this.tree == this.context.tree)
      return this;
    let newCx = this.context.changes(tr.changes, tr.state);
    let upto = this.context.treeLen == tr.startState.doc.length ? void 0 : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to);
    if (!newCx.work(20, upto))
      newCx.takeTree();
    return new LanguageState(newCx);
  }
  static init(state) {
    let vpTo = Math.min(3e3, state.doc.length);
    let parseState = ParseContext.create(state.facet(language).parser, state, { from: 0, to: vpTo });
    if (!parseState.work(20, vpTo))
      parseState.takeTree();
    return new LanguageState(parseState);
  }
};
Language.state = /* @__PURE__ */ StateField.define({
  create: LanguageState.init,
  update(value, tr) {
    for (let e3 of tr.effects)
      if (e3.is(Language.setState))
        return e3.value;
    if (tr.startState.facet(language) != tr.state.facet(language))
      return LanguageState.init(tr.state);
    return value.apply(tr);
  }
});
var requestIdle = (callback) => {
  let timeout = setTimeout(() => callback(), 500);
  return () => clearTimeout(timeout);
};
if (typeof requestIdleCallback != "undefined")
  requestIdle = (callback) => {
    let idle = -1, timeout = setTimeout(() => {
      idle = requestIdleCallback(callback, { timeout: 500 - 100 });
    }, 100);
    return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle);
  };
var isInputPending = typeof navigator != "undefined" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending) ? () => navigator.scheduling.isInputPending() : null;
var parseWorker = /* @__PURE__ */ ViewPlugin.fromClass(class ParseWorker {
  constructor(view) {
    this.view = view;
    this.working = null;
    this.workScheduled = 0;
    this.chunkEnd = -1;
    this.chunkBudget = -1;
    this.work = this.work.bind(this);
    this.scheduleWork();
  }
  update(update2) {
    let cx = this.view.state.field(Language.state).context;
    if (cx.updateViewport(update2.view.viewport) || this.view.viewport.to > cx.treeLen)
      this.scheduleWork();
    if (update2.docChanged) {
      if (this.view.hasFocus)
        this.chunkBudget += 50;
      this.scheduleWork();
    }
    this.checkAsyncSchedule(cx);
  }
  scheduleWork() {
    if (this.working)
      return;
    let { state } = this.view, field = state.field(Language.state);
    if (field.tree != field.context.tree || !field.context.isDone(state.doc.length))
      this.working = requestIdle(this.work);
  }
  work(deadline) {
    this.working = null;
    let now = Date.now();
    if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) {
      this.chunkEnd = now + 3e4;
      this.chunkBudget = 3e3;
    }
    if (this.chunkBudget <= 0)
      return;
    let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state);
    if (field.tree == field.context.tree && field.context.isDone(vpTo + 1e5))
      return;
    let endTime = Date.now() + Math.min(this.chunkBudget, 100, deadline && !isInputPending ? Math.max(25, deadline.timeRemaining() - 5) : 1e9);
    let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1e3;
    let done = field.context.work(() => {
      return isInputPending && isInputPending() || Date.now() > endTime;
    }, vpTo + (viewportFirst ? 0 : 1e5));
    this.chunkBudget -= Date.now() - now;
    if (done || this.chunkBudget <= 0) {
      field.context.takeTree();
      this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) });
    }
    if (this.chunkBudget > 0 && !(done && !viewportFirst))
      this.scheduleWork();
    this.checkAsyncSchedule(field.context);
  }
  checkAsyncSchedule(cx) {
    if (cx.scheduleOn) {
      this.workScheduled++;
      cx.scheduleOn.then(() => this.scheduleWork()).catch((err2) => logException(this.view.state, err2)).then(() => this.workScheduled--);
      cx.scheduleOn = null;
    }
  }
  destroy() {
    if (this.working)
      this.working();
  }
  isWorking() {
    return !!(this.working || this.workScheduled > 0);
  }
}, {
  eventHandlers: { focus() {
    this.scheduleWork();
  } }
});
var language = /* @__PURE__ */ Facet.define({
  combine(languages) {
    return languages.length ? languages[0] : null;
  },
  enables: (language2) => [
    Language.state,
    parseWorker,
    EditorView.contentAttributes.compute([language2], (state) => {
      let lang2 = state.facet(language2);
      return lang2 && lang2.name ? { "data-language": lang2.name } : {};
    })
  ]
});
var LanguageSupport = class {
  constructor(language2, support = []) {
    this.language = language2;
    this.support = support;
    this.extension = [language2, support];
  }
};
var indentService = /* @__PURE__ */ Facet.define();
var indentUnit = /* @__PURE__ */ Facet.define({
  combine: (values) => {
    if (!values.length)
      return "  ";
    if (!/^(?: +|\t+)$/.test(values[0]))
      throw new Error("Invalid indent unit: " + JSON.stringify(values[0]));
    return values[0];
  }
});
function getIndentUnit(state) {
  let unit2 = state.facet(indentUnit);
  return unit2.charCodeAt(0) == 9 ? state.tabSize * unit2.length : unit2.length;
}
function indentString(state, cols) {
  let result = "", ts = state.tabSize;
  if (state.facet(indentUnit).charCodeAt(0) == 9)
    while (cols >= ts) {
      result += "	";
      cols -= ts;
    }
  for (let i = 0; i < cols; i++)
    result += " ";
  return result;
}
function getIndentation(context, pos) {
  if (context instanceof EditorState)
    context = new IndentContext(context);
  for (let service of context.state.facet(indentService)) {
    let result = service(context, pos);
    if (result != null)
      return result;
  }
  let tree = syntaxTree(context.state);
  return tree ? syntaxIndentation(context, tree, pos) : null;
}
var IndentContext = class {
  constructor(state, options2 = {}) {
    this.state = state;
    this.options = options2;
    this.unit = getIndentUnit(state);
  }
  lineAt(pos, bias = 1) {
    let line = this.state.doc.lineAt(pos);
    let { simulateBreak, simulateDoubleBreak } = this.options;
    if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) {
      if (simulateDoubleBreak && simulateBreak == pos)
        return { text: "", from: pos };
      else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos)
        return { text: line.text.slice(simulateBreak - line.from), from: simulateBreak };
      else
        return { text: line.text.slice(0, simulateBreak - line.from), from: line.from };
    }
    return line;
  }
  textAfterPos(pos, bias = 1) {
    if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak)
      return "";
    let { text: text2, from } = this.lineAt(pos, bias);
    return text2.slice(pos - from, Math.min(text2.length, pos + 100 - from));
  }
  column(pos, bias = 1) {
    let { text: text2, from } = this.lineAt(pos, bias);
    let result = this.countColumn(text2, pos - from);
    let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1;
    if (override > -1)
      result += override - this.countColumn(text2, text2.search(/\S|$/));
    return result;
  }
  countColumn(line, pos = line.length) {
    return countColumn(line, this.state.tabSize, pos);
  }
  lineIndent(pos, bias = 1) {
    let { text: text2, from } = this.lineAt(pos, bias);
    let override = this.options.overrideIndentation;
    if (override) {
      let overriden = override(from);
      if (overriden > -1)
        return overriden;
    }
    return this.countColumn(text2, text2.search(/\S|$/));
  }
  get simulatedBreak() {
    return this.options.simulateBreak || null;
  }
};
var indentNodeProp = /* @__PURE__ */ new NodeProp();
function syntaxIndentation(cx, ast, pos) {
  return indentFrom(ast.resolveInner(pos).enterUnfinishedNodesBefore(pos), pos, cx);
}
function ignoreClosed(cx) {
  return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak;
}
function indentStrategy(tree) {
  let strategy = tree.type.prop(indentNodeProp);
  if (strategy)
    return strategy;
  let first = tree.firstChild, close;
  if (first && (close = first.type.prop(NodeProp.closedBy))) {
    let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1;
    return (cx) => delimitedStrategy(cx, true, 1, void 0, closed && !ignoreClosed(cx) ? last.from : void 0);
  }
  return tree.parent == null ? topIndent : null;
}
function indentFrom(node, pos, base2) {
  for (; node; node = node.parent) {
    let strategy = indentStrategy(node);
    if (strategy)
      return strategy(TreeIndentContext.create(base2, pos, node));
  }
  return null;
}
function topIndent() {
  return 0;
}
var TreeIndentContext = class extends IndentContext {
  constructor(base2, pos, node) {
    super(base2.state, base2.options);
    this.base = base2;
    this.pos = pos;
    this.node = node;
  }
  static create(base2, pos, node) {
    return new TreeIndentContext(base2, pos, node);
  }
  get textAfter() {
    return this.textAfterPos(this.pos);
  }
  get baseIndent() {
    let line = this.state.doc.lineAt(this.node.from);
    for (; ; ) {
      let atBreak = this.node.resolve(line.from);
      while (atBreak.parent && atBreak.parent.from == atBreak.from)
        atBreak = atBreak.parent;
      if (isParent(atBreak, this.node))
        break;
      line = this.state.doc.lineAt(atBreak.from);
    }
    return this.lineIndent(line.from);
  }
  continue() {
    let parent2 = this.node.parent;
    return parent2 ? indentFrom(parent2, this.pos, this.base) : 0;
  }
};
function isParent(parent2, of) {
  for (let cur2 = of; cur2; cur2 = cur2.parent)
    if (parent2 == cur2)
      return true;
  return false;
}
function bracketedAligned(context) {
  let tree = context.node;
  let openToken = tree.childAfter(tree.from), last = tree.lastChild;
  if (!openToken)
    return null;
  let sim = context.options.simulateBreak;
  let openLine = context.state.doc.lineAt(openToken.from);
  let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim);
  for (let pos = openToken.to; ; ) {
    let next = tree.childAfter(pos);
    if (!next || next == last)
      return null;
    if (!next.type.isSkipped)
      return next.from < lineEnd ? openToken : null;
    pos = next.to;
  }
}
function delimitedStrategy(context, align, units, closing2, closedAt) {
  let after = context.textAfter, space2 = after.match(/^\s*/)[0].length;
  let closed = closing2 && after.slice(space2, space2 + closing2.length) == closing2 || closedAt == context.pos + space2;
  let aligned = align ? bracketedAligned(context) : null;
  if (aligned)
    return closed ? context.column(aligned.from) : context.column(aligned.to);
  return context.baseIndent + (closed ? 0 : context.unit * units);
}
var DontIndentBeyond = 200;
function indentOnInput() {
  return EditorState.transactionFilter.of((tr) => {
    if (!tr.docChanged || !tr.isUserEvent("input.type") && !tr.isUserEvent("input.complete"))
      return tr;
    let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head);
    if (!rules.length)
      return tr;
    let doc2 = tr.newDoc, { head } = tr.newSelection.main, line = doc2.lineAt(head);
    if (head > line.from + DontIndentBeyond)
      return tr;
    let lineStart = doc2.sliceString(line.from, head);
    if (!rules.some((r) => r.test(lineStart)))
      return tr;
    let { state } = tr, last = -1, changes = [];
    for (let { head: head2 } of state.selection.ranges) {
      let line2 = state.doc.lineAt(head2);
      if (line2.from == last)
        continue;
      last = line2.from;
      let indent = getIndentation(state, line2.from);
      if (indent == null)
        continue;
      let cur2 = /^\s*/.exec(line2.text)[0];
      let norm = indentString(state, indent);
      if (cur2 != norm)
        changes.push({ from: line2.from, to: line2.from + cur2.length, insert: norm });
    }
    return changes.length ? [tr, { changes, sequential: true }] : tr;
  });
}
var foldService = /* @__PURE__ */ Facet.define();
var foldNodeProp = /* @__PURE__ */ new NodeProp();
function syntaxFolding(state, start, end) {
  let tree = syntaxTree(state);
  if (tree.length < end)
    return null;
  let inner = tree.resolveInner(end);
  let found = null;
  for (let cur2 = inner; cur2; cur2 = cur2.parent) {
    if (cur2.to <= end || cur2.from > end)
      continue;
    if (found && cur2.from < start)
      break;
    let prop = cur2.type.prop(foldNodeProp);
    if (prop && (cur2.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur2))) {
      let value = prop(cur2, state);
      if (value && value.from <= end && value.from >= start && value.to > end)
        found = value;
    }
  }
  return found;
}
function isUnfinished(node) {
  let ch = node.lastChild;
  return ch && ch.to == node.to && ch.type.isError;
}
function foldable(state, lineStart, lineEnd) {
  for (let service of state.facet(foldService)) {
    let result = service(state, lineStart, lineEnd);
    if (result)
      return result;
  }
  return syntaxFolding(state, lineStart, lineEnd);
}
function mapRange(range2, mapping) {
  let from = mapping.mapPos(range2.from, 1), to = mapping.mapPos(range2.to, -1);
  return from >= to ? void 0 : { from, to };
}
var foldEffect = /* @__PURE__ */ StateEffect.define({ map: mapRange });
var unfoldEffect = /* @__PURE__ */ StateEffect.define({ map: mapRange });
function selectedLines(view) {
  let lines = [];
  for (let { head } of view.state.selection.ranges) {
    if (lines.some((l) => l.from <= head && l.to >= head))
      continue;
    lines.push(view.lineBlockAt(head));
  }
  return lines;
}
var foldState = /* @__PURE__ */ StateField.define({
  create() {
    return Decoration.none;
  },
  update(folded, tr) {
    folded = folded.map(tr.changes);
    for (let e3 of tr.effects) {
      if (e3.is(foldEffect) && !foldExists(folded, e3.value.from, e3.value.to))
        folded = folded.update({ add: [foldWidget.range(e3.value.from, e3.value.to)] });
      else if (e3.is(unfoldEffect))
        folded = folded.update({
          filter: (from, to) => e3.value.from != from || e3.value.to != to,
          filterFrom: e3.value.from,
          filterTo: e3.value.to
        });
    }
    if (tr.selection) {
      let onSelection = false, { head } = tr.selection.main;
      folded.between(head, head, (a, b) => {
        if (a < head && b > head)
          onSelection = true;
      });
      if (onSelection)
        folded = folded.update({
          filterFrom: head,
          filterTo: head,
          filter: (a, b) => b <= head || a >= head
        });
    }
    return folded;
  },
  provide: (f) => EditorView.decorations.from(f),
  toJSON(folded, state) {
    let ranges = [];
    folded.between(0, state.doc.length, (from, to) => {
      ranges.push(from, to);
    });
    return ranges;
  },
  fromJSON(value) {
    if (!Array.isArray(value) || value.length % 2)
      throw new RangeError("Invalid JSON for fold state");
    let ranges = [];
    for (let i = 0; i < value.length; ) {
      let from = value[i++], to = value[i++];
      if (typeof from != "number" || typeof to != "number")
        throw new RangeError("Invalid JSON for fold state");
      ranges.push(foldWidget.range(from, to));
    }
    return Decoration.set(ranges, true);
  }
});
function findFold(state, from, to) {
  var _a2;
  let found = null;
  (_a2 = state.field(foldState, false)) === null || _a2 === void 0 ? void 0 : _a2.between(from, to, (from2, to2) => {
    if (!found || found.from > from2)
      found = { from: from2, to: to2 };
  });
  return found;
}
function foldExists(folded, from, to) {
  let found = false;
  folded.between(from, from, (a, b) => {
    if (a == from && b == to)
      found = true;
  });
  return found;
}
function maybeEnable(state, other) {
  return state.field(foldState, false) ? other : other.concat(StateEffect.appendConfig.of(codeFolding()));
}
var foldCode = (view) => {
  for (let line of selectedLines(view)) {
    let range2 = foldable(view.state, line.from, line.to);
    if (range2) {
      view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range2), announceFold(view, range2)]) });
      return true;
    }
  }
  return false;
};
var unfoldCode = (view) => {
  if (!view.state.field(foldState, false))
    return false;
  let effects = [];
  for (let line of selectedLines(view)) {
    let folded = findFold(view.state, line.from, line.to);
    if (folded)
      effects.push(unfoldEffect.of(folded), announceFold(view, folded, false));
  }
  if (effects.length)
    view.dispatch({ effects });
  return effects.length > 0;
};
function announceFold(view, range2, fold = true) {
  let lineFrom = view.state.doc.lineAt(range2.from).number, lineTo = view.state.doc.lineAt(range2.to).number;
  return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`);
}
var foldAll = (view) => {
  let { state } = view, effects = [];
  for (let pos = 0; pos < state.doc.length; ) {
    let line = view.lineBlockAt(pos), range2 = foldable(state, line.from, line.to);
    if (range2)
      effects.push(foldEffect.of(range2));
    pos = (range2 ? view.lineBlockAt(range2.to) : line).to + 1;
  }
  if (effects.length)
    view.dispatch({ effects: maybeEnable(view.state, effects) });
  return !!effects.length;
};
var unfoldAll = (view) => {
  let field = view.state.field(foldState, false);
  if (!field || !field.size)
    return false;
  let effects = [];
  field.between(0, view.state.doc.length, (from, to) => {
    effects.push(unfoldEffect.of({ from, to }));
  });
  view.dispatch({ effects });
  return true;
};
var foldKeymap = [
  { key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode },
  { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode },
  { key: "Ctrl-Alt-[", run: foldAll },
  { key: "Ctrl-Alt-]", run: unfoldAll }
];
var defaultConfig = {
  placeholderDOM: null,
  placeholderText: "\u2026"
};
var foldConfig = /* @__PURE__ */ Facet.define({
  combine(values) {
    return combineConfig(values, defaultConfig);
  }
});
function codeFolding(config2) {
  let result = [foldState, baseTheme$12];
  if (config2)
    result.push(foldConfig.of(config2));
  return result;
}
var foldWidget = /* @__PURE__ */ Decoration.replace({ widget: /* @__PURE__ */ new class extends WidgetType {
  toDOM(view) {
    let { state } = view, conf = state.facet(foldConfig);
    let onclick = (event) => {
      let line = view.lineBlockAt(view.posAtDOM(event.target));
      let folded = findFold(view.state, line.from, line.to);
      if (folded)
        view.dispatch({ effects: unfoldEffect.of(folded) });
      event.preventDefault();
    };
    if (conf.placeholderDOM)
      return conf.placeholderDOM(view, onclick);
    let element2 = document.createElement("span");
    element2.textContent = conf.placeholderText;
    element2.setAttribute("aria-label", state.phrase("folded code"));
    element2.title = state.phrase("unfold");
    element2.className = "cm-foldPlaceholder";
    element2.onclick = onclick;
    return element2;
  }
}() });
var foldGutterDefaults = {
  openText: "\u2304",
  closedText: "\u203A",
  markerDOM: null,
  domEventHandlers: {},
  foldingChanged: () => false
};
var FoldMarker = class extends GutterMarker {
  constructor(config2, open) {
    super();
    this.config = config2;
    this.open = open;
  }
  eq(other) {
    return this.config == other.config && this.open == other.open;
  }
  toDOM(view) {
    if (this.config.markerDOM)
      return this.config.markerDOM(this.open);
    let span = document.createElement("span");
    span.textContent = this.open ? this.config.openText : this.config.closedText;
    span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line");
    return span;
  }
};
function foldGutter(config2 = {}) {
  let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config2);
  let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false);
  let markers = ViewPlugin.fromClass(class {
    constructor(view) {
      this.from = view.viewport.from;
      this.markers = this.buildMarkers(view);
    }
    update(update2) {
      if (update2.docChanged || update2.viewportChanged || update2.startState.facet(language) != update2.state.facet(language) || update2.startState.field(foldState, false) != update2.state.field(foldState, false) || syntaxTree(update2.startState) != syntaxTree(update2.state) || fullConfig.foldingChanged(update2))
        this.markers = this.buildMarkers(update2.view);
    }
    buildMarkers(view) {
      let builder = new RangeSetBuilder();
      for (let line of view.viewportLineBlocks) {
        let mark = findFold(view.state, line.from, line.to) ? canUnfold : foldable(view.state, line.from, line.to) ? canFold : null;
        if (mark)
          builder.add(line.from, line.from, mark);
      }
      return builder.finish();
    }
  });
  let { domEventHandlers } = fullConfig;
  return [
    markers,
    gutter({
      class: "cm-foldGutter",
      markers(view) {
        var _a2;
        return ((_a2 = view.plugin(markers)) === null || _a2 === void 0 ? void 0 : _a2.markers) || RangeSet.empty;
      },
      initialSpacer() {
        return new FoldMarker(fullConfig, false);
      },
      domEventHandlers: Object.assign(Object.assign({}, domEventHandlers), { click: (view, line, event) => {
        if (domEventHandlers.click && domEventHandlers.click(view, line, event))
          return true;
        let folded = findFold(view.state, line.from, line.to);
        if (folded) {
          view.dispatch({ effects: unfoldEffect.of(folded) });
          return true;
        }
        let range2 = foldable(view.state, line.from, line.to);
        if (range2) {
          view.dispatch({ effects: foldEffect.of(range2) });
          return true;
        }
        return false;
      } })
    }),
    codeFolding()
  ];
}
var baseTheme$12 = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-foldPlaceholder": {
    backgroundColor: "#eee",
    border: "1px solid #ddd",
    color: "#888",
    borderRadius: ".2em",
    margin: "0 1px",
    padding: "0 1px",
    cursor: "pointer"
  },
  ".cm-foldGutter span": {
    padding: "0 1px",
    cursor: "pointer"
  }
});
var HighlightStyle = class {
  constructor(specs, options2) {
    this.specs = specs;
    let modSpec;
    function def(spec) {
      let cls = StyleModule.newName();
      (modSpec || (modSpec = /* @__PURE__ */ Object.create(null)))["." + cls] = spec;
      return cls;
    }
    const all = typeof options2.all == "string" ? options2.all : options2.all ? def(options2.all) : void 0;
    const scopeOpt = options2.scope;
    this.scope = scopeOpt instanceof Language ? (type) => type.prop(languageDataProp) == scopeOpt.data : scopeOpt ? (type) => type == scopeOpt : void 0;
    this.style = tagHighlighter(specs.map((style) => ({
      tag: style.tag,
      class: style.class || def(Object.assign({}, style, { tag: null }))
    })), {
      all
    }).style;
    this.module = modSpec ? new StyleModule(modSpec) : null;
    this.themeType = options2.themeType;
  }
  static define(specs, options2) {
    return new HighlightStyle(specs, options2 || {});
  }
};
var highlighterFacet = /* @__PURE__ */ Facet.define();
var fallbackHighlighter = /* @__PURE__ */ Facet.define({
  combine(values) {
    return values.length ? [values[0]] : null;
  }
});
function getHighlighters(state) {
  let main = state.facet(highlighterFacet);
  return main.length ? main : state.facet(fallbackHighlighter);
}
function syntaxHighlighting(highlighter, options2) {
  let ext2 = [treeHighlighter], themeType;
  if (highlighter instanceof HighlightStyle) {
    if (highlighter.module)
      ext2.push(EditorView.styleModule.of(highlighter.module));
    themeType = highlighter.themeType;
  }
  if (options2 === null || options2 === void 0 ? void 0 : options2.fallback)
    ext2.push(fallbackHighlighter.of(highlighter));
  else if (themeType)
    ext2.push(highlighterFacet.computeN([EditorView.darkTheme], (state) => {
      return state.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : [];
    }));
  else
    ext2.push(highlighterFacet.of(highlighter));
  return ext2;
}
var TreeHighlighter = class {
  constructor(view) {
    this.markCache = /* @__PURE__ */ Object.create(null);
    this.tree = syntaxTree(view.state);
    this.decorations = this.buildDeco(view, getHighlighters(view.state));
  }
  update(update2) {
    let tree = syntaxTree(update2.state), highlighters = getHighlighters(update2.state);
    let styleChange = highlighters != getHighlighters(update2.startState);
    if (tree.length < update2.view.viewport.to && !styleChange && tree.type == this.tree.type) {
      this.decorations = this.decorations.map(update2.changes);
    } else if (tree != this.tree || update2.viewportChanged || styleChange) {
      this.tree = tree;
      this.decorations = this.buildDeco(update2.view, highlighters);
    }
  }
  buildDeco(view, highlighters) {
    if (!highlighters || !this.tree.length)
      return Decoration.none;
    let builder = new RangeSetBuilder();
    for (let { from, to } of view.visibleRanges) {
      highlightTree(this.tree, highlighters, (from2, to2, style) => {
        builder.add(from2, to2, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style })));
      }, from, to);
    }
    return builder.finish();
  }
};
var treeHighlighter = /* @__PURE__ */ Prec.high(/* @__PURE__ */ ViewPlugin.fromClass(TreeHighlighter, {
  decorations: (v) => v.decorations
}));
var defaultHighlightStyle = /* @__PURE__ */ HighlightStyle.define([
  {
    tag: tags2.meta,
    color: "#7a757a"
  },
  {
    tag: tags2.link,
    textDecoration: "underline"
  },
  {
    tag: tags2.heading,
    textDecoration: "underline",
    fontWeight: "bold"
  },
  {
    tag: tags2.emphasis,
    fontStyle: "italic"
  },
  {
    tag: tags2.strong,
    fontWeight: "bold"
  },
  {
    tag: tags2.strikethrough,
    textDecoration: "line-through"
  },
  {
    tag: tags2.keyword,
    color: "#708"
  },
  {
    tag: [tags2.atom, tags2.bool, tags2.url, tags2.contentSeparator, tags2.labelName],
    color: "#219"
  },
  {
    tag: [tags2.literal, tags2.inserted],
    color: "#164"
  },
  {
    tag: [tags2.string, tags2.deleted],
    color: "#a11"
  },
  {
    tag: [tags2.regexp, tags2.escape, /* @__PURE__ */ tags2.special(tags2.string)],
    color: "#e40"
  },
  {
    tag: /* @__PURE__ */ tags2.definition(tags2.variableName),
    color: "#00f"
  },
  {
    tag: /* @__PURE__ */ tags2.local(tags2.variableName),
    color: "#30a"
  },
  {
    tag: [tags2.typeName, tags2.namespace],
    color: "#085"
  },
  {
    tag: tags2.className,
    color: "#167"
  },
  {
    tag: [/* @__PURE__ */ tags2.special(tags2.variableName), tags2.macroName],
    color: "#256"
  },
  {
    tag: /* @__PURE__ */ tags2.definition(tags2.propertyName),
    color: "#00c"
  },
  {
    tag: tags2.comment,
    color: "#940"
  },
  {
    tag: tags2.invalid,
    color: "#f00"
  }
]);
var baseTheme2 = /* @__PURE__ */ EditorView.baseTheme({
  "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" },
  "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" }
});
var DefaultScanDist = 1e4;
var DefaultBrackets = "()[]{}";
var bracketMatchingConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      afterCursor: true,
      brackets: DefaultBrackets,
      maxScanDistance: DefaultScanDist,
      renderMatch: defaultRenderMatch
    });
  }
});
var matchingMark = /* @__PURE__ */ Decoration.mark({ class: "cm-matchingBracket" });
var nonmatchingMark = /* @__PURE__ */ Decoration.mark({ class: "cm-nonmatchingBracket" });
function defaultRenderMatch(match) {
  let decorations2 = [];
  let mark = match.matched ? matchingMark : nonmatchingMark;
  decorations2.push(mark.range(match.start.from, match.start.to));
  if (match.end)
    decorations2.push(mark.range(match.end.from, match.end.to));
  return decorations2;
}
var bracketMatchingState = /* @__PURE__ */ StateField.define({
  create() {
    return Decoration.none;
  },
  update(deco, tr) {
    if (!tr.docChanged && !tr.selection)
      return deco;
    let decorations2 = [];
    let config2 = tr.state.facet(bracketMatchingConfig);
    for (let range2 of tr.state.selection.ranges) {
      if (!range2.empty)
        continue;
      let match = matchBrackets(tr.state, range2.head, -1, config2) || range2.head > 0 && matchBrackets(tr.state, range2.head - 1, 1, config2) || config2.afterCursor && (matchBrackets(tr.state, range2.head, 1, config2) || range2.head < tr.state.doc.length && matchBrackets(tr.state, range2.head + 1, -1, config2));
      if (match)
        decorations2 = decorations2.concat(config2.renderMatch(match, tr.state));
    }
    return Decoration.set(decorations2, true);
  },
  provide: (f) => EditorView.decorations.from(f)
});
var bracketMatchingUnique = [
  bracketMatchingState,
  baseTheme2
];
function bracketMatching(config2 = {}) {
  return [bracketMatchingConfig.of(config2), bracketMatchingUnique];
}
function matchingNodes(node, dir, brackets) {
  let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy);
  if (byProp)
    return byProp;
  if (node.name.length == 1) {
    let index2 = brackets.indexOf(node.name);
    if (index2 > -1 && index2 % 2 == (dir < 0 ? 1 : 0))
      return [brackets[index2 + dir]];
  }
  return null;
}
function matchBrackets(state, pos, dir, config2 = {}) {
  let maxScanDistance = config2.maxScanDistance || DefaultScanDist, brackets = config2.brackets || DefaultBrackets;
  let tree = syntaxTree(state), node = tree.resolveInner(pos, dir);
  for (let cur2 = node; cur2; cur2 = cur2.parent) {
    let matches = matchingNodes(cur2.type, dir, brackets);
    if (matches && cur2.from < cur2.to)
      return matchMarkedBrackets(state, pos, dir, cur2, matches, brackets);
  }
  return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets);
}
function matchMarkedBrackets(_state, _pos, dir, token, matching, brackets) {
  let parent2 = token.parent, firstToken = { from: token.from, to: token.to };
  let depth = 0, cursor = parent2 === null || parent2 === void 0 ? void 0 : parent2.cursor();
  if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to)))
    do {
      if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) {
        if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) {
          return { start: firstToken, end: { from: cursor.from, to: cursor.to }, matched: true };
        } else if (matchingNodes(cursor.type, dir, brackets)) {
          depth++;
        } else if (matchingNodes(cursor.type, -dir, brackets)) {
          if (depth == 0)
            return {
              start: firstToken,
              end: cursor.from == cursor.to ? void 0 : { from: cursor.from, to: cursor.to },
              matched: false
            };
          depth--;
        }
      }
    } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling());
  return { start: firstToken, matched: false };
}
function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) {
  let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1);
  let bracket2 = brackets.indexOf(startCh);
  if (bracket2 < 0 || bracket2 % 2 == 0 != dir > 0)
    return null;
  let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos };
  let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth = 0;
  for (let distance = 0; !iter.next().done && distance <= maxScanDistance; ) {
    let text2 = iter.value;
    if (dir < 0)
      distance += text2.length;
    let basePos = pos + distance * dir;
    for (let pos2 = dir > 0 ? 0 : text2.length - 1, end = dir > 0 ? text2.length : -1; pos2 != end; pos2 += dir) {
      let found = brackets.indexOf(text2[pos2]);
      if (found < 0 || tree.resolveInner(basePos + pos2, 1).type != tokenType)
        continue;
      if (found % 2 == 0 == dir > 0) {
        depth++;
      } else if (depth == 1) {
        return { start: startToken, end: { from: basePos + pos2, to: basePos + pos2 + 1 }, matched: found >> 1 == bracket2 >> 1 };
      } else {
        depth--;
      }
    }
    if (dir > 0)
      distance += text2.length;
  }
  return iter.done ? { start: startToken, matched: false } : null;
}
function countCol(string5, end, tabSize, startIndex = 0, startValue = 0) {
  if (end == null) {
    end = string5.search(/[^\s\u00a0]/);
    if (end == -1)
      end = string5.length;
  }
  let n = startValue;
  for (let i = startIndex; i < end; i++) {
    if (string5.charCodeAt(i) == 9)
      n += tabSize - n % tabSize;
    else
      n++;
  }
  return n;
}
var StringStream = class {
  constructor(string5, tabSize, indentUnit2) {
    this.string = string5;
    this.tabSize = tabSize;
    this.indentUnit = indentUnit2;
    this.pos = 0;
    this.start = 0;
    this.lastColumnPos = 0;
    this.lastColumnValue = 0;
  }
  eol() {
    return this.pos >= this.string.length;
  }
  sol() {
    return this.pos == 0;
  }
  peek() {
    return this.string.charAt(this.pos) || void 0;
  }
  next() {
    if (this.pos < this.string.length)
      return this.string.charAt(this.pos++);
  }
  eat(match) {
    let ch = this.string.charAt(this.pos);
    let ok2;
    if (typeof match == "string")
      ok2 = ch == match;
    else
      ok2 = ch && (match instanceof RegExp ? match.test(ch) : match(ch));
    if (ok2) {
      ++this.pos;
      return ch;
    }
  }
  eatWhile(match) {
    let start = this.pos;
    while (this.eat(match)) {
    }
    return this.pos > start;
  }
  eatSpace() {
    let start = this.pos;
    while (/[\s\u00a0]/.test(this.string.charAt(this.pos)))
      ++this.pos;
    return this.pos > start;
  }
  skipToEnd() {
    this.pos = this.string.length;
  }
  skipTo(ch) {
    let found = this.string.indexOf(ch, this.pos);
    if (found > -1) {
      this.pos = found;
      return true;
    }
  }
  backUp(n) {
    this.pos -= n;
  }
  column() {
    if (this.lastColumnPos < this.start) {
      this.lastColumnValue = countCol(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
      this.lastColumnPos = this.start;
    }
    return this.lastColumnValue;
  }
  indentation() {
    return countCol(this.string, null, this.tabSize);
  }
  match(pattern, consume, caseInsensitive) {
    if (typeof pattern == "string") {
      let cased = (str) => caseInsensitive ? str.toLowerCase() : str;
      let substr = this.string.substr(this.pos, pattern.length);
      if (cased(substr) == cased(pattern)) {
        if (consume !== false)
          this.pos += pattern.length;
        return true;
      } else
        return null;
    } else {
      let match = this.string.slice(this.pos).match(pattern);
      if (match && match.index > 0)
        return null;
      if (match && consume !== false)
        this.pos += match[0].length;
      return match;
    }
  }
  current() {
    return this.string.slice(this.start, this.pos);
  }
};
function fullParser(spec) {
  return {
    name: spec.name || "",
    token: spec.token,
    blankLine: spec.blankLine || (() => {
    }),
    startState: spec.startState || (() => true),
    copyState: spec.copyState || defaultCopyState,
    indent: spec.indent || (() => null),
    languageData: spec.languageData || {},
    tokenTable: spec.tokenTable || noTokens
  };
}
function defaultCopyState(state) {
  if (typeof state != "object")
    return state;
  let newState = {};
  for (let prop in state) {
    let val = state[prop];
    newState[prop] = val instanceof Array ? val.slice() : val;
  }
  return newState;
}
var StreamLanguage = class extends Language {
  constructor(parser) {
    let data = defineLanguageFacet(parser.languageData);
    let p = fullParser(parser), self2;
    let impl = new class extends Parser {
      createParse(input, fragments, ranges) {
        return new Parse(self2, input, fragments, ranges);
      }
    }();
    super(data, impl, [indentService.of((cx, pos) => this.getIndent(cx, pos))], parser.name);
    this.topNode = docID(data);
    self2 = this;
    this.streamParser = p;
    this.stateAfter = new NodeProp({ perNode: true });
    this.tokenTable = parser.tokenTable ? new TokenTable(p.tokenTable) : defaultTokenTable;
  }
  static define(spec) {
    return new StreamLanguage(spec);
  }
  getIndent(cx, pos) {
    let tree = syntaxTree(cx.state), at = tree.resolve(pos);
    while (at && at.type != this.topNode)
      at = at.parent;
    if (!at)
      return null;
    let start = findState(this, tree, 0, at.from, pos), statePos, state;
    if (start) {
      state = start.state;
      statePos = start.pos + 1;
    } else {
      state = this.streamParser.startState(cx.unit);
      statePos = 0;
    }
    if (pos - statePos > 1e4)
      return null;
    while (statePos < pos) {
      let line = cx.state.doc.lineAt(statePos), end = Math.min(pos, line.to);
      if (line.length) {
        let stream = new StringStream(line.text, cx.state.tabSize, cx.unit);
        while (stream.pos < end - line.from)
          readToken(this.streamParser.token, stream, state);
      } else {
        this.streamParser.blankLine(state, cx.unit);
      }
      if (end == pos)
        break;
      statePos = line.to + 1;
    }
    let { text: text2 } = cx.lineAt(pos);
    return this.streamParser.indent(state, /^\s*(.*)/.exec(text2)[1], cx);
  }
  get allowsNesting() {
    return false;
  }
};
function findState(lang2, tree, off, startPos, before) {
  let state = off >= startPos && off + tree.length <= before && tree.prop(lang2.stateAfter);
  if (state)
    return { state: lang2.streamParser.copyState(state), pos: off + tree.length };
  for (let i = tree.children.length - 1; i >= 0; i--) {
    let child = tree.children[i], pos = off + tree.positions[i];
    let found = child instanceof Tree && pos < before && findState(lang2, child, pos, startPos, before);
    if (found)
      return found;
  }
  return null;
}
function cutTree(lang2, tree, from, to, inside2) {
  if (inside2 && from <= 0 && to >= tree.length)
    return tree;
  if (!inside2 && tree.type == lang2.topNode)
    inside2 = true;
  for (let i = tree.children.length - 1; i >= 0; i--) {
    let pos = tree.positions[i], child = tree.children[i], inner;
    if (pos < to && child instanceof Tree) {
      if (!(inner = cutTree(lang2, child, from - pos, to - pos, inside2)))
        break;
      return !inside2 ? inner : new Tree(tree.type, tree.children.slice(0, i).concat(inner), tree.positions.slice(0, i + 1), pos + inner.length);
    }
  }
  return null;
}
function findStartInFragments(lang2, fragments, startPos, editorState) {
  for (let f of fragments) {
    let from = f.from + (f.openStart ? 25 : 0), to = f.to - (f.openEnd ? 25 : 0);
    let found = from <= startPos && to > startPos && findState(lang2, f.tree, 0 - f.offset, startPos, to), tree;
    if (found && (tree = cutTree(lang2, f.tree, startPos + f.offset, found.pos + f.offset, false)))
      return { state: found.state, tree };
  }
  return { state: lang2.streamParser.startState(editorState ? getIndentUnit(editorState) : 4), tree: Tree.empty };
}
var Parse = class {
  constructor(lang2, input, fragments, ranges) {
    this.lang = lang2;
    this.input = input;
    this.fragments = fragments;
    this.ranges = ranges;
    this.stoppedAt = null;
    this.chunks = [];
    this.chunkPos = [];
    this.chunk = [];
    this.chunkReused = void 0;
    this.rangeIndex = 0;
    this.to = ranges[ranges.length - 1].to;
    let context = ParseContext.get(), from = ranges[0].from;
    let { state, tree } = findStartInFragments(lang2, fragments, from, context === null || context === void 0 ? void 0 : context.state);
    this.state = state;
    this.parsedPos = this.chunkStart = from + tree.length;
    for (let i = 0; i < tree.children.length; i++) {
      this.chunks.push(tree.children[i]);
      this.chunkPos.push(tree.positions[i]);
    }
    if (context && this.parsedPos < context.viewport.from - 1e5) {
      this.state = this.lang.streamParser.startState(getIndentUnit(context.state));
      context.skipUntilInView(this.parsedPos, context.viewport.from);
      this.parsedPos = context.viewport.from;
    }
    this.moveRangeIndex();
  }
  advance() {
    let context = ParseContext.get();
    let parseEnd = this.stoppedAt == null ? this.to : Math.min(this.to, this.stoppedAt);
    let end = Math.min(parseEnd, this.chunkStart + 2048);
    if (context)
      end = Math.min(end, context.viewport.to);
    while (this.parsedPos < end)
      this.parseLine(context);
    if (this.chunkStart < this.parsedPos)
      this.finishChunk();
    if (this.parsedPos >= parseEnd)
      return this.finish();
    if (context && this.parsedPos >= context.viewport.to) {
      context.skipUntilInView(this.parsedPos, parseEnd);
      return this.finish();
    }
    return null;
  }
  stopAt(pos) {
    this.stoppedAt = pos;
  }
  lineAfter(pos) {
    let chunk = this.input.chunk(pos);
    if (!this.input.lineChunks) {
      let eol = chunk.indexOf("\n");
      if (eol > -1)
        chunk = chunk.slice(0, eol);
    } else if (chunk == "\n") {
      chunk = "";
    }
    return pos + chunk.length <= this.to ? chunk : chunk.slice(0, this.to - pos);
  }
  nextLine() {
    let from = this.parsedPos, line = this.lineAfter(from), end = from + line.length;
    for (let index2 = this.rangeIndex; ; ) {
      let rangeEnd2 = this.ranges[index2].to;
      if (rangeEnd2 >= end)
        break;
      line = line.slice(0, rangeEnd2 - (end - line.length));
      index2++;
      if (index2 == this.ranges.length)
        break;
      let rangeStart = this.ranges[index2].from;
      let after = this.lineAfter(rangeStart);
      line += after;
      end = rangeStart + after.length;
    }
    return { line, end };
  }
  skipGapsTo(pos, offset, side) {
    for (; ; ) {
      let end = this.ranges[this.rangeIndex].to, offPos = pos + offset;
      if (side > 0 ? end > offPos : end >= offPos)
        break;
      let start = this.ranges[++this.rangeIndex].from;
      offset += start - end;
    }
    return offset;
  }
  moveRangeIndex() {
    while (this.ranges[this.rangeIndex].to < this.parsedPos)
      this.rangeIndex++;
  }
  emitToken(id, from, to, size, offset) {
    if (this.ranges.length > 1) {
      offset = this.skipGapsTo(from, offset, 1);
      from += offset;
      let len0 = this.chunk.length;
      offset = this.skipGapsTo(to, offset, -1);
      to += offset;
      size += this.chunk.length - len0;
    }
    this.chunk.push(id, from, to, size);
    return offset;
  }
  parseLine(context) {
    let { line, end } = this.nextLine(), offset = 0, { streamParser } = this.lang;
    let stream = new StringStream(line, context ? context.state.tabSize : 4, context ? getIndentUnit(context.state) : 2);
    if (stream.eol()) {
      streamParser.blankLine(this.state, stream.indentUnit);
    } else {
      while (!stream.eol()) {
        let token = readToken(streamParser.token, stream, this.state);
        if (token)
          offset = this.emitToken(this.lang.tokenTable.resolve(token), this.parsedPos + stream.start, this.parsedPos + stream.pos, 4, offset);
        if (stream.start > 1e4)
          break;
      }
    }
    this.parsedPos = end;
    this.moveRangeIndex();
    if (this.parsedPos < this.to)
      this.parsedPos++;
  }
  finishChunk() {
    let tree = Tree.build({
      buffer: this.chunk,
      start: this.chunkStart,
      length: this.parsedPos - this.chunkStart,
      nodeSet,
      topID: 0,
      maxBufferLength: 2048,
      reused: this.chunkReused
    });
    tree = new Tree(tree.type, tree.children, tree.positions, tree.length, [[this.lang.stateAfter, this.lang.streamParser.copyState(this.state)]]);
    this.chunks.push(tree);
    this.chunkPos.push(this.chunkStart - this.ranges[0].from);
    this.chunk = [];
    this.chunkReused = void 0;
    this.chunkStart = this.parsedPos;
  }
  finish() {
    return new Tree(this.lang.topNode, this.chunks, this.chunkPos, this.parsedPos - this.ranges[0].from).balance();
  }
};
function readToken(token, stream, state) {
  stream.start = stream.pos;
  for (let i = 0; i < 10; i++) {
    let result = token(stream, state);
    if (stream.pos > stream.start)
      return result;
  }
  throw new Error("Stream parser failed to advance stream.");
}
var noTokens = /* @__PURE__ */ Object.create(null);
var typeArray = [NodeType.none];
var nodeSet = /* @__PURE__ */ new NodeSet(typeArray);
var warned = [];
var defaultTable = /* @__PURE__ */ Object.create(null);
for (let [legacyName, name2] of [
  ["variable", "variableName"],
  ["variable-2", "variableName.special"],
  ["string-2", "string.special"],
  ["def", "variableName.definition"],
  ["tag", "tagName"],
  ["attribute", "attributeName"],
  ["type", "typeName"],
  ["builtin", "variableName.standard"],
  ["qualifier", "modifier"],
  ["error", "invalid"],
  ["header", "heading"],
  ["property", "propertyName"]
])
  defaultTable[legacyName] = /* @__PURE__ */ createTokenType(noTokens, name2);
var TokenTable = class {
  constructor(extra) {
    this.extra = extra;
    this.table = Object.assign(/* @__PURE__ */ Object.create(null), defaultTable);
  }
  resolve(tag2) {
    return !tag2 ? 0 : this.table[tag2] || (this.table[tag2] = createTokenType(this.extra, tag2));
  }
};
var defaultTokenTable = /* @__PURE__ */ new TokenTable(noTokens);
function warnForPart(part, msg) {
  if (warned.indexOf(part) > -1)
    return;
  warned.push(part);
  console.warn(msg);
}
function createTokenType(extra, tagStr) {
  let tag2 = null;
  for (let part of tagStr.split(".")) {
    let value = extra[part] || tags2[part];
    if (!value) {
      warnForPart(part, `Unknown highlighting tag ${part}`);
    } else if (typeof value == "function") {
      if (!tag2)
        warnForPart(part, `Modifier ${part} used at start of tag`);
      else
        tag2 = value(tag2);
    } else {
      if (tag2)
        warnForPart(part, `Tag ${part} used as modifier`);
      else
        tag2 = value;
    }
  }
  if (!tag2)
    return 0;
  let name2 = tagStr.replace(/ /g, "_"), type = NodeType.define({
    id: typeArray.length,
    name: name2,
    props: [styleTags({ [name2]: tag2 })]
  });
  typeArray.push(type);
  return type.id;
}
function docID(data) {
  let type = NodeType.define({ id: typeArray.length, name: "Document", props: [languageDataProp.add(() => data)] });
  typeArray.push(type);
  return type;
}

// node_modules/@codemirror/autocomplete/dist/index.js
var CompletionContext = class {
  constructor(state, pos, explicit) {
    this.state = state;
    this.pos = pos;
    this.explicit = explicit;
    this.abortListeners = [];
  }
  tokenBefore(types2) {
    let token = syntaxTree(this.state).resolveInner(this.pos, -1);
    while (token && types2.indexOf(token.name) < 0)
      token = token.parent;
    return token ? {
      from: token.from,
      to: this.pos,
      text: this.state.sliceDoc(token.from, this.pos),
      type: token.type
    } : null;
  }
  matchBefore(expr) {
    let line = this.state.doc.lineAt(this.pos);
    let start = Math.max(line.from, this.pos - 250);
    let str = line.text.slice(start - line.from, this.pos - line.from);
    let found = str.search(ensureAnchor(expr, false));
    return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) };
  }
  get aborted() {
    return this.abortListeners == null;
  }
  addEventListener(type, listener) {
    if (type == "abort" && this.abortListeners)
      this.abortListeners.push(listener);
  }
};
function toSet(chars) {
  let flat = Object.keys(chars).join("");
  let words = /\w/.test(flat);
  if (words)
    flat = flat.replace(/\w/g, "");
  return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`;
}
function prefixMatch(options2) {
  let first = /* @__PURE__ */ Object.create(null), rest = /* @__PURE__ */ Object.create(null);
  for (let { label } of options2) {
    first[label[0]] = true;
    for (let i = 1; i < label.length; i++)
      rest[label[i]] = true;
  }
  let source = toSet(first) + toSet(rest) + "*$";
  return [new RegExp("^" + source), new RegExp(source)];
}
function completeFromList(list) {
  let options2 = list.map((o) => typeof o == "string" ? { label: o } : o);
  let [validFor, match] = options2.every((o) => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options2);
  return (context) => {
    let token = context.matchBefore(match);
    return token || context.explicit ? { from: token ? token.from : context.pos, options: options2, validFor } : null;
  };
}
var Option = class {
  constructor(completion, source, match) {
    this.completion = completion;
    this.source = source;
    this.match = match;
  }
};
function cur(state) {
  return state.selection.main.head;
}
function ensureAnchor(expr, start) {
  var _a2;
  let { source } = expr;
  let addStart = start && source[0] != "^", addEnd = source[source.length - 1] != "$";
  if (!addStart && !addEnd)
    return expr;
  return new RegExp(`${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`, (_a2 = expr.flags) !== null && _a2 !== void 0 ? _a2 : expr.ignoreCase ? "i" : "");
}
function insertCompletionText(state, text2, from, to) {
  return Object.assign(Object.assign({}, state.changeByRange((range2) => {
    if (range2 == state.selection.main)
      return {
        changes: { from, to, insert: text2 },
        range: EditorSelection.cursor(from + text2.length)
      };
    let len = to - from;
    if (!range2.empty || len && state.sliceDoc(range2.from - len, range2.from) != state.sliceDoc(from, to))
      return { range: range2 };
    return {
      changes: { from: range2.from - len, to: range2.from, insert: text2 },
      range: EditorSelection.cursor(range2.from - len + text2.length)
    };
  })), { userEvent: "input.complete" });
}
function applyCompletion(view, option) {
  const apply = option.completion.apply || option.completion.label;
  let result = option.source;
  if (typeof apply == "string")
    view.dispatch(insertCompletionText(view.state, apply, result.from, result.to));
  else
    apply(view, option.completion, result.from, result.to);
}
var SourceCache = /* @__PURE__ */ new WeakMap();
function asSource(source) {
  if (!Array.isArray(source))
    return source;
  let known = SourceCache.get(source);
  if (!known)
    SourceCache.set(source, known = completeFromList(source));
  return known;
}
var FuzzyMatcher = class {
  constructor(pattern) {
    this.pattern = pattern;
    this.chars = [];
    this.folded = [];
    this.any = [];
    this.precise = [];
    this.byWord = [];
    for (let p = 0; p < pattern.length; ) {
      let char = codePointAt(pattern, p), size = codePointSize(char);
      this.chars.push(char);
      let part = pattern.slice(p, p + size), upper = part.toUpperCase();
      this.folded.push(codePointAt(upper == part ? part.toLowerCase() : upper, 0));
      p += size;
    }
    this.astral = pattern.length != this.chars.length;
  }
  match(word) {
    if (this.pattern.length == 0)
      return [0];
    if (word.length < this.pattern.length)
      return null;
    let { chars, folded, any, precise, byWord } = this;
    if (chars.length == 1) {
      let first = codePointAt(word, 0);
      return first == chars[0] ? [0, 0, codePointSize(first)] : first == folded[0] ? [-200, 0, codePointSize(first)] : null;
    }
    let direct = word.indexOf(this.pattern);
    if (direct == 0)
      return [0, 0, this.pattern.length];
    let len = chars.length, anyTo = 0;
    if (direct < 0) {
      for (let i = 0, e3 = Math.min(word.length, 200); i < e3 && anyTo < len; ) {
        let next = codePointAt(word, i);
        if (next == chars[anyTo] || next == folded[anyTo])
          any[anyTo++] = i;
        i += codePointSize(next);
      }
      if (anyTo < len)
        return null;
    }
    let preciseTo = 0;
    let byWordTo = 0, byWordFolded = false;
    let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1;
    let hasLower = /[a-z]/.test(word), wordAdjacent = true;
    for (let i = 0, e3 = Math.min(word.length, 200), prevType = 0; i < e3 && byWordTo < len; ) {
      let next = codePointAt(word, i);
      if (direct < 0) {
        if (preciseTo < len && next == chars[preciseTo])
          precise[preciseTo++] = i;
        if (adjacentTo < len) {
          if (next == chars[adjacentTo] || next == folded[adjacentTo]) {
            if (adjacentTo == 0)
              adjacentStart = i;
            adjacentEnd = i + 1;
            adjacentTo++;
          } else {
            adjacentTo = 0;
          }
        }
      }
      let ch, type = next < 255 ? next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 : next >= 65 && next <= 90 ? 1 : 0 : (ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 : ch != ch.toUpperCase() ? 2 : 0;
      if (!i || type == 1 && hasLower || prevType == 0 && type != 0) {
        if (chars[byWordTo] == next || folded[byWordTo] == next && (byWordFolded = true))
          byWord[byWordTo++] = i;
        else if (byWord.length)
          wordAdjacent = false;
      }
      prevType = type;
      i += codePointSize(next);
    }
    if (byWordTo == len && byWord[0] == 0 && wordAdjacent)
      return this.result(-100 + (byWordFolded ? -200 : 0), byWord, word);
    if (adjacentTo == len && adjacentStart == 0)
      return [-200 - word.length, 0, adjacentEnd];
    if (direct > -1)
      return [-700 - word.length, direct, direct + this.pattern.length];
    if (adjacentTo == len)
      return [-200 + -700 - word.length, adjacentStart, adjacentEnd];
    if (byWordTo == len)
      return this.result(-100 + (byWordFolded ? -200 : 0) + -700 + (wordAdjacent ? 0 : -1100), byWord, word);
    return chars.length == 2 ? null : this.result((any[0] ? -700 : 0) + -200 + -1100, any, word);
  }
  result(score2, positions, word) {
    let result = [score2 - word.length], i = 1;
    for (let pos of positions) {
      let to = pos + (this.astral ? codePointSize(codePointAt(word, pos)) : 1);
      if (i > 1 && result[i - 1] == pos)
        result[i - 1] = to;
      else {
        result[i++] = pos;
        result[i++] = to;
      }
    }
    return result;
  }
};
var completionConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      activateOnTyping: true,
      selectOnOpen: true,
      override: null,
      closeOnBlur: true,
      maxRenderedOptions: 100,
      defaultKeymap: true,
      optionClass: () => "",
      aboveCursor: false,
      icons: true,
      addToOptions: [],
      compareCompletions: (a, b) => a.label.localeCompare(b.label),
      interactionDelay: 75
    }, {
      defaultKeymap: (a, b) => a && b,
      closeOnBlur: (a, b) => a && b,
      icons: (a, b) => a && b,
      optionClass: (a, b) => (c) => joinClass(a(c), b(c)),
      addToOptions: (a, b) => a.concat(b)
    });
  }
});
function joinClass(a, b) {
  return a ? b ? a + " " + b : a : b;
}
function optionContent(config2) {
  let content2 = config2.addToOptions.slice();
  if (config2.icons)
    content2.push({
      render(completion) {
        let icon = document.createElement("div");
        icon.classList.add("cm-completionIcon");
        if (completion.type)
          icon.classList.add(...completion.type.split(/\s+/g).map((cls) => "cm-completionIcon-" + cls));
        icon.setAttribute("aria-hidden", "true");
        return icon;
      },
      position: 20
    });
  content2.push({
    render(completion, _s, match) {
      let labelElt = document.createElement("span");
      labelElt.className = "cm-completionLabel";
      let { label } = completion, off = 0;
      for (let j = 1; j < match.length; ) {
        let from = match[j++], to = match[j++];
        if (from > off)
          labelElt.appendChild(document.createTextNode(label.slice(off, from)));
        let span = labelElt.appendChild(document.createElement("span"));
        span.appendChild(document.createTextNode(label.slice(from, to)));
        span.className = "cm-completionMatchedText";
        off = to;
      }
      if (off < label.length)
        labelElt.appendChild(document.createTextNode(label.slice(off)));
      return labelElt;
    },
    position: 50
  }, {
    render(completion) {
      if (!completion.detail)
        return null;
      let detailElt = document.createElement("span");
      detailElt.className = "cm-completionDetail";
      detailElt.textContent = completion.detail;
      return detailElt;
    },
    position: 80
  });
  return content2.sort((a, b) => a.position - b.position).map((a) => a.render);
}
function rangeAroundSelected(total, selected, max3) {
  if (total <= max3)
    return { from: 0, to: total };
  if (selected < 0)
    selected = 0;
  if (selected <= total >> 1) {
    let off2 = Math.floor(selected / max3);
    return { from: off2 * max3, to: (off2 + 1) * max3 };
  }
  let off = Math.floor((total - selected) / max3);
  return { from: total - (off + 1) * max3, to: total - off * max3 };
}
var CompletionTooltip = class {
  constructor(view, stateField) {
    this.view = view;
    this.stateField = stateField;
    this.info = null;
    this.placeInfo = {
      read: () => this.measureInfo(),
      write: (pos) => this.positionInfo(pos),
      key: this
    };
    let cState = view.state.field(stateField);
    let { options: options2, selected } = cState.open;
    let config2 = view.state.facet(completionConfig);
    this.optionContent = optionContent(config2);
    this.optionClass = config2.optionClass;
    this.range = rangeAroundSelected(options2.length, selected, config2.maxRenderedOptions);
    this.dom = document.createElement("div");
    this.dom.className = "cm-tooltip-autocomplete";
    this.dom.addEventListener("mousedown", (e3) => {
      for (let dom = e3.target, match; dom && dom != this.dom; dom = dom.parentNode) {
        if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options2.length) {
          applyCompletion(view, options2[+match[1]]);
          e3.preventDefault();
          return;
        }
      }
    });
    this.list = this.dom.appendChild(this.createListBox(options2, cState.id, this.range));
    this.list.addEventListener("scroll", () => {
      if (this.info)
        this.view.requestMeasure(this.placeInfo);
    });
  }
  mount() {
    this.updateSel();
  }
  update(update2) {
    if (update2.state.field(this.stateField) != update2.startState.field(this.stateField))
      this.updateSel();
  }
  positioned() {
    if (this.info)
      this.view.requestMeasure(this.placeInfo);
  }
  updateSel() {
    let cState = this.view.state.field(this.stateField), open = cState.open;
    if (open.selected > -1 && open.selected < this.range.from || open.selected >= this.range.to) {
      this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions);
      this.list.remove();
      this.list = this.dom.appendChild(this.createListBox(open.options, cState.id, this.range));
      this.list.addEventListener("scroll", () => {
        if (this.info)
          this.view.requestMeasure(this.placeInfo);
      });
    }
    if (this.updateSelectedOption(open.selected)) {
      if (this.info) {
        this.info.remove();
        this.info = null;
      }
      let { completion } = open.options[open.selected];
      let { info } = completion;
      if (!info)
        return;
      let infoResult = typeof info === "string" ? document.createTextNode(info) : info(completion);
      if (!infoResult)
        return;
      if ("then" in infoResult) {
        infoResult.then((node) => {
          if (node && this.view.state.field(this.stateField, false) == cState)
            this.addInfoPane(node);
        }).catch((e3) => logException(this.view.state, e3, "completion info"));
      } else {
        this.addInfoPane(infoResult);
      }
    }
  }
  addInfoPane(content2) {
    let dom = this.info = document.createElement("div");
    dom.className = "cm-tooltip cm-completionInfo";
    dom.appendChild(content2);
    this.dom.appendChild(dom);
    this.view.requestMeasure(this.placeInfo);
  }
  updateSelectedOption(selected) {
    let set = null;
    for (let opt = this.list.firstChild, i = this.range.from; opt; opt = opt.nextSibling, i++) {
      if (i == selected) {
        if (!opt.hasAttribute("aria-selected")) {
          opt.setAttribute("aria-selected", "true");
          set = opt;
        }
      } else {
        if (opt.hasAttribute("aria-selected"))
          opt.removeAttribute("aria-selected");
      }
    }
    if (set)
      scrollIntoView2(this.list, set);
    return set;
  }
  measureInfo() {
    let sel = this.dom.querySelector("[aria-selected]");
    if (!sel || !this.info)
      return null;
    let win = this.dom.ownerDocument.defaultView || window;
    let listRect = this.dom.getBoundingClientRect();
    let infoRect = this.info.getBoundingClientRect();
    let selRect = sel.getBoundingClientRect();
    if (selRect.top > Math.min(win.innerHeight, listRect.bottom) - 10 || selRect.bottom < Math.max(0, listRect.top) + 10)
      return null;
    let rtl = this.view.textDirection == Direction.RTL, left2 = rtl, narrow = false, maxWidth;
    let top3 = "", bottom2 = "";
    let spaceLeft = listRect.left, spaceRight = win.innerWidth - listRect.right;
    if (left2 && spaceLeft < Math.min(infoRect.width, spaceRight))
      left2 = false;
    else if (!left2 && spaceRight < Math.min(infoRect.width, spaceLeft))
      left2 = true;
    if (infoRect.width <= (left2 ? spaceLeft : spaceRight)) {
      top3 = Math.max(0, Math.min(selRect.top, win.innerHeight - infoRect.height)) - listRect.top + "px";
      maxWidth = Math.min(400, left2 ? spaceLeft : spaceRight) + "px";
    } else {
      narrow = true;
      maxWidth = Math.min(400, (rtl ? listRect.right : win.innerWidth - listRect.left) - 30) + "px";
      let spaceBelow = win.innerHeight - listRect.bottom;
      if (spaceBelow >= infoRect.height || spaceBelow > listRect.top)
        top3 = selRect.bottom - listRect.top + "px";
      else
        bottom2 = listRect.bottom - selRect.top + "px";
    }
    return {
      top: top3,
      bottom: bottom2,
      maxWidth,
      class: narrow ? rtl ? "left-narrow" : "right-narrow" : left2 ? "left" : "right"
    };
  }
  positionInfo(pos) {
    if (this.info) {
      if (pos) {
        this.info.style.top = pos.top;
        this.info.style.bottom = pos.bottom;
        this.info.style.maxWidth = pos.maxWidth;
        this.info.className = "cm-tooltip cm-completionInfo cm-completionInfo-" + pos.class;
      } else {
        this.info.style.top = "-1e6px";
      }
    }
  }
  createListBox(options2, id, range2) {
    const ul = document.createElement("ul");
    ul.id = id;
    ul.setAttribute("role", "listbox");
    ul.setAttribute("aria-expanded", "true");
    ul.setAttribute("aria-label", this.view.state.phrase("Completions"));
    for (let i = range2.from; i < range2.to; i++) {
      let { completion, match } = options2[i];
      const li = ul.appendChild(document.createElement("li"));
      li.id = id + "-" + i;
      li.setAttribute("role", "option");
      let cls = this.optionClass(completion);
      if (cls)
        li.className = cls;
      for (let source of this.optionContent) {
        let node = source(completion, this.view.state, match);
        if (node)
          li.appendChild(node);
      }
    }
    if (range2.from)
      ul.classList.add("cm-completionListIncompleteTop");
    if (range2.to < options2.length)
      ul.classList.add("cm-completionListIncompleteBottom");
    return ul;
  }
};
function completionTooltip(stateField) {
  return (view) => new CompletionTooltip(view, stateField);
}
function scrollIntoView2(container, element2) {
  let parent2 = container.getBoundingClientRect();
  let self2 = element2.getBoundingClientRect();
  if (self2.top < parent2.top)
    container.scrollTop -= parent2.top - self2.top;
  else if (self2.bottom > parent2.bottom)
    container.scrollTop += self2.bottom - parent2.bottom;
}
function score(option) {
  return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) + (option.type ? 1 : 0);
}
function sortOptions(active, state) {
  let options2 = [], i = 0;
  for (let a of active)
    if (a.hasResult()) {
      if (a.result.filter === false) {
        let getMatch = a.result.getMatch;
        for (let option of a.result.options) {
          let match = [1e9 - i++];
          if (getMatch)
            for (let n of getMatch(option))
              match.push(n);
          options2.push(new Option(option, a, match));
        }
      } else {
        let matcher = new FuzzyMatcher(state.sliceDoc(a.from, a.to)), match;
        for (let option of a.result.options)
          if (match = matcher.match(option.label)) {
            if (option.boost != null)
              match[0] += option.boost;
            options2.push(new Option(option, a, match));
          }
      }
    }
  let result = [], prev = null;
  let compare2 = state.facet(completionConfig).compareCompletions;
  for (let opt of options2.sort((a, b) => b.match[0] - a.match[0] || compare2(a.completion, b.completion))) {
    if (!prev || prev.label != opt.completion.label || prev.detail != opt.completion.detail || prev.type != null && opt.completion.type != null && prev.type != opt.completion.type || prev.apply != opt.completion.apply)
      result.push(opt);
    else if (score(opt.completion) > score(prev))
      result[result.length - 1] = opt;
    prev = opt.completion;
  }
  return result;
}
var CompletionDialog = class {
  constructor(options2, attrs, tooltip2, timestamp, selected) {
    this.options = options2;
    this.attrs = attrs;
    this.tooltip = tooltip2;
    this.timestamp = timestamp;
    this.selected = selected;
  }
  setSelected(selected, id) {
    return selected == this.selected || selected >= this.options.length ? this : new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected);
  }
  static build(active, state, id, prev, conf) {
    let options2 = sortOptions(active, state);
    if (!options2.length)
      return null;
    let selected = state.facet(completionConfig).selectOnOpen ? 0 : -1;
    if (prev && prev.selected != selected && prev.selected != -1) {
      let selectedValue = prev.options[prev.selected].completion;
      for (let i = 0; i < options2.length; i++)
        if (options2[i].completion == selectedValue) {
          selected = i;
          break;
        }
    }
    return new CompletionDialog(options2, makeAttrs(id, selected), {
      pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8),
      create: completionTooltip(completionState),
      above: conf.aboveCursor
    }, prev ? prev.timestamp : Date.now(), selected);
  }
  map(changes) {
    return new CompletionDialog(this.options, this.attrs, Object.assign(Object.assign({}, this.tooltip), { pos: changes.mapPos(this.tooltip.pos) }), this.timestamp, this.selected);
  }
};
var CompletionState = class {
  constructor(active, id, open) {
    this.active = active;
    this.id = id;
    this.open = open;
  }
  static start() {
    return new CompletionState(none2, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null);
  }
  update(tr) {
    let { state } = tr, conf = state.facet(completionConfig);
    let sources = conf.override || state.languageDataAt("autocomplete", cur(state)).map(asSource);
    let active = sources.map((source) => {
      let value = this.active.find((s) => s.source == source) || new ActiveSource(source, this.active.some((a) => a.state != 0) ? 1 : 0);
      return value.update(tr, conf);
    });
    if (active.length == this.active.length && active.every((a, i) => a == this.active[i]))
      active = this.active;
    let open = tr.selection || active.some((a) => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) || !sameResults(active, this.active) ? CompletionDialog.build(active, state, this.id, this.open, conf) : this.open && tr.docChanged ? this.open.map(tr.changes) : this.open;
    if (!open && active.every((a) => a.state != 1) && active.some((a) => a.hasResult()))
      active = active.map((a) => a.hasResult() ? new ActiveSource(a.source, 0) : a);
    for (let effect of tr.effects)
      if (effect.is(setSelectedEffect))
        open = open && open.setSelected(effect.value, this.id);
    return active == this.active && open == this.open ? this : new CompletionState(active, this.id, open);
  }
  get tooltip() {
    return this.open ? this.open.tooltip : null;
  }
  get attrs() {
    return this.open ? this.open.attrs : baseAttrs;
  }
};
function sameResults(a, b) {
  if (a == b)
    return true;
  for (let iA = 0, iB = 0; ; ) {
    while (iA < a.length && !a[iA].hasResult)
      iA++;
    while (iB < b.length && !b[iB].hasResult)
      iB++;
    let endA = iA == a.length, endB = iB == b.length;
    if (endA || endB)
      return endA == endB;
    if (a[iA++].result != b[iB++].result)
      return false;
  }
}
var baseAttrs = {
  "aria-autocomplete": "list"
};
function makeAttrs(id, selected) {
  let result = {
    "aria-autocomplete": "list",
    "aria-haspopup": "listbox",
    "aria-controls": id
  };
  if (selected > -1)
    result["aria-activedescendant"] = id + "-" + selected;
  return result;
}
var none2 = [];
function getUserEvent(tr) {
  return tr.isUserEvent("input.type") ? "input" : tr.isUserEvent("delete.backward") ? "delete" : null;
}
var ActiveSource = class {
  constructor(source, state, explicitPos = -1) {
    this.source = source;
    this.state = state;
    this.explicitPos = explicitPos;
  }
  hasResult() {
    return false;
  }
  update(tr, conf) {
    let event = getUserEvent(tr), value = this;
    if (event)
      value = value.handleUserEvent(tr, event, conf);
    else if (tr.docChanged)
      value = value.handleChange(tr);
    else if (tr.selection && value.state != 0)
      value = new ActiveSource(value.source, 0);
    for (let effect of tr.effects) {
      if (effect.is(startCompletionEffect))
        value = new ActiveSource(value.source, 1, effect.value ? cur(tr.state) : -1);
      else if (effect.is(closeCompletionEffect))
        value = new ActiveSource(value.source, 0);
      else if (effect.is(setActiveEffect)) {
        for (let active of effect.value)
          if (active.source == value.source)
            value = active;
      }
    }
    return value;
  }
  handleUserEvent(tr, type, conf) {
    return type == "delete" || !conf.activateOnTyping ? this.map(tr.changes) : new ActiveSource(this.source, 1);
  }
  handleChange(tr) {
    return tr.changes.touchesRange(cur(tr.startState)) ? new ActiveSource(this.source, 0) : this.map(tr.changes);
  }
  map(changes) {
    return changes.empty || this.explicitPos < 0 ? this : new ActiveSource(this.source, this.state, changes.mapPos(this.explicitPos));
  }
};
var ActiveResult = class extends ActiveSource {
  constructor(source, explicitPos, result, from, to) {
    super(source, 2, explicitPos);
    this.result = result;
    this.from = from;
    this.to = to;
  }
  hasResult() {
    return true;
  }
  handleUserEvent(tr, type, conf) {
    var _a2;
    let from = tr.changes.mapPos(this.from), to = tr.changes.mapPos(this.to, 1);
    let pos = cur(tr.state);
    if ((this.explicitPos < 0 ? pos <= from : pos < this.from) || pos > to || type == "delete" && cur(tr.startState) == this.from)
      return new ActiveSource(this.source, type == "input" && conf.activateOnTyping ? 1 : 0);
    let explicitPos = this.explicitPos < 0 ? -1 : tr.changes.mapPos(this.explicitPos), updated;
    if (checkValid(this.result.validFor, tr.state, from, to))
      return new ActiveResult(this.source, explicitPos, this.result, from, to);
    if (this.result.update && (updated = this.result.update(this.result, from, to, new CompletionContext(tr.state, pos, explicitPos >= 0))))
      return new ActiveResult(this.source, explicitPos, updated, updated.from, (_a2 = updated.to) !== null && _a2 !== void 0 ? _a2 : cur(tr.state));
    return new ActiveSource(this.source, 1, explicitPos);
  }
  handleChange(tr) {
    return tr.changes.touchesRange(this.from, this.to) ? new ActiveSource(this.source, 0) : this.map(tr.changes);
  }
  map(mapping) {
    return mapping.empty ? this : new ActiveResult(this.source, this.explicitPos < 0 ? -1 : mapping.mapPos(this.explicitPos), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1));
  }
};
function checkValid(validFor, state, from, to) {
  if (!validFor)
    return false;
  let text2 = state.sliceDoc(from, to);
  return typeof validFor == "function" ? validFor(text2, from, to, state) : ensureAnchor(validFor, true).test(text2);
}
var startCompletionEffect = /* @__PURE__ */ StateEffect.define();
var closeCompletionEffect = /* @__PURE__ */ StateEffect.define();
var setActiveEffect = /* @__PURE__ */ StateEffect.define({
  map(sources, mapping) {
    return sources.map((s) => s.map(mapping));
  }
});
var setSelectedEffect = /* @__PURE__ */ StateEffect.define();
var completionState = /* @__PURE__ */ StateField.define({
  create() {
    return CompletionState.start();
  },
  update(value, tr) {
    return value.update(tr);
  },
  provide: (f) => [
    showTooltip.from(f, (val) => val.tooltip),
    EditorView.contentAttributes.from(f, (state) => state.attrs)
  ]
});
function moveCompletionSelection(forward, by = "option") {
  return (view) => {
    let cState = view.state.field(completionState, false);
    if (!cState || !cState.open || Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay)
      return false;
    let step = 1, tooltip2;
    if (by == "page" && (tooltip2 = getTooltip(view, cState.open.tooltip)))
      step = Math.max(2, Math.floor(tooltip2.dom.offsetHeight / tooltip2.dom.querySelector("li").offsetHeight) - 1);
    let { length } = cState.open.options;
    let selected = cState.open.selected > -1 ? cState.open.selected + step * (forward ? 1 : -1) : forward ? 0 : length - 1;
    if (selected < 0)
      selected = by == "page" ? 0 : length - 1;
    else if (selected >= length)
      selected = by == "page" ? length - 1 : 0;
    view.dispatch({ effects: setSelectedEffect.of(selected) });
    return true;
  };
}
var acceptCompletion = (view) => {
  let cState = view.state.field(completionState, false);
  if (view.state.readOnly || !cState || !cState.open || cState.open.selected < 0 || Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay)
    return false;
  applyCompletion(view, cState.open.options[cState.open.selected]);
  return true;
};
var startCompletion = (view) => {
  let cState = view.state.field(completionState, false);
  if (!cState)
    return false;
  view.dispatch({ effects: startCompletionEffect.of(true) });
  return true;
};
var closeCompletion = (view) => {
  let cState = view.state.field(completionState, false);
  if (!cState || !cState.active.some((a) => a.state != 0))
    return false;
  view.dispatch({ effects: closeCompletionEffect.of(null) });
  return true;
};
var RunningQuery = class {
  constructor(active, context) {
    this.active = active;
    this.context = context;
    this.time = Date.now();
    this.updates = [];
    this.done = void 0;
  }
};
var DebounceTime = 50;
var MaxUpdateCount = 50;
var MinAbortTime = 1e3;
var completionPlugin = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.debounceUpdate = -1;
    this.running = [];
    this.debounceAccept = -1;
    this.composing = 0;
    for (let active of view.state.field(completionState).active)
      if (active.state == 1)
        this.startQuery(active);
  }
  update(update2) {
    let cState = update2.state.field(completionState);
    if (!update2.selectionSet && !update2.docChanged && update2.startState.field(completionState) == cState)
      return;
    let doesReset = update2.transactions.some((tr) => {
      return (tr.selection || tr.docChanged) && !getUserEvent(tr);
    });
    for (let i = 0; i < this.running.length; i++) {
      let query = this.running[i];
      if (doesReset || query.updates.length + update2.transactions.length > MaxUpdateCount && Date.now() - query.time > MinAbortTime) {
        for (let handler of query.context.abortListeners) {
          try {
            handler();
          } catch (e3) {
            logException(this.view.state, e3);
          }
        }
        query.context.abortListeners = null;
        this.running.splice(i--, 1);
      } else {
        query.updates.push(...update2.transactions);
      }
    }
    if (this.debounceUpdate > -1)
      clearTimeout(this.debounceUpdate);
    this.debounceUpdate = cState.active.some((a) => a.state == 1 && !this.running.some((q) => q.active.source == a.source)) ? setTimeout(() => this.startUpdate(), DebounceTime) : -1;
    if (this.composing != 0)
      for (let tr of update2.transactions) {
        if (getUserEvent(tr) == "input")
          this.composing = 2;
        else if (this.composing == 2 && tr.selection)
          this.composing = 3;
      }
  }
  startUpdate() {
    this.debounceUpdate = -1;
    let { state } = this.view, cState = state.field(completionState);
    for (let active of cState.active) {
      if (active.state == 1 && !this.running.some((r) => r.active.source == active.source))
        this.startQuery(active);
    }
  }
  startQuery(active) {
    let { state } = this.view, pos = cur(state);
    let context = new CompletionContext(state, pos, active.explicitPos == pos);
    let pending = new RunningQuery(active, context);
    this.running.push(pending);
    Promise.resolve(active.source(context)).then((result) => {
      if (!pending.context.aborted) {
        pending.done = result || null;
        this.scheduleAccept();
      }
    }, (err2) => {
      this.view.dispatch({ effects: closeCompletionEffect.of(null) });
      logException(this.view.state, err2);
    });
  }
  scheduleAccept() {
    if (this.running.every((q) => q.done !== void 0))
      this.accept();
    else if (this.debounceAccept < 0)
      this.debounceAccept = setTimeout(() => this.accept(), DebounceTime);
  }
  accept() {
    var _a2;
    if (this.debounceAccept > -1)
      clearTimeout(this.debounceAccept);
    this.debounceAccept = -1;
    let updated = [];
    let conf = this.view.state.facet(completionConfig);
    for (let i = 0; i < this.running.length; i++) {
      let query = this.running[i];
      if (query.done === void 0)
        continue;
      this.running.splice(i--, 1);
      if (query.done) {
        let active = new ActiveResult(query.active.source, query.active.explicitPos, query.done, query.done.from, (_a2 = query.done.to) !== null && _a2 !== void 0 ? _a2 : cur(query.updates.length ? query.updates[0].startState : this.view.state));
        for (let tr of query.updates)
          active = active.update(tr, conf);
        if (active.hasResult()) {
          updated.push(active);
          continue;
        }
      }
      let current = this.view.state.field(completionState).active.find((a) => a.source == query.active.source);
      if (current && current.state == 1) {
        if (query.done == null) {
          let active = new ActiveSource(query.active.source, 0);
          for (let tr of query.updates)
            active = active.update(tr, conf);
          if (active.state != 1)
            updated.push(active);
        } else {
          this.startQuery(current);
        }
      }
    }
    if (updated.length)
      this.view.dispatch({ effects: setActiveEffect.of(updated) });
  }
}, {
  eventHandlers: {
    blur() {
      let state = this.view.state.field(completionState, false);
      if (state && state.tooltip && this.view.state.facet(completionConfig).closeOnBlur)
        this.view.dispatch({ effects: closeCompletionEffect.of(null) });
    },
    compositionstart() {
      this.composing = 1;
    },
    compositionend() {
      if (this.composing == 3) {
        setTimeout(() => this.view.dispatch({ effects: startCompletionEffect.of(false) }), 20);
      }
      this.composing = 0;
    }
  }
});
var baseTheme3 = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-tooltip.cm-tooltip-autocomplete": {
    "& > ul": {
      fontFamily: "monospace",
      whiteSpace: "nowrap",
      overflow: "hidden auto",
      maxWidth_fallback: "700px",
      maxWidth: "min(700px, 95vw)",
      minWidth: "250px",
      maxHeight: "10em",
      listStyle: "none",
      margin: 0,
      padding: 0,
      "& > li": {
        overflowX: "hidden",
        textOverflow: "ellipsis",
        cursor: "pointer",
        padding: "1px 3px",
        lineHeight: 1.2
      }
    }
  },
  "&light .cm-tooltip-autocomplete ul li[aria-selected]": {
    background: "#17c",
    color: "white"
  },
  "&dark .cm-tooltip-autocomplete ul li[aria-selected]": {
    background: "#347",
    color: "white"
  },
  ".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after": {
    content: '"\xB7\xB7\xB7"',
    opacity: 0.5,
    display: "block",
    textAlign: "center"
  },
  ".cm-tooltip.cm-completionInfo": {
    position: "absolute",
    padding: "3px 9px",
    width: "max-content",
    maxWidth: `${400}px`,
    boxSizing: "border-box"
  },
  ".cm-completionInfo.cm-completionInfo-left": { right: "100%" },
  ".cm-completionInfo.cm-completionInfo-right": { left: "100%" },
  ".cm-completionInfo.cm-completionInfo-left-narrow": { right: `${30}px` },
  ".cm-completionInfo.cm-completionInfo-right-narrow": { left: `${30}px` },
  "&light .cm-snippetField": { backgroundColor: "#00000022" },
  "&dark .cm-snippetField": { backgroundColor: "#ffffff22" },
  ".cm-snippetFieldPosition": {
    verticalAlign: "text-top",
    width: 0,
    height: "1.15em",
    display: "inline-block",
    margin: "0 -0.7px -.7em",
    borderLeft: "1.4px dotted #888"
  },
  ".cm-completionMatchedText": {
    textDecoration: "underline"
  },
  ".cm-completionDetail": {
    marginLeft: "0.5em",
    fontStyle: "italic"
  },
  ".cm-completionIcon": {
    fontSize: "90%",
    width: ".8em",
    display: "inline-block",
    textAlign: "center",
    paddingRight: ".6em",
    opacity: "0.6"
  },
  ".cm-completionIcon-function, .cm-completionIcon-method": {
    "&:after": { content: "'\u0192'" }
  },
  ".cm-completionIcon-class": {
    "&:after": { content: "'\u25CB'" }
  },
  ".cm-completionIcon-interface": {
    "&:after": { content: "'\u25CC'" }
  },
  ".cm-completionIcon-variable": {
    "&:after": { content: "'\u{1D465}'" }
  },
  ".cm-completionIcon-constant": {
    "&:after": { content: "'\u{1D436}'" }
  },
  ".cm-completionIcon-type": {
    "&:after": { content: "'\u{1D461}'" }
  },
  ".cm-completionIcon-enum": {
    "&:after": { content: "'\u222A'" }
  },
  ".cm-completionIcon-property": {
    "&:after": { content: "'\u25A1'" }
  },
  ".cm-completionIcon-keyword": {
    "&:after": { content: "'\u{1F511}\uFE0E'" }
  },
  ".cm-completionIcon-namespace": {
    "&:after": { content: "'\u25A2'" }
  },
  ".cm-completionIcon-text": {
    "&:after": { content: "'abc'", fontSize: "50%", verticalAlign: "middle" }
  }
});
var FieldPos = class {
  constructor(field, line, from, to) {
    this.field = field;
    this.line = line;
    this.from = from;
    this.to = to;
  }
};
var FieldRange = class {
  constructor(field, from, to) {
    this.field = field;
    this.from = from;
    this.to = to;
  }
  map(changes) {
    let from = changes.mapPos(this.from, -1, MapMode.TrackDel);
    let to = changes.mapPos(this.to, 1, MapMode.TrackDel);
    return from == null || to == null ? null : new FieldRange(this.field, from, to);
  }
};
var Snippet = class {
  constructor(lines, fieldPositions) {
    this.lines = lines;
    this.fieldPositions = fieldPositions;
  }
  instantiate(state, pos) {
    let text2 = [], lineStart = [pos];
    let lineObj = state.doc.lineAt(pos), baseIndent = /^\s*/.exec(lineObj.text)[0];
    for (let line of this.lines) {
      if (text2.length) {
        let indent = baseIndent, tabs = /^\t*/.exec(line)[0].length;
        for (let i = 0; i < tabs; i++)
          indent += state.facet(indentUnit);
        lineStart.push(pos + indent.length - tabs);
        line = indent + line.slice(tabs);
      }
      text2.push(line);
      pos += line.length + 1;
    }
    let ranges = this.fieldPositions.map((pos2) => new FieldRange(pos2.field, lineStart[pos2.line] + pos2.from, lineStart[pos2.line] + pos2.to));
    return { text: text2, ranges };
  }
  static parse(template) {
    let fields = [];
    let lines = [], positions = [], m;
    for (let line of template.split(/\r\n?|\n/)) {
      while (m = /[#$]\{(?:(\d+)(?::([^}]*))?|([^}]*))\}/.exec(line)) {
        let seq = m[1] ? +m[1] : null, name2 = m[2] || m[3] || "", found = -1;
        for (let i = 0; i < fields.length; i++) {
          if (seq != null ? fields[i].seq == seq : name2 ? fields[i].name == name2 : false)
            found = i;
        }
        if (found < 0) {
          let i = 0;
          while (i < fields.length && (seq == null || fields[i].seq != null && fields[i].seq < seq))
            i++;
          fields.splice(i, 0, { seq, name: name2 });
          found = i;
          for (let pos of positions)
            if (pos.field >= found)
              pos.field++;
        }
        positions.push(new FieldPos(found, lines.length, m.index, m.index + name2.length));
        line = line.slice(0, m.index) + name2 + line.slice(m.index + m[0].length);
      }
      for (let esc; esc = /([$#])\\{/.exec(line); ) {
        line = line.slice(0, esc.index) + esc[1] + "{" + line.slice(esc.index + esc[0].length);
        for (let pos of positions)
          if (pos.line == lines.length && pos.from > esc.index) {
            pos.from--;
            pos.to--;
          }
      }
      lines.push(line);
    }
    return new Snippet(lines, positions);
  }
};
var fieldMarker = /* @__PURE__ */ Decoration.widget({ widget: /* @__PURE__ */ new class extends WidgetType {
  toDOM() {
    let span = document.createElement("span");
    span.className = "cm-snippetFieldPosition";
    return span;
  }
  ignoreEvent() {
    return false;
  }
}() });
var fieldRange = /* @__PURE__ */ Decoration.mark({ class: "cm-snippetField" });
var ActiveSnippet = class {
  constructor(ranges, active) {
    this.ranges = ranges;
    this.active = active;
    this.deco = Decoration.set(ranges.map((r) => (r.from == r.to ? fieldMarker : fieldRange).range(r.from, r.to)));
  }
  map(changes) {
    let ranges = [];
    for (let r of this.ranges) {
      let mapped = r.map(changes);
      if (!mapped)
        return null;
      ranges.push(mapped);
    }
    return new ActiveSnippet(ranges, this.active);
  }
  selectionInsideField(sel) {
    return sel.ranges.every((range2) => this.ranges.some((r) => r.field == this.active && r.from <= range2.from && r.to >= range2.to));
  }
};
var setActive = /* @__PURE__ */ StateEffect.define({
  map(value, changes) {
    return value && value.map(changes);
  }
});
var moveToField = /* @__PURE__ */ StateEffect.define();
var snippetState = /* @__PURE__ */ StateField.define({
  create() {
    return null;
  },
  update(value, tr) {
    for (let effect of tr.effects) {
      if (effect.is(setActive))
        return effect.value;
      if (effect.is(moveToField) && value)
        return new ActiveSnippet(value.ranges, effect.value);
    }
    if (value && tr.docChanged)
      value = value.map(tr.changes);
    if (value && tr.selection && !value.selectionInsideField(tr.selection))
      value = null;
    return value;
  },
  provide: (f) => EditorView.decorations.from(f, (val) => val ? val.deco : Decoration.none)
});
function fieldSelection(ranges, field) {
  return EditorSelection.create(ranges.filter((r) => r.field == field).map((r) => EditorSelection.range(r.from, r.to)));
}
function snippet(template) {
  let snippet2 = Snippet.parse(template);
  return (editor, _completion, from, to) => {
    let { text: text2, ranges } = snippet2.instantiate(editor.state, from);
    let spec = {
      changes: { from, to, insert: Text.of(text2) },
      scrollIntoView: true
    };
    if (ranges.length)
      spec.selection = fieldSelection(ranges, 0);
    if (ranges.length > 1) {
      let active = new ActiveSnippet(ranges, 0);
      let effects = spec.effects = [setActive.of(active)];
      if (editor.state.field(snippetState, false) === void 0)
        effects.push(StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme3]));
    }
    editor.dispatch(editor.state.update(spec));
  };
}
function moveField(dir) {
  return ({ state, dispatch }) => {
    let active = state.field(snippetState, false);
    if (!active || dir < 0 && active.active == 0)
      return false;
    let next = active.active + dir, last = dir > 0 && !active.ranges.some((r) => r.field == next + dir);
    dispatch(state.update({
      selection: fieldSelection(active.ranges, next),
      effects: setActive.of(last ? null : new ActiveSnippet(active.ranges, next))
    }));
    return true;
  };
}
var clearSnippet = ({ state, dispatch }) => {
  let active = state.field(snippetState, false);
  if (!active)
    return false;
  dispatch(state.update({ effects: setActive.of(null) }));
  return true;
};
var nextSnippetField = /* @__PURE__ */ moveField(1);
var prevSnippetField = /* @__PURE__ */ moveField(-1);
var defaultSnippetKeymap = [
  { key: "Tab", run: nextSnippetField, shift: prevSnippetField },
  { key: "Escape", run: clearSnippet }
];
var snippetKeymap = /* @__PURE__ */ Facet.define({
  combine(maps) {
    return maps.length ? maps[0] : defaultSnippetKeymap;
  }
});
var addSnippetKeymap = /* @__PURE__ */ Prec.highest(/* @__PURE__ */ keymap.compute([snippetKeymap], (state) => state.facet(snippetKeymap)));
function snippetCompletion(template, completion) {
  return Object.assign(Object.assign({}, completion), { apply: snippet(template) });
}
var snippetPointerHandler = /* @__PURE__ */ EditorView.domEventHandlers({
  mousedown(event, view) {
    let active = view.state.field(snippetState, false), pos;
    if (!active || (pos = view.posAtCoords({ x: event.clientX, y: event.clientY })) == null)
      return false;
    let match = active.ranges.find((r) => r.from <= pos && r.to >= pos);
    if (!match || match.field == active.active)
      return false;
    view.dispatch({
      selection: fieldSelection(active.ranges, match.field),
      effects: setActive.of(active.ranges.some((r) => r.field > match.field) ? new ActiveSnippet(active.ranges, match.field) : null)
    });
    return true;
  }
});
var defaults2 = {
  brackets: ["(", "[", "{", "'", '"'],
  before: ")]}:;>",
  stringPrefixes: []
};
var closeBracketEffect = /* @__PURE__ */ StateEffect.define({
  map(value, mapping) {
    let mapped = mapping.mapPos(value, -1, MapMode.TrackAfter);
    return mapped == null ? void 0 : mapped;
  }
});
var skipBracketEffect = /* @__PURE__ */ StateEffect.define({
  map(value, mapping) {
    return mapping.mapPos(value);
  }
});
var closedBracket = /* @__PURE__ */ new class extends RangeValue {
}();
closedBracket.startSide = 1;
closedBracket.endSide = -1;
var bracketState = /* @__PURE__ */ StateField.define({
  create() {
    return RangeSet.empty;
  },
  update(value, tr) {
    if (tr.selection) {
      let lineStart = tr.state.doc.lineAt(tr.selection.main.head).from;
      let prevLineStart = tr.startState.doc.lineAt(tr.startState.selection.main.head).from;
      if (lineStart != tr.changes.mapPos(prevLineStart, -1))
        value = RangeSet.empty;
    }
    value = value.map(tr.changes);
    for (let effect of tr.effects) {
      if (effect.is(closeBracketEffect))
        value = value.update({ add: [closedBracket.range(effect.value, effect.value + 1)] });
      else if (effect.is(skipBracketEffect))
        value = value.update({ filter: (from) => from != effect.value });
    }
    return value;
  }
});
function closeBrackets() {
  return [inputHandler2, bracketState];
}
var definedClosing = "()[]{}<>";
function closing(ch) {
  for (let i = 0; i < definedClosing.length; i += 2)
    if (definedClosing.charCodeAt(i) == ch)
      return definedClosing.charAt(i + 1);
  return fromCodePoint(ch < 128 ? ch : ch + 1);
}
function config(state, pos) {
  return state.languageDataAt("closeBrackets", pos)[0] || defaults2;
}
var android = typeof navigator == "object" && /* @__PURE__ */ /Android\b/.test(navigator.userAgent);
var inputHandler2 = /* @__PURE__ */ EditorView.inputHandler.of((view, from, to, insert3) => {
  if ((android ? view.composing : view.compositionStarted) || view.state.readOnly)
    return false;
  let sel = view.state.selection.main;
  if (insert3.length > 2 || insert3.length == 2 && codePointSize(codePointAt(insert3, 0)) == 1 || from != sel.from || to != sel.to)
    return false;
  let tr = insertBracket(view.state, insert3);
  if (!tr)
    return false;
  view.dispatch(tr);
  return true;
});
var deleteBracketPair = ({ state, dispatch }) => {
  if (state.readOnly)
    return false;
  let conf = config(state, state.selection.main.head);
  let tokens = conf.brackets || defaults2.brackets;
  let dont = null, changes = state.changeByRange((range2) => {
    if (range2.empty) {
      let before = prevChar(state.doc, range2.head);
      for (let token of tokens) {
        if (token == before && nextChar(state.doc, range2.head) == closing(codePointAt(token, 0)))
          return {
            changes: { from: range2.head - token.length, to: range2.head + token.length },
            range: EditorSelection.cursor(range2.head - token.length)
          };
      }
    }
    return { range: dont = range2 };
  });
  if (!dont)
    dispatch(state.update(changes, { scrollIntoView: true, userEvent: "delete.backward" }));
  return !dont;
};
var closeBracketsKeymap = [
  { key: "Backspace", run: deleteBracketPair }
];
function insertBracket(state, bracket2) {
  let conf = config(state, state.selection.main.head);
  let tokens = conf.brackets || defaults2.brackets;
  for (let tok of tokens) {
    let closed = closing(codePointAt(tok, 0));
    if (bracket2 == tok)
      return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1, conf) : handleOpen(state, tok, closed, conf.before || defaults2.before);
    if (bracket2 == closed && closedBracketAt(state, state.selection.main.from))
      return handleClose(state, tok, closed);
  }
  return null;
}
function closedBracketAt(state, pos) {
  let found = false;
  state.field(bracketState).between(0, state.doc.length, (from) => {
    if (from == pos)
      found = true;
  });
  return found;
}
function nextChar(doc2, pos) {
  let next = doc2.sliceString(pos, pos + 2);
  return next.slice(0, codePointSize(codePointAt(next, 0)));
}
function prevChar(doc2, pos) {
  let prev = doc2.sliceString(pos - 2, pos);
  return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1);
}
function handleOpen(state, open, close, closeBefore) {
  let dont = null, changes = state.changeByRange((range2) => {
    if (!range2.empty)
      return {
        changes: [{ insert: open, from: range2.from }, { insert: close, from: range2.to }],
        effects: closeBracketEffect.of(range2.to + open.length),
        range: EditorSelection.range(range2.anchor + open.length, range2.head + open.length)
      };
    let next = nextChar(state.doc, range2.head);
    if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1)
      return {
        changes: { insert: open + close, from: range2.head },
        effects: closeBracketEffect.of(range2.head + open.length),
        range: EditorSelection.cursor(range2.head + open.length)
      };
    return { range: dont = range2 };
  });
  return dont ? null : state.update(changes, {
    scrollIntoView: true,
    userEvent: "input.type"
  });
}
function handleClose(state, _open, close) {
  let dont = null, moved = state.selection.ranges.map((range2) => {
    if (range2.empty && nextChar(state.doc, range2.head) == close)
      return EditorSelection.cursor(range2.head + close.length);
    return dont = range2;
  });
  return dont ? null : state.update({
    selection: EditorSelection.create(moved, state.selection.mainIndex),
    scrollIntoView: true,
    effects: state.selection.ranges.map(({ from }) => skipBracketEffect.of(from))
  });
}
function handleSame(state, token, allowTriple, config2) {
  let stringPrefixes = config2.stringPrefixes || defaults2.stringPrefixes;
  let dont = null, changes = state.changeByRange((range2) => {
    if (!range2.empty)
      return {
        changes: [{ insert: token, from: range2.from }, { insert: token, from: range2.to }],
        effects: closeBracketEffect.of(range2.to + token.length),
        range: EditorSelection.range(range2.anchor + token.length, range2.head + token.length)
      };
    let pos = range2.head, next = nextChar(state.doc, pos), start;
    if (next == token) {
      if (nodeStart(state, pos)) {
        return {
          changes: { insert: token + token, from: pos },
          effects: closeBracketEffect.of(pos + token.length),
          range: EditorSelection.cursor(pos + token.length)
        };
      } else if (closedBracketAt(state, pos)) {
        let isTriple = allowTriple && state.sliceDoc(pos, pos + token.length * 3) == token + token + token;
        return {
          range: EditorSelection.cursor(pos + token.length * (isTriple ? 3 : 1)),
          effects: skipBracketEffect.of(pos)
        };
      }
    } else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token && (start = canStartStringAt(state, pos - 2 * token.length, stringPrefixes)) > -1 && nodeStart(state, start)) {
      return {
        changes: { insert: token + token + token + token, from: pos },
        effects: closeBracketEffect.of(pos + token.length),
        range: EditorSelection.cursor(pos + token.length)
      };
    } else if (state.charCategorizer(pos)(next) != CharCategory.Word) {
      if (canStartStringAt(state, pos, stringPrefixes) > -1 && !probablyInString(state, pos, token, stringPrefixes))
        return {
          changes: { insert: token + token, from: pos },
          effects: closeBracketEffect.of(pos + token.length),
          range: EditorSelection.cursor(pos + token.length)
        };
    }
    return { range: dont = range2 };
  });
  return dont ? null : state.update(changes, {
    scrollIntoView: true,
    userEvent: "input.type"
  });
}
function nodeStart(state, pos) {
  let tree = syntaxTree(state).resolveInner(pos + 1);
  return tree.parent && tree.from == pos;
}
function probablyInString(state, pos, quoteToken, prefixes2) {
  let node = syntaxTree(state).resolveInner(pos, -1);
  let maxPrefix = prefixes2.reduce((m, p) => Math.max(m, p.length), 0);
  for (let i = 0; i < 5; i++) {
    let start = state.sliceDoc(node.from, Math.min(node.to, node.from + quoteToken.length + maxPrefix));
    let quotePos = start.indexOf(quoteToken);
    if (!quotePos || quotePos > -1 && prefixes2.indexOf(start.slice(0, quotePos)) > -1) {
      let first = node.firstChild;
      while (first && first.from == node.from && first.to - first.from > quoteToken.length + quotePos) {
        if (state.sliceDoc(first.to - quoteToken.length, first.to) == quoteToken)
          return false;
        first = first.firstChild;
      }
      return true;
    }
    let parent2 = node.to == pos && node.parent;
    if (!parent2)
      break;
    node = parent2;
  }
  return false;
}
function canStartStringAt(state, pos, prefixes2) {
  let charCat = state.charCategorizer(pos);
  if (charCat(state.sliceDoc(pos - 1, pos)) != CharCategory.Word)
    return pos;
  for (let prefix of prefixes2) {
    let start = pos - prefix.length;
    if (state.sliceDoc(start, pos) == prefix && charCat(state.sliceDoc(start - 1, start)) != CharCategory.Word)
      return start;
  }
  return -1;
}
function autocompletion(config2 = {}) {
  return [
    completionState,
    completionConfig.of(config2),
    completionPlugin,
    completionKeymapExt,
    baseTheme3
  ];
}
var completionKeymap = [
  { key: "Ctrl-Space", run: startCompletion },
  { key: "Escape", run: closeCompletion },
  { key: "ArrowDown", run: /* @__PURE__ */ moveCompletionSelection(true) },
  { key: "ArrowUp", run: /* @__PURE__ */ moveCompletionSelection(false) },
  { key: "PageDown", run: /* @__PURE__ */ moveCompletionSelection(true, "page") },
  { key: "PageUp", run: /* @__PURE__ */ moveCompletionSelection(false, "page") },
  { key: "Enter", run: acceptCompletion }
];
var completionKeymapExt = /* @__PURE__ */ Prec.highest(/* @__PURE__ */ keymap.computeN([completionConfig], (state) => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : []));

// node_modules/@codemirror/commands/dist/index.js
var toggleComment = (target) => {
  let config2 = getConfig(target.state);
  return config2.line ? toggleLineComment(target) : config2.block ? toggleBlockCommentByLine(target) : false;
};
function command(f, option) {
  return ({ state, dispatch }) => {
    if (state.readOnly)
      return false;
    let tr = f(option, state);
    if (!tr)
      return false;
    dispatch(state.update(tr));
    return true;
  };
}
var toggleLineComment = /* @__PURE__ */ command(changeLineComment, 0);
var toggleBlockComment = /* @__PURE__ */ command(changeBlockComment, 0);
var toggleBlockCommentByLine = /* @__PURE__ */ command((o, s) => changeBlockComment(o, s, selectedLineRanges(s)), 0);
function getConfig(state, pos = state.selection.main.head) {
  let data = state.languageDataAt("commentTokens", pos);
  return data.length ? data[0] : {};
}
var SearchMargin = 50;
function findBlockComment(state, { open, close }, from, to) {
  let textBefore = state.sliceDoc(from - SearchMargin, from);
  let textAfter = state.sliceDoc(to, to + SearchMargin);
  let spaceBefore = /\s*$/.exec(textBefore)[0].length, spaceAfter = /^\s*/.exec(textAfter)[0].length;
  let beforeOff = textBefore.length - spaceBefore;
  if (textBefore.slice(beforeOff - open.length, beforeOff) == open && textAfter.slice(spaceAfter, spaceAfter + close.length) == close) {
    return {
      open: { pos: from - spaceBefore, margin: spaceBefore && 1 },
      close: { pos: to + spaceAfter, margin: spaceAfter && 1 }
    };
  }
  let startText, endText;
  if (to - from <= 2 * SearchMargin) {
    startText = endText = state.sliceDoc(from, to);
  } else {
    startText = state.sliceDoc(from, from + SearchMargin);
    endText = state.sliceDoc(to - SearchMargin, to);
  }
  let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length;
  let endOff = endText.length - endSpace - close.length;
  if (startText.slice(startSpace, startSpace + open.length) == open && endText.slice(endOff, endOff + close.length) == close) {
    return {
      open: {
        pos: from + startSpace + open.length,
        margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0
      },
      close: {
        pos: to - endSpace - close.length,
        margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0
      }
    };
  }
  return null;
}
function selectedLineRanges(state) {
  let ranges = [];
  for (let r of state.selection.ranges) {
    let fromLine = state.doc.lineAt(r.from);
    let toLine = r.to <= fromLine.to ? fromLine : state.doc.lineAt(r.to);
    let last = ranges.length - 1;
    if (last >= 0 && ranges[last].to > fromLine.from)
      ranges[last].to = toLine.to;
    else
      ranges.push({ from: fromLine.from, to: toLine.to });
  }
  return ranges;
}
function changeBlockComment(option, state, ranges = state.selection.ranges) {
  let tokens = ranges.map((r) => getConfig(state, r.from).block);
  if (!tokens.every((c) => c))
    return null;
  let comments = ranges.map((r, i) => findBlockComment(state, tokens[i], r.from, r.to));
  if (option != 2 && !comments.every((c) => c)) {
    return { changes: state.changes(ranges.map((range2, i) => {
      if (comments[i])
        return [];
      return [{ from: range2.from, insert: tokens[i].open + " " }, { from: range2.to, insert: " " + tokens[i].close }];
    })) };
  } else if (option != 1 && comments.some((c) => c)) {
    let changes = [];
    for (let i = 0, comment3; i < comments.length; i++)
      if (comment3 = comments[i]) {
        let token = tokens[i], { open, close } = comment3;
        changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length });
      }
    return { changes };
  }
  return null;
}
function changeLineComment(option, state, ranges = state.selection.ranges) {
  let lines = [];
  let prevLine = -1;
  for (let { from, to } of ranges) {
    let startI = lines.length, minIndent = 1e9;
    for (let pos = from; pos <= to; ) {
      let line = state.doc.lineAt(pos);
      if (line.from > prevLine && (from == to || to > line.from)) {
        prevLine = line.from;
        let token = getConfig(state, pos).line;
        if (!token)
          continue;
        let indent = /^\s*/.exec(line.text)[0].length;
        let empty4 = indent == line.length;
        let comment3 = line.text.slice(indent, indent + token.length) == token ? indent : -1;
        if (indent < line.text.length && indent < minIndent)
          minIndent = indent;
        lines.push({ line, comment: comment3, token, indent, empty: empty4, single: false });
      }
      pos = line.to + 1;
    }
    if (minIndent < 1e9) {
      for (let i = startI; i < lines.length; i++)
        if (lines[i].indent < lines[i].line.text.length)
          lines[i].indent = minIndent;
    }
    if (lines.length == startI + 1)
      lines[startI].single = true;
  }
  if (option != 2 && lines.some((l) => l.comment < 0 && (!l.empty || l.single))) {
    let changes = [];
    for (let { line, token, indent, empty: empty4, single } of lines)
      if (single || !empty4)
        changes.push({ from: line.from + indent, insert: token + " " });
    let changeSet = state.changes(changes);
    return { changes: changeSet, selection: state.selection.map(changeSet, 1) };
  } else if (option != 1 && lines.some((l) => l.comment >= 0)) {
    let changes = [];
    for (let { line, comment: comment3, token } of lines)
      if (comment3 >= 0) {
        let from = line.from + comment3, to = from + token.length;
        if (line.text[to - line.from] == " ")
          to++;
        changes.push({ from, to });
      }
    return { changes };
  }
  return null;
}
var fromHistory = /* @__PURE__ */ Annotation.define();
var isolateHistory = /* @__PURE__ */ Annotation.define();
var invertedEffects = /* @__PURE__ */ Facet.define();
var historyConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      minDepth: 100,
      newGroupDelay: 500
    }, { minDepth: Math.max, newGroupDelay: Math.min });
  }
});
function changeEnd(changes) {
  let end = 0;
  changes.iterChangedRanges((_2, to) => end = to);
  return end;
}
var historyField_ = /* @__PURE__ */ StateField.define({
  create() {
    return HistoryState.empty;
  },
  update(state, tr) {
    let config2 = tr.state.facet(historyConfig);
    let fromHist = tr.annotation(fromHistory);
    if (fromHist) {
      let selection2 = tr.docChanged ? EditorSelection.single(changeEnd(tr.changes)) : void 0;
      let item = HistEvent.fromTransaction(tr, selection2), from = fromHist.side;
      let other = from == 0 ? state.undone : state.done;
      if (item)
        other = updateBranch(other, other.length, config2.minDepth, item);
      else
        other = addSelection(other, tr.startState.selection);
      return new HistoryState(from == 0 ? fromHist.rest : other, from == 0 ? other : fromHist.rest);
    }
    let isolate = tr.annotation(isolateHistory);
    if (isolate == "full" || isolate == "before")
      state = state.isolate();
    if (tr.annotation(Transaction2.addToHistory) === false)
      return !tr.changes.empty ? state.addMapping(tr.changes.desc) : state;
    let event = HistEvent.fromTransaction(tr);
    let time = tr.annotation(Transaction2.time), userEvent = tr.annotation(Transaction2.userEvent);
    if (event)
      state = state.addChanges(event, time, userEvent, config2.newGroupDelay, config2.minDepth);
    else if (tr.selection)
      state = state.addSelection(tr.startState.selection, time, userEvent, config2.newGroupDelay);
    if (isolate == "full" || isolate == "after")
      state = state.isolate();
    return state;
  },
  toJSON(value) {
    return { done: value.done.map((e3) => e3.toJSON()), undone: value.undone.map((e3) => e3.toJSON()) };
  },
  fromJSON(json) {
    return new HistoryState(json.done.map(HistEvent.fromJSON), json.undone.map(HistEvent.fromJSON));
  }
});
function history(config2 = {}) {
  return [
    historyField_,
    historyConfig.of(config2),
    EditorView.domEventHandlers({
      beforeinput(e3, view) {
        let command2 = e3.inputType == "historyUndo" ? undo : e3.inputType == "historyRedo" ? redo : null;
        if (!command2)
          return false;
        e3.preventDefault();
        return command2(view);
      }
    })
  ];
}
function cmd(side, selection2) {
  return function({ state, dispatch }) {
    if (!selection2 && state.readOnly)
      return false;
    let historyState = state.field(historyField_, false);
    if (!historyState)
      return false;
    let tr = historyState.pop(side, state, selection2);
    if (!tr)
      return false;
    dispatch(tr);
    return true;
  };
}
var undo = /* @__PURE__ */ cmd(0, false);
var redo = /* @__PURE__ */ cmd(1, false);
var undoSelection = /* @__PURE__ */ cmd(0, true);
var redoSelection = /* @__PURE__ */ cmd(1, true);
var HistEvent = class {
  constructor(changes, effects, mapped, startSelection, selectionsAfter) {
    this.changes = changes;
    this.effects = effects;
    this.mapped = mapped;
    this.startSelection = startSelection;
    this.selectionsAfter = selectionsAfter;
  }
  setSelAfter(after) {
    return new HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after);
  }
  toJSON() {
    var _a2, _b, _c;
    return {
      changes: (_a2 = this.changes) === null || _a2 === void 0 ? void 0 : _a2.toJSON(),
      mapped: (_b = this.mapped) === null || _b === void 0 ? void 0 : _b.toJSON(),
      startSelection: (_c = this.startSelection) === null || _c === void 0 ? void 0 : _c.toJSON(),
      selectionsAfter: this.selectionsAfter.map((s) => s.toJSON())
    };
  }
  static fromJSON(json) {
    return new HistEvent(json.changes && ChangeSet.fromJSON(json.changes), [], json.mapped && ChangeDesc.fromJSON(json.mapped), json.startSelection && EditorSelection.fromJSON(json.startSelection), json.selectionsAfter.map(EditorSelection.fromJSON));
  }
  static fromTransaction(tr, selection2) {
    let effects = none3;
    for (let invert of tr.startState.facet(invertedEffects)) {
      let result = invert(tr);
      if (result.length)
        effects = effects.concat(result);
    }
    if (!effects.length && tr.changes.empty)
      return null;
    return new HistEvent(tr.changes.invert(tr.startState.doc), effects, void 0, selection2 || tr.startState.selection, none3);
  }
  static selection(selections) {
    return new HistEvent(void 0, none3, void 0, void 0, selections);
  }
};
function updateBranch(branch, to, maxLen, newEvent) {
  let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0;
  let newBranch = branch.slice(start, to);
  newBranch.push(newEvent);
  return newBranch;
}
function isAdjacent(a, b) {
  let ranges = [], isAdjacent2 = false;
  a.iterChangedRanges((f, t4) => ranges.push(f, t4));
  b.iterChangedRanges((_f, _t, f, t4) => {
    for (let i = 0; i < ranges.length; ) {
      let from = ranges[i++], to = ranges[i++];
      if (t4 >= from && f <= to)
        isAdjacent2 = true;
    }
  });
  return isAdjacent2;
}
function eqSelectionShape(a, b) {
  return a.ranges.length == b.ranges.length && a.ranges.filter((r, i) => r.empty != b.ranges[i].empty).length === 0;
}
function conc(a, b) {
  return !a.length ? b : !b.length ? a : a.concat(b);
}
var none3 = [];
var MaxSelectionsPerEvent = 200;
function addSelection(branch, selection2) {
  if (!branch.length) {
    return [HistEvent.selection([selection2])];
  } else {
    let lastEvent = branch[branch.length - 1];
    let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent));
    if (sels.length && sels[sels.length - 1].eq(selection2))
      return branch;
    sels.push(selection2);
    return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels));
  }
}
function popSelection(branch) {
  let last = branch[branch.length - 1];
  let newBranch = branch.slice();
  newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1));
  return newBranch;
}
function addMappingToBranch(branch, mapping) {
  if (!branch.length)
    return branch;
  let length = branch.length, selections = none3;
  while (length) {
    let event = mapEvent(branch[length - 1], mapping, selections);
    if (event.changes && !event.changes.empty || event.effects.length) {
      let result = branch.slice(0, length);
      result[length - 1] = event;
      return result;
    } else {
      mapping = event.mapped;
      length--;
      selections = event.selectionsAfter;
    }
  }
  return selections.length ? [HistEvent.selection(selections)] : none3;
}
function mapEvent(event, mapping, extraSelections) {
  let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map((s) => s.map(mapping)) : none3, extraSelections);
  if (!event.changes)
    return HistEvent.selection(selections);
  let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, true);
  let fullMapping = event.mapped ? event.mapped.composeDesc(before) : before;
  return new HistEvent(mappedChanges, StateEffect.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections);
}
var joinableUserEvent = /^(input\.type|delete)($|\.)/;
var HistoryState = class {
  constructor(done, undone, prevTime = 0, prevUserEvent = void 0) {
    this.done = done;
    this.undone = undone;
    this.prevTime = prevTime;
    this.prevUserEvent = prevUserEvent;
  }
  isolate() {
    return this.prevTime ? new HistoryState(this.done, this.undone) : this;
  }
  addChanges(event, time, userEvent, newGroupDelay, maxLen) {
    let done = this.done, lastEvent = done[done.length - 1];
    if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes && (!userEvent || joinableUserEvent.test(userEvent)) && (!lastEvent.selectionsAfter.length && time - this.prevTime < newGroupDelay && isAdjacent(lastEvent.changes, event.changes) || userEvent == "input.type.compose")) {
      done = updateBranch(done, done.length - 1, maxLen, new HistEvent(event.changes.compose(lastEvent.changes), conc(event.effects, lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none3));
    } else {
      done = updateBranch(done, done.length, maxLen, event);
    }
    return new HistoryState(done, none3, time, userEvent);
  }
  addSelection(selection2, time, userEvent, newGroupDelay) {
    let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none3;
    if (last.length > 0 && time - this.prevTime < newGroupDelay && userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) && eqSelectionShape(last[last.length - 1], selection2))
      return this;
    return new HistoryState(addSelection(this.done, selection2), this.undone, time, userEvent);
  }
  addMapping(mapping) {
    return new HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent);
  }
  pop(side, state, selection2) {
    let branch = side == 0 ? this.done : this.undone;
    if (branch.length == 0)
      return null;
    let event = branch[branch.length - 1];
    if (selection2 && event.selectionsAfter.length) {
      return state.update({
        selection: event.selectionsAfter[event.selectionsAfter.length - 1],
        annotations: fromHistory.of({ side, rest: popSelection(branch) }),
        userEvent: side == 0 ? "select.undo" : "select.redo",
        scrollIntoView: true
      });
    } else if (!event.changes) {
      return null;
    } else {
      let rest = branch.length == 1 ? none3 : branch.slice(0, branch.length - 1);
      if (event.mapped)
        rest = addMappingToBranch(rest, event.mapped);
      return state.update({
        changes: event.changes,
        selection: event.startSelection,
        effects: event.effects,
        annotations: fromHistory.of({ side, rest }),
        filter: false,
        userEvent: side == 0 ? "undo" : "redo",
        scrollIntoView: true
      });
    }
  }
};
HistoryState.empty = /* @__PURE__ */ new HistoryState(none3, none3);
var historyKeymap = [
  { key: "Mod-z", run: undo, preventDefault: true },
  { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: true },
  { linux: "Ctrl-Shift-z", run: redo, preventDefault: true },
  { key: "Mod-u", run: undoSelection, preventDefault: true },
  { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: true }
];
function updateSel(sel, by) {
  return EditorSelection.create(sel.ranges.map(by), sel.mainIndex);
}
function setSel(state, selection2) {
  return state.update({ selection: selection2, scrollIntoView: true, userEvent: "select" });
}
function moveSel({ state, dispatch }, how) {
  let selection2 = updateSel(state.selection, how);
  if (selection2.eq(state.selection))
    return false;
  dispatch(setSel(state, selection2));
  return true;
}
function rangeEnd(range2, forward) {
  return EditorSelection.cursor(forward ? range2.to : range2.from);
}
function cursorByChar(view, forward) {
  return moveSel(view, (range2) => range2.empty ? view.moveByChar(range2, forward) : rangeEnd(range2, forward));
}
function ltrAtCursor(view) {
  return view.textDirectionAt(view.state.selection.main.head) == Direction.LTR;
}
var cursorCharLeft = (view) => cursorByChar(view, !ltrAtCursor(view));
var cursorCharRight = (view) => cursorByChar(view, ltrAtCursor(view));
function cursorByGroup(view, forward) {
  return moveSel(view, (range2) => range2.empty ? view.moveByGroup(range2, forward) : rangeEnd(range2, forward));
}
var cursorGroupLeft = (view) => cursorByGroup(view, !ltrAtCursor(view));
var cursorGroupRight = (view) => cursorByGroup(view, ltrAtCursor(view));
function interestingNode(state, node, bracketProp) {
  if (node.type.prop(bracketProp))
    return true;
  let len = node.to - node.from;
  return len && (len > 2 || /[^\s,.;:]/.test(state.sliceDoc(node.from, node.to))) || node.firstChild;
}
function moveBySyntax(state, start, forward) {
  let pos = syntaxTree(state).resolveInner(start.head);
  let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy;
  for (let at = start.head; ; ) {
    let next = forward ? pos.childAfter(at) : pos.childBefore(at);
    if (!next)
      break;
    if (interestingNode(state, next, bracketProp))
      pos = next;
    else
      at = forward ? next.to : next.from;
  }
  let bracket2 = pos.type.prop(bracketProp), match, newPos;
  if (bracket2 && (match = forward ? matchBrackets(state, pos.from, 1) : matchBrackets(state, pos.to, -1)) && match.matched)
    newPos = forward ? match.end.to : match.end.from;
  else
    newPos = forward ? pos.to : pos.from;
  return EditorSelection.cursor(newPos, forward ? -1 : 1);
}
var cursorSyntaxLeft = (view) => moveSel(view, (range2) => moveBySyntax(view.state, range2, !ltrAtCursor(view)));
var cursorSyntaxRight = (view) => moveSel(view, (range2) => moveBySyntax(view.state, range2, ltrAtCursor(view)));
function cursorByLine(view, forward) {
  return moveSel(view, (range2) => {
    if (!range2.empty)
      return rangeEnd(range2, forward);
    let moved = view.moveVertically(range2, forward);
    return moved.head != range2.head ? moved : view.moveToLineBoundary(range2, forward);
  });
}
var cursorLineUp = (view) => cursorByLine(view, false);
var cursorLineDown = (view) => cursorByLine(view, true);
function pageHeight(view) {
  return Math.max(view.defaultLineHeight, Math.min(view.dom.clientHeight, innerHeight) - 5);
}
function cursorByPage(view, forward) {
  let { state } = view, selection2 = updateSel(state.selection, (range2) => {
    return range2.empty ? view.moveVertically(range2, forward, pageHeight(view)) : rangeEnd(range2, forward);
  });
  if (selection2.eq(state.selection))
    return false;
  let startPos = view.coordsAtPos(state.selection.main.head);
  let scrollRect = view.scrollDOM.getBoundingClientRect();
  let effect;
  if (startPos && startPos.top > scrollRect.top && startPos.bottom < scrollRect.bottom && startPos.top - scrollRect.top <= view.scrollDOM.scrollHeight - view.scrollDOM.scrollTop - view.scrollDOM.clientHeight)
    effect = EditorView.scrollIntoView(selection2.main.head, { y: "start", yMargin: startPos.top - scrollRect.top });
  view.dispatch(setSel(state, selection2), { effects: effect });
  return true;
}
var cursorPageUp = (view) => cursorByPage(view, false);
var cursorPageDown = (view) => cursorByPage(view, true);
function moveByLineBoundary(view, start, forward) {
  let line = view.lineBlockAt(start.head), moved = view.moveToLineBoundary(start, forward);
  if (moved.head == start.head && moved.head != (forward ? line.to : line.from))
    moved = view.moveToLineBoundary(start, forward, false);
  if (!forward && moved.head == line.from && line.length) {
    let space2 = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length;
    if (space2 && start.head != line.from + space2)
      moved = EditorSelection.cursor(line.from + space2);
  }
  return moved;
}
var cursorLineBoundaryForward = (view) => moveSel(view, (range2) => moveByLineBoundary(view, range2, true));
var cursorLineBoundaryBackward = (view) => moveSel(view, (range2) => moveByLineBoundary(view, range2, false));
var cursorLineBoundaryLeft = (view) => moveSel(view, (range2) => moveByLineBoundary(view, range2, !ltrAtCursor(view)));
var cursorLineBoundaryRight = (view) => moveSel(view, (range2) => moveByLineBoundary(view, range2, ltrAtCursor(view)));
var cursorLineStart = (view) => moveSel(view, (range2) => EditorSelection.cursor(view.lineBlockAt(range2.head).from, 1));
var cursorLineEnd = (view) => moveSel(view, (range2) => EditorSelection.cursor(view.lineBlockAt(range2.head).to, -1));
function toMatchingBracket(state, dispatch, extend3) {
  let found = false, selection2 = updateSel(state.selection, (range2) => {
    let matching = matchBrackets(state, range2.head, -1) || matchBrackets(state, range2.head, 1) || range2.head > 0 && matchBrackets(state, range2.head - 1, 1) || range2.head < state.doc.length && matchBrackets(state, range2.head + 1, -1);
    if (!matching || !matching.end)
      return range2;
    found = true;
    let head = matching.start.from == range2.head ? matching.end.to : matching.end.from;
    return extend3 ? EditorSelection.range(range2.anchor, head) : EditorSelection.cursor(head);
  });
  if (!found)
    return false;
  dispatch(setSel(state, selection2));
  return true;
}
var cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, false);
function extendSel(view, how) {
  let selection2 = updateSel(view.state.selection, (range2) => {
    let head = how(range2);
    return EditorSelection.range(range2.anchor, head.head, head.goalColumn);
  });
  if (selection2.eq(view.state.selection))
    return false;
  view.dispatch(setSel(view.state, selection2));
  return true;
}
function selectByChar(view, forward) {
  return extendSel(view, (range2) => view.moveByChar(range2, forward));
}
var selectCharLeft = (view) => selectByChar(view, !ltrAtCursor(view));
var selectCharRight = (view) => selectByChar(view, ltrAtCursor(view));
function selectByGroup(view, forward) {
  return extendSel(view, (range2) => view.moveByGroup(range2, forward));
}
var selectGroupLeft = (view) => selectByGroup(view, !ltrAtCursor(view));
var selectGroupRight = (view) => selectByGroup(view, ltrAtCursor(view));
var selectSyntaxLeft = (view) => extendSel(view, (range2) => moveBySyntax(view.state, range2, !ltrAtCursor(view)));
var selectSyntaxRight = (view) => extendSel(view, (range2) => moveBySyntax(view.state, range2, ltrAtCursor(view)));
function selectByLine(view, forward) {
  return extendSel(view, (range2) => view.moveVertically(range2, forward));
}
var selectLineUp = (view) => selectByLine(view, false);
var selectLineDown = (view) => selectByLine(view, true);
function selectByPage(view, forward) {
  return extendSel(view, (range2) => view.moveVertically(range2, forward, pageHeight(view)));
}
var selectPageUp = (view) => selectByPage(view, false);
var selectPageDown = (view) => selectByPage(view, true);
var selectLineBoundaryForward = (view) => extendSel(view, (range2) => moveByLineBoundary(view, range2, true));
var selectLineBoundaryBackward = (view) => extendSel(view, (range2) => moveByLineBoundary(view, range2, false));
var selectLineBoundaryLeft = (view) => extendSel(view, (range2) => moveByLineBoundary(view, range2, !ltrAtCursor(view)));
var selectLineBoundaryRight = (view) => extendSel(view, (range2) => moveByLineBoundary(view, range2, ltrAtCursor(view)));
var selectLineStart = (view) => extendSel(view, (range2) => EditorSelection.cursor(view.lineBlockAt(range2.head).from));
var selectLineEnd = (view) => extendSel(view, (range2) => EditorSelection.cursor(view.lineBlockAt(range2.head).to));
var cursorDocStart = ({ state, dispatch }) => {
  dispatch(setSel(state, { anchor: 0 }));
  return true;
};
var cursorDocEnd = ({ state, dispatch }) => {
  dispatch(setSel(state, { anchor: state.doc.length }));
  return true;
};
var selectDocStart = ({ state, dispatch }) => {
  dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 }));
  return true;
};
var selectDocEnd = ({ state, dispatch }) => {
  dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length }));
  return true;
};
var selectAll = ({ state, dispatch }) => {
  dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, userEvent: "select" }));
  return true;
};
var selectLine = ({ state, dispatch }) => {
  let ranges = selectedLineBlocks(state).map(({ from, to }) => EditorSelection.range(from, Math.min(to + 1, state.doc.length)));
  dispatch(state.update({ selection: EditorSelection.create(ranges), userEvent: "select" }));
  return true;
};
var selectParentSyntax = ({ state, dispatch }) => {
  let selection2 = updateSel(state.selection, (range2) => {
    var _a2;
    let context = syntaxTree(state).resolveInner(range2.head, 1);
    while (!(context.from < range2.from && context.to >= range2.to || context.to > range2.to && context.from <= range2.from || !((_a2 = context.parent) === null || _a2 === void 0 ? void 0 : _a2.parent)))
      context = context.parent;
    return EditorSelection.range(context.to, context.from);
  });
  dispatch(setSel(state, selection2));
  return true;
};
var simplifySelection = ({ state, dispatch }) => {
  let cur2 = state.selection, selection2 = null;
  if (cur2.ranges.length > 1)
    selection2 = EditorSelection.create([cur2.main]);
  else if (!cur2.main.empty)
    selection2 = EditorSelection.create([EditorSelection.cursor(cur2.main.head)]);
  if (!selection2)
    return false;
  dispatch(setSel(state, selection2));
  return true;
};
function deleteBy(target, by) {
  if (target.state.readOnly)
    return false;
  let event = "delete.selection", { state } = target;
  let changes = state.changeByRange((range2) => {
    let { from, to } = range2;
    if (from == to) {
      let towards = by(from);
      if (towards < from) {
        event = "delete.backward";
        towards = skipAtomic(target, towards, false);
      } else if (towards > from) {
        event = "delete.forward";
        towards = skipAtomic(target, towards, true);
      }
      from = Math.min(from, towards);
      to = Math.max(to, towards);
    } else {
      from = skipAtomic(target, from, false);
      to = skipAtomic(target, to, true);
    }
    return from == to ? { range: range2 } : { changes: { from, to }, range: EditorSelection.cursor(from) };
  });
  if (changes.changes.empty)
    return false;
  target.dispatch(state.update(changes, {
    scrollIntoView: true,
    userEvent: event,
    effects: event == "delete.selection" ? EditorView.announce.of(state.phrase("Selection deleted")) : void 0
  }));
  return true;
}
function skipAtomic(target, pos, forward) {
  if (target instanceof EditorView)
    for (let ranges of target.state.facet(EditorView.atomicRanges).map((f) => f(target)))
      ranges.between(pos, pos, (from, to) => {
        if (from < pos && to > pos)
          pos = forward ? to : from;
      });
  return pos;
}
var deleteByChar = (target, forward) => deleteBy(target, (pos) => {
  let { state } = target, line = state.doc.lineAt(pos), before, targetPos;
  if (!forward && pos > line.from && pos < line.from + 200 && !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) {
    if (before[before.length - 1] == "	")
      return pos - 1;
    let col = countColumn(before, state.tabSize), drop2 = col % getIndentUnit(state) || getIndentUnit(state);
    for (let i = 0; i < drop2 && before[before.length - 1 - i] == " "; i++)
      pos--;
    targetPos = pos;
  } else {
    targetPos = findClusterBreak(line.text, pos - line.from, forward, forward) + line.from;
    if (targetPos == pos && line.number != (forward ? state.doc.lines : 1))
      targetPos += forward ? 1 : -1;
  }
  return targetPos;
});
var deleteCharBackward = (view) => deleteByChar(view, false);
var deleteCharForward = (view) => deleteByChar(view, true);
var deleteByGroup = (target, forward) => deleteBy(target, (start) => {
  let pos = start, { state } = target, line = state.doc.lineAt(pos);
  let categorize = state.charCategorizer(pos);
  for (let cat = null; ; ) {
    if (pos == (forward ? line.to : line.from)) {
      if (pos == start && line.number != (forward ? state.doc.lines : 1))
        pos += forward ? 1 : -1;
      break;
    }
    let next = findClusterBreak(line.text, pos - line.from, forward) + line.from;
    let nextChar2 = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from);
    let nextCat = categorize(nextChar2);
    if (cat != null && nextCat != cat)
      break;
    if (nextChar2 != " " || pos != start)
      cat = nextCat;
    pos = next;
  }
  return pos;
});
var deleteGroupBackward = (target) => deleteByGroup(target, false);
var deleteGroupForward = (target) => deleteByGroup(target, true);
var deleteToLineEnd = (view) => deleteBy(view, (pos) => {
  let lineEnd = view.lineBlockAt(pos).to;
  return pos < lineEnd ? lineEnd : Math.min(view.state.doc.length, pos + 1);
});
var deleteToLineStart = (view) => deleteBy(view, (pos) => {
  let lineStart = view.lineBlockAt(pos).from;
  return pos > lineStart ? lineStart : Math.max(0, pos - 1);
});
var splitLine = ({ state, dispatch }) => {
  if (state.readOnly)
    return false;
  let changes = state.changeByRange((range2) => {
    return {
      changes: { from: range2.from, to: range2.to, insert: Text.of(["", ""]) },
      range: EditorSelection.cursor(range2.from)
    };
  });
  dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" }));
  return true;
};
var transposeChars = ({ state, dispatch }) => {
  if (state.readOnly)
    return false;
  let changes = state.changeByRange((range2) => {
    if (!range2.empty || range2.from == 0 || range2.from == state.doc.length)
      return { range: range2 };
    let pos = range2.from, line = state.doc.lineAt(pos);
    let from = pos == line.from ? pos - 1 : findClusterBreak(line.text, pos - line.from, false) + line.from;
    let to = pos == line.to ? pos + 1 : findClusterBreak(line.text, pos - line.from, true) + line.from;
    return {
      changes: { from, to, insert: state.doc.slice(pos, to).append(state.doc.slice(from, pos)) },
      range: EditorSelection.cursor(to)
    };
  });
  if (changes.changes.empty)
    return false;
  dispatch(state.update(changes, { scrollIntoView: true, userEvent: "move.character" }));
  return true;
};
function selectedLineBlocks(state) {
  let blocks = [], upto = -1;
  for (let range2 of state.selection.ranges) {
    let startLine = state.doc.lineAt(range2.from), endLine = state.doc.lineAt(range2.to);
    if (!range2.empty && range2.to == endLine.from)
      endLine = state.doc.lineAt(range2.to - 1);
    if (upto >= startLine.number) {
      let prev = blocks[blocks.length - 1];
      prev.to = endLine.to;
      prev.ranges.push(range2);
    } else {
      blocks.push({ from: startLine.from, to: endLine.to, ranges: [range2] });
    }
    upto = endLine.number + 1;
  }
  return blocks;
}
function moveLine(state, dispatch, forward) {
  if (state.readOnly)
    return false;
  let changes = [], ranges = [];
  for (let block of selectedLineBlocks(state)) {
    if (forward ? block.to == state.doc.length : block.from == 0)
      continue;
    let nextLine = state.doc.lineAt(forward ? block.to + 1 : block.from - 1);
    let size = nextLine.length + 1;
    if (forward) {
      changes.push({ from: block.to, to: nextLine.to }, { from: block.from, insert: nextLine.text + state.lineBreak });
      for (let r of block.ranges)
        ranges.push(EditorSelection.range(Math.min(state.doc.length, r.anchor + size), Math.min(state.doc.length, r.head + size)));
    } else {
      changes.push({ from: nextLine.from, to: block.from }, { from: block.to, insert: state.lineBreak + nextLine.text });
      for (let r of block.ranges)
        ranges.push(EditorSelection.range(r.anchor - size, r.head - size));
    }
  }
  if (!changes.length)
    return false;
  dispatch(state.update({
    changes,
    scrollIntoView: true,
    selection: EditorSelection.create(ranges, state.selection.mainIndex),
    userEvent: "move.line"
  }));
  return true;
}
var moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, false);
var moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, true);
function copyLine(state, dispatch, forward) {
  if (state.readOnly)
    return false;
  let changes = [];
  for (let block of selectedLineBlocks(state)) {
    if (forward)
      changes.push({ from: block.from, insert: state.doc.slice(block.from, block.to) + state.lineBreak });
    else
      changes.push({ from: block.to, insert: state.lineBreak + state.doc.slice(block.from, block.to) });
  }
  dispatch(state.update({ changes, scrollIntoView: true, userEvent: "input.copyline" }));
  return true;
}
var copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, false);
var copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, true);
var deleteLine = (view) => {
  if (view.state.readOnly)
    return false;
  let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from, to }) => {
    if (from > 0)
      from--;
    else if (to < state.doc.length)
      to++;
    return { from, to };
  }));
  let selection2 = updateSel(state.selection, (range2) => view.moveVertically(range2, true)).map(changes);
  view.dispatch({ changes, selection: selection2, scrollIntoView: true, userEvent: "delete.line" });
  return true;
};
function isBetweenBrackets(state, pos) {
  if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos - 1, pos + 1)))
    return { from: pos, to: pos };
  let context = syntaxTree(state).resolveInner(pos);
  let before = context.childBefore(pos), after = context.childAfter(pos), closedBy;
  if (before && after && before.to <= pos && after.from >= pos && (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 && state.doc.lineAt(before.to).from == state.doc.lineAt(after.from).from)
    return { from: before.to, to: after.from };
  return null;
}
var insertNewlineAndIndent = /* @__PURE__ */ newlineAndIndent(false);
var insertBlankLine = /* @__PURE__ */ newlineAndIndent(true);
function newlineAndIndent(atEof) {
  return ({ state, dispatch }) => {
    if (state.readOnly)
      return false;
    let changes = state.changeByRange((range2) => {
      let { from, to } = range2, line = state.doc.lineAt(from);
      let explode = !atEof && from == to && isBetweenBrackets(state, from);
      if (atEof)
        from = to = (to <= line.to ? line : state.doc.lineAt(to)).to;
      let cx = new IndentContext(state, { simulateBreak: from, simulateDoubleBreak: !!explode });
      let indent = getIndentation(cx, from);
      if (indent == null)
        indent = /^\s*/.exec(state.doc.lineAt(from).text)[0].length;
      while (to < line.to && /\s/.test(line.text[to - line.from]))
        to++;
      if (explode)
        ({ from, to } = explode);
      else if (from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from)))
        from = line.from;
      let insert3 = ["", indentString(state, indent)];
      if (explode)
        insert3.push(indentString(state, cx.lineIndent(line.from, -1)));
      return {
        changes: { from, to, insert: Text.of(insert3) },
        range: EditorSelection.cursor(from + 1 + insert3[1].length)
      };
    });
    dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" }));
    return true;
  };
}
function changeBySelectedLine(state, f) {
  let atLine = -1;
  return state.changeByRange((range2) => {
    let changes = [];
    for (let pos = range2.from; pos <= range2.to; ) {
      let line = state.doc.lineAt(pos);
      if (line.number > atLine && (range2.empty || range2.to > line.from)) {
        f(line, changes, range2);
        atLine = line.number;
      }
      pos = line.to + 1;
    }
    let changeSet = state.changes(changes);
    return {
      changes,
      range: EditorSelection.range(changeSet.mapPos(range2.anchor, 1), changeSet.mapPos(range2.head, 1))
    };
  });
}
var indentSelection = ({ state, dispatch }) => {
  if (state.readOnly)
    return false;
  let updated = /* @__PURE__ */ Object.create(null);
  let context = new IndentContext(state, { overrideIndentation: (start) => {
    let found = updated[start];
    return found == null ? -1 : found;
  } });
  let changes = changeBySelectedLine(state, (line, changes2, range2) => {
    let indent = getIndentation(context, line.from);
    if (indent == null)
      return;
    if (!/\S/.test(line.text))
      indent = 0;
    let cur2 = /^\s*/.exec(line.text)[0];
    let norm = indentString(state, indent);
    if (cur2 != norm || range2.from < line.from + cur2.length) {
      updated[line.from] = indent;
      changes2.push({ from: line.from, to: line.from + cur2.length, insert: norm });
    }
  });
  if (!changes.changes.empty)
    dispatch(state.update(changes, { userEvent: "indent" }));
  return true;
};
var indentMore = ({ state, dispatch }) => {
  if (state.readOnly)
    return false;
  dispatch(state.update(changeBySelectedLine(state, (line, changes) => {
    changes.push({ from: line.from, insert: state.facet(indentUnit) });
  }), { userEvent: "input.indent" }));
  return true;
};
var indentLess = ({ state, dispatch }) => {
  if (state.readOnly)
    return false;
  dispatch(state.update(changeBySelectedLine(state, (line, changes) => {
    let space2 = /^\s*/.exec(line.text)[0];
    if (!space2)
      return;
    let col = countColumn(space2, state.tabSize), keep = 0;
    let insert3 = indentString(state, Math.max(0, col - getIndentUnit(state)));
    while (keep < space2.length && keep < insert3.length && space2.charCodeAt(keep) == insert3.charCodeAt(keep))
      keep++;
    changes.push({ from: line.from + keep, to: line.from + space2.length, insert: insert3.slice(keep) });
  }), { userEvent: "delete.dedent" }));
  return true;
};
var emacsStyleKeymap = [
  { key: "Ctrl-b", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true },
  { key: "Ctrl-f", run: cursorCharRight, shift: selectCharRight },
  { key: "Ctrl-p", run: cursorLineUp, shift: selectLineUp },
  { key: "Ctrl-n", run: cursorLineDown, shift: selectLineDown },
  { key: "Ctrl-a", run: cursorLineStart, shift: selectLineStart },
  { key: "Ctrl-e", run: cursorLineEnd, shift: selectLineEnd },
  { key: "Ctrl-d", run: deleteCharForward },
  { key: "Ctrl-h", run: deleteCharBackward },
  { key: "Ctrl-k", run: deleteToLineEnd },
  { key: "Ctrl-Alt-h", run: deleteGroupBackward },
  { key: "Ctrl-o", run: splitLine },
  { key: "Ctrl-t", run: transposeChars },
  { key: "Ctrl-v", run: cursorPageDown }
];
var standardKeymap = /* @__PURE__ */ [
  { key: "ArrowLeft", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true },
  { key: "Mod-ArrowLeft", mac: "Alt-ArrowLeft", run: cursorGroupLeft, shift: selectGroupLeft, preventDefault: true },
  { mac: "Cmd-ArrowLeft", run: cursorLineBoundaryLeft, shift: selectLineBoundaryLeft, preventDefault: true },
  { key: "ArrowRight", run: cursorCharRight, shift: selectCharRight, preventDefault: true },
  { key: "Mod-ArrowRight", mac: "Alt-ArrowRight", run: cursorGroupRight, shift: selectGroupRight, preventDefault: true },
  { mac: "Cmd-ArrowRight", run: cursorLineBoundaryRight, shift: selectLineBoundaryRight, preventDefault: true },
  { key: "ArrowUp", run: cursorLineUp, shift: selectLineUp, preventDefault: true },
  { mac: "Cmd-ArrowUp", run: cursorDocStart, shift: selectDocStart },
  { mac: "Ctrl-ArrowUp", run: cursorPageUp, shift: selectPageUp },
  { key: "ArrowDown", run: cursorLineDown, shift: selectLineDown, preventDefault: true },
  { mac: "Cmd-ArrowDown", run: cursorDocEnd, shift: selectDocEnd },
  { mac: "Ctrl-ArrowDown", run: cursorPageDown, shift: selectPageDown },
  { key: "PageUp", run: cursorPageUp, shift: selectPageUp },
  { key: "PageDown", run: cursorPageDown, shift: selectPageDown },
  { key: "Home", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward, preventDefault: true },
  { key: "Mod-Home", run: cursorDocStart, shift: selectDocStart },
  { key: "End", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward, preventDefault: true },
  { key: "Mod-End", run: cursorDocEnd, shift: selectDocEnd },
  { key: "Enter", run: insertNewlineAndIndent },
  { key: "Mod-a", run: selectAll },
  { key: "Backspace", run: deleteCharBackward, shift: deleteCharBackward },
  { key: "Delete", run: deleteCharForward },
  { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward },
  { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward },
  { mac: "Mod-Backspace", run: deleteToLineStart },
  { mac: "Mod-Delete", run: deleteToLineEnd }
].concat(/* @__PURE__ */ emacsStyleKeymap.map((b) => ({ mac: b.key, run: b.run, shift: b.shift })));
var defaultKeymap = /* @__PURE__ */ [
  { key: "Alt-ArrowLeft", mac: "Ctrl-ArrowLeft", run: cursorSyntaxLeft, shift: selectSyntaxLeft },
  { key: "Alt-ArrowRight", mac: "Ctrl-ArrowRight", run: cursorSyntaxRight, shift: selectSyntaxRight },
  { key: "Alt-ArrowUp", run: moveLineUp },
  { key: "Shift-Alt-ArrowUp", run: copyLineUp },
  { key: "Alt-ArrowDown", run: moveLineDown },
  { key: "Shift-Alt-ArrowDown", run: copyLineDown },
  { key: "Escape", run: simplifySelection },
  { key: "Mod-Enter", run: insertBlankLine },
  { key: "Alt-l", mac: "Ctrl-l", run: selectLine },
  { key: "Mod-i", run: selectParentSyntax, preventDefault: true },
  { key: "Mod-[", run: indentLess },
  { key: "Mod-]", run: indentMore },
  { key: "Mod-Alt-\\", run: indentSelection },
  { key: "Shift-Mod-k", run: deleteLine },
  { key: "Shift-Mod-\\", run: cursorMatchingBracket },
  { key: "Mod-/", run: toggleComment },
  { key: "Alt-A", run: toggleBlockComment }
].concat(standardKeymap);
var indentWithTab = { key: "Tab", run: indentMore, shift: indentLess };

// node_modules/crelt/index.es.js
function crelt() {
  var elt = arguments[0];
  if (typeof elt == "string")
    elt = document.createElement(elt);
  var i = 1, next = arguments[1];
  if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) {
    for (var name2 in next)
      if (Object.prototype.hasOwnProperty.call(next, name2)) {
        var value = next[name2];
        if (typeof value == "string")
          elt.setAttribute(name2, value);
        else if (value != null)
          elt[name2] = value;
      }
    i++;
  }
  for (; i < arguments.length; i++)
    add(elt, arguments[i]);
  return elt;
}
function add(elt, child) {
  if (typeof child == "string") {
    elt.appendChild(document.createTextNode(child));
  } else if (child == null) {
  } else if (child.nodeType != null) {
    elt.appendChild(child);
  } else if (Array.isArray(child)) {
    for (var i = 0; i < child.length; i++)
      add(elt, child[i]);
  } else {
    throw new RangeError("Unsupported child node: " + child);
  }
}

// node_modules/@codemirror/lint/dist/index.js
var SelectedDiagnostic = class {
  constructor(from, to, diagnostic) {
    this.from = from;
    this.to = to;
    this.diagnostic = diagnostic;
  }
};
var LintState = class {
  constructor(diagnostics, panel, selected) {
    this.diagnostics = diagnostics;
    this.panel = panel;
    this.selected = selected;
  }
  static init(diagnostics, panel, state) {
    let markedDiagnostics = diagnostics;
    let diagnosticFilter = state.facet(lintConfig).markerFilter;
    if (diagnosticFilter)
      markedDiagnostics = diagnosticFilter(markedDiagnostics);
    let ranges = Decoration.set(markedDiagnostics.map((d) => {
      return d.from == d.to || d.from == d.to - 1 && state.doc.lineAt(d.from).to == d.from ? Decoration.widget({
        widget: new DiagnosticWidget(d),
        diagnostic: d
      }).range(d.from) : Decoration.mark({
        attributes: { class: "cm-lintRange cm-lintRange-" + d.severity },
        diagnostic: d
      }).range(d.from, d.to);
    }), true);
    return new LintState(ranges, panel, findDiagnostic(ranges));
  }
};
function findDiagnostic(diagnostics, diagnostic = null, after = 0) {
  let found = null;
  diagnostics.between(after, 1e9, (from, to, { spec }) => {
    if (diagnostic && spec.diagnostic != diagnostic)
      return;
    found = new SelectedDiagnostic(from, to, spec.diagnostic);
    return false;
  });
  return found;
}
function hideTooltip(tr, tooltip2) {
  return !!(tr.effects.some((e3) => e3.is(setDiagnosticsEffect)) || tr.changes.touchesRange(tooltip2.pos));
}
function maybeEnableLint(state, effects) {
  return state.field(lintState, false) ? effects : effects.concat(StateEffect.appendConfig.of([
    lintState,
    EditorView.decorations.compute([lintState], (state2) => {
      let { selected, panel } = state2.field(lintState);
      return !selected || !panel || selected.from == selected.to ? Decoration.none : Decoration.set([
        activeMark.range(selected.from, selected.to)
      ]);
    }),
    hoverTooltip(lintTooltip, { hideOn: hideTooltip }),
    baseTheme4
  ]));
}
function setDiagnostics(state, diagnostics) {
  return {
    effects: maybeEnableLint(state, [setDiagnosticsEffect.of(diagnostics)])
  };
}
var setDiagnosticsEffect = /* @__PURE__ */ StateEffect.define();
var togglePanel = /* @__PURE__ */ StateEffect.define();
var movePanelSelection = /* @__PURE__ */ StateEffect.define();
var lintState = /* @__PURE__ */ StateField.define({
  create() {
    return new LintState(Decoration.none, null, null);
  },
  update(value, tr) {
    if (tr.docChanged) {
      let mapped = value.diagnostics.map(tr.changes), selected = null;
      if (value.selected) {
        let selPos = tr.changes.mapPos(value.selected.from, 1);
        selected = findDiagnostic(mapped, value.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos);
      }
      value = new LintState(mapped, value.panel, selected);
    }
    for (let effect of tr.effects) {
      if (effect.is(setDiagnosticsEffect)) {
        value = LintState.init(effect.value, value.panel, tr.state);
      } else if (effect.is(togglePanel)) {
        value = new LintState(value.diagnostics, effect.value ? LintPanel.open : null, value.selected);
      } else if (effect.is(movePanelSelection)) {
        value = new LintState(value.diagnostics, value.panel, effect.value);
      }
    }
    return value;
  },
  provide: (f) => [
    showPanel.from(f, (val) => val.panel),
    EditorView.decorations.from(f, (s) => s.diagnostics)
  ]
});
var activeMark = /* @__PURE__ */ Decoration.mark({ class: "cm-lintRange cm-lintRange-active" });
function lintTooltip(view, pos, side) {
  let { diagnostics } = view.state.field(lintState);
  let found = [], stackStart = 2e8, stackEnd = 0;
  diagnostics.between(pos - (side < 0 ? 1 : 0), pos + (side > 0 ? 1 : 0), (from, to, { spec }) => {
    if (pos >= from && pos <= to && (from == to || (pos > from || side > 0) && (pos < to || side < 0))) {
      found.push(spec.diagnostic);
      stackStart = Math.min(from, stackStart);
      stackEnd = Math.max(to, stackEnd);
    }
  });
  let diagnosticFilter = view.state.facet(lintConfig).tooltipFilter;
  if (diagnosticFilter)
    found = diagnosticFilter(found);
  if (!found.length)
    return null;
  return {
    pos: stackStart,
    end: stackEnd,
    above: view.state.doc.lineAt(stackStart).to < stackEnd,
    create() {
      return { dom: diagnosticsTooltip(view, found) };
    }
  };
}
function diagnosticsTooltip(view, diagnostics) {
  return crelt("ul", { class: "cm-tooltip-lint" }, diagnostics.map((d) => renderDiagnostic(view, d, false)));
}
var openLintPanel = (view) => {
  let field = view.state.field(lintState, false);
  if (!field || !field.panel)
    view.dispatch({ effects: maybeEnableLint(view.state, [togglePanel.of(true)]) });
  let panel = getPanel(view, LintPanel.open);
  if (panel)
    panel.dom.querySelector(".cm-panel-lint ul").focus();
  return true;
};
var closeLintPanel = (view) => {
  let field = view.state.field(lintState, false);
  if (!field || !field.panel)
    return false;
  view.dispatch({ effects: togglePanel.of(false) });
  return true;
};
var nextDiagnostic = (view) => {
  let field = view.state.field(lintState, false);
  if (!field)
    return false;
  let sel = view.state.selection.main, next = field.diagnostics.iter(sel.to + 1);
  if (!next.value) {
    next = field.diagnostics.iter(0);
    if (!next.value || next.from == sel.from && next.to == sel.to)
      return false;
  }
  view.dispatch({ selection: { anchor: next.from, head: next.to }, scrollIntoView: true });
  return true;
};
var lintKeymap = [
  { key: "Mod-Shift-m", run: openLintPanel },
  { key: "F8", run: nextDiagnostic }
];
var lintPlugin = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.timeout = -1;
    this.set = true;
    let { delay } = view.state.facet(lintConfig);
    this.lintTime = Date.now() + delay;
    this.run = this.run.bind(this);
    this.timeout = setTimeout(this.run, delay);
  }
  run() {
    let now = Date.now();
    if (now < this.lintTime - 10) {
      setTimeout(this.run, this.lintTime - now);
    } else {
      this.set = false;
      let { state } = this.view, { sources } = state.facet(lintConfig);
      Promise.all(sources.map((source) => Promise.resolve(source(this.view)))).then((annotations) => {
        let all = annotations.reduce((a, b) => a.concat(b));
        if (this.view.state.doc == state.doc)
          this.view.dispatch(setDiagnostics(this.view.state, all));
      }, (error) => {
        logException(this.view.state, error);
      });
    }
  }
  update(update2) {
    let config2 = update2.state.facet(lintConfig);
    if (update2.docChanged || config2 != update2.startState.facet(lintConfig)) {
      this.lintTime = Date.now() + config2.delay;
      if (!this.set) {
        this.set = true;
        this.timeout = setTimeout(this.run, config2.delay);
      }
    }
  }
  force() {
    if (this.set) {
      this.lintTime = Date.now();
      this.run();
    }
  }
  destroy() {
    clearTimeout(this.timeout);
  }
});
var lintConfig = /* @__PURE__ */ Facet.define({
  combine(input) {
    return Object.assign({ sources: input.map((i) => i.source) }, combineConfig(input.map((i) => i.config), {
      delay: 750,
      markerFilter: null,
      tooltipFilter: null
    }));
  },
  enables: lintPlugin
});
function assignKeys(actions) {
  let assigned = [];
  if (actions)
    actions:
      for (let { name: name2 } of actions) {
        for (let i = 0; i < name2.length; i++) {
          let ch = name2[i];
          if (/[a-zA-Z]/.test(ch) && !assigned.some((c) => c.toLowerCase() == ch.toLowerCase())) {
            assigned.push(ch);
            continue actions;
          }
        }
        assigned.push("");
      }
  return assigned;
}
function renderDiagnostic(view, diagnostic, inPanel) {
  var _a2;
  let keys = inPanel ? assignKeys(diagnostic.actions) : [];
  return crelt("li", { class: "cm-diagnostic cm-diagnostic-" + diagnostic.severity }, crelt("span", { class: "cm-diagnosticText" }, diagnostic.renderMessage ? diagnostic.renderMessage() : diagnostic.message), (_a2 = diagnostic.actions) === null || _a2 === void 0 ? void 0 : _a2.map((action, i) => {
    let click = (e3) => {
      e3.preventDefault();
      let found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic);
      if (found)
        action.apply(view, found.from, found.to);
    };
    let { name: name2 } = action, keyIndex = keys[i] ? name2.indexOf(keys[i]) : -1;
    let nameElt = keyIndex < 0 ? name2 : [
      name2.slice(0, keyIndex),
      crelt("u", name2.slice(keyIndex, keyIndex + 1)),
      name2.slice(keyIndex + 1)
    ];
    return crelt("button", {
      type: "button",
      class: "cm-diagnosticAction",
      onclick: click,
      onmousedown: click,
      "aria-label": ` Action: ${name2}${keyIndex < 0 ? "" : ` (access key "${keys[i]})"`}.`
    }, nameElt);
  }), diagnostic.source && crelt("div", { class: "cm-diagnosticSource" }, diagnostic.source));
}
var DiagnosticWidget = class extends WidgetType {
  constructor(diagnostic) {
    super();
    this.diagnostic = diagnostic;
  }
  eq(other) {
    return other.diagnostic == this.diagnostic;
  }
  toDOM() {
    return crelt("span", { class: "cm-lintPoint cm-lintPoint-" + this.diagnostic.severity });
  }
};
var PanelItem = class {
  constructor(view, diagnostic) {
    this.diagnostic = diagnostic;
    this.id = "item_" + Math.floor(Math.random() * 4294967295).toString(16);
    this.dom = renderDiagnostic(view, diagnostic, true);
    this.dom.id = this.id;
    this.dom.setAttribute("role", "option");
  }
};
var LintPanel = class {
  constructor(view) {
    this.view = view;
    this.items = [];
    let onkeydown = (event) => {
      if (event.keyCode == 27) {
        closeLintPanel(this.view);
        this.view.focus();
      } else if (event.keyCode == 38 || event.keyCode == 33) {
        this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length);
      } else if (event.keyCode == 40 || event.keyCode == 34) {
        this.moveSelection((this.selectedIndex + 1) % this.items.length);
      } else if (event.keyCode == 36) {
        this.moveSelection(0);
      } else if (event.keyCode == 35) {
        this.moveSelection(this.items.length - 1);
      } else if (event.keyCode == 13) {
        this.view.focus();
      } else if (event.keyCode >= 65 && event.keyCode <= 90 && this.selectedIndex >= 0) {
        let { diagnostic } = this.items[this.selectedIndex], keys = assignKeys(diagnostic.actions);
        for (let i = 0; i < keys.length; i++)
          if (keys[i].toUpperCase().charCodeAt(0) == event.keyCode) {
            let found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic);
            if (found)
              diagnostic.actions[i].apply(view, found.from, found.to);
          }
      } else {
        return;
      }
      event.preventDefault();
    };
    let onclick = (event) => {
      for (let i = 0; i < this.items.length; i++) {
        if (this.items[i].dom.contains(event.target))
          this.moveSelection(i);
      }
    };
    this.list = crelt("ul", {
      tabIndex: 0,
      role: "listbox",
      "aria-label": this.view.state.phrase("Diagnostics"),
      onkeydown,
      onclick
    });
    this.dom = crelt("div", { class: "cm-panel-lint" }, this.list, crelt("button", {
      type: "button",
      name: "close",
      "aria-label": this.view.state.phrase("close"),
      onclick: () => closeLintPanel(this.view)
    }, "\xD7"));
    this.update();
  }
  get selectedIndex() {
    let selected = this.view.state.field(lintState).selected;
    if (!selected)
      return -1;
    for (let i = 0; i < this.items.length; i++)
      if (this.items[i].diagnostic == selected.diagnostic)
        return i;
    return -1;
  }
  update() {
    let { diagnostics, selected } = this.view.state.field(lintState);
    let i = 0, needsSync = false, newSelectedItem = null;
    diagnostics.between(0, this.view.state.doc.length, (_start, _end, { spec }) => {
      let found = -1, item;
      for (let j = i; j < this.items.length; j++)
        if (this.items[j].diagnostic == spec.diagnostic) {
          found = j;
          break;
        }
      if (found < 0) {
        item = new PanelItem(this.view, spec.diagnostic);
        this.items.splice(i, 0, item);
        needsSync = true;
      } else {
        item = this.items[found];
        if (found > i) {
          this.items.splice(i, found - i);
          needsSync = true;
        }
      }
      if (selected && item.diagnostic == selected.diagnostic) {
        if (!item.dom.hasAttribute("aria-selected")) {
          item.dom.setAttribute("aria-selected", "true");
          newSelectedItem = item;
        }
      } else if (item.dom.hasAttribute("aria-selected")) {
        item.dom.removeAttribute("aria-selected");
      }
      i++;
    });
    while (i < this.items.length && !(this.items.length == 1 && this.items[0].diagnostic.from < 0)) {
      needsSync = true;
      this.items.pop();
    }
    if (this.items.length == 0) {
      this.items.push(new PanelItem(this.view, {
        from: -1,
        to: -1,
        severity: "info",
        message: this.view.state.phrase("No diagnostics")
      }));
      needsSync = true;
    }
    if (newSelectedItem) {
      this.list.setAttribute("aria-activedescendant", newSelectedItem.id);
      this.view.requestMeasure({
        key: this,
        read: () => ({ sel: newSelectedItem.dom.getBoundingClientRect(), panel: this.list.getBoundingClientRect() }),
        write: ({ sel, panel }) => {
          if (sel.top < panel.top)
            this.list.scrollTop -= panel.top - sel.top;
          else if (sel.bottom > panel.bottom)
            this.list.scrollTop += sel.bottom - panel.bottom;
        }
      });
    } else if (this.selectedIndex < 0) {
      this.list.removeAttribute("aria-activedescendant");
    }
    if (needsSync)
      this.sync();
  }
  sync() {
    let domPos = this.list.firstChild;
    function rm2() {
      let prev = domPos;
      domPos = prev.nextSibling;
      prev.remove();
    }
    for (let item of this.items) {
      if (item.dom.parentNode == this.list) {
        while (domPos != item.dom)
          rm2();
        domPos = item.dom.nextSibling;
      } else {
        this.list.insertBefore(item.dom, domPos);
      }
    }
    while (domPos)
      rm2();
  }
  moveSelection(selectedIndex) {
    if (this.selectedIndex < 0)
      return;
    let field = this.view.state.field(lintState);
    let selection2 = findDiagnostic(field.diagnostics, this.items[selectedIndex].diagnostic);
    if (!selection2)
      return;
    this.view.dispatch({
      selection: { anchor: selection2.from, head: selection2.to },
      scrollIntoView: true,
      effects: movePanelSelection.of(selection2)
    });
  }
  static open(view) {
    return new LintPanel(view);
  }
};
function svg(content2, attrs = `viewBox="0 0 40 40"`) {
  return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content2)}</svg>')`;
}
function underline(color2) {
  return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color2}" fill="none" stroke-width=".7"/>`, `width="6" height="3"`);
}
var baseTheme4 = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-diagnostic": {
    padding: "3px 6px 3px 8px",
    marginLeft: "-1px",
    display: "block",
    whiteSpace: "pre-wrap"
  },
  ".cm-diagnostic-error": { borderLeft: "5px solid #d11" },
  ".cm-diagnostic-warning": { borderLeft: "5px solid orange" },
  ".cm-diagnostic-info": { borderLeft: "5px solid #999" },
  ".cm-diagnosticAction": {
    font: "inherit",
    border: "none",
    padding: "2px 4px",
    backgroundColor: "#444",
    color: "white",
    borderRadius: "3px",
    marginLeft: "8px"
  },
  ".cm-diagnosticSource": {
    fontSize: "70%",
    opacity: 0.7
  },
  ".cm-lintRange": {
    backgroundPosition: "left bottom",
    backgroundRepeat: "repeat-x",
    paddingBottom: "0.7px"
  },
  ".cm-lintRange-error": { backgroundImage: /* @__PURE__ */ underline("#d11") },
  ".cm-lintRange-warning": { backgroundImage: /* @__PURE__ */ underline("orange") },
  ".cm-lintRange-info": { backgroundImage: /* @__PURE__ */ underline("#999") },
  ".cm-lintRange-active": { backgroundColor: "#ffdd9980" },
  ".cm-tooltip-lint": {
    padding: 0,
    margin: 0
  },
  ".cm-lintPoint": {
    position: "relative",
    "&:after": {
      content: '""',
      position: "absolute",
      bottom: 0,
      left: "-2px",
      borderLeft: "3px solid transparent",
      borderRight: "3px solid transparent",
      borderBottom: "4px solid #d11"
    }
  },
  ".cm-lintPoint-warning": {
    "&:after": { borderBottomColor: "orange" }
  },
  ".cm-lintPoint-info": {
    "&:after": { borderBottomColor: "#999" }
  },
  ".cm-panel.cm-panel-lint": {
    position: "relative",
    "& ul": {
      maxHeight: "100px",
      overflowY: "auto",
      "& [aria-selected]": {
        backgroundColor: "#ddd",
        "& u": { textDecoration: "underline" }
      },
      "&:focus [aria-selected]": {
        background_fallback: "#bdf",
        backgroundColor: "Highlight",
        color_fallback: "white",
        color: "HighlightText"
      },
      "& u": { textDecoration: "none" },
      padding: 0,
      margin: 0
    },
    "& [name=close]": {
      position: "absolute",
      top: "0",
      right: "2px",
      background: "inherit",
      border: "none",
      font: "inherit",
      padding: 0,
      margin: 0
    }
  }
});

// node_modules/@codemirror/search/dist/index.js
var basicNormalize = typeof String.prototype.normalize == "function" ? (x2) => x2.normalize("NFKD") : (x2) => x2;
var SearchCursor = class {
  constructor(text2, query, from = 0, to = text2.length, normalize2, test) {
    this.test = test;
    this.value = { from: 0, to: 0 };
    this.done = false;
    this.matches = [];
    this.buffer = "";
    this.bufferPos = 0;
    this.iter = text2.iterRange(from, to);
    this.bufferStart = from;
    this.normalize = normalize2 ? (x2) => normalize2(basicNormalize(x2)) : basicNormalize;
    this.query = this.normalize(query);
  }
  peek() {
    if (this.bufferPos == this.buffer.length) {
      this.bufferStart += this.buffer.length;
      this.iter.next();
      if (this.iter.done)
        return -1;
      this.bufferPos = 0;
      this.buffer = this.iter.value;
    }
    return codePointAt(this.buffer, this.bufferPos);
  }
  next() {
    while (this.matches.length)
      this.matches.pop();
    return this.nextOverlapping();
  }
  nextOverlapping() {
    for (; ; ) {
      let next = this.peek();
      if (next < 0) {
        this.done = true;
        return this;
      }
      let str = fromCodePoint(next), start = this.bufferStart + this.bufferPos;
      this.bufferPos += codePointSize(next);
      let norm = this.normalize(str);
      for (let i = 0, pos = start; ; i++) {
        let code = norm.charCodeAt(i);
        let match = this.match(code, pos);
        if (match) {
          this.value = match;
          return this;
        }
        if (i == norm.length - 1)
          break;
        if (pos == start && i < str.length && str.charCodeAt(i) == code)
          pos++;
      }
    }
  }
  match(code, pos) {
    let match = null;
    for (let i = 0; i < this.matches.length; i += 2) {
      let index2 = this.matches[i], keep = false;
      if (this.query.charCodeAt(index2) == code) {
        if (index2 == this.query.length - 1) {
          match = { from: this.matches[i + 1], to: pos + 1 };
        } else {
          this.matches[i]++;
          keep = true;
        }
      }
      if (!keep) {
        this.matches.splice(i, 2);
        i -= 2;
      }
    }
    if (this.query.charCodeAt(0) == code) {
      if (this.query.length == 1)
        match = { from: pos, to: pos + 1 };
      else
        this.matches.push(1, pos);
    }
    if (match && this.test && !this.test(match.from, match.to, this.buffer, this.bufferPos))
      match = null;
    return match;
  }
};
if (typeof Symbol != "undefined")
  SearchCursor.prototype[Symbol.iterator] = function() {
    return this;
  };
var empty2 = { from: -1, to: -1, match: /* @__PURE__ */ /.*/.exec("") };
var baseFlags = "gm" + (/x/.unicode == null ? "" : "u");
var RegExpCursor = class {
  constructor(text2, query, options2, from = 0, to = text2.length) {
    this.text = text2;
    this.to = to;
    this.curLine = "";
    this.done = false;
    this.value = empty2;
    if (/\\[sWDnr]|\n|\r|\[\^/.test(query))
      return new MultilineRegExpCursor(text2, query, options2, from, to);
    this.re = new RegExp(query, baseFlags + ((options2 === null || options2 === void 0 ? void 0 : options2.ignoreCase) ? "i" : ""));
    this.test = options2 === null || options2 === void 0 ? void 0 : options2.test;
    this.iter = text2.iter();
    let startLine = text2.lineAt(from);
    this.curLineStart = startLine.from;
    this.matchPos = toCharEnd(text2, from);
    this.getLine(this.curLineStart);
  }
  getLine(skip) {
    this.iter.next(skip);
    if (this.iter.lineBreak) {
      this.curLine = "";
    } else {
      this.curLine = this.iter.value;
      if (this.curLineStart + this.curLine.length > this.to)
        this.curLine = this.curLine.slice(0, this.to - this.curLineStart);
      this.iter.next();
    }
  }
  nextLine() {
    this.curLineStart = this.curLineStart + this.curLine.length + 1;
    if (this.curLineStart > this.to)
      this.curLine = "";
    else
      this.getLine(0);
  }
  next() {
    for (let off = this.matchPos - this.curLineStart; ; ) {
      this.re.lastIndex = off;
      let match = this.matchPos <= this.to && this.re.exec(this.curLine);
      if (match) {
        let from = this.curLineStart + match.index, to = from + match[0].length;
        this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0));
        if (from == this.curLineStart + this.curLine.length)
          this.nextLine();
        if ((from < to || from > this.value.to) && (!this.test || this.test(from, to, match))) {
          this.value = { from, to, match };
          return this;
        }
        off = this.matchPos - this.curLineStart;
      } else if (this.curLineStart + this.curLine.length < this.to) {
        this.nextLine();
        off = 0;
      } else {
        this.done = true;
        return this;
      }
    }
  }
};
var flattened = /* @__PURE__ */ new WeakMap();
var FlattenedDoc = class {
  constructor(from, text2) {
    this.from = from;
    this.text = text2;
  }
  get to() {
    return this.from + this.text.length;
  }
  static get(doc2, from, to) {
    let cached = flattened.get(doc2);
    if (!cached || cached.from >= to || cached.to <= from) {
      let flat = new FlattenedDoc(from, doc2.sliceString(from, to));
      flattened.set(doc2, flat);
      return flat;
    }
    if (cached.from == from && cached.to == to)
      return cached;
    let { text: text2, from: cachedFrom } = cached;
    if (cachedFrom > from) {
      text2 = doc2.sliceString(from, cachedFrom) + text2;
      cachedFrom = from;
    }
    if (cached.to < to)
      text2 += doc2.sliceString(cached.to, to);
    flattened.set(doc2, new FlattenedDoc(cachedFrom, text2));
    return new FlattenedDoc(from, text2.slice(from - cachedFrom, to - cachedFrom));
  }
};
var MultilineRegExpCursor = class {
  constructor(text2, query, options2, from, to) {
    this.text = text2;
    this.to = to;
    this.done = false;
    this.value = empty2;
    this.matchPos = toCharEnd(text2, from);
    this.re = new RegExp(query, baseFlags + ((options2 === null || options2 === void 0 ? void 0 : options2.ignoreCase) ? "i" : ""));
    this.test = options2 === null || options2 === void 0 ? void 0 : options2.test;
    this.flat = FlattenedDoc.get(text2, from, this.chunkEnd(from + 5e3));
  }
  chunkEnd(pos) {
    return pos >= this.to ? this.to : this.text.lineAt(pos).to;
  }
  next() {
    for (; ; ) {
      let off = this.re.lastIndex = this.matchPos - this.flat.from;
      let match = this.re.exec(this.flat.text);
      if (match && !match[0] && match.index == off) {
        this.re.lastIndex = off + 1;
        match = this.re.exec(this.flat.text);
      }
      if (match) {
        let from = this.flat.from + match.index, to = from + match[0].length;
        if ((this.flat.to >= this.to || match.index + match[0].length <= this.flat.text.length - 10) && (!this.test || this.test(from, to, match))) {
          this.value = { from, to, match };
          this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0));
          return this;
        }
      }
      if (this.flat.to == this.to) {
        this.done = true;
        return this;
      }
      this.flat = FlattenedDoc.get(this.text, this.flat.from, this.chunkEnd(this.flat.from + this.flat.text.length * 2));
    }
  }
};
if (typeof Symbol != "undefined") {
  RegExpCursor.prototype[Symbol.iterator] = MultilineRegExpCursor.prototype[Symbol.iterator] = function() {
    return this;
  };
}
function validRegExp(source) {
  try {
    new RegExp(source, baseFlags);
    return true;
  } catch (_a2) {
    return false;
  }
}
function toCharEnd(text2, pos) {
  if (pos >= text2.length)
    return pos;
  let line = text2.lineAt(pos), next;
  while (pos < line.to && (next = line.text.charCodeAt(pos - line.from)) >= 56320 && next < 57344)
    pos++;
  return pos;
}
function createLineDialog(view) {
  let input = crelt("input", { class: "cm-textfield", name: "line" });
  let dom = crelt("form", {
    class: "cm-gotoLine",
    onkeydown: (event) => {
      if (event.keyCode == 27) {
        event.preventDefault();
        view.dispatch({ effects: dialogEffect.of(false) });
        view.focus();
      } else if (event.keyCode == 13) {
        event.preventDefault();
        go();
      }
    },
    onsubmit: (event) => {
      event.preventDefault();
      go();
    }
  }, crelt("label", view.state.phrase("Go to line"), ": ", input), " ", crelt("button", { class: "cm-button", type: "submit" }, view.state.phrase("go")));
  function go() {
    let match = /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value);
    if (!match)
      return;
    let { state } = view, startLine = state.doc.lineAt(state.selection.main.head);
    let [, sign, ln, cl, percent] = match;
    let col = cl ? +cl.slice(1) : 0;
    let line = ln ? +ln : startLine.number;
    if (ln && percent) {
      let pc = line / 100;
      if (sign)
        pc = pc * (sign == "-" ? -1 : 1) + startLine.number / state.doc.lines;
      line = Math.round(state.doc.lines * pc);
    } else if (ln && sign) {
      line = line * (sign == "-" ? -1 : 1) + startLine.number;
    }
    let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line)));
    view.dispatch({
      effects: dialogEffect.of(false),
      selection: EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length))),
      scrollIntoView: true
    });
    view.focus();
  }
  return { dom };
}
var dialogEffect = /* @__PURE__ */ StateEffect.define();
var dialogField = /* @__PURE__ */ StateField.define({
  create() {
    return true;
  },
  update(value, tr) {
    for (let e3 of tr.effects)
      if (e3.is(dialogEffect))
        value = e3.value;
    return value;
  },
  provide: (f) => showPanel.from(f, (val) => val ? createLineDialog : null)
});
var gotoLine = (view) => {
  let panel = getPanel(view, createLineDialog);
  if (!panel) {
    let effects = [dialogEffect.of(true)];
    if (view.state.field(dialogField, false) == null)
      effects.push(StateEffect.appendConfig.of([dialogField, baseTheme$13]));
    view.dispatch({ effects });
    panel = getPanel(view, createLineDialog);
  }
  if (panel)
    panel.dom.querySelector("input").focus();
  return true;
};
var baseTheme$13 = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-panel.cm-gotoLine": {
    padding: "2px 6px 4px",
    "& label": { fontSize: "80%" }
  }
});
var defaultHighlightOptions = {
  highlightWordAroundCursor: false,
  minSelectionLength: 1,
  maxMatches: 100,
  wholeWords: false
};
var highlightConfig = /* @__PURE__ */ Facet.define({
  combine(options2) {
    return combineConfig(options2, defaultHighlightOptions, {
      highlightWordAroundCursor: (a, b) => a || b,
      minSelectionLength: Math.min,
      maxMatches: Math.min
    });
  }
});
function highlightSelectionMatches(options2) {
  let ext2 = [defaultTheme, matchHighlighter];
  if (options2)
    ext2.push(highlightConfig.of(options2));
  return ext2;
}
var matchDeco = /* @__PURE__ */ Decoration.mark({ class: "cm-selectionMatch" });
var mainMatchDeco = /* @__PURE__ */ Decoration.mark({ class: "cm-selectionMatch cm-selectionMatch-main" });
function insideWordBoundaries(check, state, from, to) {
  return (from == 0 || check(state.sliceDoc(from - 1, from)) != CharCategory.Word) && (to == state.doc.length || check(state.sliceDoc(to, to + 1)) != CharCategory.Word);
}
function insideWord(check, state, from, to) {
  return check(state.sliceDoc(from, from + 1)) == CharCategory.Word && check(state.sliceDoc(to - 1, to)) == CharCategory.Word;
}
var matchHighlighter = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.decorations = this.getDeco(view);
  }
  update(update2) {
    if (update2.selectionSet || update2.docChanged || update2.viewportChanged)
      this.decorations = this.getDeco(update2.view);
  }
  getDeco(view) {
    let conf = view.state.facet(highlightConfig);
    let { state } = view, sel = state.selection;
    if (sel.ranges.length > 1)
      return Decoration.none;
    let range2 = sel.main, query, check = null;
    if (range2.empty) {
      if (!conf.highlightWordAroundCursor)
        return Decoration.none;
      let word = state.wordAt(range2.head);
      if (!word)
        return Decoration.none;
      check = state.charCategorizer(range2.head);
      query = state.sliceDoc(word.from, word.to);
    } else {
      let len = range2.to - range2.from;
      if (len < conf.minSelectionLength || len > 200)
        return Decoration.none;
      if (conf.wholeWords) {
        query = state.sliceDoc(range2.from, range2.to);
        check = state.charCategorizer(range2.head);
        if (!(insideWordBoundaries(check, state, range2.from, range2.to) && insideWord(check, state, range2.from, range2.to)))
          return Decoration.none;
      } else {
        query = state.sliceDoc(range2.from, range2.to).trim();
        if (!query)
          return Decoration.none;
      }
    }
    let deco = [];
    for (let part of view.visibleRanges) {
      let cursor = new SearchCursor(state.doc, query, part.from, part.to);
      while (!cursor.next().done) {
        let { from, to } = cursor.value;
        if (!check || insideWordBoundaries(check, state, from, to)) {
          if (range2.empty && from <= range2.from && to >= range2.to)
            deco.push(mainMatchDeco.range(from, to));
          else if (from >= range2.to || to <= range2.from)
            deco.push(matchDeco.range(from, to));
          if (deco.length > conf.maxMatches)
            return Decoration.none;
        }
      }
    }
    return Decoration.set(deco);
  }
}, {
  decorations: (v) => v.decorations
});
var defaultTheme = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-selectionMatch": { backgroundColor: "#99ff7780" },
  ".cm-searchMatch .cm-selectionMatch": { backgroundColor: "transparent" }
});
var selectWord = ({ state, dispatch }) => {
  let { selection: selection2 } = state;
  let newSel = EditorSelection.create(selection2.ranges.map((range2) => state.wordAt(range2.head) || EditorSelection.cursor(range2.head)), selection2.mainIndex);
  if (newSel.eq(selection2))
    return false;
  dispatch(state.update({ selection: newSel }));
  return true;
};
function findNextOccurrence(state, query) {
  let { main, ranges } = state.selection;
  let word = state.wordAt(main.head), fullWord = word && word.from == main.from && word.to == main.to;
  for (let cycled = false, cursor = new SearchCursor(state.doc, query, ranges[ranges.length - 1].to); ; ) {
    cursor.next();
    if (cursor.done) {
      if (cycled)
        return null;
      cursor = new SearchCursor(state.doc, query, 0, Math.max(0, ranges[ranges.length - 1].from - 1));
      cycled = true;
    } else {
      if (cycled && ranges.some((r) => r.from == cursor.value.from))
        continue;
      if (fullWord) {
        let word2 = state.wordAt(cursor.value.from);
        if (!word2 || word2.from != cursor.value.from || word2.to != cursor.value.to)
          continue;
      }
      return cursor.value;
    }
  }
}
var selectNextOccurrence = ({ state, dispatch }) => {
  let { ranges } = state.selection;
  if (ranges.some((sel) => sel.from === sel.to))
    return selectWord({ state, dispatch });
  let searchedText = state.sliceDoc(ranges[0].from, ranges[0].to);
  if (state.selection.ranges.some((r) => state.sliceDoc(r.from, r.to) != searchedText))
    return false;
  let range2 = findNextOccurrence(state, searchedText);
  if (!range2)
    return false;
  dispatch(state.update({
    selection: state.selection.addRange(EditorSelection.range(range2.from, range2.to), false),
    effects: EditorView.scrollIntoView(range2.to)
  }));
  return true;
};
var searchConfigFacet = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      top: false,
      caseSensitive: false,
      literal: false,
      wholeWord: false,
      createPanel: (view) => new SearchPanel(view)
    });
  }
});
var SearchQuery = class {
  constructor(config2) {
    this.search = config2.search;
    this.caseSensitive = !!config2.caseSensitive;
    this.literal = !!config2.literal;
    this.regexp = !!config2.regexp;
    this.replace = config2.replace || "";
    this.valid = !!this.search && (!this.regexp || validRegExp(this.search));
    this.unquoted = this.unquote(this.search);
    this.wholeWord = !!config2.wholeWord;
  }
  unquote(text2) {
    return this.literal ? text2 : text2.replace(/\\([nrt\\])/g, (_2, ch) => ch == "n" ? "\n" : ch == "r" ? "\r" : ch == "t" ? "	" : "\\");
  }
  eq(other) {
    return this.search == other.search && this.replace == other.replace && this.caseSensitive == other.caseSensitive && this.regexp == other.regexp && this.wholeWord == other.wholeWord;
  }
  create() {
    return this.regexp ? new RegExpQuery(this) : new StringQuery(this);
  }
  getCursor(state, from = 0, to) {
    let st = state.doc ? state : EditorState.create({ doc: state });
    if (to == null)
      to = st.doc.length;
    return this.regexp ? regexpCursor(this, st, from, to) : stringCursor(this, st, from, to);
  }
};
var QueryType2 = class {
  constructor(spec) {
    this.spec = spec;
  }
};
function stringCursor(spec, state, from, to) {
  return new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? void 0 : (x2) => x2.toLowerCase(), spec.wholeWord ? stringWordTest(state.doc, state.charCategorizer(state.selection.main.head)) : void 0);
}
function stringWordTest(doc2, categorizer) {
  return (from, to, buf, bufPos) => {
    if (bufPos > from || bufPos + buf.length < to) {
      bufPos = Math.max(0, from - 2);
      buf = doc2.sliceString(bufPos, Math.min(doc2.length, to + 2));
    }
    return (categorizer(charBefore(buf, from - bufPos)) != CharCategory.Word || categorizer(charAfter(buf, from - bufPos)) != CharCategory.Word) && (categorizer(charAfter(buf, to - bufPos)) != CharCategory.Word || categorizer(charBefore(buf, to - bufPos)) != CharCategory.Word);
  };
}
var StringQuery = class extends QueryType2 {
  constructor(spec) {
    super(spec);
  }
  nextMatch(state, curFrom, curTo) {
    let cursor = stringCursor(this.spec, state, curTo, state.doc.length).nextOverlapping();
    if (cursor.done)
      cursor = stringCursor(this.spec, state, 0, curFrom).nextOverlapping();
    return cursor.done ? null : cursor.value;
  }
  prevMatchInRange(state, from, to) {
    for (let pos = to; ; ) {
      let start = Math.max(from, pos - 1e4 - this.spec.unquoted.length);
      let cursor = stringCursor(this.spec, state, start, pos), range2 = null;
      while (!cursor.nextOverlapping().done)
        range2 = cursor.value;
      if (range2)
        return range2;
      if (start == from)
        return null;
      pos -= 1e4;
    }
  }
  prevMatch(state, curFrom, curTo) {
    return this.prevMatchInRange(state, 0, curFrom) || this.prevMatchInRange(state, curTo, state.doc.length);
  }
  getReplacement(_result) {
    return this.spec.unquote(this.spec.replace);
  }
  matchAll(state, limit) {
    let cursor = stringCursor(this.spec, state, 0, state.doc.length), ranges = [];
    while (!cursor.next().done) {
      if (ranges.length >= limit)
        return null;
      ranges.push(cursor.value);
    }
    return ranges;
  }
  highlight(state, from, to, add3) {
    let cursor = stringCursor(this.spec, state, Math.max(0, from - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, state.doc.length));
    while (!cursor.next().done)
      add3(cursor.value.from, cursor.value.to);
  }
};
function regexpCursor(spec, state, from, to) {
  return new RegExpCursor(state.doc, spec.search, {
    ignoreCase: !spec.caseSensitive,
    test: spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : void 0
  }, from, to);
}
function charBefore(str, index2) {
  return str.slice(findClusterBreak(str, index2, false), index2);
}
function charAfter(str, index2) {
  return str.slice(index2, findClusterBreak(str, index2));
}
function regexpWordTest(categorizer) {
  return (_from, _to, match) => !match[0].length || (categorizer(charBefore(match.input, match.index)) != CharCategory.Word || categorizer(charAfter(match.input, match.index)) != CharCategory.Word) && (categorizer(charAfter(match.input, match.index + match[0].length)) != CharCategory.Word || categorizer(charBefore(match.input, match.index + match[0].length)) != CharCategory.Word);
}
var RegExpQuery = class extends QueryType2 {
  nextMatch(state, curFrom, curTo) {
    let cursor = regexpCursor(this.spec, state, curTo, state.doc.length).next();
    if (cursor.done)
      cursor = regexpCursor(this.spec, state, 0, curFrom).next();
    return cursor.done ? null : cursor.value;
  }
  prevMatchInRange(state, from, to) {
    for (let size = 1; ; size++) {
      let start = Math.max(from, to - size * 1e4);
      let cursor = regexpCursor(this.spec, state, start, to), range2 = null;
      while (!cursor.next().done)
        range2 = cursor.value;
      if (range2 && (start == from || range2.from > start + 10))
        return range2;
      if (start == from)
        return null;
    }
  }
  prevMatch(state, curFrom, curTo) {
    return this.prevMatchInRange(state, 0, curFrom) || this.prevMatchInRange(state, curTo, state.doc.length);
  }
  getReplacement(result) {
    return this.spec.unquote(this.spec.replace.replace(/\$([$&\d+])/g, (m, i) => i == "$" ? "$" : i == "&" ? result.match[0] : i != "0" && +i < result.match.length ? result.match[i] : m));
  }
  matchAll(state, limit) {
    let cursor = regexpCursor(this.spec, state, 0, state.doc.length), ranges = [];
    while (!cursor.next().done) {
      if (ranges.length >= limit)
        return null;
      ranges.push(cursor.value);
    }
    return ranges;
  }
  highlight(state, from, to, add3) {
    let cursor = regexpCursor(this.spec, state, Math.max(0, from - 250), Math.min(to + 250, state.doc.length));
    while (!cursor.next().done)
      add3(cursor.value.from, cursor.value.to);
  }
};
var setSearchQuery = /* @__PURE__ */ StateEffect.define();
var togglePanel2 = /* @__PURE__ */ StateEffect.define();
var searchState = /* @__PURE__ */ StateField.define({
  create(state) {
    return new SearchState(defaultQuery(state).create(), null);
  },
  update(value, tr) {
    for (let effect of tr.effects) {
      if (effect.is(setSearchQuery))
        value = new SearchState(effect.value.create(), value.panel);
      else if (effect.is(togglePanel2))
        value = new SearchState(value.query, effect.value ? createSearchPanel : null);
    }
    return value;
  },
  provide: (f) => showPanel.from(f, (val) => val.panel)
});
var SearchState = class {
  constructor(query, panel) {
    this.query = query;
    this.panel = panel;
  }
};
var matchMark = /* @__PURE__ */ Decoration.mark({ class: "cm-searchMatch" });
var selectedMatchMark = /* @__PURE__ */ Decoration.mark({ class: "cm-searchMatch cm-searchMatch-selected" });
var searchHighlighter = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.decorations = this.highlight(view.state.field(searchState));
  }
  update(update2) {
    let state = update2.state.field(searchState);
    if (state != update2.startState.field(searchState) || update2.docChanged || update2.selectionSet || update2.viewportChanged)
      this.decorations = this.highlight(state);
  }
  highlight({ query, panel }) {
    if (!panel || !query.spec.valid)
      return Decoration.none;
    let { view } = this;
    let builder = new RangeSetBuilder();
    for (let i = 0, ranges = view.visibleRanges, l = ranges.length; i < l; i++) {
      let { from, to } = ranges[i];
      while (i < l - 1 && to > ranges[i + 1].from - 2 * 250)
        to = ranges[++i].to;
      query.highlight(view.state, from, to, (from2, to2) => {
        let selected = view.state.selection.ranges.some((r) => r.from == from2 && r.to == to2);
        builder.add(from2, to2, selected ? selectedMatchMark : matchMark);
      });
    }
    return builder.finish();
  }
}, {
  decorations: (v) => v.decorations
});
function searchCommand(f) {
  return (view) => {
    let state = view.state.field(searchState, false);
    return state && state.query.spec.valid ? f(view, state) : openSearchPanel(view);
  };
}
var findNext = /* @__PURE__ */ searchCommand((view, { query }) => {
  let { to } = view.state.selection.main;
  let next = query.nextMatch(view.state, to, to);
  if (!next)
    return false;
  view.dispatch({
    selection: { anchor: next.from, head: next.to },
    scrollIntoView: true,
    effects: announceMatch(view, next),
    userEvent: "select.search"
  });
  return true;
});
var findPrevious = /* @__PURE__ */ searchCommand((view, { query }) => {
  let { state } = view, { from } = state.selection.main;
  let range2 = query.prevMatch(state, from, from);
  if (!range2)
    return false;
  view.dispatch({
    selection: { anchor: range2.from, head: range2.to },
    scrollIntoView: true,
    effects: announceMatch(view, range2),
    userEvent: "select.search"
  });
  return true;
});
var selectMatches = /* @__PURE__ */ searchCommand((view, { query }) => {
  let ranges = query.matchAll(view.state, 1e3);
  if (!ranges || !ranges.length)
    return false;
  view.dispatch({
    selection: EditorSelection.create(ranges.map((r) => EditorSelection.range(r.from, r.to))),
    userEvent: "select.search.matches"
  });
  return true;
});
var selectSelectionMatches = ({ state, dispatch }) => {
  let sel = state.selection;
  if (sel.ranges.length > 1 || sel.main.empty)
    return false;
  let { from, to } = sel.main;
  let ranges = [], main = 0;
  for (let cur2 = new SearchCursor(state.doc, state.sliceDoc(from, to)); !cur2.next().done; ) {
    if (ranges.length > 1e3)
      return false;
    if (cur2.value.from == from)
      main = ranges.length;
    ranges.push(EditorSelection.range(cur2.value.from, cur2.value.to));
  }
  dispatch(state.update({
    selection: EditorSelection.create(ranges, main),
    userEvent: "select.search.matches"
  }));
  return true;
};
var replaceNext = /* @__PURE__ */ searchCommand((view, { query }) => {
  let { state } = view, { from, to } = state.selection.main;
  if (state.readOnly)
    return false;
  let next = query.nextMatch(state, from, from);
  if (!next)
    return false;
  let changes = [], selection2, replacement;
  let announce = [];
  if (next.from == from && next.to == to) {
    replacement = state.toText(query.getReplacement(next));
    changes.push({ from: next.from, to: next.to, insert: replacement });
    next = query.nextMatch(state, next.from, next.to);
    announce.push(EditorView.announce.of(state.phrase("replaced match on line $", state.doc.lineAt(from).number) + "."));
  }
  if (next) {
    let off = changes.length == 0 || changes[0].from >= next.to ? 0 : next.to - next.from - replacement.length;
    selection2 = { anchor: next.from - off, head: next.to - off };
    announce.push(announceMatch(view, next));
  }
  view.dispatch({
    changes,
    selection: selection2,
    scrollIntoView: !!selection2,
    effects: announce,
    userEvent: "input.replace"
  });
  return true;
});
var replaceAll = /* @__PURE__ */ searchCommand((view, { query }) => {
  if (view.state.readOnly)
    return false;
  let changes = query.matchAll(view.state, 1e9).map((match) => {
    let { from, to } = match;
    return { from, to, insert: query.getReplacement(match) };
  });
  if (!changes.length)
    return false;
  let announceText = view.state.phrase("replaced $ matches", changes.length) + ".";
  view.dispatch({
    changes,
    effects: EditorView.announce.of(announceText),
    userEvent: "input.replace.all"
  });
  return true;
});
function createSearchPanel(view) {
  return view.state.facet(searchConfigFacet).createPanel(view);
}
function defaultQuery(state, fallback) {
  var _a2, _b, _c, _d;
  let sel = state.selection.main;
  let selText = sel.empty || sel.to > sel.from + 100 ? "" : state.sliceDoc(sel.from, sel.to);
  if (fallback && !selText)
    return fallback;
  let config2 = state.facet(searchConfigFacet);
  return new SearchQuery({
    search: ((_a2 = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _a2 !== void 0 ? _a2 : config2.literal) ? selText : selText.replace(/\n/g, "\\n"),
    caseSensitive: (_b = fallback === null || fallback === void 0 ? void 0 : fallback.caseSensitive) !== null && _b !== void 0 ? _b : config2.caseSensitive,
    literal: (_c = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _c !== void 0 ? _c : config2.literal,
    wholeWord: (_d = fallback === null || fallback === void 0 ? void 0 : fallback.wholeWord) !== null && _d !== void 0 ? _d : config2.wholeWord
  });
}
var openSearchPanel = (view) => {
  let state = view.state.field(searchState, false);
  if (state && state.panel) {
    let panel = getPanel(view, createSearchPanel);
    if (!panel)
      return false;
    let searchInput = panel.dom.querySelector("[main-field]");
    if (searchInput && searchInput != view.root.activeElement) {
      let query = defaultQuery(view.state, state.query.spec);
      if (query.valid)
        view.dispatch({ effects: setSearchQuery.of(query) });
      searchInput.focus();
      searchInput.select();
    }
  } else {
    view.dispatch({ effects: [
      togglePanel2.of(true),
      state ? setSearchQuery.of(defaultQuery(view.state, state.query.spec)) : StateEffect.appendConfig.of(searchExtensions)
    ] });
  }
  return true;
};
var closeSearchPanel = (view) => {
  let state = view.state.field(searchState, false);
  if (!state || !state.panel)
    return false;
  let panel = getPanel(view, createSearchPanel);
  if (panel && panel.dom.contains(view.root.activeElement))
    view.focus();
  view.dispatch({ effects: togglePanel2.of(false) });
  return true;
};
var searchKeymap = [
  { key: "Mod-f", run: openSearchPanel, scope: "editor search-panel" },
  { key: "F3", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true },
  { key: "Mod-g", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true },
  { key: "Escape", run: closeSearchPanel, scope: "editor search-panel" },
  { key: "Mod-Shift-l", run: selectSelectionMatches },
  { key: "Alt-g", run: gotoLine },
  { key: "Mod-d", run: selectNextOccurrence, preventDefault: true }
];
var SearchPanel = class {
  constructor(view) {
    this.view = view;
    let query = this.query = view.state.field(searchState).query.spec;
    this.commit = this.commit.bind(this);
    this.searchField = crelt("input", {
      value: query.search,
      placeholder: phrase(view, "Find"),
      "aria-label": phrase(view, "Find"),
      class: "cm-textfield",
      name: "search",
      form: "",
      "main-field": "true",
      onchange: this.commit,
      onkeyup: this.commit
    });
    this.replaceField = crelt("input", {
      value: query.replace,
      placeholder: phrase(view, "Replace"),
      "aria-label": phrase(view, "Replace"),
      class: "cm-textfield",
      name: "replace",
      form: "",
      onchange: this.commit,
      onkeyup: this.commit
    });
    this.caseField = crelt("input", {
      type: "checkbox",
      name: "case",
      form: "",
      checked: query.caseSensitive,
      onchange: this.commit
    });
    this.reField = crelt("input", {
      type: "checkbox",
      name: "re",
      form: "",
      checked: query.regexp,
      onchange: this.commit
    });
    this.wordField = crelt("input", {
      type: "checkbox",
      name: "word",
      form: "",
      checked: query.wholeWord,
      onchange: this.commit
    });
    function button(name2, onclick, content2) {
      return crelt("button", { class: "cm-button", name: name2, onclick, type: "button" }, content2);
    }
    this.dom = crelt("div", { onkeydown: (e3) => this.keydown(e3), class: "cm-search" }, [
      this.searchField,
      button("next", () => findNext(view), [phrase(view, "next")]),
      button("prev", () => findPrevious(view), [phrase(view, "previous")]),
      button("select", () => selectMatches(view), [phrase(view, "all")]),
      crelt("label", null, [this.caseField, phrase(view, "match case")]),
      crelt("label", null, [this.reField, phrase(view, "regexp")]),
      crelt("label", null, [this.wordField, phrase(view, "by word")]),
      ...view.state.readOnly ? [] : [
        crelt("br"),
        this.replaceField,
        button("replace", () => replaceNext(view), [phrase(view, "replace")]),
        button("replaceAll", () => replaceAll(view), [phrase(view, "replace all")]),
        crelt("button", {
          name: "close",
          onclick: () => closeSearchPanel(view),
          "aria-label": phrase(view, "close"),
          type: "button"
        }, ["\xD7"])
      ]
    ]);
  }
  commit() {
    let query = new SearchQuery({
      search: this.searchField.value,
      caseSensitive: this.caseField.checked,
      regexp: this.reField.checked,
      wholeWord: this.wordField.checked,
      replace: this.replaceField.value
    });
    if (!query.eq(this.query)) {
      this.query = query;
      this.view.dispatch({ effects: setSearchQuery.of(query) });
    }
  }
  keydown(e3) {
    if (runScopeHandlers(this.view, e3, "search-panel")) {
      e3.preventDefault();
    } else if (e3.keyCode == 13 && e3.target == this.searchField) {
      e3.preventDefault();
      (e3.shiftKey ? findPrevious : findNext)(this.view);
    } else if (e3.keyCode == 13 && e3.target == this.replaceField) {
      e3.preventDefault();
      replaceNext(this.view);
    }
  }
  update(update2) {
    for (let tr of update2.transactions)
      for (let effect of tr.effects) {
        if (effect.is(setSearchQuery) && !effect.value.eq(this.query))
          this.setQuery(effect.value);
      }
  }
  setQuery(query) {
    this.query = query;
    this.searchField.value = query.search;
    this.replaceField.value = query.replace;
    this.caseField.checked = query.caseSensitive;
    this.reField.checked = query.regexp;
    this.wordField.checked = query.wholeWord;
  }
  mount() {
    this.searchField.select();
  }
  get pos() {
    return 80;
  }
  get top() {
    return this.view.state.facet(searchConfigFacet).top;
  }
};
function phrase(view, phrase2) {
  return view.state.phrase(phrase2);
}
var AnnounceMargin = 30;
var Break = /[\s\.,:;?!]/;
function announceMatch(view, { from, to }) {
  let line = view.state.doc.lineAt(from), lineEnd = view.state.doc.lineAt(to).to;
  let start = Math.max(line.from, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin);
  let text2 = view.state.sliceDoc(start, end);
  if (start != line.from) {
    for (let i = 0; i < AnnounceMargin; i++)
      if (!Break.test(text2[i + 1]) && Break.test(text2[i])) {
        text2 = text2.slice(i);
        break;
      }
  }
  if (end != lineEnd) {
    for (let i = text2.length - 1; i > text2.length - AnnounceMargin; i--)
      if (!Break.test(text2[i - 1]) && Break.test(text2[i])) {
        text2 = text2.slice(0, i);
        break;
      }
  }
  return EditorView.announce.of(`${view.state.phrase("current match")}. ${text2} ${view.state.phrase("on line")} ${line.number}.`);
}
var baseTheme5 = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-panel.cm-search": {
    padding: "2px 6px 4px",
    position: "relative",
    "& [name=close]": {
      position: "absolute",
      top: "0",
      right: "4px",
      backgroundColor: "inherit",
      border: "none",
      font: "inherit",
      padding: 0,
      margin: 0
    },
    "& input, & button, & label": {
      margin: ".2em .6em .2em 0"
    },
    "& input[type=checkbox]": {
      marginRight: ".2em"
    },
    "& label": {
      fontSize: "80%",
      whiteSpace: "pre"
    }
  },
  "&light .cm-searchMatch": { backgroundColor: "#ffff0054" },
  "&dark .cm-searchMatch": { backgroundColor: "#00ffff8a" },
  "&light .cm-searchMatch-selected": { backgroundColor: "#ff6a0054" },
  "&dark .cm-searchMatch-selected": { backgroundColor: "#ff00ff8a" }
});
var searchExtensions = [
  searchState,
  /* @__PURE__ */ Prec.lowest(searchHighlighter),
  baseTheme5
];

// src/codemirror/beancount-snippets.ts
var beancountSnippets = () => {
  const today = todayAsString();
  return [
    snippetCompletion(
      `${today} #{*} "#{}" "#{}"
  #{Account:A}  #{Amount}
  #{Account:B}`,
      {
        label: `${today} * transaction`
      }
    )
  ];
};

// src/codemirror/account-regex.ts
var account_regex_default = /(?:(?:[A-Z\xC0-\xD6\xD8-\xDE\u0100\u0102\u0104\u0106\u0108\u010A\u010C\u010E\u0110\u0112\u0114\u0116\u0118\u011A\u011C\u011E\u0120\u0122\u0124\u0126\u0128\u012A\u012C\u012E\u0130\u0132\u0134\u0136\u0139\u013B\u013D\u013F\u0141\u0143\u0145\u0147\u014A\u014C\u014E\u0150\u0152\u0154\u0156\u0158\u015A\u015C\u015E\u0160\u0162\u0164\u0166\u0168\u016A\u016C\u016E\u0170\u0172\u0174\u0176\u0178\u0179\u017B\u017D\u0181\u0182\u0184\u0186\u0187\u0189-\u018B\u018E-\u0191\u0193\u0194\u0196-\u0198\u019C\u019D\u019F\u01A0\u01A2\u01A4\u01A6\u01A7\u01A9\u01AC\u01AE\u01AF\u01B1-\u01B3\u01B5\u01B7\u01B8\u01BC\u01C4\u01C7\u01CA\u01CD\u01CF\u01D1\u01D3\u01D5\u01D7\u01D9\u01DB\u01DE\u01E0\u01E2\u01E4\u01E6\u01E8\u01EA\u01EC\u01EE\u01F1\u01F4\u01F6-\u01F8\u01FA\u01FC\u01FE\u0200\u0202\u0204\u0206\u0208\u020A\u020C\u020E\u0210\u0212\u0214\u0216\u0218\u021A\u021C\u021E\u0220\u0222\u0224\u0226\u0228\u022A\u022C\u022E\u0230\u0232\u023A\u023B\u023D\u023E\u0241\u0243-\u0246\u0248\u024A\u024C\u024E\u0370\u0372\u0376\u037F\u0386\u0388-\u038A\u038C\u038E\u038F\u0391-\u03A1\u03A3-\u03AB\u03CF\u03D2-\u03D4\u03D8\u03DA\u03DC\u03DE\u03E0\u03E2\u03E4\u03E6\u03E8\u03EA\u03EC\u03EE\u03F4\u03F7\u03F9\u03FA\u03FD-\u042F\u0460\u0462\u0464\u0466\u0468\u046A\u046C\u046E\u0470\u0472\u0474\u0476\u0478\u047A\u047C\u047E\u0480\u048A\u048C\u048E\u0490\u0492\u0494\u0496\u0498\u049A\u049C\u049E\u04A0\u04A2\u04A4\u04A6\u04A8\u04AA\u04AC\u04AE\u04B0\u04B2\u04B4\u04B6\u04B8\u04BA\u04BC\u04BE\u04C0\u04C1\u04C3\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04D2\u04D4\u04D6\u04D8\u04DA\u04DC\u04DE\u04E0\u04E2\u04E4\u04E6\u04E8\u04EA\u04EC\u04EE\u04F0\u04F2\u04F4\u04F6\u04F8\u04FA\u04FC\u04FE\u0500\u0502\u0504\u0506\u0508\u050A\u050C\u050E\u0510\u0512\u0514\u0516\u0518\u051A\u051C\u051E\u0520\u0522\u0524\u0526\u0528\u052A\u052C\u052E\u0531-\u0556\u10A0-\u10C5\u10C7\u10CD\u13A0-\u13F5\u1C90-\u1CBA\u1CBD-\u1CBF\u1E00\u1E02\u1E04\u1E06\u1E08\u1E0A\u1E0C\u1E0E\u1E10\u1E12\u1E14\u1E16\u1E18\u1E1A\u1E1C\u1E1E\u1E20\u1E22\u1E24\u1E26\u1E28\u1E2A\u1E2C\u1E2E\u1E30\u1E32\u1E34\u1E36\u1E38\u1E3A\u1E3C\u1E3E\u1E40\u1E42\u1E44\u1E46\u1E48\u1E4A\u1E4C\u1E4E\u1E50\u1E52\u1E54\u1E56\u1E58\u1E5A\u1E5C\u1E5E\u1E60\u1E62\u1E64\u1E66\u1E68\u1E6A\u1E6C\u1E6E\u1E70\u1E72\u1E74\u1E76\u1E78\u1E7A\u1E7C\u1E7E\u1E80\u1E82\u1E84\u1E86\u1E88\u1E8A\u1E8C\u1E8E\u1E90\u1E92\u1E94\u1E9E\u1EA0\u1EA2\u1EA4\u1EA6\u1EA8\u1EAA\u1EAC\u1EAE\u1EB0\u1EB2\u1EB4\u1EB6\u1EB8\u1EBA\u1EBC\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1EC8\u1ECA\u1ECC\u1ECE\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EDA\u1EDC\u1EDE\u1EE0\u1EE2\u1EE4\u1EE6\u1EE8\u1EEA\u1EEC\u1EEE\u1EF0\u1EF2\u1EF4\u1EF6\u1EF8\u1EFA\u1EFC\u1EFE\u1F08-\u1F0F\u1F18-\u1F1D\u1F28-\u1F2F\u1F38-\u1F3F\u1F48-\u1F4D\u1F59\u1F5B\u1F5D\u1F5F\u1F68-\u1F6F\u1FB8-\u1FBB\u1FC8-\u1FCB\u1FD8-\u1FDB\u1FE8-\u1FEC\u1FF8-\u1FFB\u2102\u2107\u210B-\u210D\u2110-\u2112\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u2130-\u2133\u213E\u213F\u2145\u2183\u2C00-\u2C2E\u2C60\u2C62-\u2C64\u2C67\u2C69\u2C6B\u2C6D-\u2C70\u2C72\u2C75\u2C7E-\u2C80\u2C82\u2C84\u2C86\u2C88\u2C8A\u2C8C\u2C8E\u2C90\u2C92\u2C94\u2C96\u2C98\u2C9A\u2C9C\u2C9E\u2CA0\u2CA2\u2CA4\u2CA6\u2CA8\u2CAA\u2CAC\u2CAE\u2CB0\u2CB2\u2CB4\u2CB6\u2CB8\u2CBA\u2CBC\u2CBE\u2CC0\u2CC2\u2CC4\u2CC6\u2CC8\u2CCA\u2CCC\u2CCE\u2CD0\u2CD2\u2CD4\u2CD6\u2CD8\u2CDA\u2CDC\u2CDE\u2CE0\u2CE2\u2CEB\u2CED\u2CF2\uA640\uA642\uA644\uA646\uA648\uA64A\uA64C\uA64E\uA650\uA652\uA654\uA656\uA658\uA65A\uA65C\uA65E\uA660\uA662\uA664\uA666\uA668\uA66A\uA66C\uA680\uA682\uA684\uA686\uA688\uA68A\uA68C\uA68E\uA690\uA692\uA694\uA696\uA698\uA69A\uA722\uA724\uA726\uA728\uA72A\uA72C\uA72E\uA732\uA734\uA736\uA738\uA73A\uA73C\uA73E\uA740\uA742\uA744\uA746\uA748\uA74A\uA74C\uA74E\uA750\uA752\uA754\uA756\uA758\uA75A\uA75C\uA75E\uA760\uA762\uA764\uA766\uA768\uA76A\uA76C\uA76E\uA779\uA77B\uA77D\uA77E\uA780\uA782\uA784\uA786\uA78B\uA78D\uA790\uA792\uA796\uA798\uA79A\uA79C\uA79E\uA7A0\uA7A2\uA7A4\uA7A6\uA7A8\uA7AA-\uA7AE\uA7B0-\uA7B4\uA7B6\uA7B8\uA7BA\uA7BC\uA7BE\uA7C2\uA7C4-\uA7C7\uA7C9\uA7F5\uFF21-\uFF3A]|\uD801[\uDC00-\uDC27\uDCB0-\uDCD3]|\uD803[\uDC80-\uDCB2]|\uD806[\uDCA0-\uDCBF]|\uD81B[\uDE40-\uDE5F]|\uD835[\uDC00-\uDC19\uDC34-\uDC4D\uDC68-\uDC81\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB5\uDCD0-\uDCE9\uDD04\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD38\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD6C-\uDD85\uDDA0-\uDDB9\uDDD4-\uDDED\uDE08-\uDE21\uDE3C-\uDE55\uDE70-\uDE89\uDEA8-\uDEC0\uDEE2-\uDEFA\uDF1C-\uDF34\uDF56-\uDF6E\uDF90-\uDFA8\uDFCA]|\uD83A[\uDD00-\uDD21])(?:[\x2D0-9A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u0660-\u0669\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08C7\u0904-\u0939\u093D\u0950\u0958-\u0961\u0966-\u096F\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AE6-\u0AEF\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B6F\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0BE6-\u0BEF\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C66-\u0C6F\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D66-\u0D6F\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DE6-\u0DEF\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F20-\u0F29\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F-\u1049\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u1090-\u1099\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A16\u1A20-\u1A54\u1A80-\u1A89\u1A90-\u1A99\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B50-\u1B59\u1B83-\u1BA0\u1BAE-\u1BE5\u1C00-\u1C23\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\u9FFC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7BF\uA7C2-\uA7CA\uA7F5-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8D0-\uA8D9\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA900-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF-\uA9D9\uA9E0-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDD30-\uDD39\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC66-\uDC6F\uDC83-\uDCAF\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD03-\uDD26\uDD36-\uDD3F\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDEF0-\uDEF9\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC50-\uDC59\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE50-\uDE59\uDE80-\uDEAA\uDEB8\uDEC0-\uDEC9\uDF00-\uDF1A\uDF30-\uDF39]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCE9\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDD50-\uDD59\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD50-\uDD59\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDDA0-\uDDA9\uDEE0-\uDEF2\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82C[\uDC00-\uDD1E\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD40-\uDD49\uDD4E\uDEC0-\uDEEB\uDEF0-\uDEF9]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD83E[\uDFF0-\uDFF9]|\uD869[\uDC00-\uDEDD\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])*)(?::(?:[0-9A-Z\xC0-\xD6\xD8-\xDE\u0100\u0102\u0104\u0106\u0108\u010A\u010C\u010E\u0110\u0112\u0114\u0116\u0118\u011A\u011C\u011E\u0120\u0122\u0124\u0126\u0128\u012A\u012C\u012E\u0130\u0132\u0134\u0136\u0139\u013B\u013D\u013F\u0141\u0143\u0145\u0147\u014A\u014C\u014E\u0150\u0152\u0154\u0156\u0158\u015A\u015C\u015E\u0160\u0162\u0164\u0166\u0168\u016A\u016C\u016E\u0170\u0172\u0174\u0176\u0178\u0179\u017B\u017D\u0181\u0182\u0184\u0186\u0187\u0189-\u018B\u018E-\u0191\u0193\u0194\u0196-\u0198\u019C\u019D\u019F\u01A0\u01A2\u01A4\u01A6\u01A7\u01A9\u01AC\u01AE\u01AF\u01B1-\u01B3\u01B5\u01B7\u01B8\u01BC\u01C4\u01C7\u01CA\u01CD\u01CF\u01D1\u01D3\u01D5\u01D7\u01D9\u01DB\u01DE\u01E0\u01E2\u01E4\u01E6\u01E8\u01EA\u01EC\u01EE\u01F1\u01F4\u01F6-\u01F8\u01FA\u01FC\u01FE\u0200\u0202\u0204\u0206\u0208\u020A\u020C\u020E\u0210\u0212\u0214\u0216\u0218\u021A\u021C\u021E\u0220\u0222\u0224\u0226\u0228\u022A\u022C\u022E\u0230\u0232\u023A\u023B\u023D\u023E\u0241\u0243-\u0246\u0248\u024A\u024C\u024E\u0370\u0372\u0376\u037F\u0386\u0388-\u038A\u038C\u038E\u038F\u0391-\u03A1\u03A3-\u03AB\u03CF\u03D2-\u03D4\u03D8\u03DA\u03DC\u03DE\u03E0\u03E2\u03E4\u03E6\u03E8\u03EA\u03EC\u03EE\u03F4\u03F7\u03F9\u03FA\u03FD-\u042F\u0460\u0462\u0464\u0466\u0468\u046A\u046C\u046E\u0470\u0472\u0474\u0476\u0478\u047A\u047C\u047E\u0480\u048A\u048C\u048E\u0490\u0492\u0494\u0496\u0498\u049A\u049C\u049E\u04A0\u04A2\u04A4\u04A6\u04A8\u04AA\u04AC\u04AE\u04B0\u04B2\u04B4\u04B6\u04B8\u04BA\u04BC\u04BE\u04C0\u04C1\u04C3\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04D2\u04D4\u04D6\u04D8\u04DA\u04DC\u04DE\u04E0\u04E2\u04E4\u04E6\u04E8\u04EA\u04EC\u04EE\u04F0\u04F2\u04F4\u04F6\u04F8\u04FA\u04FC\u04FE\u0500\u0502\u0504\u0506\u0508\u050A\u050C\u050E\u0510\u0512\u0514\u0516\u0518\u051A\u051C\u051E\u0520\u0522\u0524\u0526\u0528\u052A\u052C\u052E\u0531-\u0556\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0DE6-\u0DEF\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u10A0-\u10C5\u10C7\u10CD\u13A0-\u13F5\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u1C90-\u1CBA\u1CBD-\u1CBF\u1E00\u1E02\u1E04\u1E06\u1E08\u1E0A\u1E0C\u1E0E\u1E10\u1E12\u1E14\u1E16\u1E18\u1E1A\u1E1C\u1E1E\u1E20\u1E22\u1E24\u1E26\u1E28\u1E2A\u1E2C\u1E2E\u1E30\u1E32\u1E34\u1E36\u1E38\u1E3A\u1E3C\u1E3E\u1E40\u1E42\u1E44\u1E46\u1E48\u1E4A\u1E4C\u1E4E\u1E50\u1E52\u1E54\u1E56\u1E58\u1E5A\u1E5C\u1E5E\u1E60\u1E62\u1E64\u1E66\u1E68\u1E6A\u1E6C\u1E6E\u1E70\u1E72\u1E74\u1E76\u1E78\u1E7A\u1E7C\u1E7E\u1E80\u1E82\u1E84\u1E86\u1E88\u1E8A\u1E8C\u1E8E\u1E90\u1E92\u1E94\u1E9E\u1EA0\u1EA2\u1EA4\u1EA6\u1EA8\u1EAA\u1EAC\u1EAE\u1EB0\u1EB2\u1EB4\u1EB6\u1EB8\u1EBA\u1EBC\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1EC8\u1ECA\u1ECC\u1ECE\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EDA\u1EDC\u1EDE\u1EE0\u1EE2\u1EE4\u1EE6\u1EE8\u1EEA\u1EEC\u1EEE\u1EF0\u1EF2\u1EF4\u1EF6\u1EF8\u1EFA\u1EFC\u1EFE\u1F08-\u1F0F\u1F18-\u1F1D\u1F28-\u1F2F\u1F38-\u1F3F\u1F48-\u1F4D\u1F59\u1F5B\u1F5D\u1F5F\u1F68-\u1F6F\u1FB8-\u1FBB\u1FC8-\u1FCB\u1FD8-\u1FDB\u1FE8-\u1FEC\u1FF8-\u1FFB\u2102\u2107\u210B-\u210D\u2110-\u2112\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u2130-\u2133\u213E\u213F\u2145\u2183\u2C00-\u2C2E\u2C60\u2C62-\u2C64\u2C67\u2C69\u2C6B\u2C6D-\u2C70\u2C72\u2C75\u2C7E-\u2C80\u2C82\u2C84\u2C86\u2C88\u2C8A\u2C8C\u2C8E\u2C90\u2C92\u2C94\u2C96\u2C98\u2C9A\u2C9C\u2C9E\u2CA0\u2CA2\u2CA4\u2CA6\u2CA8\u2CAA\u2CAC\u2CAE\u2CB0\u2CB2\u2CB4\u2CB6\u2CB8\u2CBA\u2CBC\u2CBE\u2CC0\u2CC2\u2CC4\u2CC6\u2CC8\u2CCA\u2CCC\u2CCE\u2CD0\u2CD2\u2CD4\u2CD6\u2CD8\u2CDA\u2CDC\u2CDE\u2CE0\u2CE2\u2CEB\u2CED\u2CF2\uA620-\uA629\uA640\uA642\uA644\uA646\uA648\uA64A\uA64C\uA64E\uA650\uA652\uA654\uA656\uA658\uA65A\uA65C\uA65E\uA660\uA662\uA664\uA666\uA668\uA66A\uA66C\uA680\uA682\uA684\uA686\uA688\uA68A\uA68C\uA68E\uA690\uA692\uA694\uA696\uA698\uA69A\uA722\uA724\uA726\uA728\uA72A\uA72C\uA72E\uA732\uA734\uA736\uA738\uA73A\uA73C\uA73E\uA740\uA742\uA744\uA746\uA748\uA74A\uA74C\uA74E\uA750\uA752\uA754\uA756\uA758\uA75A\uA75C\uA75E\uA760\uA762\uA764\uA766\uA768\uA76A\uA76C\uA76E\uA779\uA77B\uA77D\uA77E\uA780\uA782\uA784\uA786\uA78B\uA78D\uA790\uA792\uA796\uA798\uA79A\uA79C\uA79E\uA7A0\uA7A2\uA7A4\uA7A6\uA7A8\uA7AA-\uA7AE\uA7B0-\uA7B4\uA7B6\uA7B8\uA7BA\uA7BC\uA7BE\uA7C2\uA7C4-\uA7C7\uA7C9\uA7F5\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uA9F0-\uA9F9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19\uFF21-\uFF3A]|\uD801[\uDC00-\uDC27\uDCA0-\uDCA9\uDCB0-\uDCD3]|\uD803[\uDC80-\uDCB2\uDD30-\uDD39]|\uD804[\uDC66-\uDC6F\uDCF0-\uDCF9\uDD36-\uDD3F\uDDD0-\uDDD9\uDEF0-\uDEF9]|[\uD805\uD807][\uDC50-\uDC59\uDCD0-\uDCD9\uDE50-\uDE59\uDEC0-\uDEC9\uDF30-\uDF39]|\uD806[\uDCA0-\uDCBF\uDCE0-\uDCE9\uDD50-\uDD59]|\uD81A[\uDE60-\uDE69\uDF50-\uDF59]|\uD81B[\uDE40-\uDE5F]|\uD835[\uDC00-\uDC19\uDC34-\uDC4D\uDC68-\uDC81\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB5\uDCD0-\uDCE9\uDD04\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD38\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD6C-\uDD85\uDDA0-\uDDB9\uDDD4-\uDDED\uDE08-\uDE21\uDE3C-\uDE55\uDE70-\uDE89\uDEA8-\uDEC0\uDEE2-\uDEFA\uDF1C-\uDF34\uDF56-\uDF6E\uDF90-\uDFA8\uDFCA\uDFCE-\uDFFF]|\uD838[\uDD40-\uDD49\uDEF0-\uDEF9]|\uD83A[\uDD00-\uDD21\uDD50-\uDD59]|\uD83E[\uDFF0-\uDFF9])(?:[\x2D0-9A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u0660-\u0669\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08C7\u0904-\u0939\u093D\u0950\u0958-\u0961\u0966-\u096F\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AE6-\u0AEF\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B6F\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0BE6-\u0BEF\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C66-\u0C6F\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D66-\u0D6F\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DE6-\u0DEF\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F20-\u0F29\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F-\u1049\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u1090-\u1099\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A16\u1A20-\u1A54\u1A80-\u1A89\u1A90-\u1A99\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B50-\u1B59\u1B83-\u1BA0\u1BAE-\u1BE5\u1C00-\u1C23\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\u9FFC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7BF\uA7C2-\uA7CA\uA7F5-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8D0-\uA8D9\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA900-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF-\uA9D9\uA9E0-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDD30-\uDD39\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC66-\uDC6F\uDC83-\uDCAF\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD03-\uDD26\uDD36-\uDD3F\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDEF0-\uDEF9\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC50-\uDC59\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE50-\uDE59\uDE80-\uDEAA\uDEB8\uDEC0-\uDEC9\uDF00-\uDF1A\uDF30-\uDF39]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCE9\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDD50-\uDD59\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD50-\uDD59\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDDA0-\uDDA9\uDEE0-\uDEF2\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82C[\uDC00-\uDD1E\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD40-\uDD49\uDD4E\uDEC0-\uDEEB\uDEF0-\uDEF9]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD83E[\uDFF0-\uDFF9]|\uD869[\uDC00-\uDEDD\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])*)+/;

// src/codemirror/beancount-stream-parser.ts
var sectionComment = /^\*.*/;
var comment2 = /^[#*;].*/;
var inlineComment = /^;.*/;
var string3 = /^"(?:[^\\]|\\.)*?"/;
var openString = /^"(?:[^\\]|\\.)*?$/;
var closeString = /^(?:[^\\]|\\.)*?"/;
var tag = /^#[A-Za-z0-9\-_/.]+/;
var commodity = /^[A-Z][A-Z0-9'._-]+[A-Z0-9]/;
var bool = /^TRUE|FALSE/;
var date2 = /^[0-9]{4,}[-/][0-9]+[-/][0-9]+/;
var number4 = /^-?(?:[0-9]+|[0-9][0-9,]+[0-9])(?:\.[0-9]*)?/;
var txn = /^([*!&#?%PSTCURM]|txn)/;
var undatedDirectives = /^(pushtag|poptag|pushmeta|popmeta|option|plugin|include)/;
var directives = /^(balance|open|close|commodity|pad|event|custom|price|note|query|document)/;
var link = /^\^[A-Za-z0-9\-_/.]+/;
var meta2 = /^[a-z][a-zA-Z0-9\-_]+:/;
var beancountStreamParser = {
  startState: () => ({ string: false }),
  token(stream, state) {
    if (state.string) {
      if (stream.match(closeString)) {
        state.string = false;
        return "string";
      }
      stream.skipToEnd();
      return "string";
    }
    if (stream.match(/\s+$/)) {
      return "invalid.special";
    }
    if (stream.eatSpace() || stream.eol()) {
      return null;
    }
    const sol = stream.sol();
    if (sol && stream.match(sectionComment)) {
      return "lineComment.special";
    }
    if (sol && stream.match(comment2)) {
      return "lineComment";
    }
    if (stream.match(tag) || stream.match(link)) {
      return "labelName";
    }
    if (stream.match(commodity)) {
      return "unit";
    }
    if (stream.match(meta2)) {
      return "propertyName";
    }
    if (sol && stream.match(undatedDirectives) || stream.match(directives) || stream.match(txn)) {
      return "keyword";
    }
    if (stream.match(inlineComment)) {
      return "comment";
    }
    if (stream.match(date2)) {
      return "number.special";
    }
    if (stream.match(number4)) {
      return "number";
    }
    if (stream.match(bool)) {
      return "bool";
    }
    if (stream.match(string3)) {
      if (stream.start === 7 && stream.string.startsWith("option ")) {
        return "string.standard";
      }
      return "string";
    }
    if (stream.match(openString)) {
      state.string = true;
      return "string.special";
    }
    if (stream.match(account_regex_default)) {
      return "className";
    }
    const char = stream.next();
    if (char === "@") {
      return "operator";
    }
    if (char === "{" || char === "}") {
      return "bracket";
    }
    stream.skipToEnd();
    return null;
  },
  languageData: {
    commentTokens: { line: ";" }
  }
};

// src/codemirror/beancount-autocomplete.ts
var undatedDirectives2 = ["option", "plugin", "include"];
var datedDirectives = [
  "*",
  "open",
  "close",
  "commodity",
  "balance",
  "pad",
  "note",
  "document",
  "price",
  "event",
  "query"
];
var res = (s, from) => ({
  options: s.map((label) => ({ label })),
  from
});
var lang = StreamLanguage.define(beancountStreamParser);
var directiveCompletions = {
  open: [accounts, currencies],
  close: [accounts],
  commodity: [currencies],
  balance: [accounts, null, currencies],
  pad: [accounts, accounts],
  note: [accounts],
  document: [accounts],
  price: [currencies, null, currencies]
};
var beancountCompletion = (context) => {
  const { state, pos } = context;
  const { doc: doc2 } = state;
  const tag2 = context.matchBefore(/#[A-Za-z0-9\-_/.]*/);
  if (tag2) {
    return res(get_store_value(tags), tag2.from + 1);
  }
  const link2 = context.matchBefore(/\^[A-Za-z0-9\-_/.]*/);
  if (link2) {
    return res(get_store_value(links), link2.from + 1);
  }
  const indented = context.matchBefore(/^\s+[A-Z]\S*/);
  if (indented) {
    const indentation = indented.text.length - indented.text.trimLeft().length;
    return res(get_store_value(accounts), indented.from + indentation);
  }
  const line = doc2.lineAt(pos);
  if (context.matchBefore(/\d+/)) {
    return { options: beancountSnippets(), from: line.from };
  }
  const currentWord = context.matchBefore(/\S*/);
  if ((currentWord == null ? void 0 : currentWord.from) === line.from && line.length > 0) {
    return res(undatedDirectives2, line.from);
  }
  const lineContent = doc2.sliceString(line.from, pos);
  const node = lang.parser.parse(lineContent).cursor();
  const tokens = [];
  while (node.next()) {
    if (node.name !== "invalid.special") {
      tokens.push({ name: node.name, from: node.from, to: node.to });
    }
  }
  if (tokens.length > 0) {
    const first = tokens[0];
    const last = tokens[tokens.length - 1];
    const lineFrom = line.from;
    if (first.name === "number.special" && line.length > last.to) {
      if (tokens.length === 1) {
        return res(datedDirectives, lineFrom + first.to + 1);
      }
      const directive = lineContent.slice(tokens[1].from, tokens[1].to);
      const compl = directiveCompletions[directive];
      if (compl) {
        const completions2 = compl[tokens.length - 2];
        if (completions2) {
          return res(get_store_value(completions2), lineFrom + last.to + 1);
        }
      }
      if (directive === "txn" || directive.length === 1) {
        if (tokens.length === 3 || last.name === "string.special") {
          return res(get_store_value(payees), lineFrom + last.from + 1);
        }
      }
    }
    if (last.name === "number" && line.length > last.to) {
      return res(get_store_value(currencies), lineFrom + last.to + 1);
    }
  }
  return null;
};

// src/codemirror/beancount-fold.ts
var MAXDEPTH = 100;
function headerLevel(line) {
  const match = /^\*+/.exec(line);
  return match ? match[0].length : MAXDEPTH;
}
var beancountFold = foldService.of(({ doc: doc2 }, lineStart, lineEnd) => {
  const startLine = doc2.lineAt(lineStart);
  const totalLines = doc2.lines;
  const level = headerLevel(startLine.text);
  if (level === MAXDEPTH) {
    return null;
  }
  let lineNo = startLine.number;
  let end = startLine.to;
  while (lineNo < totalLines) {
    lineNo += 1;
    const line = doc2.line(lineNo);
    if (headerLevel(line.text) <= level) {
      break;
    }
    end = line.to;
  }
  return { from: lineEnd, to: end };
});

// src/codemirror/beancount-format.ts
var beancountFormat = (cm) => {
  put("format_source", { source: cm.state.doc.toString() }).then(
    (data) => {
      cm.dispatch({
        changes: { from: 0, to: cm.state.doc.length, insert: data }
      });
    },
    (error) => {
      if (error instanceof Error) {
        notify(error.message, "error");
      }
    }
  );
  return true;
};

// src/codemirror/beancount-highlight.ts
var beancountHighlight = HighlightStyle.define([
  {
    tag: tags2.special(tags2.number),
    color: "var(--editor-date)"
  },
  {
    tag: tags2.className,
    color: "var(--editor-account)"
  },
  {
    tag: tags2.comment,
    color: "var(--editor-comment)"
  },
  {
    tag: tags2.special(tags2.lineComment),
    color: "var(--editor-comment)",
    border: "solid 1px var(--editor-comment)",
    borderRadius: "2px",
    paddingRight: "10px",
    fontWeight: "500"
  },
  {
    tag: tags2.unit,
    color: "#708"
  },
  {
    tag: tags2.keyword,
    fontWeight: "500",
    color: "var(--editor-directive)"
  },
  {
    tag: tags2.standard(tags2.string),
    color: "var(--editor-class)"
  },
  {
    tag: tags2.invalid,
    color: "var(--editor-invalid)"
  },
  {
    tag: tags2.special(tags2.invalid),
    backgroundColor: "var(--editor-trailing-whitespace)"
  }
]);

// src/codemirror/beancount-indent.ts
var beancountIndent = indentService.of((context, pos) => {
  const textAfterPos = context.textAfterPos(pos);
  if (/^\s*\d\d\d\d/.exec(textAfterPos)) {
    return null;
  }
  const line = context.state.doc.lineAt(pos);
  if (/^\s+\S+/.exec(line.text) || /^\d\d\d\d/.exec(line.text)) {
    return context.unit;
  }
  return null;
});

// src/codemirror/beancount.ts
var beancountLanguage = StreamLanguage.define(beancountStreamParser);
var beancount = new LanguageSupport(beancountLanguage, [
  beancountFold,
  syntaxHighlighting(beancountHighlight),
  beancountIndent,
  keymap.of([{ key: "Control-d", mac: "Meta-d", run: beancountFormat }]),
  beancountLanguage.data.of({
    autocomplete: beancountCompletion,
    indentOnInput: /^\s+\d\d\d\d/
  })
]);

// src/codemirror/bql-grammar.ts
var bql_grammar_default = {
  columns: [
    "account",
    "balance",
    "change",
    "cost_currency",
    "cost_date",
    "cost_label",
    "cost_number",
    "currency",
    "date",
    "day",
    "description",
    "filename",
    "flag",
    "id",
    "lineno",
    "links",
    "location",
    "month",
    "narration",
    "number",
    "other_accounts",
    "payee",
    "position",
    "posting_flag",
    "price",
    "tags",
    "type",
    "weight",
    "year"
  ],
  functions: [
    "abs",
    "account_sortkey",
    "any_meta",
    "close_date",
    "coalesce",
    "commodity",
    "commodity_meta",
    "convert",
    "cost",
    "count",
    "currency",
    "currency_meta",
    "date",
    "date_add",
    "date_diff",
    "day",
    "entry_meta",
    "filter_currency",
    "findfirst",
    "first",
    "getitem",
    "getprice",
    "grep",
    "grepn",
    "joinstr",
    "last",
    "leaf",
    "length",
    "lower",
    "max",
    "maxwidth",
    "meta",
    "min",
    "month",
    "neg",
    "number",
    "only",
    "open_date",
    "open_meta",
    "parent",
    "possign",
    "quarter",
    "root",
    "safediv",
    "str",
    "subst",
    "sum",
    "today",
    "units",
    "upper",
    "value",
    "weekday",
    "year",
    "ymonth"
  ],
  keywords: [
    "and",
    "as",
    "asc",
    "at",
    "balances",
    "by",
    "clear",
    "close",
    "desc",
    "distinct",
    "errors",
    "explain",
    "false",
    "flatten",
    "from",
    "group",
    "having",
    "in",
    "journal",
    "limit",
    "not",
    "null",
    "on",
    "open",
    "or",
    "order",
    "pivot",
    "print",
    "reload",
    "run",
    "select",
    "true",
    "where"
  ]
};

// src/codemirror/bql-autocomplete.ts
var { columns, functions, keywords } = bql_grammar_default;
var completions = [...columns, ...functions.map((f) => `${f}(`), ...keywords];
var allCompletionOptions = completions.map((label) => ({ label }));
var commands = [
  "balances",
  "errors",
  "explain",
  "help",
  "lex",
  "parse",
  "print",
  "runcustom",
  "select",
  "tokenize"
];
var firstWordCompletions = commands.map((label) => ({ label }));
var bqlCompletion = (context) => {
  const token = context.matchBefore(/\w+/);
  if (!token) {
    return null;
  }
  if (token.from === 0) {
    return { from: token.from, options: firstWordCompletions };
  }
  return { from: token.from, options: allCompletionOptions };
};

// src/codemirror/bql-stream-parser.ts
var keywords2 = new Set(bql_grammar_default.keywords);
var columns2 = new Set(bql_grammar_default.columns);
var functions2 = new Set(bql_grammar_default.functions);
var string4 = /^("[^"]*"|'[^']*')/;
var date3 = /^(?:#(?:"[^"]*"|'[^']*')|\d\d\d\d-\d\d-\d\d)/;
var decimal = /^[-+]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)/;
var integer = /^[-+]?[0-9]+/;
var bqlStreamParser = {
  token(stream) {
    if (stream.eatSpace() || stream.eol()) {
      return null;
    }
    if (stream.match(string4)) {
      return "string";
    }
    if (stream.match(date3) || stream.match(decimal) || stream.match(integer)) {
      return "number";
    }
    if (stream.match(/\w+/)) {
      const word = stream.current().toLowerCase();
      if (keywords2.has(word)) {
        return "keyword";
      }
      if (columns2.has(word)) {
        return "typeName";
      }
      if (functions2.has(word) && stream.peek() === "(") {
        return "macroName";
      }
      return "name";
    }
    const char = stream.next();
    if (char === "*") {
      return "typeName";
    }
    return null;
  }
};

// src/codemirror/bql.ts
var bqlLanguage = StreamLanguage.define(bqlStreamParser);
var bql = new LanguageSupport(
  bqlLanguage,
  bqlLanguage.data.of({
    autocomplete: bqlCompletion
  })
);

// src/codemirror/setup.ts
var baseExtensions = [
  lineNumbers(),
  highlightSpecialChars(),
  history(),
  foldGutter(),
  drawSelection(),
  EditorState.allowMultipleSelections.of(true),
  indentOnInput(),
  syntaxHighlighting(defaultHighlightStyle),
  bracketMatching(),
  closeBrackets(),
  autocompletion(),
  rectangularSelection(),
  highlightActiveLine(),
  highlightSelectionMatches(),
  keymap.of([
    ...closeBracketsKeymap,
    ...defaultKeymap,
    ...searchKeymap,
    ...historyKeymap,
    ...foldKeymap,
    ...completionKeymap,
    ...lintKeymap,
    indentWithTab
  ])
];
function setup(value, extensions) {
  const view = new EditorView({
    state: EditorState.create({ doc: value, extensions })
  });
  return [view, (el) => el.appendChild(view.dom)];
}
function initDocumentPreviewEditor(value) {
  return setup(value, [
    baseExtensions,
    EditorState.readOnly.of(true),
    placeholder("Loading...")
  ]);
}
var BeancountTextarea = class extends HTMLTextAreaElement {
  constructor() {
    var _a2;
    super();
    const [view] = setup(this.value, [
      beancount,
      syntaxHighlighting(defaultHighlightStyle),
      EditorView.editable.of(false)
    ]);
    (_a2 = this.parentNode) == null ? void 0 : _a2.insertBefore(view.dom, this);
    this.style.display = "none";
  }
};
function initBeancountEditor(value, onDocChanges, commands2) {
  return setup(value, [
    beancount,
    indentUnit.of(" ".repeat(get_store_value(fava_options).indent)),
    keymap.of(commands2),
    EditorView.updateListener.of((update2) => {
      if (update2.docChanged) {
        onDocChanges(update2.state);
      }
    }),
    baseExtensions
  ]);
}
function initReadonlyQueryEditor(value) {
  return setup(value, [
    bql,
    syntaxHighlighting(defaultHighlightStyle),
    EditorView.editable.of(false)
  ]);
}
function initQueryEditor(value, onDocChanges, _placeholder, submit) {
  return setup(value, [
    bql,
    EditorView.updateListener.of((update2) => {
      if (update2.docChanged) {
        onDocChanges(update2.state);
      }
    }),
    keymap.of([
      {
        key: "Control-Enter",
        mac: "Meta-Enter",
        run: () => {
          submit();
          return true;
        }
      }
    ]),
    placeholder(_placeholder),
    baseExtensions
  ]);
}

// src/stores/journal.ts
var defaultValue2 = [
  "balance",
  "budget",
  "cleared",
  "custom",
  "discovered",
  "document",
  "note",
  "pending",
  "query",
  "statement",
  "transaction"
];
var journalShow = localStorageSyncedStore(
  "journal-show",
  array(string),
  () => defaultValue2
);
var defaultSortOrder = ["date", "desc"];
var journalSortOrder = localStorageSyncedStore(
  "journal-sort-order",
  tuple([string, union(constant("asc"), constant("desc"))]),
  () => defaultSortOrder
);

// src/sort.ts
function parseNumber(num) {
  const cleaned = num.replace(/[^\-?0-9.]/g, "");
  const n = parseFloat(cleaned);
  return Number.isNaN(n) ? 0 : n;
}
function stringComparator(A, B) {
  const a = A.toLowerCase();
  const b = B.toLowerCase();
  if (a === b) {
    return 0;
  }
  return a < b ? -1 : 1;
}
function numComparator(a, b) {
  return parseNumber(a) - parseNumber(b);
}
function getValue(el) {
  return (el == null ? void 0 : el.getAttribute("data-sort-value")) || (el == null ? void 0 : el.textContent) || "";
}
function sortFunc(type, order, getter) {
  const comparator = type === "num" ? numComparator : stringComparator;
  function func(a, b) {
    return (order === "asc" ? 1 : -1) * comparator(getter(a), getter(b));
  }
  return func;
}
function sortElements(parent2, elements, selector, order, type) {
  const sortFunction = sortFunc(type, order, (a) => getValue(selector(a)));
  const fragment = document.createDocumentFragment();
  elements.sort(sortFunction).forEach((el) => {
    fragment.appendChild(el);
  });
  parent2.appendChild(fragment);
}
function getSortOrder(headerElement) {
  if (!headerElement.getAttribute("data-order")) {
    return headerElement.getAttribute("data-sort-default") === "desc" ? "desc" : "asc";
  }
  return headerElement.getAttribute("data-order") === "asc" ? "desc" : "asc";
}
function sortableJournal(ol) {
  const head = ol.querySelector(".head");
  if (!head) {
    throw new Error("Journal is missing header.");
  }
  const headers = head.querySelectorAll("span[data-sort]");
  const [initialColumn, initialOrder] = get_store_value(journalSortOrder);
  headers.forEach((header) => {
    const headerClass = header.classList[0];
    const name2 = header.getAttribute("data-sort-name");
    const type = header.getAttribute("data-sort");
    if (!headerClass || !name2 || !type) {
      throw new Error(`Journal has invalid header: ${header.innerHTML}.`);
    }
    const sort = (order) => {
      headers.forEach((el) => el.removeAttribute("data-order"));
      header.setAttribute("data-order", order);
      sortElements(
        ol,
        [].slice.call(ol.children, 1),
        (li) => li.querySelector(`.${headerClass}`),
        order,
        type
      );
    };
    if (name2 === initialColumn) {
      sort(initialOrder);
    }
    header.addEventListener("click", () => {
      const order = getSortOrder(header);
      sort(order);
      journalSortOrder.set([name2, order]);
    });
  });
}
var SortableTable = class extends HTMLTableElement {
  constructor() {
    super();
    const body = this.tBodies.item(0);
    if (!this.tHead || !body) {
      return;
    }
    const headers = [...this.tHead.querySelectorAll("th[data-sort]")];
    headers.forEach((header) => {
      header.addEventListener("click", () => {
        const order = getSortOrder(header);
        const type = header.getAttribute("data-sort");
        const index2 = headers.indexOf(header);
        headers.forEach((el) => {
          el.removeAttribute("data-order");
        });
        header.setAttribute("data-order", order);
        sortElements(
          body,
          [...body.querySelectorAll("tr")],
          (tr) => tr.cells.item(index2),
          order,
          type
        );
      });
    });
  }
};

// src/keyboard-shortcuts.ts
function showTooltip2(target) {
  var _a2;
  const tooltip2 = document.createElement("div");
  const isHidden = target.classList.contains("hidden");
  if (isHidden) {
    target.classList.remove("hidden");
  }
  tooltip2.className = "keyboard-tooltip";
  tooltip2.textContent = (_a2 = target.getAttribute("data-key")) != null ? _a2 : "";
  document.body.appendChild(tooltip2);
  const parentCoords = target.getBoundingClientRect();
  const left2 = parentCoords.left + Math.min((target.offsetWidth - tooltip2.offsetWidth) / 2, 10);
  const top3 = parentCoords.top + (target.offsetHeight - tooltip2.offsetHeight) / 2;
  tooltip2.style.left = `${left2}px`;
  tooltip2.style.top = `${top3 + window.pageYOffset}px`;
  return () => {
    tooltip2.remove();
    if (isHidden) {
      target.classList.add("hidden");
    }
  };
}
function showTooltips() {
  const removes = [];
  document.querySelectorAll("[data-key]").forEach((el) => {
    if (el instanceof HTMLElement) {
      removes.push(showTooltip2(el));
    }
  });
  return () => {
    removes.forEach((r) => r());
  };
}
function isEditableElement(element2) {
  return element2 instanceof HTMLElement && (element2 instanceof HTMLInputElement || element2 instanceof HTMLSelectElement || element2 instanceof HTMLTextAreaElement || element2.isContentEditable);
}
var keyboardShortcuts = /* @__PURE__ */ new Map();
var lastChar = "";
function keydown(event) {
  var _a2;
  if (isEditableElement(event.target)) {
    return;
  }
  let eventKey = event.key;
  if (event.metaKey) {
    eventKey = `Meta+${eventKey}`;
  }
  if (event.altKey) {
    eventKey = `Alt+${eventKey}`;
  }
  if (event.ctrlKey) {
    eventKey = `Control+${eventKey}`;
  }
  const lastTwoKeys = `${lastChar} ${eventKey}`;
  const handler = (_a2 = keyboardShortcuts.get(lastTwoKeys)) != null ? _a2 : keyboardShortcuts.get(eventKey);
  if (handler) {
    if (handler instanceof HTMLInputElement) {
      event.preventDefault();
      handler.focus();
    } else if (handler instanceof HTMLElement) {
      handler.click();
    } else {
      handler(event);
    }
  }
  if (event.key !== "Alt" && event.key !== "Control" && event.key !== "Shift") {
    lastChar = eventKey;
  }
}
document.addEventListener("keydown", keydown);
var currentPlatform2 = typeof navigator !== "undefined" && /Mac/.test(navigator.platform) ? "mac" : "key";
var modKey = currentPlatform2 === "mac" ? "Cmd" : "Ctrl";
function getKeySpecKey(keySpec) {
  if (typeof keySpec === "string") {
    return keySpec;
  }
  return currentPlatform2 === "mac" ? keySpec.mac : keySpec.key;
}
function bindKey(keySpec, handler) {
  const key = getKeySpecKey(keySpec);
  const sequence = key.split(" ");
  if (sequence.length > 2) {
    console.error("Only key sequences of length <=2 are supported: ", key);
  }
  if (keyboardShortcuts.has(key)) {
    console.warn("Duplicate keyboard shortcut: ", key, handler);
  }
  keyboardShortcuts.set(key, handler);
  return () => {
    keyboardShortcuts.delete(key);
  };
}
function keyboardShortcut(node, key) {
  if (!key) {
    return {};
  }
  node.setAttribute("data-key", key);
  const destroy = bindKey(key, node);
  return { destroy };
}
function initCurrentKeyboardShortcuts() {
  for (const [key, action] of keyboardShortcuts.entries()) {
    if (action instanceof HTMLElement && !document.contains(action)) {
      keyboardShortcuts.delete(key);
    }
  }
  document.querySelectorAll("[data-keyboard-shortcut]").forEach((element2) => {
    const key = element2.getAttribute("data-keyboard-shortcut");
    if (key && element2 instanceof HTMLElement) {
      element2.removeAttribute("data-keyboard-shortcut");
      element2.setAttribute("data-key", key);
      bindKey(key, element2);
    }
  });
}
function initGlobalKeyboardShortcuts() {
  bindKey("?", () => {
    const hide2 = showTooltips();
    const once = () => {
      hide2();
      document.removeEventListener("mousedown", once);
      document.removeEventListener("keydown", once);
    };
    document.addEventListener("mousedown", once);
    document.addEventListener("keydown", once);
  });
}

// src/journal/JournalFilters.svelte
function get_each_context(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[4] = list[i][0];
  child_ctx[5] = list[i][1];
  child_ctx[6] = list[i][2];
  child_ctx[7] = list[i][3];
  child_ctx[8] = list[i][4];
  return child_ctx;
}
function create_each_block(ctx2) {
  let button;
  let t0_value = ctx2[5] + "";
  let t03;
  let t13;
  let button_title_value;
  let keyboardShortcut_action;
  let mounted;
  let dispose;
  function click_handler() {
    return ctx2[3](ctx2[4]);
  }
  return {
    c() {
      var _a2;
      button = element("button");
      t03 = text(t0_value);
      t13 = space();
      attr(button, "type", "button");
      attr(button, "title", button_title_value = (_a2 = ctx2[6]) != null ? _a2 : format2(toggleText, { type: ctx2[5] }));
      toggle_class(button, "inactive", !ctx2[0](ctx2[4], ctx2[8]));
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, t03);
      append(button, t13);
      if (!mounted) {
        dispose = [
          action_destroyer(keyboardShortcut_action = keyboardShortcut.call(null, button, ctx2[7])),
          listen(button, "click", click_handler)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & 1) {
        toggle_class(button, "inactive", !ctx2[0](ctx2[4], ctx2[8]));
      }
    },
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_fragment(ctx2) {
  let form;
  let each_value = buttons;
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block(get_each_context(ctx2, each_value, i));
  }
  return {
    c() {
      form = element("form");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(form, "class", "flex-row svelte-h52b2r");
    },
    m(target, anchor) {
      insert(target, form, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(form, null);
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & 1) {
        each_value = buttons;
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(form, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(form);
      destroy_each(each_blocks, detaching);
    }
  };
}
var toggleText = _("Toggle %(type)s entries");
var buttons = [
  ["open", "Open", null, "s o"],
  ["close", "Close", null, "s c"],
  ["transaction", "Transaction", null, "s t"],
  ["cleared", "*", _("Cleared transactions"), "t c", "transaction"],
  ["pending", "!", _("Pending transactions"), "t p", "transaction"],
  ["other", "x", _("Other transactions"), "t o", "transaction"],
  ["balance", "Balance", null, "s b"],
  ["note", "Note", null, "s n"],
  ["document", "Document", null, "s d"],
  ["discovered", "D", _("Documents with a #discovered tag"), "d d", "document"],
  ["linked", "L", _("Documents with a #linked tag"), "d l", "document"],
  ["pad", "Pad", null, "s p"],
  ["query", "Query", null, "s q"],
  ["custom", "Custom", null, "s C"],
  ["budget", "B", _("Budget entries"), "s B", "custom"],
  ["metadata", _("Metadata"), _("Toggle metadata"), "m"],
  ["postings", _("Postings"), _("Toggle postings"), "p"]
];
function toggle(type) {
  journalShow.update((show) => {
    const set = new Set(show);
    const toggle_func = set.has(type) ? set.delete.bind(set) : set.add.bind(set);
    toggle_func(type);
    buttons.filter((b) => b[4] === type).forEach((b) => toggle_func(b[0]));
    return [...set].sort();
  });
}
function instance($$self, $$props, $$invalidate) {
  let shownSet;
  let active;
  let $journalShow;
  component_subscribe($$self, journalShow, ($$value) => $$invalidate(2, $journalShow = $$value));
  const click_handler = (type) => toggle(type);
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 4) {
      $:
        $$invalidate(1, shownSet = new Set($journalShow));
    }
    if ($$self.$$.dirty & 2) {
      $:
        $$invalidate(0, active = (type, supertype) => supertype ? shownSet.has(type) && shownSet.has(supertype) : shownSet.has(type));
    }
  };
  return [active, shownSet, $journalShow, click_handler];
}
var JournalFilters = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance, create_fragment, safe_not_equal, {});
  }
};
var JournalFilters_default = JournalFilters;

// src/journal/index.ts
function escape(value) {
  return value.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");
}
function addFilter(value) {
  fql_filter.update(
    (fql_filter_val) => fql_filter_val ? `${fql_filter_val} ${value}` : value
  );
}
function handleClick({ target }) {
  if (!(target instanceof HTMLElement) || target instanceof HTMLAnchorElement) {
    return;
  }
  if (target.className === "tag" || target.className === "link") {
    addFilter(target.innerText);
  } else if (target.className === "payee") {
    addFilter(`payee:"^${escape(target.innerText)}$"`);
  } else if (target.tagName === "DT") {
    const expr = `${target.innerText}""`;
    if (target.closest(".postings")) {
      addFilter(`any(${expr})`);
    } else {
      addFilter(expr);
    }
  } else if (target.tagName === "DD") {
    const key = target.previousElementSibling.innerText;
    const value = `"^${escape(target.innerText)}$"`;
    const expr = `${key}${value}`;
    if (target.closest(".postings")) {
      addFilter(`any(${expr})`);
    } else {
      addFilter(expr);
    }
  } else if (target.closest(".indicators")) {
    const entry = target.closest(".transaction");
    if (entry) {
      entry.classList.toggle("show-postings");
    }
  }
}
var FavaJournal = class extends HTMLElement {
  connectedCallback() {
    const ol = this.querySelector("ol");
    if (!ol) {
      throw new Error("fava-journal is missing its <ol>");
    }
    this.unsubscribe = journalShow.subscribe((show) => {
      const classes = [...show].map((s) => `show-${s}`).join(" ");
      ol.className = `flex-table journal ${classes}`;
    });
    this.component = new JournalFilters_default({ target: this, anchor: ol });
    sortableJournal(ol);
    delegate(this, "click", "li", handleClick);
  }
  disconnectedCallback() {
    var _a2, _b;
    (_a2 = this.unsubscribe) == null ? void 0 : _a2.call(this);
    (_b = this.component) == null ? void 0 : _b.$destroy();
  }
};

// src/sidebar/index.ts
function updateSidebar() {
  document.querySelectorAll("aside a").forEach((el) => {
    el.classList.remove("selected");
    const href = el.getAttribute("href");
    if (!el.hasAttribute("data-remote") && (href == null ? void 0 : href.includes(window.location.pathname)) && !el.matches(".submenu a")) {
      el.classList.add("selected");
    }
  });
}
function initErrorCount() {
  const el = document.getElementById("error-count");
  if (el instanceof HTMLLIElement) {
    errorCount.subscribe((count2) => {
      el.classList.toggle("hidden", count2 === 0);
      const span = el.querySelector("span");
      if (span) {
        span.textContent = `${count2}`;
      }
    });
  }
}
function initAsideButton() {
  const el = document.getElementById("aside-button");
  if (el instanceof HTMLButtonElement) {
    el.addEventListener("click", () => {
      var _a2;
      (_a2 = document.querySelector("aside")) == null ? void 0 : _a2.classList.toggle("active");
      el.classList.toggle("active");
    });
  }
}
function initSidebar() {
  initErrorCount();
  initAsideButton();
}

// node_modules/d3-axis/src/identity.js
function identity_default2(x2) {
  return x2;
}

// node_modules/d3-axis/src/axis.js
var top2 = 1;
var right = 2;
var bottom = 3;
var left = 4;
var epsilon = 1e-6;
function translateX(x2) {
  return "translate(" + x2 + ",0)";
}
function translateY(y2) {
  return "translate(0," + y2 + ")";
}
function number5(scale) {
  return (d) => +scale(d);
}
function center(scale, offset) {
  offset = Math.max(0, scale.bandwidth() - offset * 2) / 2;
  if (scale.round())
    offset = Math.round(offset);
  return (d) => +scale(d) + offset;
}
function entering() {
  return !this.__axis;
}
function axis(orient, scale) {
  var tickArguments = [], tickValues = null, tickFormat2 = null, tickSizeInner = 6, tickSizeOuter = 6, tickPadding = 3, offset = typeof window !== "undefined" && window.devicePixelRatio > 1 ? 0 : 0.5, k = orient === top2 || orient === left ? -1 : 1, x2 = orient === left || orient === right ? "x" : "y", transform = orient === top2 || orient === bottom ? translateX : translateY;
  function axis2(context) {
    var values = tickValues == null ? scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain() : tickValues, format3 = tickFormat2 == null ? scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments) : identity_default2 : tickFormat2, spacing = Math.max(tickSizeInner, 0) + tickPadding, range2 = scale.range(), range0 = +range2[0] + offset, range1 = +range2[range2.length - 1] + offset, position = (scale.bandwidth ? center : number5)(scale.copy(), offset), selection2 = context.selection ? context.selection() : context, path2 = selection2.selectAll(".domain").data([null]), tick2 = selection2.selectAll(".tick").data(values, scale).order(), tickExit = tick2.exit(), tickEnter = tick2.enter().append("g").attr("class", "tick"), line = tick2.select("line"), text2 = tick2.select("text");
    path2 = path2.merge(path2.enter().insert("path", ".tick").attr("class", "domain").attr("stroke", "currentColor"));
    tick2 = tick2.merge(tickEnter);
    line = line.merge(tickEnter.append("line").attr("stroke", "currentColor").attr(x2 + "2", k * tickSizeInner));
    text2 = text2.merge(tickEnter.append("text").attr("fill", "currentColor").attr(x2, k * spacing).attr("dy", orient === top2 ? "0em" : orient === bottom ? "0.71em" : "0.32em"));
    if (context !== selection2) {
      path2 = path2.transition(context);
      tick2 = tick2.transition(context);
      line = line.transition(context);
      text2 = text2.transition(context);
      tickExit = tickExit.transition(context).attr("opacity", epsilon).attr("transform", function(d) {
        return isFinite(d = position(d)) ? transform(d + offset) : this.getAttribute("transform");
      });
      tickEnter.attr("opacity", epsilon).attr("transform", function(d) {
        var p = this.parentNode.__axis;
        return transform((p && isFinite(p = p(d)) ? p : position(d)) + offset);
      });
    }
    tickExit.remove();
    path2.attr("d", orient === left || orient === right ? tickSizeOuter ? "M" + k * tickSizeOuter + "," + range0 + "H" + offset + "V" + range1 + "H" + k * tickSizeOuter : "M" + offset + "," + range0 + "V" + range1 : tickSizeOuter ? "M" + range0 + "," + k * tickSizeOuter + "V" + offset + "H" + range1 + "V" + k * tickSizeOuter : "M" + range0 + "," + offset + "H" + range1);
    tick2.attr("opacity", 1).attr("transform", function(d) {
      return transform(position(d) + offset);
    });
    line.attr(x2 + "2", k * tickSizeInner);
    text2.attr(x2, k * spacing).text(format3);
    selection2.filter(entering).attr("fill", "none").attr("font-size", 10).attr("font-family", "sans-serif").attr("text-anchor", orient === right ? "start" : orient === left ? "end" : "middle");
    selection2.each(function() {
      this.__axis = position;
    });
  }
  axis2.scale = function(_2) {
    return arguments.length ? (scale = _2, axis2) : scale;
  };
  axis2.ticks = function() {
    return tickArguments = Array.from(arguments), axis2;
  };
  axis2.tickArguments = function(_2) {
    return arguments.length ? (tickArguments = _2 == null ? [] : Array.from(_2), axis2) : tickArguments.slice();
  };
  axis2.tickValues = function(_2) {
    return arguments.length ? (tickValues = _2 == null ? null : Array.from(_2), axis2) : tickValues && tickValues.slice();
  };
  axis2.tickFormat = function(_2) {
    return arguments.length ? (tickFormat2 = _2, axis2) : tickFormat2;
  };
  axis2.tickSize = function(_2) {
    return arguments.length ? (tickSizeInner = tickSizeOuter = +_2, axis2) : tickSizeInner;
  };
  axis2.tickSizeInner = function(_2) {
    return arguments.length ? (tickSizeInner = +_2, axis2) : tickSizeInner;
  };
  axis2.tickSizeOuter = function(_2) {
    return arguments.length ? (tickSizeOuter = +_2, axis2) : tickSizeOuter;
  };
  axis2.tickPadding = function(_2) {
    return arguments.length ? (tickPadding = +_2, axis2) : tickPadding;
  };
  axis2.offset = function(_2) {
    return arguments.length ? (offset = +_2, axis2) : offset;
  };
  return axis2;
}
function axisBottom(scale) {
  return axis(bottom, scale);
}
function axisLeft(scale) {
  return axis(left, scale);
}

// node_modules/d3-scale/src/init.js
function initRange(domain, range2) {
  switch (arguments.length) {
    case 0:
      break;
    case 1:
      this.range(domain);
      break;
    default:
      this.range(range2).domain(domain);
      break;
  }
  return this;
}

// node_modules/d3-scale/src/ordinal.js
var implicit = Symbol("implicit");
function ordinal() {
  var index2 = new InternMap(), domain = [], range2 = [], unknown2 = implicit;
  function scale(d) {
    let i = index2.get(d);
    if (i === void 0) {
      if (unknown2 !== implicit)
        return unknown2;
      index2.set(d, i = domain.push(d) - 1);
    }
    return range2[i % range2.length];
  }
  scale.domain = function(_2) {
    if (!arguments.length)
      return domain.slice();
    domain = [], index2 = new InternMap();
    for (const value of _2) {
      if (index2.has(value))
        continue;
      index2.set(value, domain.push(value) - 1);
    }
    return scale;
  };
  scale.range = function(_2) {
    return arguments.length ? (range2 = Array.from(_2), scale) : range2.slice();
  };
  scale.unknown = function(_2) {
    return arguments.length ? (unknown2 = _2, scale) : unknown2;
  };
  scale.copy = function() {
    return ordinal(domain, range2).unknown(unknown2);
  };
  initRange.apply(scale, arguments);
  return scale;
}

// node_modules/d3-scale/src/band.js
function band() {
  var scale = ordinal().unknown(void 0), domain = scale.domain, ordinalRange = scale.range, r0 = 0, r1 = 1, step, bandwidth, round = false, paddingInner = 0, paddingOuter = 0, align = 0.5;
  delete scale.unknown;
  function rescale() {
    var n = domain().length, reverse = r1 < r0, start = reverse ? r1 : r0, stop = reverse ? r0 : r1;
    step = (stop - start) / Math.max(1, n - paddingInner + paddingOuter * 2);
    if (round)
      step = Math.floor(step);
    start += (stop - start - step * (n - paddingInner)) * align;
    bandwidth = step * (1 - paddingInner);
    if (round)
      start = Math.round(start), bandwidth = Math.round(bandwidth);
    var values = range(n).map(function(i) {
      return start + step * i;
    });
    return ordinalRange(reverse ? values.reverse() : values);
  }
  scale.domain = function(_2) {
    return arguments.length ? (domain(_2), rescale()) : domain();
  };
  scale.range = function(_2) {
    return arguments.length ? ([r0, r1] = _2, r0 = +r0, r1 = +r1, rescale()) : [r0, r1];
  };
  scale.rangeRound = function(_2) {
    return [r0, r1] = _2, r0 = +r0, r1 = +r1, round = true, rescale();
  };
  scale.bandwidth = function() {
    return bandwidth;
  };
  scale.step = function() {
    return step;
  };
  scale.round = function(_2) {
    return arguments.length ? (round = !!_2, rescale()) : round;
  };
  scale.padding = function(_2) {
    return arguments.length ? (paddingInner = Math.min(1, paddingOuter = +_2), rescale()) : paddingInner;
  };
  scale.paddingInner = function(_2) {
    return arguments.length ? (paddingInner = Math.min(1, _2), rescale()) : paddingInner;
  };
  scale.paddingOuter = function(_2) {
    return arguments.length ? (paddingOuter = +_2, rescale()) : paddingOuter;
  };
  scale.align = function(_2) {
    return arguments.length ? (align = Math.max(0, Math.min(1, _2)), rescale()) : align;
  };
  scale.copy = function() {
    return band(domain(), [r0, r1]).round(round).paddingInner(paddingInner).paddingOuter(paddingOuter).align(align);
  };
  return initRange.apply(rescale(), arguments);
}
function pointish(scale) {
  var copy2 = scale.copy;
  scale.padding = scale.paddingOuter;
  delete scale.paddingInner;
  delete scale.paddingOuter;
  scale.copy = function() {
    return pointish(copy2());
  };
  return scale;
}
function point() {
  return pointish(band.apply(null, arguments).paddingInner(1));
}

// node_modules/d3-color/src/define.js
function define_default(constructor, factory, prototype) {
  constructor.prototype = factory.prototype = prototype;
  prototype.constructor = constructor;
}
function extend2(parent2, definition) {
  var prototype = Object.create(parent2.prototype);
  for (var key in definition)
    prototype[key] = definition[key];
  return prototype;
}

// node_modules/d3-color/src/color.js
function Color() {
}
var darker = 0.7;
var brighter = 1 / darker;
var reI = "\\s*([+-]?\\d+)\\s*";
var reN = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*";
var reP = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*";
var reHex = /^#([0-9a-f]{3,8})$/;
var reRgbInteger = new RegExp(`^rgb\\(${reI},${reI},${reI}\\)$`);
var reRgbPercent = new RegExp(`^rgb\\(${reP},${reP},${reP}\\)$`);
var reRgbaInteger = new RegExp(`^rgba\\(${reI},${reI},${reI},${reN}\\)$`);
var reRgbaPercent = new RegExp(`^rgba\\(${reP},${reP},${reP},${reN}\\)$`);
var reHslPercent = new RegExp(`^hsl\\(${reN},${reP},${reP}\\)$`);
var reHslaPercent = new RegExp(`^hsla\\(${reN},${reP},${reP},${reN}\\)$`);
var named = {
  aliceblue: 15792383,
  antiquewhite: 16444375,
  aqua: 65535,
  aquamarine: 8388564,
  azure: 15794175,
  beige: 16119260,
  bisque: 16770244,
  black: 0,
  blanchedalmond: 16772045,
  blue: 255,
  blueviolet: 9055202,
  brown: 10824234,
  burlywood: 14596231,
  cadetblue: 6266528,
  chartreuse: 8388352,
  chocolate: 13789470,
  coral: 16744272,
  cornflowerblue: 6591981,
  cornsilk: 16775388,
  crimson: 14423100,
  cyan: 65535,
  darkblue: 139,
  darkcyan: 35723,
  darkgoldenrod: 12092939,
  darkgray: 11119017,
  darkgreen: 25600,
  darkgrey: 11119017,
  darkkhaki: 12433259,
  darkmagenta: 9109643,
  darkolivegreen: 5597999,
  darkorange: 16747520,
  darkorchid: 10040012,
  darkred: 9109504,
  darksalmon: 15308410,
  darkseagreen: 9419919,
  darkslateblue: 4734347,
  darkslategray: 3100495,
  darkslategrey: 3100495,
  darkturquoise: 52945,
  darkviolet: 9699539,
  deeppink: 16716947,
  deepskyblue: 49151,
  dimgray: 6908265,
  dimgrey: 6908265,
  dodgerblue: 2003199,
  firebrick: 11674146,
  floralwhite: 16775920,
  forestgreen: 2263842,
  fuchsia: 16711935,
  gainsboro: 14474460,
  ghostwhite: 16316671,
  gold: 16766720,
  goldenrod: 14329120,
  gray: 8421504,
  green: 32768,
  greenyellow: 11403055,
  grey: 8421504,
  honeydew: 15794160,
  hotpink: 16738740,
  indianred: 13458524,
  indigo: 4915330,
  ivory: 16777200,
  khaki: 15787660,
  lavender: 15132410,
  lavenderblush: 16773365,
  lawngreen: 8190976,
  lemonchiffon: 16775885,
  lightblue: 11393254,
  lightcoral: 15761536,
  lightcyan: 14745599,
  lightgoldenrodyellow: 16448210,
  lightgray: 13882323,
  lightgreen: 9498256,
  lightgrey: 13882323,
  lightpink: 16758465,
  lightsalmon: 16752762,
  lightseagreen: 2142890,
  lightskyblue: 8900346,
  lightslategray: 7833753,
  lightslategrey: 7833753,
  lightsteelblue: 11584734,
  lightyellow: 16777184,
  lime: 65280,
  limegreen: 3329330,
  linen: 16445670,
  magenta: 16711935,
  maroon: 8388608,
  mediumaquamarine: 6737322,
  mediumblue: 205,
  mediumorchid: 12211667,
  mediumpurple: 9662683,
  mediumseagreen: 3978097,
  mediumslateblue: 8087790,
  mediumspringgreen: 64154,
  mediumturquoise: 4772300,
  mediumvioletred: 13047173,
  midnightblue: 1644912,
  mintcream: 16121850,
  mistyrose: 16770273,
  moccasin: 16770229,
  navajowhite: 16768685,
  navy: 128,
  oldlace: 16643558,
  olive: 8421376,
  olivedrab: 7048739,
  orange: 16753920,
  orangered: 16729344,
  orchid: 14315734,
  palegoldenrod: 15657130,
  palegreen: 10025880,
  paleturquoise: 11529966,
  palevioletred: 14381203,
  papayawhip: 16773077,
  peachpuff: 16767673,
  peru: 13468991,
  pink: 16761035,
  plum: 14524637,
  powderblue: 11591910,
  purple: 8388736,
  rebeccapurple: 6697881,
  red: 16711680,
  rosybrown: 12357519,
  royalblue: 4286945,
  saddlebrown: 9127187,
  salmon: 16416882,
  sandybrown: 16032864,
  seagreen: 3050327,
  seashell: 16774638,
  sienna: 10506797,
  silver: 12632256,
  skyblue: 8900331,
  slateblue: 6970061,
  slategray: 7372944,
  slategrey: 7372944,
  snow: 16775930,
  springgreen: 65407,
  steelblue: 4620980,
  tan: 13808780,
  teal: 32896,
  thistle: 14204888,
  tomato: 16737095,
  turquoise: 4251856,
  violet: 15631086,
  wheat: 16113331,
  white: 16777215,
  whitesmoke: 16119285,
  yellow: 16776960,
  yellowgreen: 10145074
};
define_default(Color, color, {
  copy(channels) {
    return Object.assign(new this.constructor(), this, channels);
  },
  displayable() {
    return this.rgb().displayable();
  },
  hex: color_formatHex,
  formatHex: color_formatHex,
  formatHex8: color_formatHex8,
  formatHsl: color_formatHsl,
  formatRgb: color_formatRgb,
  toString: color_formatRgb
});
function color_formatHex() {
  return this.rgb().formatHex();
}
function color_formatHex8() {
  return this.rgb().formatHex8();
}
function color_formatHsl() {
  return hslConvert(this).formatHsl();
}
function color_formatRgb() {
  return this.rgb().formatRgb();
}
function color(format3) {
  var m, l;
  format3 = (format3 + "").trim().toLowerCase();
  return (m = reHex.exec(format3)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) : l === 3 ? new Rgb(m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, (m & 15) << 4 | m & 15, 1) : l === 8 ? rgba(m >> 24 & 255, m >> 16 & 255, m >> 8 & 255, (m & 255) / 255) : l === 4 ? rgba(m >> 12 & 15 | m >> 8 & 240, m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, ((m & 15) << 4 | m & 15) / 255) : null) : (m = reRgbInteger.exec(format3)) ? new Rgb(m[1], m[2], m[3], 1) : (m = reRgbPercent.exec(format3)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) : (m = reRgbaInteger.exec(format3)) ? rgba(m[1], m[2], m[3], m[4]) : (m = reRgbaPercent.exec(format3)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) : (m = reHslPercent.exec(format3)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) : (m = reHslaPercent.exec(format3)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) : named.hasOwnProperty(format3) ? rgbn(named[format3]) : format3 === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null;
}
function rgbn(n) {
  return new Rgb(n >> 16 & 255, n >> 8 & 255, n & 255, 1);
}
function rgba(r, g, b, a) {
  if (a <= 0)
    r = g = b = NaN;
  return new Rgb(r, g, b, a);
}
function rgbConvert(o) {
  if (!(o instanceof Color))
    o = color(o);
  if (!o)
    return new Rgb();
  o = o.rgb();
  return new Rgb(o.r, o.g, o.b, o.opacity);
}
function rgb(r, g, b, opacity) {
  return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
}
function Rgb(r, g, b, opacity) {
  this.r = +r;
  this.g = +g;
  this.b = +b;
  this.opacity = +opacity;
}
define_default(Rgb, rgb, extend2(Color, {
  brighter(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  darker(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  rgb() {
    return this;
  },
  clamp() {
    return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity));
  },
  displayable() {
    return -0.5 <= this.r && this.r < 255.5 && (-0.5 <= this.g && this.g < 255.5) && (-0.5 <= this.b && this.b < 255.5) && (0 <= this.opacity && this.opacity <= 1);
  },
  hex: rgb_formatHex,
  formatHex: rgb_formatHex,
  formatHex8: rgb_formatHex8,
  formatRgb: rgb_formatRgb,
  toString: rgb_formatRgb
}));
function rgb_formatHex() {
  return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`;
}
function rgb_formatHex8() {
  return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;
}
function rgb_formatRgb() {
  const a = clampa(this.opacity);
  return `${a === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? ")" : `, ${a})`}`;
}
function clampa(opacity) {
  return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));
}
function clampi(value) {
  return Math.max(0, Math.min(255, Math.round(value) || 0));
}
function hex(value) {
  value = clampi(value);
  return (value < 16 ? "0" : "") + value.toString(16);
}
function hsla(h, s, l, a) {
  if (a <= 0)
    h = s = l = NaN;
  else if (l <= 0 || l >= 1)
    h = s = NaN;
  else if (s <= 0)
    h = NaN;
  return new Hsl(h, s, l, a);
}
function hslConvert(o) {
  if (o instanceof Hsl)
    return new Hsl(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Color))
    o = color(o);
  if (!o)
    return new Hsl();
  if (o instanceof Hsl)
    return o;
  o = o.rgb();
  var r = o.r / 255, g = o.g / 255, b = o.b / 255, min3 = Math.min(r, g, b), max3 = Math.max(r, g, b), h = NaN, s = max3 - min3, l = (max3 + min3) / 2;
  if (s) {
    if (r === max3)
      h = (g - b) / s + (g < b) * 6;
    else if (g === max3)
      h = (b - r) / s + 2;
    else
      h = (r - g) / s + 4;
    s /= l < 0.5 ? max3 + min3 : 2 - max3 - min3;
    h *= 60;
  } else {
    s = l > 0 && l < 1 ? 0 : h;
  }
  return new Hsl(h, s, l, o.opacity);
}
function hsl(h, s, l, opacity) {
  return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
}
function Hsl(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}
define_default(Hsl, hsl, extend2(Color, {
  brighter(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  darker(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  rgb() {
    var h = this.h % 360 + (this.h < 0) * 360, s = isNaN(h) || isNaN(this.s) ? 0 : this.s, l = this.l, m2 = l + (l < 0.5 ? l : 1 - l) * s, m1 = 2 * l - m2;
    return new Rgb(
      hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
      hsl2rgb(h, m1, m2),
      hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
      this.opacity
    );
  },
  clamp() {
    return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity));
  },
  displayable() {
    return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && (0 <= this.l && this.l <= 1) && (0 <= this.opacity && this.opacity <= 1);
  },
  formatHsl() {
    const a = clampa(this.opacity);
    return `${a === 1 ? "hsl(" : "hsla("}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? ")" : `, ${a})`}`;
  }
}));
function clamph(value) {
  value = (value || 0) % 360;
  return value < 0 ? value + 360 : value;
}
function clampt(value) {
  return Math.max(0, Math.min(1, value || 0));
}
function hsl2rgb(h, m1, m2) {
  return (h < 60 ? m1 + (m2 - m1) * h / 60 : h < 180 ? m2 : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60 : m1) * 255;
}

// node_modules/d3-color/src/math.js
var radians = Math.PI / 180;
var degrees = 180 / Math.PI;

// node_modules/d3-color/src/lab.js
var K = 18;
var Xn = 0.96422;
var Yn = 1;
var Zn = 0.82521;
var t02 = 4 / 29;
var t12 = 6 / 29;
var t2 = 3 * t12 * t12;
var t3 = t12 * t12 * t12;
function labConvert(o) {
  if (o instanceof Lab)
    return new Lab(o.l, o.a, o.b, o.opacity);
  if (o instanceof Hcl)
    return hcl2lab(o);
  if (!(o instanceof Rgb))
    o = rgbConvert(o);
  var r = rgb2lrgb(o.r), g = rgb2lrgb(o.g), b = rgb2lrgb(o.b), y2 = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x2, z;
  if (r === g && g === b)
    x2 = z = y2;
  else {
    x2 = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);
    z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);
  }
  return new Lab(116 * y2 - 16, 500 * (x2 - y2), 200 * (y2 - z), o.opacity);
}
function lab(l, a, b, opacity) {
  return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);
}
function Lab(l, a, b, opacity) {
  this.l = +l;
  this.a = +a;
  this.b = +b;
  this.opacity = +opacity;
}
define_default(Lab, lab, extend2(Color, {
  brighter(k) {
    return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  darker(k) {
    return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  rgb() {
    var y2 = (this.l + 16) / 116, x2 = isNaN(this.a) ? y2 : y2 + this.a / 500, z = isNaN(this.b) ? y2 : y2 - this.b / 200;
    x2 = Xn * lab2xyz(x2);
    y2 = Yn * lab2xyz(y2);
    z = Zn * lab2xyz(z);
    return new Rgb(
      lrgb2rgb(3.1338561 * x2 - 1.6168667 * y2 - 0.4906146 * z),
      lrgb2rgb(-0.9787684 * x2 + 1.9161415 * y2 + 0.033454 * z),
      lrgb2rgb(0.0719453 * x2 - 0.2289914 * y2 + 1.4052427 * z),
      this.opacity
    );
  }
}));
function xyz2lab(t4) {
  return t4 > t3 ? Math.pow(t4, 1 / 3) : t4 / t2 + t02;
}
function lab2xyz(t4) {
  return t4 > t12 ? t4 * t4 * t4 : t2 * (t4 - t02);
}
function lrgb2rgb(x2) {
  return 255 * (x2 <= 31308e-7 ? 12.92 * x2 : 1.055 * Math.pow(x2, 1 / 2.4) - 0.055);
}
function rgb2lrgb(x2) {
  return (x2 /= 255) <= 0.04045 ? x2 / 12.92 : Math.pow((x2 + 0.055) / 1.055, 2.4);
}
function hclConvert(o) {
  if (o instanceof Hcl)
    return new Hcl(o.h, o.c, o.l, o.opacity);
  if (!(o instanceof Lab))
    o = labConvert(o);
  if (o.a === 0 && o.b === 0)
    return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity);
  var h = Math.atan2(o.b, o.a) * degrees;
  return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
}
function hcl(h, c, l, opacity) {
  return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
}
function Hcl(h, c, l, opacity) {
  this.h = +h;
  this.c = +c;
  this.l = +l;
  this.opacity = +opacity;
}
function hcl2lab(o) {
  if (isNaN(o.h))
    return new Lab(o.l, 0, 0, o.opacity);
  var h = o.h * radians;
  return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
}
define_default(Hcl, hcl, extend2(Color, {
  brighter(k) {
    return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);
  },
  darker(k) {
    return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);
  },
  rgb() {
    return hcl2lab(this).rgb();
  }
}));

// node_modules/d3-interpolate/src/basis.js
function basis(t13, v0, v1, v2, v3) {
  var t22 = t13 * t13, t32 = t22 * t13;
  return ((1 - 3 * t13 + 3 * t22 - t32) * v0 + (4 - 6 * t22 + 3 * t32) * v1 + (1 + 3 * t13 + 3 * t22 - 3 * t32) * v2 + t32 * v3) / 6;
}
function basis_default(values) {
  var n = values.length - 1;
  return function(t4) {
    var i = t4 <= 0 ? t4 = 0 : t4 >= 1 ? (t4 = 1, n - 1) : Math.floor(t4 * n), v1 = values[i], v2 = values[i + 1], v0 = i > 0 ? values[i - 1] : 2 * v1 - v2, v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;
    return basis((t4 - i / n) * n, v0, v1, v2, v3);
  };
}

// node_modules/d3-interpolate/src/basisClosed.js
function basisClosed_default(values) {
  var n = values.length;
  return function(t4) {
    var i = Math.floor(((t4 %= 1) < 0 ? ++t4 : t4) * n), v0 = values[(i + n - 1) % n], v1 = values[i % n], v2 = values[(i + 1) % n], v3 = values[(i + 2) % n];
    return basis((t4 - i / n) * n, v0, v1, v2, v3);
  };
}

// node_modules/d3-interpolate/src/constant.js
var constant_default = (x2) => () => x2;

// node_modules/d3-interpolate/src/color.js
function linear(a, d) {
  return function(t4) {
    return a + t4 * d;
  };
}
function exponential(a, b, y2) {
  return a = Math.pow(a, y2), b = Math.pow(b, y2) - a, y2 = 1 / y2, function(t4) {
    return Math.pow(a + t4 * b, y2);
  };
}
function gamma(y2) {
  return (y2 = +y2) === 1 ? nogamma : function(a, b) {
    return b - a ? exponential(a, b, y2) : constant_default(isNaN(a) ? b : a);
  };
}
function nogamma(a, b) {
  var d = b - a;
  return d ? linear(a, d) : constant_default(isNaN(a) ? b : a);
}

// node_modules/d3-interpolate/src/rgb.js
var rgb_default = function rgbGamma(y2) {
  var color2 = gamma(y2);
  function rgb2(start, end) {
    var r = color2((start = rgb(start)).r, (end = rgb(end)).r), g = color2(start.g, end.g), b = color2(start.b, end.b), opacity = nogamma(start.opacity, end.opacity);
    return function(t4) {
      start.r = r(t4);
      start.g = g(t4);
      start.b = b(t4);
      start.opacity = opacity(t4);
      return start + "";
    };
  }
  rgb2.gamma = rgbGamma;
  return rgb2;
}(1);
function rgbSpline(spline) {
  return function(colors) {
    var n = colors.length, r = new Array(n), g = new Array(n), b = new Array(n), i, color2;
    for (i = 0; i < n; ++i) {
      color2 = rgb(colors[i]);
      r[i] = color2.r || 0;
      g[i] = color2.g || 0;
      b[i] = color2.b || 0;
    }
    r = spline(r);
    g = spline(g);
    b = spline(b);
    color2.opacity = 1;
    return function(t4) {
      color2.r = r(t4);
      color2.g = g(t4);
      color2.b = b(t4);
      return color2 + "";
    };
  };
}
var rgbBasis = rgbSpline(basis_default);
var rgbBasisClosed = rgbSpline(basisClosed_default);

// node_modules/d3-interpolate/src/numberArray.js
function numberArray_default(a, b) {
  if (!b)
    b = [];
  var n = a ? Math.min(b.length, a.length) : 0, c = b.slice(), i;
  return function(t4) {
    for (i = 0; i < n; ++i)
      c[i] = a[i] * (1 - t4) + b[i] * t4;
    return c;
  };
}
function isNumberArray(x2) {
  return ArrayBuffer.isView(x2) && !(x2 instanceof DataView);
}

// node_modules/d3-interpolate/src/array.js
function genericArray(a, b) {
  var nb = b ? b.length : 0, na = a ? Math.min(nb, a.length) : 0, x2 = new Array(na), c = new Array(nb), i;
  for (i = 0; i < na; ++i)
    x2[i] = value_default(a[i], b[i]);
  for (; i < nb; ++i)
    c[i] = b[i];
  return function(t4) {
    for (i = 0; i < na; ++i)
      c[i] = x2[i](t4);
    return c;
  };
}

// node_modules/d3-interpolate/src/date.js
function date_default(a, b) {
  var d = new Date();
  return a = +a, b = +b, function(t4) {
    return d.setTime(a * (1 - t4) + b * t4), d;
  };
}

// node_modules/d3-interpolate/src/number.js
function number_default(a, b) {
  return a = +a, b = +b, function(t4) {
    return a * (1 - t4) + b * t4;
  };
}

// node_modules/d3-interpolate/src/object.js
function object_default(a, b) {
  var i = {}, c = {}, k;
  if (a === null || typeof a !== "object")
    a = {};
  if (b === null || typeof b !== "object")
    b = {};
  for (k in b) {
    if (k in a) {
      i[k] = value_default(a[k], b[k]);
    } else {
      c[k] = b[k];
    }
  }
  return function(t4) {
    for (k in i)
      c[k] = i[k](t4);
    return c;
  };
}

// node_modules/d3-interpolate/src/string.js
var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;
var reB = new RegExp(reA.source, "g");
function zero2(b) {
  return function() {
    return b;
  };
}
function one(b) {
  return function(t4) {
    return b(t4) + "";
  };
}
function string_default(a, b) {
  var bi = reA.lastIndex = reB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = [];
  a = a + "", b = b + "";
  while ((am = reA.exec(a)) && (bm = reB.exec(b))) {
    if ((bs = bm.index) > bi) {
      bs = b.slice(bi, bs);
      if (s[i])
        s[i] += bs;
      else
        s[++i] = bs;
    }
    if ((am = am[0]) === (bm = bm[0])) {
      if (s[i])
        s[i] += bm;
      else
        s[++i] = bm;
    } else {
      s[++i] = null;
      q.push({ i, x: number_default(am, bm) });
    }
    bi = reB.lastIndex;
  }
  if (bi < b.length) {
    bs = b.slice(bi);
    if (s[i])
      s[i] += bs;
    else
      s[++i] = bs;
  }
  return s.length < 2 ? q[0] ? one(q[0].x) : zero2(b) : (b = q.length, function(t4) {
    for (var i2 = 0, o; i2 < b; ++i2)
      s[(o = q[i2]).i] = o.x(t4);
    return s.join("");
  });
}

// node_modules/d3-interpolate/src/value.js
function value_default(a, b) {
  var t4 = typeof b, c;
  return b == null || t4 === "boolean" ? constant_default(b) : (t4 === "number" ? number_default : t4 === "string" ? (c = color(b)) ? (b = c, rgb_default) : string_default : b instanceof color ? rgb_default : b instanceof Date ? date_default : isNumberArray(b) ? numberArray_default : Array.isArray(b) ? genericArray : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object_default : number_default)(a, b);
}

// node_modules/d3-interpolate/src/round.js
function round_default(a, b) {
  return a = +a, b = +b, function(t4) {
    return Math.round(a * (1 - t4) + b * t4);
  };
}

// node_modules/d3-scale/src/constant.js
function constants(x2) {
  return function() {
    return x2;
  };
}

// node_modules/d3-scale/src/number.js
function number6(x2) {
  return +x2;
}

// node_modules/d3-scale/src/continuous.js
var unit = [0, 1];
function identity2(x2) {
  return x2;
}
function normalize(a, b) {
  return (b -= a = +a) ? function(x2) {
    return (x2 - a) / b;
  } : constants(isNaN(b) ? NaN : 0.5);
}
function clamper(a, b) {
  var t4;
  if (a > b)
    t4 = a, a = b, b = t4;
  return function(x2) {
    return Math.max(a, Math.min(b, x2));
  };
}
function bimap(domain, range2, interpolate) {
  var d0 = domain[0], d1 = domain[1], r0 = range2[0], r1 = range2[1];
  if (d1 < d0)
    d0 = normalize(d1, d0), r0 = interpolate(r1, r0);
  else
    d0 = normalize(d0, d1), r0 = interpolate(r0, r1);
  return function(x2) {
    return r0(d0(x2));
  };
}
function polymap(domain, range2, interpolate) {
  var j = Math.min(domain.length, range2.length) - 1, d = new Array(j), r = new Array(j), i = -1;
  if (domain[j] < domain[0]) {
    domain = domain.slice().reverse();
    range2 = range2.slice().reverse();
  }
  while (++i < j) {
    d[i] = normalize(domain[i], domain[i + 1]);
    r[i] = interpolate(range2[i], range2[i + 1]);
  }
  return function(x2) {
    var i2 = bisect_default(domain, x2, 1, j) - 1;
    return r[i2](d[i2](x2));
  };
}
function copy(source, target) {
  return target.domain(source.domain()).range(source.range()).interpolate(source.interpolate()).clamp(source.clamp()).unknown(source.unknown());
}
function transformer() {
  var domain = unit, range2 = unit, interpolate = value_default, transform, untransform, unknown2, clamp = identity2, piecewise, output, input;
  function rescale() {
    var n = Math.min(domain.length, range2.length);
    if (clamp !== identity2)
      clamp = clamper(domain[0], domain[n - 1]);
    piecewise = n > 2 ? polymap : bimap;
    output = input = null;
    return scale;
  }
  function scale(x2) {
    return x2 == null || isNaN(x2 = +x2) ? unknown2 : (output || (output = piecewise(domain.map(transform), range2, interpolate)))(transform(clamp(x2)));
  }
  scale.invert = function(y2) {
    return clamp(untransform((input || (input = piecewise(range2, domain.map(transform), number_default)))(y2)));
  };
  scale.domain = function(_2) {
    return arguments.length ? (domain = Array.from(_2, number6), rescale()) : domain.slice();
  };
  scale.range = function(_2) {
    return arguments.length ? (range2 = Array.from(_2), rescale()) : range2.slice();
  };
  scale.rangeRound = function(_2) {
    return range2 = Array.from(_2), interpolate = round_default, rescale();
  };
  scale.clamp = function(_2) {
    return arguments.length ? (clamp = _2 ? true : identity2, rescale()) : clamp !== identity2;
  };
  scale.interpolate = function(_2) {
    return arguments.length ? (interpolate = _2, rescale()) : interpolate;
  };
  scale.unknown = function(_2) {
    return arguments.length ? (unknown2 = _2, scale) : unknown2;
  };
  return function(t4, u) {
    transform = t4, untransform = u;
    return rescale();
  };
}
function continuous() {
  return transformer()(identity2, identity2);
}

// node_modules/d3-scale/src/tickFormat.js
function tickFormat(start, stop, count2, specifier) {
  var step = tickStep(start, stop, count2), precision;
  specifier = formatSpecifier(specifier == null ? ",f" : specifier);
  switch (specifier.type) {
    case "s": {
      var value = Math.max(Math.abs(start), Math.abs(stop));
      if (specifier.precision == null && !isNaN(precision = precisionPrefix_default(step, value)))
        specifier.precision = precision;
      return formatPrefix(specifier, value);
    }
    case "":
    case "e":
    case "g":
    case "p":
    case "r": {
      if (specifier.precision == null && !isNaN(precision = precisionRound_default(step, Math.max(Math.abs(start), Math.abs(stop)))))
        specifier.precision = precision - (specifier.type === "e");
      break;
    }
    case "f":
    case "%": {
      if (specifier.precision == null && !isNaN(precision = precisionFixed_default(step)))
        specifier.precision = precision - (specifier.type === "%") * 2;
      break;
    }
  }
  return format(specifier);
}

// node_modules/d3-scale/src/linear.js
function linearish(scale) {
  var domain = scale.domain;
  scale.ticks = function(count2) {
    var d = domain();
    return ticks(d[0], d[d.length - 1], count2 == null ? 10 : count2);
  };
  scale.tickFormat = function(count2, specifier) {
    var d = domain();
    return tickFormat(d[0], d[d.length - 1], count2 == null ? 10 : count2, specifier);
  };
  scale.nice = function(count2) {
    if (count2 == null)
      count2 = 10;
    var d = domain();
    var i0 = 0;
    var i1 = d.length - 1;
    var start = d[i0];
    var stop = d[i1];
    var prestep;
    var step;
    var maxIter = 10;
    if (stop < start) {
      step = start, start = stop, stop = step;
      step = i0, i0 = i1, i1 = step;
    }
    while (maxIter-- > 0) {
      step = tickIncrement(start, stop, count2);
      if (step === prestep) {
        d[i0] = start;
        d[i1] = stop;
        return domain(d);
      } else if (step > 0) {
        start = Math.floor(start / step) * step;
        stop = Math.ceil(stop / step) * step;
      } else if (step < 0) {
        start = Math.ceil(start * step) / step;
        stop = Math.floor(stop * step) / step;
      } else {
        break;
      }
      prestep = step;
    }
    return scale;
  };
  return scale;
}
function linear2() {
  var scale = continuous();
  scale.copy = function() {
    return copy(scale, linear2());
  };
  initRange.apply(scale, arguments);
  return linearish(scale);
}

// node_modules/d3-scale/src/nice.js
function nice(domain, interval2) {
  domain = domain.slice();
  var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], t4;
  if (x1 < x0) {
    t4 = i0, i0 = i1, i1 = t4;
    t4 = x0, x0 = x1, x1 = t4;
  }
  domain[i0] = interval2.floor(x0);
  domain[i1] = interval2.ceil(x1);
  return domain;
}

// node_modules/d3-scale/src/pow.js
function transformPow(exponent) {
  return function(x2) {
    return x2 < 0 ? -Math.pow(-x2, exponent) : Math.pow(x2, exponent);
  };
}
function transformSqrt(x2) {
  return x2 < 0 ? -Math.sqrt(-x2) : Math.sqrt(x2);
}
function transformSquare(x2) {
  return x2 < 0 ? -x2 * x2 : x2 * x2;
}
function powish(transform) {
  var scale = transform(identity2, identity2), exponent = 1;
  function rescale() {
    return exponent === 1 ? transform(identity2, identity2) : exponent === 0.5 ? transform(transformSqrt, transformSquare) : transform(transformPow(exponent), transformPow(1 / exponent));
  }
  scale.exponent = function(_2) {
    return arguments.length ? (exponent = +_2, rescale()) : exponent;
  };
  return linearish(scale);
}
function pow() {
  var scale = powish(transformer());
  scale.copy = function() {
    return copy(scale, pow()).exponent(scale.exponent());
  };
  initRange.apply(scale, arguments);
  return scale;
}
function sqrt() {
  return pow.apply(null, arguments).exponent(0.5);
}

// node_modules/d3-scale/src/time.js
function date4(t4) {
  return new Date(t4);
}
function number7(t4) {
  return t4 instanceof Date ? +t4 : +new Date(+t4);
}
function calendar(ticks2, tickInterval, year2, month2, week, day3, hour2, minute2, second2, format3) {
  var scale = continuous(), invert = scale.invert, domain = scale.domain;
  var formatMillisecond = format3(".%L"), formatSecond = format3(":%S"), formatMinute = format3("%I:%M"), formatHour = format3("%I %p"), formatDay = format3("%a %d"), formatWeek = format3("%b %d"), formatMonth = format3("%B"), formatYear2 = format3("%Y");
  function tickFormat2(date5) {
    return (second2(date5) < date5 ? formatMillisecond : minute2(date5) < date5 ? formatSecond : hour2(date5) < date5 ? formatMinute : day3(date5) < date5 ? formatHour : month2(date5) < date5 ? week(date5) < date5 ? formatDay : formatWeek : year2(date5) < date5 ? formatMonth : formatYear2)(date5);
  }
  scale.invert = function(y2) {
    return new Date(invert(y2));
  };
  scale.domain = function(_2) {
    return arguments.length ? domain(Array.from(_2, number7)) : domain().map(date4);
  };
  scale.ticks = function(interval2) {
    var d = domain();
    return ticks2(d[0], d[d.length - 1], interval2 == null ? 10 : interval2);
  };
  scale.tickFormat = function(count2, specifier) {
    return specifier == null ? tickFormat2 : format3(specifier);
  };
  scale.nice = function(interval2) {
    var d = domain();
    if (!interval2 || typeof interval2.range !== "function")
      interval2 = tickInterval(d[0], d[d.length - 1], interval2 == null ? 10 : interval2);
    return interval2 ? domain(nice(d, interval2)) : scale;
  };
  scale.copy = function() {
    return copy(scale, calendar(ticks2, tickInterval, year2, month2, week, day3, hour2, minute2, second2, format3));
  };
  return scale;
}

// node_modules/d3-scale/src/utcTime.js
function utcTime() {
  return initRange.apply(calendar(utcTicks, utcTickInterval, utcYear_default, utcMonth_default, utcSunday, utcDay_default, utcHour_default, utcMinute_default, second_default, utcFormat).domain([Date.UTC(2e3, 0, 1), Date.UTC(2e3, 0, 2)]), arguments);
}

// node_modules/d3-selection/src/namespaces.js
var xhtml = "http://www.w3.org/1999/xhtml";
var namespaces_default = {
  svg: "http://www.w3.org/2000/svg",
  xhtml,
  xlink: "http://www.w3.org/1999/xlink",
  xml: "http://www.w3.org/XML/1998/namespace",
  xmlns: "http://www.w3.org/2000/xmlns/"
};

// node_modules/d3-selection/src/namespace.js
function namespace_default(name2) {
  var prefix = name2 += "", i = prefix.indexOf(":");
  if (i >= 0 && (prefix = name2.slice(0, i)) !== "xmlns")
    name2 = name2.slice(i + 1);
  return namespaces_default.hasOwnProperty(prefix) ? { space: namespaces_default[prefix], local: name2 } : name2;
}

// node_modules/d3-selection/src/creator.js
function creatorInherit(name2) {
  return function() {
    var document2 = this.ownerDocument, uri = this.namespaceURI;
    return uri === xhtml && document2.documentElement.namespaceURI === xhtml ? document2.createElement(name2) : document2.createElementNS(uri, name2);
  };
}
function creatorFixed(fullname) {
  return function() {
    return this.ownerDocument.createElementNS(fullname.space, fullname.local);
  };
}
function creator_default(name2) {
  var fullname = namespace_default(name2);
  return (fullname.local ? creatorFixed : creatorInherit)(fullname);
}

// node_modules/d3-selection/src/selector.js
function none4() {
}
function selector_default(selector) {
  return selector == null ? none4 : function() {
    return this.querySelector(selector);
  };
}

// node_modules/d3-selection/src/selection/select.js
function select_default(select) {
  if (typeof select !== "function")
    select = selector_default(select);
  for (var groups2 = this._groups, m = groups2.length, subgroups = new Array(m), j = 0; j < m; ++j) {
    for (var group2 = groups2[j], n = group2.length, subgroup = subgroups[j] = new Array(n), node, subnode, i = 0; i < n; ++i) {
      if ((node = group2[i]) && (subnode = select.call(node, node.__data__, i, group2))) {
        if ("__data__" in node)
          subnode.__data__ = node.__data__;
        subgroup[i] = subnode;
      }
    }
  }
  return new Selection(subgroups, this._parents);
}

// node_modules/d3-selection/src/array.js
function array2(x2) {
  return x2 == null ? [] : Array.isArray(x2) ? x2 : Array.from(x2);
}

// node_modules/d3-selection/src/selectorAll.js
function empty3() {
  return [];
}
function selectorAll_default(selector) {
  return selector == null ? empty3 : function() {
    return this.querySelectorAll(selector);
  };
}

// node_modules/d3-selection/src/selection/selectAll.js
function arrayAll(select) {
  return function() {
    return array2(select.apply(this, arguments));
  };
}
function selectAll_default(select) {
  if (typeof select === "function")
    select = arrayAll(select);
  else
    select = selectorAll_default(select);
  for (var groups2 = this._groups, m = groups2.length, subgroups = [], parents = [], j = 0; j < m; ++j) {
    for (var group2 = groups2[j], n = group2.length, node, i = 0; i < n; ++i) {
      if (node = group2[i]) {
        subgroups.push(select.call(node, node.__data__, i, group2));
        parents.push(node);
      }
    }
  }
  return new Selection(subgroups, parents);
}

// node_modules/d3-selection/src/matcher.js
function matcher_default(selector) {
  return function() {
    return this.matches(selector);
  };
}
function childMatcher(selector) {
  return function(node) {
    return node.matches(selector);
  };
}

// node_modules/d3-selection/src/selection/selectChild.js
var find2 = Array.prototype.find;
function childFind(match) {
  return function() {
    return find2.call(this.children, match);
  };
}
function childFirst() {
  return this.firstElementChild;
}
function selectChild_default(match) {
  return this.select(match == null ? childFirst : childFind(typeof match === "function" ? match : childMatcher(match)));
}

// node_modules/d3-selection/src/selection/selectChildren.js
var filter = Array.prototype.filter;
function children2() {
  return Array.from(this.children);
}
function childrenFilter(match) {
  return function() {
    return filter.call(this.children, match);
  };
}
function selectChildren_default(match) {
  return this.selectAll(match == null ? children2 : childrenFilter(typeof match === "function" ? match : childMatcher(match)));
}

// node_modules/d3-selection/src/selection/filter.js
function filter_default(match) {
  if (typeof match !== "function")
    match = matcher_default(match);
  for (var groups2 = this._groups, m = groups2.length, subgroups = new Array(m), j = 0; j < m; ++j) {
    for (var group2 = groups2[j], n = group2.length, subgroup = subgroups[j] = [], node, i = 0; i < n; ++i) {
      if ((node = group2[i]) && match.call(node, node.__data__, i, group2)) {
        subgroup.push(node);
      }
    }
  }
  return new Selection(subgroups, this._parents);
}

// node_modules/d3-selection/src/selection/sparse.js
function sparse_default(update2) {
  return new Array(update2.length);
}

// node_modules/d3-selection/src/selection/enter.js
function enter_default() {
  return new Selection(this._enter || this._groups.map(sparse_default), this._parents);
}
function EnterNode(parent2, datum2) {
  this.ownerDocument = parent2.ownerDocument;
  this.namespaceURI = parent2.namespaceURI;
  this._next = null;
  this._parent = parent2;
  this.__data__ = datum2;
}
EnterNode.prototype = {
  constructor: EnterNode,
  appendChild: function(child) {
    return this._parent.insertBefore(child, this._next);
  },
  insertBefore: function(child, next) {
    return this._parent.insertBefore(child, next);
  },
  querySelector: function(selector) {
    return this._parent.querySelector(selector);
  },
  querySelectorAll: function(selector) {
    return this._parent.querySelectorAll(selector);
  }
};

// node_modules/d3-selection/src/constant.js
function constant_default2(x2) {
  return function() {
    return x2;
  };
}

// node_modules/d3-selection/src/selection/data.js
function bindIndex(parent2, group2, enter, update2, exit, data) {
  var i = 0, node, groupLength = group2.length, dataLength = data.length;
  for (; i < dataLength; ++i) {
    if (node = group2[i]) {
      node.__data__ = data[i];
      update2[i] = node;
    } else {
      enter[i] = new EnterNode(parent2, data[i]);
    }
  }
  for (; i < groupLength; ++i) {
    if (node = group2[i]) {
      exit[i] = node;
    }
  }
}
function bindKey2(parent2, group2, enter, update2, exit, data, key) {
  var i, node, nodeByKeyValue = /* @__PURE__ */ new Map(), groupLength = group2.length, dataLength = data.length, keyValues = new Array(groupLength), keyValue;
  for (i = 0; i < groupLength; ++i) {
    if (node = group2[i]) {
      keyValues[i] = keyValue = key.call(node, node.__data__, i, group2) + "";
      if (nodeByKeyValue.has(keyValue)) {
        exit[i] = node;
      } else {
        nodeByKeyValue.set(keyValue, node);
      }
    }
  }
  for (i = 0; i < dataLength; ++i) {
    keyValue = key.call(parent2, data[i], i, data) + "";
    if (node = nodeByKeyValue.get(keyValue)) {
      update2[i] = node;
      node.__data__ = data[i];
      nodeByKeyValue.delete(keyValue);
    } else {
      enter[i] = new EnterNode(parent2, data[i]);
    }
  }
  for (i = 0; i < groupLength; ++i) {
    if ((node = group2[i]) && nodeByKeyValue.get(keyValues[i]) === node) {
      exit[i] = node;
    }
  }
}
function datum(node) {
  return node.__data__;
}
function data_default(value, key) {
  if (!arguments.length)
    return Array.from(this, datum);
  var bind2 = key ? bindKey2 : bindIndex, parents = this._parents, groups2 = this._groups;
  if (typeof value !== "function")
    value = constant_default2(value);
  for (var m = groups2.length, update2 = new Array(m), enter = new Array(m), exit = new Array(m), j = 0; j < m; ++j) {
    var parent2 = parents[j], group2 = groups2[j], groupLength = group2.length, data = arraylike(value.call(parent2, parent2 && parent2.__data__, j, parents)), dataLength = data.length, enterGroup = enter[j] = new Array(dataLength), updateGroup = update2[j] = new Array(dataLength), exitGroup = exit[j] = new Array(groupLength);
    bind2(parent2, group2, enterGroup, updateGroup, exitGroup, data, key);
    for (var i0 = 0, i1 = 0, previous, next; i0 < dataLength; ++i0) {
      if (previous = enterGroup[i0]) {
        if (i0 >= i1)
          i1 = i0 + 1;
        while (!(next = updateGroup[i1]) && ++i1 < dataLength)
          ;
        previous._next = next || null;
      }
    }
  }
  update2 = new Selection(update2, parents);
  update2._enter = enter;
  update2._exit = exit;
  return update2;
}
function arraylike(data) {
  return typeof data === "object" && "length" in data ? data : Array.from(data);
}

// node_modules/d3-selection/src/selection/exit.js
function exit_default() {
  return new Selection(this._exit || this._groups.map(sparse_default), this._parents);
}

// node_modules/d3-selection/src/selection/join.js
function join_default(onenter, onupdate, onexit) {
  var enter = this.enter(), update2 = this, exit = this.exit();
  if (typeof onenter === "function") {
    enter = onenter(enter);
    if (enter)
      enter = enter.selection();
  } else {
    enter = enter.append(onenter + "");
  }
  if (onupdate != null) {
    update2 = onupdate(update2);
    if (update2)
      update2 = update2.selection();
  }
  if (onexit == null)
    exit.remove();
  else
    onexit(exit);
  return enter && update2 ? enter.merge(update2).order() : update2;
}

// node_modules/d3-selection/src/selection/merge.js
function merge_default(context) {
  var selection2 = context.selection ? context.selection() : context;
  for (var groups0 = this._groups, groups1 = selection2._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {
    for (var group0 = groups0[j], group1 = groups1[j], n = group0.length, merge2 = merges[j] = new Array(n), node, i = 0; i < n; ++i) {
      if (node = group0[i] || group1[i]) {
        merge2[i] = node;
      }
    }
  }
  for (; j < m0; ++j) {
    merges[j] = groups0[j];
  }
  return new Selection(merges, this._parents);
}

// node_modules/d3-selection/src/selection/order.js
function order_default() {
  for (var groups2 = this._groups, j = -1, m = groups2.length; ++j < m; ) {
    for (var group2 = groups2[j], i = group2.length - 1, next = group2[i], node; --i >= 0; ) {
      if (node = group2[i]) {
        if (next && node.compareDocumentPosition(next) ^ 4)
          next.parentNode.insertBefore(node, next);
        next = node;
      }
    }
  }
  return this;
}

// node_modules/d3-selection/src/selection/sort.js
function sort_default(compare2) {
  if (!compare2)
    compare2 = ascending2;
  function compareNode(a, b) {
    return a && b ? compare2(a.__data__, b.__data__) : !a - !b;
  }
  for (var groups2 = this._groups, m = groups2.length, sortgroups = new Array(m), j = 0; j < m; ++j) {
    for (var group2 = groups2[j], n = group2.length, sortgroup = sortgroups[j] = new Array(n), node, i = 0; i < n; ++i) {
      if (node = group2[i]) {
        sortgroup[i] = node;
      }
    }
    sortgroup.sort(compareNode);
  }
  return new Selection(sortgroups, this._parents).order();
}
function ascending2(a, b) {
  return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

// node_modules/d3-selection/src/selection/call.js
function call_default() {
  var callback = arguments[0];
  arguments[0] = this;
  callback.apply(null, arguments);
  return this;
}

// node_modules/d3-selection/src/selection/nodes.js
function nodes_default() {
  return Array.from(this);
}

// node_modules/d3-selection/src/selection/node.js
function node_default() {
  for (var groups2 = this._groups, j = 0, m = groups2.length; j < m; ++j) {
    for (var group2 = groups2[j], i = 0, n = group2.length; i < n; ++i) {
      var node = group2[i];
      if (node)
        return node;
    }
  }
  return null;
}

// node_modules/d3-selection/src/selection/size.js
function size_default() {
  let size = 0;
  for (const node of this)
    ++size;
  return size;
}

// node_modules/d3-selection/src/selection/empty.js
function empty_default() {
  return !this.node();
}

// node_modules/d3-selection/src/selection/each.js
function each_default(callback) {
  for (var groups2 = this._groups, j = 0, m = groups2.length; j < m; ++j) {
    for (var group2 = groups2[j], i = 0, n = group2.length, node; i < n; ++i) {
      if (node = group2[i])
        callback.call(node, node.__data__, i, group2);
    }
  }
  return this;
}

// node_modules/d3-selection/src/selection/attr.js
function attrRemove(name2) {
  return function() {
    this.removeAttribute(name2);
  };
}
function attrRemoveNS(fullname) {
  return function() {
    this.removeAttributeNS(fullname.space, fullname.local);
  };
}
function attrConstant(name2, value) {
  return function() {
    this.setAttribute(name2, value);
  };
}
function attrConstantNS(fullname, value) {
  return function() {
    this.setAttributeNS(fullname.space, fullname.local, value);
  };
}
function attrFunction(name2, value) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null)
      this.removeAttribute(name2);
    else
      this.setAttribute(name2, v);
  };
}
function attrFunctionNS(fullname, value) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null)
      this.removeAttributeNS(fullname.space, fullname.local);
    else
      this.setAttributeNS(fullname.space, fullname.local, v);
  };
}
function attr_default(name2, value) {
  var fullname = namespace_default(name2);
  if (arguments.length < 2) {
    var node = this.node();
    return fullname.local ? node.getAttributeNS(fullname.space, fullname.local) : node.getAttribute(fullname);
  }
  return this.each((value == null ? fullname.local ? attrRemoveNS : attrRemove : typeof value === "function" ? fullname.local ? attrFunctionNS : attrFunction : fullname.local ? attrConstantNS : attrConstant)(fullname, value));
}

// node_modules/d3-selection/src/window.js
function window_default(node) {
  return node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView;
}

// node_modules/d3-selection/src/selection/style.js
function styleRemove(name2) {
  return function() {
    this.style.removeProperty(name2);
  };
}
function styleConstant(name2, value, priority) {
  return function() {
    this.style.setProperty(name2, value, priority);
  };
}
function styleFunction(name2, value, priority) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null)
      this.style.removeProperty(name2);
    else
      this.style.setProperty(name2, v, priority);
  };
}
function style_default(name2, value, priority) {
  return arguments.length > 1 ? this.each((value == null ? styleRemove : typeof value === "function" ? styleFunction : styleConstant)(name2, value, priority == null ? "" : priority)) : styleValue(this.node(), name2);
}
function styleValue(node, name2) {
  return node.style.getPropertyValue(name2) || window_default(node).getComputedStyle(node, null).getPropertyValue(name2);
}

// node_modules/d3-selection/src/selection/property.js
function propertyRemove(name2) {
  return function() {
    delete this[name2];
  };
}
function propertyConstant(name2, value) {
  return function() {
    this[name2] = value;
  };
}
function propertyFunction(name2, value) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null)
      delete this[name2];
    else
      this[name2] = v;
  };
}
function property_default(name2, value) {
  return arguments.length > 1 ? this.each((value == null ? propertyRemove : typeof value === "function" ? propertyFunction : propertyConstant)(name2, value)) : this.node()[name2];
}

// node_modules/d3-selection/src/selection/classed.js
function classArray(string5) {
  return string5.trim().split(/^|\s+/);
}
function classList(node) {
  return node.classList || new ClassList(node);
}
function ClassList(node) {
  this._node = node;
  this._names = classArray(node.getAttribute("class") || "");
}
ClassList.prototype = {
  add: function(name2) {
    var i = this._names.indexOf(name2);
    if (i < 0) {
      this._names.push(name2);
      this._node.setAttribute("class", this._names.join(" "));
    }
  },
  remove: function(name2) {
    var i = this._names.indexOf(name2);
    if (i >= 0) {
      this._names.splice(i, 1);
      this._node.setAttribute("class", this._names.join(" "));
    }
  },
  contains: function(name2) {
    return this._names.indexOf(name2) >= 0;
  }
};
function classedAdd(node, names) {
  var list = classList(node), i = -1, n = names.length;
  while (++i < n)
    list.add(names[i]);
}
function classedRemove(node, names) {
  var list = classList(node), i = -1, n = names.length;
  while (++i < n)
    list.remove(names[i]);
}
function classedTrue(names) {
  return function() {
    classedAdd(this, names);
  };
}
function classedFalse(names) {
  return function() {
    classedRemove(this, names);
  };
}
function classedFunction(names, value) {
  return function() {
    (value.apply(this, arguments) ? classedAdd : classedRemove)(this, names);
  };
}
function classed_default(name2, value) {
  var names = classArray(name2 + "");
  if (arguments.length < 2) {
    var list = classList(this.node()), i = -1, n = names.length;
    while (++i < n)
      if (!list.contains(names[i]))
        return false;
    return true;
  }
  return this.each((typeof value === "function" ? classedFunction : value ? classedTrue : classedFalse)(names, value));
}

// node_modules/d3-selection/src/selection/text.js
function textRemove() {
  this.textContent = "";
}
function textConstant(value) {
  return function() {
    this.textContent = value;
  };
}
function textFunction(value) {
  return function() {
    var v = value.apply(this, arguments);
    this.textContent = v == null ? "" : v;
  };
}
function text_default(value) {
  return arguments.length ? this.each(value == null ? textRemove : (typeof value === "function" ? textFunction : textConstant)(value)) : this.node().textContent;
}

// node_modules/d3-selection/src/selection/html.js
function htmlRemove() {
  this.innerHTML = "";
}
function htmlConstant(value) {
  return function() {
    this.innerHTML = value;
  };
}
function htmlFunction(value) {
  return function() {
    var v = value.apply(this, arguments);
    this.innerHTML = v == null ? "" : v;
  };
}
function html_default(value) {
  return arguments.length ? this.each(value == null ? htmlRemove : (typeof value === "function" ? htmlFunction : htmlConstant)(value)) : this.node().innerHTML;
}

// node_modules/d3-selection/src/selection/raise.js
function raise() {
  if (this.nextSibling)
    this.parentNode.appendChild(this);
}
function raise_default() {
  return this.each(raise);
}

// node_modules/d3-selection/src/selection/lower.js
function lower() {
  if (this.previousSibling)
    this.parentNode.insertBefore(this, this.parentNode.firstChild);
}
function lower_default() {
  return this.each(lower);
}

// node_modules/d3-selection/src/selection/append.js
function append_default(name2) {
  var create2 = typeof name2 === "function" ? name2 : creator_default(name2);
  return this.select(function() {
    return this.appendChild(create2.apply(this, arguments));
  });
}

// node_modules/d3-selection/src/selection/insert.js
function constantNull() {
  return null;
}
function insert_default(name2, before) {
  var create2 = typeof name2 === "function" ? name2 : creator_default(name2), select = before == null ? constantNull : typeof before === "function" ? before : selector_default(before);
  return this.select(function() {
    return this.insertBefore(create2.apply(this, arguments), select.apply(this, arguments) || null);
  });
}

// node_modules/d3-selection/src/selection/remove.js
function remove2() {
  var parent2 = this.parentNode;
  if (parent2)
    parent2.removeChild(this);
}
function remove_default() {
  return this.each(remove2);
}

// node_modules/d3-selection/src/selection/clone.js
function selection_cloneShallow() {
  var clone = this.cloneNode(false), parent2 = this.parentNode;
  return parent2 ? parent2.insertBefore(clone, this.nextSibling) : clone;
}
function selection_cloneDeep() {
  var clone = this.cloneNode(true), parent2 = this.parentNode;
  return parent2 ? parent2.insertBefore(clone, this.nextSibling) : clone;
}
function clone_default(deep) {
  return this.select(deep ? selection_cloneDeep : selection_cloneShallow);
}

// node_modules/d3-selection/src/selection/datum.js
function datum_default(value) {
  return arguments.length ? this.property("__data__", value) : this.node().__data__;
}

// node_modules/d3-selection/src/selection/on.js
function contextListener(listener) {
  return function(event) {
    listener.call(this, event, this.__data__);
  };
}
function parseTypenames(typenames) {
  return typenames.trim().split(/^|\s+/).map(function(t4) {
    var name2 = "", i = t4.indexOf(".");
    if (i >= 0)
      name2 = t4.slice(i + 1), t4 = t4.slice(0, i);
    return { type: t4, name: name2 };
  });
}
function onRemove(typename) {
  return function() {
    var on = this.__on;
    if (!on)
      return;
    for (var j = 0, i = -1, m = on.length, o; j < m; ++j) {
      if (o = on[j], (!typename.type || o.type === typename.type) && o.name === typename.name) {
        this.removeEventListener(o.type, o.listener, o.options);
      } else {
        on[++i] = o;
      }
    }
    if (++i)
      on.length = i;
    else
      delete this.__on;
  };
}
function onAdd(typename, value, options2) {
  return function() {
    var on = this.__on, o, listener = contextListener(value);
    if (on)
      for (var j = 0, m = on.length; j < m; ++j) {
        if ((o = on[j]).type === typename.type && o.name === typename.name) {
          this.removeEventListener(o.type, o.listener, o.options);
          this.addEventListener(o.type, o.listener = listener, o.options = options2);
          o.value = value;
          return;
        }
      }
    this.addEventListener(typename.type, listener, options2);
    o = { type: typename.type, name: typename.name, value, listener, options: options2 };
    if (!on)
      this.__on = [o];
    else
      on.push(o);
  };
}
function on_default(typename, value, options2) {
  var typenames = parseTypenames(typename + ""), i, n = typenames.length, t4;
  if (arguments.length < 2) {
    var on = this.node().__on;
    if (on)
      for (var j = 0, m = on.length, o; j < m; ++j) {
        for (i = 0, o = on[j]; i < n; ++i) {
          if ((t4 = typenames[i]).type === o.type && t4.name === o.name) {
            return o.value;
          }
        }
      }
    return;
  }
  on = value ? onAdd : onRemove;
  for (i = 0; i < n; ++i)
    this.each(on(typenames[i], value, options2));
  return this;
}

// node_modules/d3-selection/src/selection/dispatch.js
function dispatchEvent(node, type, params) {
  var window2 = window_default(node), event = window2.CustomEvent;
  if (typeof event === "function") {
    event = new event(type, params);
  } else {
    event = window2.document.createEvent("Event");
    if (params)
      event.initEvent(type, params.bubbles, params.cancelable), event.detail = params.detail;
    else
      event.initEvent(type, false, false);
  }
  node.dispatchEvent(event);
}
function dispatchConstant(type, params) {
  return function() {
    return dispatchEvent(this, type, params);
  };
}
function dispatchFunction(type, params) {
  return function() {
    return dispatchEvent(this, type, params.apply(this, arguments));
  };
}
function dispatch_default(type, params) {
  return this.each((typeof params === "function" ? dispatchFunction : dispatchConstant)(type, params));
}

// node_modules/d3-selection/src/selection/iterator.js
function* iterator_default() {
  for (var groups2 = this._groups, j = 0, m = groups2.length; j < m; ++j) {
    for (var group2 = groups2[j], i = 0, n = group2.length, node; i < n; ++i) {
      if (node = group2[i])
        yield node;
    }
  }
}

// node_modules/d3-selection/src/selection/index.js
var root = [null];
function Selection(groups2, parents) {
  this._groups = groups2;
  this._parents = parents;
}
function selection() {
  return new Selection([[document.documentElement]], root);
}
function selection_selection() {
  return this;
}
Selection.prototype = selection.prototype = {
  constructor: Selection,
  select: select_default,
  selectAll: selectAll_default,
  selectChild: selectChild_default,
  selectChildren: selectChildren_default,
  filter: filter_default,
  data: data_default,
  enter: enter_default,
  exit: exit_default,
  join: join_default,
  merge: merge_default,
  selection: selection_selection,
  order: order_default,
  sort: sort_default,
  call: call_default,
  nodes: nodes_default,
  node: node_default,
  size: size_default,
  empty: empty_default,
  each: each_default,
  attr: attr_default,
  style: style_default,
  property: property_default,
  classed: classed_default,
  text: text_default,
  html: html_default,
  raise: raise_default,
  lower: lower_default,
  append: append_default,
  insert: insert_default,
  remove: remove_default,
  clone: clone_default,
  datum: datum_default,
  on: on_default,
  dispatch: dispatch_default,
  [Symbol.iterator]: iterator_default
};

// node_modules/d3-selection/src/select.js
function select_default2(selector) {
  return typeof selector === "string" ? new Selection([[document.querySelector(selector)]], [document.documentElement]) : new Selection([[selector]], root);
}

// node_modules/d3-selection/src/sourceEvent.js
function sourceEvent_default(event) {
  let sourceEvent;
  while (sourceEvent = event.sourceEvent)
    event = sourceEvent;
  return event;
}

// node_modules/d3-selection/src/pointer.js
function pointer_default(event, node) {
  event = sourceEvent_default(event);
  if (node === void 0)
    node = event.currentTarget;
  if (node) {
    var svg2 = node.ownerSVGElement || node;
    if (svg2.createSVGPoint) {
      var point2 = svg2.createSVGPoint();
      point2.x = event.clientX, point2.y = event.clientY;
      point2 = point2.matrixTransform(node.getScreenCTM().inverse());
      return [point2.x, point2.y];
    }
    if (node.getBoundingClientRect) {
      var rect = node.getBoundingClientRect();
      return [event.clientX - rect.left - node.clientLeft, event.clientY - rect.top - node.clientTop];
    }
  }
  return [event.pageX, event.pageY];
}

// src/charts/Axis.svelte
function create_fragment2(ctx2) {
  let g;
  let use_action;
  let mounted;
  let dispose;
  return {
    c() {
      g = svg_element("g");
      attr(g, "transform", ctx2[2]);
      attr(g, "class", "svelte-w3gjk0");
      toggle_class(g, "y", ctx2[1]);
    },
    m(target, anchor) {
      insert(target, g, anchor);
      if (!mounted) {
        dispose = action_destroyer(use_action = ctx2[3].call(null, g, ctx2[0]));
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & 4) {
        attr(g, "transform", ctx3[2]);
      }
      if (use_action && is_function(use_action.update) && dirty & 1)
        use_action.update.call(null, ctx3[0]);
      if (dirty & 2) {
        toggle_class(g, "y", ctx3[1]);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(g);
      mounted = false;
      dispose();
    }
  };
}
function instance2($$self, $$props, $$invalidate) {
  let transform;
  let { axis: axis2 } = $$props;
  let { x: x2 = false } = $$props;
  let { y: y2 = false } = $$props;
  let { innerHeight: innerHeight2 = 0 } = $$props;
  function use(node, ax) {
    const selection2 = select_default2(node);
    ax(selection2);
    return {
      update(a) {
        a(selection2);
      }
    };
  }
  $$self.$$set = ($$props2) => {
    if ("axis" in $$props2)
      $$invalidate(0, axis2 = $$props2.axis);
    if ("x" in $$props2)
      $$invalidate(4, x2 = $$props2.x);
    if ("y" in $$props2)
      $$invalidate(1, y2 = $$props2.y);
    if ("innerHeight" in $$props2)
      $$invalidate(5, innerHeight2 = $$props2.innerHeight);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 48) {
      $:
        $$invalidate(2, transform = x2 ? `translate(0,${innerHeight2})` : void 0);
    }
  };
  return [axis2, y2, transform, use, x2, innerHeight2];
}
var Axis = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance2, create_fragment2, safe_not_equal, { axis: 0, x: 4, y: 1, innerHeight: 5 });
  }
};
var Axis_default = Axis;

// src/charts/helpers.ts
function urlForTimeFilter(date5) {
  const url = new URL(window.location.href);
  url.searchParams.set("time", get_store_value(currentTimeFilterDateFormat)(date5));
  return url.toString();
}
function filterTicks(domain, count2) {
  if (domain.length <= count2) {
    return domain;
  }
  const showIndices = Math.ceil(domain.length / count2);
  return domain.filter((d, i) => i % showIndices === 0);
}
function hclColorRange(count2, chroma = 45, luminance = 70) {
  const offset = 270;
  const delta = 360 / count2;
  const colors = [...Array(count2).keys()].map((index2) => {
    const hue = (index2 * delta + offset) % 360;
    return hcl(hue, chroma, luminance);
  });
  return colors.map((c) => c.toString());
}
var colors10 = hclColorRange(10);
var colors15 = hclColorRange(15, 30, 80);
var scatterplotScale = ordinal(colors10);
var treemapScale = derived(
  accounts,
  (accounts_val) => ordinal(colors15).domain(accounts_val)
);
var sunburstScale = derived(
  accounts,
  (accounts_val) => ordinal(colors10).domain(accounts_val)
);
var currenciesScale = derived(
  [operating_currency, currencies_sorted],
  ([operating_currency_val, currencies_sorted_val]) => ordinal(colors10).domain([
    ...operating_currency_val,
    ...currencies_sorted_val
  ])
);

// src/charts/tooltip.ts
var tooltip = (() => {
  let value = null;
  return () => {
    if (value === null) {
      value = document.createElement("div");
      value.className = "tooltip";
      document.body.appendChild(value);
    }
    return value;
  };
})();
var hide = () => {
  const t4 = tooltip();
  t4.style.opacity = "0";
};
var domHelpers = {
  br: () => document.createElement("br"),
  em: (content2) => {
    const em = document.createElement("em");
    em.textContent = content2;
    return em;
  },
  t: (text2) => document.createTextNode(text2)
};
function followingTooltip(node, text2) {
  let getter = text2;
  function followMouse(event) {
    const t4 = tooltip();
    t4.style.opacity = "1";
    t4.style.left = `${event.pageX}px`;
    t4.style.top = `${event.pageY - 15}px`;
  }
  node.addEventListener("mouseenter", () => {
    const t4 = tooltip();
    t4.replaceChildren(...getter());
  });
  node.addEventListener("mousemove", followMouse);
  node.addEventListener("mouseleave", hide);
  return {
    destroy: hide,
    update(t4) {
      getter = t4;
    }
  };
}
function positionedTooltip(node, find3) {
  function mousemove(event) {
    const [xPointer, yPointer] = pointer_default(event);
    const res2 = find3(xPointer, yPointer);
    const matrix = node.getScreenCTM();
    if (res2 && matrix) {
      const [x2, y2, content2] = res2;
      const t4 = tooltip();
      t4.style.opacity = "1";
      t4.replaceChildren(...content2);
      t4.style.left = `${window.scrollX + x2 + matrix.e}px`;
      t4.style.top = `${window.scrollY + y2 + matrix.f - 15}px`;
    } else {
      hide();
    }
  }
  node.addEventListener("mousemove", mousemove);
  node.addEventListener("mouseleave", hide);
  return {
    destroy: hide
  };
}

// src/charts/BarChart.svelte
function get_each_context2(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[33] = list[i][0];
  child_ctx[34] = list[i][1];
  return child_ctx;
}
function get_each_context_1(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[37] = list[i];
  const constants_0 = child_ctx[37].key;
  child_ctx[38] = constants_0;
  return child_ctx;
}
function get_each_context_2(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[41] = list[i];
  return child_ctx;
}
function get_each_context_3(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[44] = list[i];
  return child_ctx;
}
function get_each_context_4(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[33] = list[i].currency;
  child_ctx[47] = list[i].value;
  child_ctx[48] = list[i].budget;
  return child_ctx;
}
function create_if_block_1(ctx2) {
  let each_1_anchor;
  let each_value_4 = ctx2[44].values;
  let each_blocks = [];
  for (let i = 0; i < each_value_4.length; i += 1) {
    each_blocks[i] = create_each_block_4(get_each_context_4(ctx2, each_value_4, i));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(target, anchor);
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx3, dirty) {
      if (dirty[0] & 1320) {
        each_value_4 = ctx3[44].values;
        let i;
        for (i = 0; i < each_value_4.length; i += 1) {
          const child_ctx = get_each_context_4(ctx3, each_value_4, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_4(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value_4.length;
      }
    },
    d(detaching) {
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
function create_each_block_4(ctx2) {
  let rect0;
  let rect0_fill_value;
  let rect0_width_value;
  let rect0_x_value;
  let rect0_y_value;
  let rect0_height_value;
  let rect1;
  let rect1_width_value;
  let rect1_x_value;
  let rect1_y_value;
  let rect1_height_value;
  return {
    c() {
      rect0 = svg_element("rect");
      rect1 = svg_element("rect");
      attr(rect0, "fill", rect0_fill_value = ctx2[10](ctx2[33]));
      attr(rect0, "width", rect0_width_value = ctx2[5].bandwidth());
      attr(rect0, "x", rect0_x_value = ctx2[5](ctx2[33]));
      attr(rect0, "y", rect0_y_value = ctx2[3](Math.max(0, ctx2[47])));
      attr(rect0, "height", rect0_height_value = Math.abs(ctx2[3](ctx2[47]) - ctx2[3](0)));
      attr(rect1, "class", "budget svelte-1azm6ea");
      attr(rect1, "width", rect1_width_value = ctx2[5].bandwidth());
      attr(rect1, "x", rect1_x_value = ctx2[5](ctx2[33]));
      attr(rect1, "y", rect1_y_value = ctx2[3](Math.max(0, ctx2[48])));
      attr(rect1, "height", rect1_height_value = Math.abs(ctx2[3](ctx2[48]) - ctx2[3](0)));
    },
    m(target, anchor) {
      insert(target, rect0, anchor);
      insert(target, rect1, anchor);
    },
    p(ctx3, dirty) {
      if (dirty[0] & 1280 && rect0_fill_value !== (rect0_fill_value = ctx3[10](ctx3[33]))) {
        attr(rect0, "fill", rect0_fill_value);
      }
      if (dirty[0] & 32 && rect0_width_value !== (rect0_width_value = ctx3[5].bandwidth())) {
        attr(rect0, "width", rect0_width_value);
      }
      if (dirty[0] & 288 && rect0_x_value !== (rect0_x_value = ctx3[5](ctx3[33]))) {
        attr(rect0, "x", rect0_x_value);
      }
      if (dirty[0] & 264 && rect0_y_value !== (rect0_y_value = ctx3[3](Math.max(0, ctx3[47])))) {
        attr(rect0, "y", rect0_y_value);
      }
      if (dirty[0] & 264 && rect0_height_value !== (rect0_height_value = Math.abs(ctx3[3](ctx3[47]) - ctx3[3](0)))) {
        attr(rect0, "height", rect0_height_value);
      }
      if (dirty[0] & 32 && rect1_width_value !== (rect1_width_value = ctx3[5].bandwidth())) {
        attr(rect1, "width", rect1_width_value);
      }
      if (dirty[0] & 288 && rect1_x_value !== (rect1_x_value = ctx3[5](ctx3[33]))) {
        attr(rect1, "x", rect1_x_value);
      }
      if (dirty[0] & 264 && rect1_y_value !== (rect1_y_value = ctx3[3](Math.max(0, ctx3[48])))) {
        attr(rect1, "y", rect1_y_value);
      }
      if (dirty[0] & 264 && rect1_height_value !== (rect1_height_value = Math.abs(ctx3[3](ctx3[48]) - ctx3[3](0)))) {
        attr(rect1, "height", rect1_height_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(rect0);
      if (detaching)
        detach(rect1);
    }
  };
}
function create_each_block_3(ctx2) {
  let g;
  let rect0;
  let rect0_x_value;
  let rect0_width_value;
  let a;
  let rect1;
  let rect1_transform_value;
  let rect1_width_value;
  let rect1_height_value;
  let a_href_value;
  let g_transform_value;
  let followingTooltip_action;
  let mounted;
  let dispose;
  let if_block = !ctx2[6] && create_if_block_1(ctx2);
  function followingTooltip_function() {
    return ctx2[25](ctx2[44]);
  }
  return {
    c() {
      var _a2;
      g = svg_element("g");
      rect0 = svg_element("rect");
      a = svg_element("a");
      rect1 = svg_element("rect");
      if (if_block)
        if_block.c();
      attr(rect0, "class", "group-box svelte-1azm6ea");
      attr(rect0, "x", rect0_x_value = (ctx2[4].bandwidth() - ctx2[4].step()) / 2);
      attr(rect0, "width", rect0_width_value = ctx2[4].step());
      attr(rect0, "height", ctx2[7]);
      attr(rect1, "class", "axis-group-box svelte-1azm6ea");
      attr(rect1, "transform", rect1_transform_value = `translate(0,${ctx2[7]})`);
      attr(rect1, "width", rect1_width_value = ctx2[4].bandwidth());
      attr(rect1, "height", rect1_height_value = ctx2[17].bottom);
      attr(a, "href", a_href_value = urlForTimeFilter(ctx2[44].date));
      attr(g, "class", "group svelte-1azm6ea");
      attr(g, "transform", g_transform_value = `translate(${(_a2 = ctx2[4](ctx2[44].label)) != null ? _a2 : 0},0)`);
      toggle_class(g, "desaturate", ctx2[44].date > ctx2[16]);
    },
    m(target, anchor) {
      insert(target, g, anchor);
      append(g, rect0);
      append(g, a);
      append(a, rect1);
      if (if_block)
        if_block.m(g, null);
      if (!mounted) {
        dispose = action_destroyer(followingTooltip_action = followingTooltip.call(null, g, followingTooltip_function));
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      var _a2;
      ctx2 = new_ctx;
      if (dirty[0] & 16 && rect0_x_value !== (rect0_x_value = (ctx2[4].bandwidth() - ctx2[4].step()) / 2)) {
        attr(rect0, "x", rect0_x_value);
      }
      if (dirty[0] & 16 && rect0_width_value !== (rect0_width_value = ctx2[4].step())) {
        attr(rect0, "width", rect0_width_value);
      }
      if (dirty[0] & 128) {
        attr(rect0, "height", ctx2[7]);
      }
      if (dirty[0] & 128 && rect1_transform_value !== (rect1_transform_value = `translate(0,${ctx2[7]})`)) {
        attr(rect1, "transform", rect1_transform_value);
      }
      if (dirty[0] & 16 && rect1_width_value !== (rect1_width_value = ctx2[4].bandwidth())) {
        attr(rect1, "width", rect1_width_value);
      }
      if (dirty[0] & 256 && a_href_value !== (a_href_value = urlForTimeFilter(ctx2[44].date))) {
        attr(a, "href", a_href_value);
      }
      if (!ctx2[6]) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_1(ctx2);
          if_block.c();
          if_block.m(g, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty[0] & 272 && g_transform_value !== (g_transform_value = `translate(${(_a2 = ctx2[4](ctx2[44].label)) != null ? _a2 : 0},0)`)) {
        attr(g, "transform", g_transform_value);
      }
      if (followingTooltip_action && is_function(followingTooltip_action.update) && dirty[0] & 772)
        followingTooltip_action.update.call(null, followingTooltip_function);
      if (dirty[0] & 65792) {
        toggle_class(g, "desaturate", ctx2[44].date > ctx2[16]);
      }
    },
    d(detaching) {
      if (detaching)
        detach(g);
      if (if_block)
        if_block.d();
      mounted = false;
      dispose();
    }
  };
}
function create_if_block(ctx2) {
  let each_1_anchor;
  let each_value = ctx2[0].stacks;
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block2(get_each_context2(ctx2, each_value, i));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(target, anchor);
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx3, dirty) {
      if (dirty[0] & 84541) {
        each_value = ctx3[0].stacks;
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context2(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block2(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    d(detaching) {
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
function create_each_block_2(ctx2) {
  let rect;
  let rect_width_value;
  let rect_x_value;
  let rect_y_value;
  let rect_height_value;
  let rect_fill_value;
  let followingTooltip_action;
  let mounted;
  let dispose;
  function mouseover_handler() {
    return ctx2[27](ctx2[38]);
  }
  function focus_handler() {
    return ctx2[28](ctx2[38]);
  }
  function followingTooltip_function_1() {
    return ctx2[31](ctx2[41], ctx2[38]);
  }
  return {
    c() {
      var _a2, _b;
      rect = svg_element("rect");
      attr(rect, "width", rect_width_value = ctx2[5].bandwidth());
      attr(rect, "x", rect_x_value = ((_a2 = ctx2[4](ctx2[41].data.label)) != null ? _a2 : 0) + ((_b = ctx2[5](ctx2[33])) != null ? _b : 0));
      attr(rect, "y", rect_y_value = ctx2[3](Math.max(ctx2[41][0], ctx2[41][1])));
      attr(rect, "height", rect_height_value = Math.abs(ctx2[3](ctx2[41][1]) - ctx2[3](ctx2[41][0])));
      attr(rect, "fill", rect_fill_value = ctx2[14](ctx2[38]));
      attr(rect, "class", "svelte-1azm6ea");
      toggle_class(rect, "desaturate", ctx2[41].data.date > ctx2[16]);
    },
    m(target, anchor) {
      insert(target, rect, anchor);
      if (!mounted) {
        dispose = [
          listen(rect, "mouseover", mouseover_handler),
          listen(rect, "focus", focus_handler),
          listen(rect, "mouseout", ctx2[29]),
          listen(rect, "blur", ctx2[30]),
          action_destroyer(followingTooltip_action = followingTooltip.call(null, rect, followingTooltip_function_1))
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      var _a2, _b;
      ctx2 = new_ctx;
      if (dirty[0] & 32 && rect_width_value !== (rect_width_value = ctx2[5].bandwidth())) {
        attr(rect, "width", rect_width_value);
      }
      if (dirty[0] & 49 && rect_x_value !== (rect_x_value = ((_a2 = ctx2[4](ctx2[41].data.label)) != null ? _a2 : 0) + ((_b = ctx2[5](ctx2[33])) != null ? _b : 0))) {
        attr(rect, "x", rect_x_value);
      }
      if (dirty[0] & 9 && rect_y_value !== (rect_y_value = ctx2[3](Math.max(ctx2[41][0], ctx2[41][1])))) {
        attr(rect, "y", rect_y_value);
      }
      if (dirty[0] & 9 && rect_height_value !== (rect_height_value = Math.abs(ctx2[3](ctx2[41][1]) - ctx2[3](ctx2[41][0])))) {
        attr(rect, "height", rect_height_value);
      }
      if (dirty[0] & 16385 && rect_fill_value !== (rect_fill_value = ctx2[14](ctx2[38]))) {
        attr(rect, "fill", rect_fill_value);
      }
      if (followingTooltip_action && is_function(followingTooltip_action.update) && dirty[0] & 517)
        followingTooltip_action.update.call(null, followingTooltip_function_1);
      if (dirty[0] & 65537) {
        toggle_class(rect, "desaturate", ctx2[41].data.date > ctx2[16]);
      }
    },
    d(detaching) {
      if (detaching)
        detach(rect);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_each_block_1(ctx2) {
  let a;
  let g;
  let a_href_value;
  let t4;
  let each_value_2 = ctx2[37].filter(ctx2[26]);
  let each_blocks = [];
  for (let i = 0; i < each_value_2.length; i += 1) {
    each_blocks[i] = create_each_block_2(get_each_context_2(ctx2, each_value_2, i));
  }
  return {
    c() {
      a = svg_element("a");
      g = svg_element("g");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t4 = text("v");
      attr(g, "class", "category svelte-1azm6ea");
      toggle_class(g, "faded", ctx2[11] && ctx2[38] !== ctx2[11]);
      attr(a, "href", a_href_value = urlForAccount(ctx2[38]));
    },
    m(target, anchor) {
      insert(target, a, anchor);
      append(a, g);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(g, null);
      }
      insert(target, t4, anchor);
    },
    p(ctx3, dirty) {
      if (dirty[0] & 84541) {
        each_value_2 = ctx3[37].filter(ctx3[26]);
        let i;
        for (i = 0; i < each_value_2.length; i += 1) {
          const child_ctx = get_each_context_2(ctx3, each_value_2, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_2(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(g, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value_2.length;
      }
      if (dirty[0] & 2049) {
        toggle_class(g, "faded", ctx3[11] && ctx3[38] !== ctx3[11]);
      }
      if (dirty[0] & 1 && a_href_value !== (a_href_value = urlForAccount(ctx3[38]))) {
        attr(a, "href", a_href_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(a);
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(t4);
    }
  };
}
function create_each_block2(ctx2) {
  let each_1_anchor;
  let each_value_1 = ctx2[34];
  let each_blocks = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks[i] = create_each_block_1(get_each_context_1(ctx2, each_value_1, i));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(target, anchor);
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx3, dirty) {
      if (dirty[0] & 84541) {
        each_value_1 = ctx3[34];
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_1(ctx3, each_value_1, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_1(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value_1.length;
      }
    },
    d(detaching) {
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
function create_fragment3(ctx2) {
  let svg2;
  let g;
  let axis0;
  let axis1;
  let each_1_anchor;
  let g_transform_value;
  let current;
  axis0 = new Axis_default({
    props: {
      x: true,
      axis: ctx2[13],
      innerHeight: ctx2[7]
    }
  });
  axis1 = new Axis_default({
    props: { y: true, axis: ctx2[12] }
  });
  let each_value_3 = ctx2[8];
  let each_blocks = [];
  for (let i = 0; i < each_value_3.length; i += 1) {
    each_blocks[i] = create_each_block_3(get_each_context_3(ctx2, each_value_3, i));
  }
  let if_block = ctx2[6] && create_if_block(ctx2);
  return {
    c() {
      svg2 = svg_element("svg");
      g = svg_element("g");
      create_component(axis0.$$.fragment);
      create_component(axis1.$$.fragment);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
      if (if_block)
        if_block.c();
      attr(g, "transform", g_transform_value = `translate(${ctx2[15]},${ctx2[17].top})`);
      attr(svg2, "width", ctx2[1]);
      attr(svg2, "height", height);
    },
    m(target, anchor) {
      insert(target, svg2, anchor);
      append(svg2, g);
      mount_component(axis0, g, null);
      mount_component(axis1, g, null);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(g, null);
      }
      append(g, each_1_anchor);
      if (if_block)
        if_block.m(g, null);
      current = true;
    },
    p(ctx3, dirty) {
      const axis0_changes = {};
      if (dirty[0] & 8192)
        axis0_changes.axis = ctx3[13];
      if (dirty[0] & 128)
        axis0_changes.innerHeight = ctx3[7];
      axis0.$set(axis0_changes);
      const axis1_changes = {};
      if (dirty[0] & 4096)
        axis1_changes.axis = ctx3[12];
      axis1.$set(axis1_changes);
      if (dirty[0] & 198652) {
        each_value_3 = ctx3[8];
        let i;
        for (i = 0; i < each_value_3.length; i += 1) {
          const child_ctx = get_each_context_3(ctx3, each_value_3, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_3(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(g, each_1_anchor);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value_3.length;
      }
      if (ctx3[6]) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block(ctx3);
          if_block.c();
          if_block.m(g, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (!current || dirty[0] & 32768 && g_transform_value !== (g_transform_value = `translate(${ctx3[15]},${ctx3[17].top})`)) {
        attr(g, "transform", g_transform_value);
      }
      if (!current || dirty[0] & 2) {
        attr(svg2, "width", ctx3[1]);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(axis0.$$.fragment, local);
      transition_in(axis1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(axis0.$$.fragment, local);
      transition_out(axis1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(svg2);
      destroy_component(axis0);
      destroy_component(axis1);
      destroy_each(each_blocks, detaching);
      if (if_block)
        if_block.d();
    }
  };
}
var maxColumnWidth = 100;
var height = 250;
function instance3($$self, $$props, $$invalidate) {
  let bar_groups;
  let accounts2;
  let currencies2;
  let innerHeight2;
  let maxWidth;
  let offset;
  let innerWidth;
  let showStackedBars;
  let x0;
  let x1;
  let y2;
  let colorScale;
  let xAxis;
  let yAxis;
  let $ctx;
  let $currenciesScale;
  let $barChartMode;
  component_subscribe($$self, ctx, ($$value) => $$invalidate(9, $ctx = $$value));
  component_subscribe($$self, currenciesScale, ($$value) => $$invalidate(10, $currenciesScale = $$value));
  component_subscribe($$self, barChartMode, ($$value) => $$invalidate(24, $barChartMode = $$value));
  let { data } = $$props;
  let { width } = $$props;
  let { tooltipText } = $$props;
  const today = new Date();
  const margin = { top: 10, right: 10, bottom: 30, left: 40 };
  let highlighted = null;
  let yMin;
  let yMax;
  const legend = getContext("chart-legend");
  const followingTooltip_function = (group2) => tooltipText($ctx, group2, "");
  const func = (b) => !Number.isNaN(b[1]);
  const mouseover_handler = (account2) => {
    $$invalidate(11, highlighted = account2);
  };
  const focus_handler = (account2) => {
    $$invalidate(11, highlighted = account2);
  };
  const mouseout_handler = () => {
    $$invalidate(11, highlighted = null);
  };
  const blur_handler = () => {
    $$invalidate(11, highlighted = null);
  };
  const followingTooltip_function_1 = (bar2, account2) => tooltipText($ctx, bar2.data, account2);
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(0, data = $$props2.data);
    if ("width" in $$props2)
      $$invalidate(1, width = $$props2.width);
    if ("tooltipText" in $$props2)
      $$invalidate(2, tooltipText = $$props2.tooltipText);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & 1) {
      $:
        $$invalidate(8, bar_groups = data.bar_groups);
    }
    if ($$self.$$.dirty[0] & 1) {
      $:
        $$invalidate(21, accounts2 = data.accounts);
    }
    if ($$self.$$.dirty[0] & 256) {
      $:
        $$invalidate(22, currencies2 = bar_groups[0].values.map((d) => d.currency));
    }
    if ($$self.$$.dirty[0] & 256) {
      $:
        $$invalidate(23, maxWidth = bar_groups.length * maxColumnWidth);
    }
    if ($$self.$$.dirty[0] & 8388610) {
      $:
        $$invalidate(15, offset = margin.left + Math.max(0, width - maxWidth) / 2);
    }
    if ($$self.$$.dirty[0] & 8388610) {
      $:
        $$invalidate(20, innerWidth = Math.min(width - margin.left - margin.right, maxWidth));
    }
    if ($$self.$$.dirty[0] & 16777217) {
      $:
        $$invalidate(6, showStackedBars = $barChartMode === "stacked" && data.hasStackedData);
    }
    if ($$self.$$.dirty[0] & 1048832) {
      $:
        $$invalidate(4, x0 = band().padding(0.1).domain(bar_groups.map((d) => d.label)).range([0, innerWidth]));
    }
    if ($$self.$$.dirty[0] & 4194320) {
      $:
        $$invalidate(5, x1 = band().domain(currencies2).range([0, x0.bandwidth()]));
    }
    if ($$self.$$.dirty[0] & 321) {
      $:
        $$invalidate(
          18,
          [yMin = 0, yMax = 0] = showStackedBars ? extent(data.stacks.flatMap(([, s]) => s.flat(2))) : extent(bar_groups.map((d) => d.values).flat(), (d) => d.value),
          yMin,
          ($$invalidate(19, yMax), $$invalidate(6, showStackedBars), $$invalidate(0, data), $$invalidate(8, bar_groups), $$invalidate(24, $barChartMode))
        );
    }
    if ($$self.$$.dirty[0] & 786560) {
      $:
        $$invalidate(3, y2 = linear2().range([innerHeight2, 0]).domain([Math.min(0, yMin), Math.max(0, yMax)]));
    }
    if ($$self.$$.dirty[0] & 2097152) {
      $:
        $$invalidate(14, colorScale = ordinal().domain(accounts2).range(hclColorRange(accounts2.length)));
    }
    if ($$self.$$.dirty[0] & 1120) {
      $:
        legend.set(showStackedBars ? [] : x1.domain().sort().map((c) => [c, $currenciesScale(c)]));
    }
    if ($$self.$$.dirty[0] & 1048592) {
      $:
        $$invalidate(13, xAxis = axisBottom(x0).tickSizeOuter(0).tickValues(filterTicks(x0.domain(), innerWidth / 70)));
    }
    if ($$self.$$.dirty[0] & 1049096) {
      $:
        $$invalidate(12, yAxis = axisLeft(y2).tickSize(-innerWidth).tickFormat($ctx.short));
    }
  };
  $:
    $$invalidate(7, innerHeight2 = height - margin.top - margin.bottom);
  return [
    data,
    width,
    tooltipText,
    y2,
    x0,
    x1,
    showStackedBars,
    innerHeight2,
    bar_groups,
    $ctx,
    $currenciesScale,
    highlighted,
    yAxis,
    xAxis,
    colorScale,
    offset,
    today,
    margin,
    yMin,
    yMax,
    innerWidth,
    accounts2,
    currencies2,
    maxWidth,
    $barChartMode,
    followingTooltip_function,
    func,
    mouseover_handler,
    focus_handler,
    mouseout_handler,
    blur_handler,
    followingTooltip_function_1
  ];
}
var BarChart = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance3, create_fragment3, safe_not_equal, { data: 0, width: 1, tooltipText: 2 }, null, [-1, -1]);
  }
};
var BarChart_default = BarChart;

// src/charts/ChartLegend.svelte
function get_each_context3(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[1] = list[i][0];
  child_ctx[2] = list[i][1];
  return child_ctx;
}
function create_each_block3(ctx2) {
  let span;
  let i;
  let t03;
  let t1_value = ctx2[1] + "";
  let t13;
  let t22;
  return {
    c() {
      span = element("span");
      i = element("i");
      t03 = space();
      t13 = text(t1_value);
      t22 = space();
      set_style(i, "background-color", ctx2[2]);
      attr(i, "class", "svelte-1unp29f");
      attr(span, "class", "svelte-1unp29f");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, i);
      append(span, t03);
      append(span, t13);
      append(span, t22);
    },
    p(ctx3, dirty) {
      if (dirty & 1) {
        set_style(i, "background-color", ctx3[2]);
      }
      if (dirty & 1 && t1_value !== (t1_value = ctx3[1] + ""))
        set_data(t13, t1_value);
    },
    d(detaching) {
      if (detaching)
        detach(span);
    }
  };
}
function create_fragment4(ctx2) {
  let each_1_anchor;
  let each_value = ctx2[0];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block3(get_each_context3(ctx2, each_value, i));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(target, anchor);
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx3, [dirty]) {
      if (dirty & 1) {
        each_value = ctx3[0];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context3(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block3(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
function instance4($$self, $$props, $$invalidate) {
  let { legend } = $$props;
  $$self.$$set = ($$props2) => {
    if ("legend" in $$props2)
      $$invalidate(0, legend = $$props2.legend);
  };
  return [legend];
}
var ChartLegend = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance4, create_fragment4, safe_not_equal, { legend: 0 });
  }
};
var ChartLegend_default = ChartLegend;

// node_modules/d3-hierarchy/src/hierarchy/count.js
function count(node) {
  var sum = 0, children3 = node.children, i = children3 && children3.length;
  if (!i)
    sum = 1;
  else
    while (--i >= 0)
      sum += children3[i].value;
  node.value = sum;
}
function count_default() {
  return this.eachAfter(count);
}

// node_modules/d3-hierarchy/src/hierarchy/each.js
function each_default2(callback, that) {
  let index2 = -1;
  for (const node of this) {
    callback.call(that, node, ++index2, this);
  }
  return this;
}

// node_modules/d3-hierarchy/src/hierarchy/eachBefore.js
function eachBefore_default(callback, that) {
  var node = this, nodes = [node], children3, i, index2 = -1;
  while (node = nodes.pop()) {
    callback.call(that, node, ++index2, this);
    if (children3 = node.children) {
      for (i = children3.length - 1; i >= 0; --i) {
        nodes.push(children3[i]);
      }
    }
  }
  return this;
}

// node_modules/d3-hierarchy/src/hierarchy/eachAfter.js
function eachAfter_default(callback, that) {
  var node = this, nodes = [node], next = [], children3, i, n, index2 = -1;
  while (node = nodes.pop()) {
    next.push(node);
    if (children3 = node.children) {
      for (i = 0, n = children3.length; i < n; ++i) {
        nodes.push(children3[i]);
      }
    }
  }
  while (node = next.pop()) {
    callback.call(that, node, ++index2, this);
  }
  return this;
}

// node_modules/d3-hierarchy/src/hierarchy/find.js
function find_default(callback, that) {
  let index2 = -1;
  for (const node of this) {
    if (callback.call(that, node, ++index2, this)) {
      return node;
    }
  }
}

// node_modules/d3-hierarchy/src/hierarchy/sum.js
function sum_default(value) {
  return this.eachAfter(function(node) {
    var sum = +value(node.data) || 0, children3 = node.children, i = children3 && children3.length;
    while (--i >= 0)
      sum += children3[i].value;
    node.value = sum;
  });
}

// node_modules/d3-hierarchy/src/hierarchy/sort.js
function sort_default2(compare2) {
  return this.eachBefore(function(node) {
    if (node.children) {
      node.children.sort(compare2);
    }
  });
}

// node_modules/d3-hierarchy/src/hierarchy/path.js
function path_default(end) {
  var start = this, ancestor = leastCommonAncestor(start, end), nodes = [start];
  while (start !== ancestor) {
    start = start.parent;
    nodes.push(start);
  }
  var k = nodes.length;
  while (end !== ancestor) {
    nodes.splice(k, 0, end);
    end = end.parent;
  }
  return nodes;
}
function leastCommonAncestor(a, b) {
  if (a === b)
    return a;
  var aNodes = a.ancestors(), bNodes = b.ancestors(), c = null;
  a = aNodes.pop();
  b = bNodes.pop();
  while (a === b) {
    c = a;
    a = aNodes.pop();
    b = bNodes.pop();
  }
  return c;
}

// node_modules/d3-hierarchy/src/hierarchy/ancestors.js
function ancestors_default() {
  var node = this, nodes = [node];
  while (node = node.parent) {
    nodes.push(node);
  }
  return nodes;
}

// node_modules/d3-hierarchy/src/hierarchy/descendants.js
function descendants_default() {
  return Array.from(this);
}

// node_modules/d3-hierarchy/src/hierarchy/leaves.js
function leaves_default() {
  var leaves = [];
  this.eachBefore(function(node) {
    if (!node.children) {
      leaves.push(node);
    }
  });
  return leaves;
}

// node_modules/d3-hierarchy/src/hierarchy/links.js
function links_default() {
  var root2 = this, links2 = [];
  root2.each(function(node) {
    if (node !== root2) {
      links2.push({ source: node.parent, target: node });
    }
  });
  return links2;
}

// node_modules/d3-hierarchy/src/hierarchy/iterator.js
function* iterator_default2() {
  var node = this, current, next = [node], children3, i, n;
  do {
    current = next.reverse(), next = [];
    while (node = current.pop()) {
      yield node;
      if (children3 = node.children) {
        for (i = 0, n = children3.length; i < n; ++i) {
          next.push(children3[i]);
        }
      }
    }
  } while (next.length);
}

// node_modules/d3-hierarchy/src/hierarchy/index.js
function hierarchy(data, children3) {
  if (data instanceof Map) {
    data = [void 0, data];
    if (children3 === void 0)
      children3 = mapChildren;
  } else if (children3 === void 0) {
    children3 = objectChildren;
  }
  var root2 = new Node2(data), node, nodes = [root2], child, childs, i, n;
  while (node = nodes.pop()) {
    if ((childs = children3(node.data)) && (n = (childs = Array.from(childs)).length)) {
      node.children = childs;
      for (i = n - 1; i >= 0; --i) {
        nodes.push(child = childs[i] = new Node2(childs[i]));
        child.parent = node;
        child.depth = node.depth + 1;
      }
    }
  }
  return root2.eachBefore(computeHeight);
}
function node_copy() {
  return hierarchy(this).eachBefore(copyData);
}
function objectChildren(d) {
  return d.children;
}
function mapChildren(d) {
  return Array.isArray(d) ? d[1] : null;
}
function copyData(node) {
  if (node.data.value !== void 0)
    node.value = node.data.value;
  node.data = node.data.data;
}
function computeHeight(node) {
  var height4 = 0;
  do
    node.height = height4;
  while ((node = node.parent) && node.height < ++height4);
}
function Node2(data) {
  this.data = data;
  this.depth = this.height = 0;
  this.parent = null;
}
Node2.prototype = hierarchy.prototype = {
  constructor: Node2,
  count: count_default,
  each: each_default2,
  eachAfter: eachAfter_default,
  eachBefore: eachBefore_default,
  find: find_default,
  sum: sum_default,
  sort: sort_default2,
  path: path_default,
  ancestors: ancestors_default,
  descendants: descendants_default,
  leaves: leaves_default,
  links: links_default,
  copy: node_copy,
  [Symbol.iterator]: iterator_default2
};

// node_modules/d3-hierarchy/src/accessors.js
function required(f) {
  if (typeof f !== "function")
    throw new Error();
  return f;
}

// node_modules/d3-hierarchy/src/constant.js
function constantZero() {
  return 0;
}
function constant_default3(x2) {
  return function() {
    return x2;
  };
}

// node_modules/d3-hierarchy/src/treemap/round.js
function round_default2(node) {
  node.x0 = Math.round(node.x0);
  node.y0 = Math.round(node.y0);
  node.x1 = Math.round(node.x1);
  node.y1 = Math.round(node.y1);
}

// node_modules/d3-hierarchy/src/treemap/dice.js
function dice_default(parent2, x0, y0, x1, y1) {
  var nodes = parent2.children, node, i = -1, n = nodes.length, k = parent2.value && (x1 - x0) / parent2.value;
  while (++i < n) {
    node = nodes[i], node.y0 = y0, node.y1 = y1;
    node.x0 = x0, node.x1 = x0 += node.value * k;
  }
}

// node_modules/d3-hierarchy/src/partition.js
function partition_default() {
  var dx = 1, dy = 1, padding = 0, round = false;
  function partition(root2) {
    var n = root2.height + 1;
    root2.x0 = root2.y0 = padding;
    root2.x1 = dx;
    root2.y1 = dy / n;
    root2.eachBefore(positionNode(dy, n));
    if (round)
      root2.eachBefore(round_default2);
    return root2;
  }
  function positionNode(dy2, n) {
    return function(node) {
      if (node.children) {
        dice_default(node, node.x0, dy2 * (node.depth + 1) / n, node.x1, dy2 * (node.depth + 2) / n);
      }
      var x0 = node.x0, y0 = node.y0, x1 = node.x1 - padding, y1 = node.y1 - padding;
      if (x1 < x0)
        x0 = x1 = (x0 + x1) / 2;
      if (y1 < y0)
        y0 = y1 = (y0 + y1) / 2;
      node.x0 = x0;
      node.y0 = y0;
      node.x1 = x1;
      node.y1 = y1;
    };
  }
  partition.round = function(x2) {
    return arguments.length ? (round = !!x2, partition) : round;
  };
  partition.size = function(x2) {
    return arguments.length ? (dx = +x2[0], dy = +x2[1], partition) : [dx, dy];
  };
  partition.padding = function(x2) {
    return arguments.length ? (padding = +x2, partition) : padding;
  };
  return partition;
}

// node_modules/d3-hierarchy/src/treemap/slice.js
function slice_default(parent2, x0, y0, x1, y1) {
  var nodes = parent2.children, node, i = -1, n = nodes.length, k = parent2.value && (y1 - y0) / parent2.value;
  while (++i < n) {
    node = nodes[i], node.x0 = x0, node.x1 = x1;
    node.y0 = y0, node.y1 = y0 += node.value * k;
  }
}

// node_modules/d3-hierarchy/src/treemap/squarify.js
var phi = (1 + Math.sqrt(5)) / 2;
function squarifyRatio(ratio, parent2, x0, y0, x1, y1) {
  var rows = [], nodes = parent2.children, row, nodeValue, i0 = 0, i1 = 0, n = nodes.length, dx, dy, value = parent2.value, sumValue, minValue, maxValue, newRatio, minRatio, alpha, beta;
  while (i0 < n) {
    dx = x1 - x0, dy = y1 - y0;
    do
      sumValue = nodes[i1++].value;
    while (!sumValue && i1 < n);
    minValue = maxValue = sumValue;
    alpha = Math.max(dy / dx, dx / dy) / (value * ratio);
    beta = sumValue * sumValue * alpha;
    minRatio = Math.max(maxValue / beta, beta / minValue);
    for (; i1 < n; ++i1) {
      sumValue += nodeValue = nodes[i1].value;
      if (nodeValue < minValue)
        minValue = nodeValue;
      if (nodeValue > maxValue)
        maxValue = nodeValue;
      beta = sumValue * sumValue * alpha;
      newRatio = Math.max(maxValue / beta, beta / minValue);
      if (newRatio > minRatio) {
        sumValue -= nodeValue;
        break;
      }
      minRatio = newRatio;
    }
    rows.push(row = { value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1) });
    if (row.dice)
      dice_default(row, x0, y0, x1, value ? y0 += dy * sumValue / value : y1);
    else
      slice_default(row, x0, y0, value ? x0 += dx * sumValue / value : x1, y1);
    value -= sumValue, i0 = i1;
  }
  return rows;
}
var squarify_default = function custom(ratio) {
  function squarify(parent2, x0, y0, x1, y1) {
    squarifyRatio(ratio, parent2, x0, y0, x1, y1);
  }
  squarify.ratio = function(x2) {
    return custom((x2 = +x2) > 1 ? x2 : 1);
  };
  return squarify;
}(phi);

// node_modules/d3-hierarchy/src/treemap/index.js
function treemap_default() {
  var tile = squarify_default, round = false, dx = 1, dy = 1, paddingStack = [0], paddingInner = constantZero, paddingTop = constantZero, paddingRight = constantZero, paddingBottom = constantZero, paddingLeft = constantZero;
  function treemap(root2) {
    root2.x0 = root2.y0 = 0;
    root2.x1 = dx;
    root2.y1 = dy;
    root2.eachBefore(positionNode);
    paddingStack = [0];
    if (round)
      root2.eachBefore(round_default2);
    return root2;
  }
  function positionNode(node) {
    var p = paddingStack[node.depth], x0 = node.x0 + p, y0 = node.y0 + p, x1 = node.x1 - p, y1 = node.y1 - p;
    if (x1 < x0)
      x0 = x1 = (x0 + x1) / 2;
    if (y1 < y0)
      y0 = y1 = (y0 + y1) / 2;
    node.x0 = x0;
    node.y0 = y0;
    node.x1 = x1;
    node.y1 = y1;
    if (node.children) {
      p = paddingStack[node.depth + 1] = paddingInner(node) / 2;
      x0 += paddingLeft(node) - p;
      y0 += paddingTop(node) - p;
      x1 -= paddingRight(node) - p;
      y1 -= paddingBottom(node) - p;
      if (x1 < x0)
        x0 = x1 = (x0 + x1) / 2;
      if (y1 < y0)
        y0 = y1 = (y0 + y1) / 2;
      tile(node, x0, y0, x1, y1);
    }
  }
  treemap.round = function(x2) {
    return arguments.length ? (round = !!x2, treemap) : round;
  };
  treemap.size = function(x2) {
    return arguments.length ? (dx = +x2[0], dy = +x2[1], treemap) : [dx, dy];
  };
  treemap.tile = function(x2) {
    return arguments.length ? (tile = required(x2), treemap) : tile;
  };
  treemap.padding = function(x2) {
    return arguments.length ? treemap.paddingInner(x2).paddingOuter(x2) : treemap.paddingInner();
  };
  treemap.paddingInner = function(x2) {
    return arguments.length ? (paddingInner = typeof x2 === "function" ? x2 : constant_default3(+x2), treemap) : paddingInner;
  };
  treemap.paddingOuter = function(x2) {
    return arguments.length ? treemap.paddingTop(x2).paddingRight(x2).paddingBottom(x2).paddingLeft(x2) : treemap.paddingTop();
  };
  treemap.paddingTop = function(x2) {
    return arguments.length ? (paddingTop = typeof x2 === "function" ? x2 : constant_default3(+x2), treemap) : paddingTop;
  };
  treemap.paddingRight = function(x2) {
    return arguments.length ? (paddingRight = typeof x2 === "function" ? x2 : constant_default3(+x2), treemap) : paddingRight;
  };
  treemap.paddingBottom = function(x2) {
    return arguments.length ? (paddingBottom = typeof x2 === "function" ? x2 : constant_default3(+x2), treemap) : paddingBottom;
  };
  treemap.paddingLeft = function(x2) {
    return arguments.length ? (paddingLeft = typeof x2 === "function" ? x2 : constant_default3(+x2), treemap) : paddingLeft;
  };
  return treemap;
}

// node_modules/d3-path/src/path.js
var pi = Math.PI;
var tau = 2 * pi;
var epsilon2 = 1e-6;
var tauEpsilon = tau - epsilon2;
function Path() {
  this._x0 = this._y0 = this._x1 = this._y1 = null;
  this._ = "";
}
function path() {
  return new Path();
}
Path.prototype = path.prototype = {
  constructor: Path,
  moveTo: function(x2, y2) {
    this._ += "M" + (this._x0 = this._x1 = +x2) + "," + (this._y0 = this._y1 = +y2);
  },
  closePath: function() {
    if (this._x1 !== null) {
      this._x1 = this._x0, this._y1 = this._y0;
      this._ += "Z";
    }
  },
  lineTo: function(x2, y2) {
    this._ += "L" + (this._x1 = +x2) + "," + (this._y1 = +y2);
  },
  quadraticCurveTo: function(x1, y1, x2, y2) {
    this._ += "Q" + +x1 + "," + +y1 + "," + (this._x1 = +x2) + "," + (this._y1 = +y2);
  },
  bezierCurveTo: function(x1, y1, x2, y2, x3, y3) {
    this._ += "C" + +x1 + "," + +y1 + "," + +x2 + "," + +y2 + "," + (this._x1 = +x3) + "," + (this._y1 = +y3);
  },
  arcTo: function(x1, y1, x2, y2, r) {
    x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;
    var x0 = this._x1, y0 = this._y1, x21 = x2 - x1, y21 = y2 - y1, x01 = x0 - x1, y01 = y0 - y1, l01_2 = x01 * x01 + y01 * y01;
    if (r < 0)
      throw new Error("negative radius: " + r);
    if (this._x1 === null) {
      this._ += "M" + (this._x1 = x1) + "," + (this._y1 = y1);
    } else if (!(l01_2 > epsilon2))
      ;
    else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon2) || !r) {
      this._ += "L" + (this._x1 = x1) + "," + (this._y1 = y1);
    } else {
      var x20 = x2 - x0, y20 = y2 - y0, l21_2 = x21 * x21 + y21 * y21, l20_2 = x20 * x20 + y20 * y20, l21 = Math.sqrt(l21_2), l01 = Math.sqrt(l01_2), l = r * Math.tan((pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2), t01 = l / l01, t21 = l / l21;
      if (Math.abs(t01 - 1) > epsilon2) {
        this._ += "L" + (x1 + t01 * x01) + "," + (y1 + t01 * y01);
      }
      this._ += "A" + r + "," + r + ",0,0," + +(y01 * x20 > x01 * y20) + "," + (this._x1 = x1 + t21 * x21) + "," + (this._y1 = y1 + t21 * y21);
    }
  },
  arc: function(x2, y2, r, a0, a1, ccw) {
    x2 = +x2, y2 = +y2, r = +r, ccw = !!ccw;
    var dx = r * Math.cos(a0), dy = r * Math.sin(a0), x0 = x2 + dx, y0 = y2 + dy, cw = 1 ^ ccw, da = ccw ? a0 - a1 : a1 - a0;
    if (r < 0)
      throw new Error("negative radius: " + r);
    if (this._x1 === null) {
      this._ += "M" + x0 + "," + y0;
    } else if (Math.abs(this._x1 - x0) > epsilon2 || Math.abs(this._y1 - y0) > epsilon2) {
      this._ += "L" + x0 + "," + y0;
    }
    if (!r)
      return;
    if (da < 0)
      da = da % tau + tau;
    if (da > tauEpsilon) {
      this._ += "A" + r + "," + r + ",0,1," + cw + "," + (x2 - dx) + "," + (y2 - dy) + "A" + r + "," + r + ",0,1," + cw + "," + (this._x1 = x0) + "," + (this._y1 = y0);
    } else if (da > epsilon2) {
      this._ += "A" + r + "," + r + ",0," + +(da >= pi) + "," + cw + "," + (this._x1 = x2 + r * Math.cos(a1)) + "," + (this._y1 = y2 + r * Math.sin(a1));
    }
  },
  rect: function(x2, y2, w, h) {
    this._ += "M" + (this._x0 = this._x1 = +x2) + "," + (this._y0 = this._y1 = +y2) + "h" + +w + "v" + +h + "h" + -w + "Z";
  },
  toString: function() {
    return this._;
  }
};
var path_default2 = path;

// node_modules/d3-shape/src/constant.js
function constant_default4(x2) {
  return function constant2() {
    return x2;
  };
}

// node_modules/d3-shape/src/math.js
var abs = Math.abs;
var atan2 = Math.atan2;
var cos = Math.cos;
var max2 = Math.max;
var min2 = Math.min;
var sin = Math.sin;
var sqrt2 = Math.sqrt;
var epsilon3 = 1e-12;
var pi2 = Math.PI;
var halfPi = pi2 / 2;
var tau2 = 2 * pi2;
function acos(x2) {
  return x2 > 1 ? 0 : x2 < -1 ? pi2 : Math.acos(x2);
}
function asin(x2) {
  return x2 >= 1 ? halfPi : x2 <= -1 ? -halfPi : Math.asin(x2);
}

// node_modules/d3-shape/src/arc.js
function arcInnerRadius(d) {
  return d.innerRadius;
}
function arcOuterRadius(d) {
  return d.outerRadius;
}
function arcStartAngle(d) {
  return d.startAngle;
}
function arcEndAngle(d) {
  return d.endAngle;
}
function arcPadAngle(d) {
  return d && d.padAngle;
}
function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  var x10 = x1 - x0, y10 = y1 - y0, x32 = x3 - x2, y32 = y3 - y2, t4 = y32 * x10 - x32 * y10;
  if (t4 * t4 < epsilon3)
    return;
  t4 = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t4;
  return [x0 + t4 * x10, y0 + t4 * y10];
}
function cornerTangents(x0, y0, x1, y1, r1, rc, cw) {
  var x01 = x0 - x1, y01 = y0 - y1, lo = (cw ? rc : -rc) / sqrt2(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x11 = x0 + ox, y11 = y0 + oy, x10 = x1 + ox, y10 = y1 + oy, x00 = (x11 + x10) / 2, y00 = (y11 + y10) / 2, dx = x10 - x11, dy = y10 - y11, d2 = dx * dx + dy * dy, r = r1 - rc, D = x11 * y10 - x10 * y11, d = (dy < 0 ? -1 : 1) * sqrt2(max2(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x00, dy0 = cy0 - y00, dx1 = cx1 - x00, dy1 = cy1 - y00;
  if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1)
    cx0 = cx1, cy0 = cy1;
  return {
    cx: cx0,
    cy: cy0,
    x01: -ox,
    y01: -oy,
    x11: cx0 * (r1 / r - 1),
    y11: cy0 * (r1 / r - 1)
  };
}
function arc_default() {
  var innerRadius = arcInnerRadius, outerRadius = arcOuterRadius, cornerRadius = constant_default4(0), padRadius = null, startAngle = arcStartAngle, endAngle = arcEndAngle, padAngle = arcPadAngle, context = null;
  function arc() {
    var buffer, r, r0 = +innerRadius.apply(this, arguments), r1 = +outerRadius.apply(this, arguments), a0 = startAngle.apply(this, arguments) - halfPi, a1 = endAngle.apply(this, arguments) - halfPi, da = abs(a1 - a0), cw = a1 > a0;
    if (!context)
      context = buffer = path_default2();
    if (r1 < r0)
      r = r1, r1 = r0, r0 = r;
    if (!(r1 > epsilon3))
      context.moveTo(0, 0);
    else if (da > tau2 - epsilon3) {
      context.moveTo(r1 * cos(a0), r1 * sin(a0));
      context.arc(0, 0, r1, a0, a1, !cw);
      if (r0 > epsilon3) {
        context.moveTo(r0 * cos(a1), r0 * sin(a1));
        context.arc(0, 0, r0, a1, a0, cw);
      }
    } else {
      var a01 = a0, a11 = a1, a00 = a0, a10 = a1, da0 = da, da1 = da, ap = padAngle.apply(this, arguments) / 2, rp = ap > epsilon3 && (padRadius ? +padRadius.apply(this, arguments) : sqrt2(r0 * r0 + r1 * r1)), rc = min2(abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments)), rc0 = rc, rc1 = rc, t03, t13;
      if (rp > epsilon3) {
        var p0 = asin(rp / r0 * sin(ap)), p1 = asin(rp / r1 * sin(ap));
        if ((da0 -= p0 * 2) > epsilon3)
          p0 *= cw ? 1 : -1, a00 += p0, a10 -= p0;
        else
          da0 = 0, a00 = a10 = (a0 + a1) / 2;
        if ((da1 -= p1 * 2) > epsilon3)
          p1 *= cw ? 1 : -1, a01 += p1, a11 -= p1;
        else
          da1 = 0, a01 = a11 = (a0 + a1) / 2;
      }
      var x01 = r1 * cos(a01), y01 = r1 * sin(a01), x10 = r0 * cos(a10), y10 = r0 * sin(a10);
      if (rc > epsilon3) {
        var x11 = r1 * cos(a11), y11 = r1 * sin(a11), x00 = r0 * cos(a00), y00 = r0 * sin(a00), oc;
        if (da < pi2 && (oc = intersect(x01, y01, x00, y00, x11, y11, x10, y10))) {
          var ax = x01 - oc[0], ay = y01 - oc[1], bx = x11 - oc[0], by = y11 - oc[1], kc = 1 / sin(acos((ax * bx + ay * by) / (sqrt2(ax * ax + ay * ay) * sqrt2(bx * bx + by * by))) / 2), lc = sqrt2(oc[0] * oc[0] + oc[1] * oc[1]);
          rc0 = min2(rc, (r0 - lc) / (kc - 1));
          rc1 = min2(rc, (r1 - lc) / (kc + 1));
        }
      }
      if (!(da1 > epsilon3))
        context.moveTo(x01, y01);
      else if (rc1 > epsilon3) {
        t03 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw);
        t13 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw);
        context.moveTo(t03.cx + t03.x01, t03.cy + t03.y01);
        if (rc1 < rc)
          context.arc(t03.cx, t03.cy, rc1, atan2(t03.y01, t03.x01), atan2(t13.y01, t13.x01), !cw);
        else {
          context.arc(t03.cx, t03.cy, rc1, atan2(t03.y01, t03.x01), atan2(t03.y11, t03.x11), !cw);
          context.arc(0, 0, r1, atan2(t03.cy + t03.y11, t03.cx + t03.x11), atan2(t13.cy + t13.y11, t13.cx + t13.x11), !cw);
          context.arc(t13.cx, t13.cy, rc1, atan2(t13.y11, t13.x11), atan2(t13.y01, t13.x01), !cw);
        }
      } else
        context.moveTo(x01, y01), context.arc(0, 0, r1, a01, a11, !cw);
      if (!(r0 > epsilon3) || !(da0 > epsilon3))
        context.lineTo(x10, y10);
      else if (rc0 > epsilon3) {
        t03 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw);
        t13 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw);
        context.lineTo(t03.cx + t03.x01, t03.cy + t03.y01);
        if (rc0 < rc)
          context.arc(t03.cx, t03.cy, rc0, atan2(t03.y01, t03.x01), atan2(t13.y01, t13.x01), !cw);
        else {
          context.arc(t03.cx, t03.cy, rc0, atan2(t03.y01, t03.x01), atan2(t03.y11, t03.x11), !cw);
          context.arc(0, 0, r0, atan2(t03.cy + t03.y11, t03.cx + t03.x11), atan2(t13.cy + t13.y11, t13.cx + t13.x11), cw);
          context.arc(t13.cx, t13.cy, rc0, atan2(t13.y11, t13.x11), atan2(t13.y01, t13.x01), !cw);
        }
      } else
        context.arc(0, 0, r0, a10, a00, cw);
    }
    context.closePath();
    if (buffer)
      return context = null, buffer + "" || null;
  }
  arc.centroid = function() {
    var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - pi2 / 2;
    return [cos(a) * r, sin(a) * r];
  };
  arc.innerRadius = function(_2) {
    return arguments.length ? (innerRadius = typeof _2 === "function" ? _2 : constant_default4(+_2), arc) : innerRadius;
  };
  arc.outerRadius = function(_2) {
    return arguments.length ? (outerRadius = typeof _2 === "function" ? _2 : constant_default4(+_2), arc) : outerRadius;
  };
  arc.cornerRadius = function(_2) {
    return arguments.length ? (cornerRadius = typeof _2 === "function" ? _2 : constant_default4(+_2), arc) : cornerRadius;
  };
  arc.padRadius = function(_2) {
    return arguments.length ? (padRadius = _2 == null ? null : typeof _2 === "function" ? _2 : constant_default4(+_2), arc) : padRadius;
  };
  arc.startAngle = function(_2) {
    return arguments.length ? (startAngle = typeof _2 === "function" ? _2 : constant_default4(+_2), arc) : startAngle;
  };
  arc.endAngle = function(_2) {
    return arguments.length ? (endAngle = typeof _2 === "function" ? _2 : constant_default4(+_2), arc) : endAngle;
  };
  arc.padAngle = function(_2) {
    return arguments.length ? (padAngle = typeof _2 === "function" ? _2 : constant_default4(+_2), arc) : padAngle;
  };
  arc.context = function(_2) {
    return arguments.length ? (context = _2 == null ? null : _2, arc) : context;
  };
  return arc;
}

// node_modules/d3-shape/src/array.js
var slice = Array.prototype.slice;
function array_default(x2) {
  return typeof x2 === "object" && "length" in x2 ? x2 : Array.from(x2);
}

// node_modules/d3-shape/src/curve/linear.js
function Linear(context) {
  this._context = context;
}
Linear.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || this._line !== 0 && this._point === 1)
      this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x2, y2) {
    x2 = +x2, y2 = +y2;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._line ? this._context.lineTo(x2, y2) : this._context.moveTo(x2, y2);
        break;
      case 1:
        this._point = 2;
      default:
        this._context.lineTo(x2, y2);
        break;
    }
  }
};
function linear_default(context) {
  return new Linear(context);
}

// node_modules/d3-shape/src/point.js
function x(p) {
  return p[0];
}
function y(p) {
  return p[1];
}

// node_modules/d3-shape/src/line.js
function line_default(x2, y2) {
  var defined = constant_default4(true), context = null, curve = linear_default, output = null;
  x2 = typeof x2 === "function" ? x2 : x2 === void 0 ? x : constant_default4(x2);
  y2 = typeof y2 === "function" ? y2 : y2 === void 0 ? y : constant_default4(y2);
  function line(data) {
    var i, n = (data = array_default(data)).length, d, defined0 = false, buffer;
    if (context == null)
      output = curve(buffer = path_default2());
    for (i = 0; i <= n; ++i) {
      if (!(i < n && defined(d = data[i], i, data)) === defined0) {
        if (defined0 = !defined0)
          output.lineStart();
        else
          output.lineEnd();
      }
      if (defined0)
        output.point(+x2(d, i, data), +y2(d, i, data));
    }
    if (buffer)
      return output = null, buffer + "" || null;
  }
  line.x = function(_2) {
    return arguments.length ? (x2 = typeof _2 === "function" ? _2 : constant_default4(+_2), line) : x2;
  };
  line.y = function(_2) {
    return arguments.length ? (y2 = typeof _2 === "function" ? _2 : constant_default4(+_2), line) : y2;
  };
  line.defined = function(_2) {
    return arguments.length ? (defined = typeof _2 === "function" ? _2 : constant_default4(!!_2), line) : defined;
  };
  line.curve = function(_2) {
    return arguments.length ? (curve = _2, context != null && (output = curve(context)), line) : curve;
  };
  line.context = function(_2) {
    return arguments.length ? (_2 == null ? context = output = null : output = curve(context = _2), line) : context;
  };
  return line;
}

// node_modules/d3-shape/src/area.js
function area_default(x0, y0, y1) {
  var x1 = null, defined = constant_default4(true), context = null, curve = linear_default, output = null;
  x0 = typeof x0 === "function" ? x0 : x0 === void 0 ? x : constant_default4(+x0);
  y0 = typeof y0 === "function" ? y0 : y0 === void 0 ? constant_default4(0) : constant_default4(+y0);
  y1 = typeof y1 === "function" ? y1 : y1 === void 0 ? y : constant_default4(+y1);
  function area(data) {
    var i, j, k, n = (data = array_default(data)).length, d, defined0 = false, buffer, x0z = new Array(n), y0z = new Array(n);
    if (context == null)
      output = curve(buffer = path_default2());
    for (i = 0; i <= n; ++i) {
      if (!(i < n && defined(d = data[i], i, data)) === defined0) {
        if (defined0 = !defined0) {
          j = i;
          output.areaStart();
          output.lineStart();
        } else {
          output.lineEnd();
          output.lineStart();
          for (k = i - 1; k >= j; --k) {
            output.point(x0z[k], y0z[k]);
          }
          output.lineEnd();
          output.areaEnd();
        }
      }
      if (defined0) {
        x0z[i] = +x0(d, i, data), y0z[i] = +y0(d, i, data);
        output.point(x1 ? +x1(d, i, data) : x0z[i], y1 ? +y1(d, i, data) : y0z[i]);
      }
    }
    if (buffer)
      return output = null, buffer + "" || null;
  }
  function arealine() {
    return line_default().defined(defined).curve(curve).context(context);
  }
  area.x = function(_2) {
    return arguments.length ? (x0 = typeof _2 === "function" ? _2 : constant_default4(+_2), x1 = null, area) : x0;
  };
  area.x0 = function(_2) {
    return arguments.length ? (x0 = typeof _2 === "function" ? _2 : constant_default4(+_2), area) : x0;
  };
  area.x1 = function(_2) {
    return arguments.length ? (x1 = _2 == null ? null : typeof _2 === "function" ? _2 : constant_default4(+_2), area) : x1;
  };
  area.y = function(_2) {
    return arguments.length ? (y0 = typeof _2 === "function" ? _2 : constant_default4(+_2), y1 = null, area) : y0;
  };
  area.y0 = function(_2) {
    return arguments.length ? (y0 = typeof _2 === "function" ? _2 : constant_default4(+_2), area) : y0;
  };
  area.y1 = function(_2) {
    return arguments.length ? (y1 = _2 == null ? null : typeof _2 === "function" ? _2 : constant_default4(+_2), area) : y1;
  };
  area.lineX0 = area.lineY0 = function() {
    return arealine().x(x0).y(y0);
  };
  area.lineY1 = function() {
    return arealine().x(x0).y(y1);
  };
  area.lineX1 = function() {
    return arealine().x(x1).y(y0);
  };
  area.defined = function(_2) {
    return arguments.length ? (defined = typeof _2 === "function" ? _2 : constant_default4(!!_2), area) : defined;
  };
  area.curve = function(_2) {
    return arguments.length ? (curve = _2, context != null && (output = curve(context)), area) : curve;
  };
  area.context = function(_2) {
    return arguments.length ? (_2 == null ? context = output = null : output = curve(context = _2), area) : context;
  };
  return area;
}

// node_modules/d3-shape/src/curve/step.js
function Step(context, t4) {
  this._context = context;
  this._t = t4;
}
Step.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x = this._y = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    if (0 < this._t && this._t < 1 && this._point === 2)
      this._context.lineTo(this._x, this._y);
    if (this._line || this._line !== 0 && this._point === 1)
      this._context.closePath();
    if (this._line >= 0)
      this._t = 1 - this._t, this._line = 1 - this._line;
  },
  point: function(x2, y2) {
    x2 = +x2, y2 = +y2;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._line ? this._context.lineTo(x2, y2) : this._context.moveTo(x2, y2);
        break;
      case 1:
        this._point = 2;
      default: {
        if (this._t <= 0) {
          this._context.lineTo(this._x, y2);
          this._context.lineTo(x2, y2);
        } else {
          var x1 = this._x * (1 - this._t) + x2 * this._t;
          this._context.lineTo(x1, this._y);
          this._context.lineTo(x1, y2);
        }
        break;
      }
    }
    this._x = x2, this._y = y2;
  }
};
function stepAfter(context) {
  return new Step(context, 1);
}

// node_modules/d3-shape/src/offset/none.js
function none_default(series, order) {
  if (!((n = series.length) > 1))
    return;
  for (var i = 1, j, s0, s1 = series[order[0]], n, m = s1.length; i < n; ++i) {
    s0 = s1, s1 = series[order[i]];
    for (j = 0; j < m; ++j) {
      s1[j][1] += s1[j][0] = isNaN(s0[j][1]) ? s0[j][0] : s0[j][1];
    }
  }
}

// node_modules/d3-shape/src/order/none.js
function none_default2(series) {
  var n = series.length, o = new Array(n);
  while (--n >= 0)
    o[n] = n;
  return o;
}

// node_modules/d3-shape/src/stack.js
function stackValue(d, key) {
  return d[key];
}
function stackSeries(key) {
  const series = [];
  series.key = key;
  return series;
}
function stack_default() {
  var keys = constant_default4([]), order = none_default2, offset = none_default, value = stackValue;
  function stack(data) {
    var sz = Array.from(keys.apply(this, arguments), stackSeries), i, n = sz.length, j = -1, oz;
    for (const d of data) {
      for (i = 0, ++j; i < n; ++i) {
        (sz[i][j] = [0, +value(d, sz[i].key, j, data)]).data = d;
      }
    }
    for (i = 0, oz = array_default(order(sz)); i < n; ++i) {
      sz[oz[i]].index = i;
    }
    offset(sz, oz);
    return sz;
  }
  stack.keys = function(_2) {
    return arguments.length ? (keys = typeof _2 === "function" ? _2 : constant_default4(Array.from(_2)), stack) : keys;
  };
  stack.value = function(_2) {
    return arguments.length ? (value = typeof _2 === "function" ? _2 : constant_default4(+_2), stack) : value;
  };
  stack.order = function(_2) {
    return arguments.length ? (order = _2 == null ? none_default2 : typeof _2 === "function" ? _2 : constant_default4(Array.from(_2)), stack) : order;
  };
  stack.offset = function(_2) {
    return arguments.length ? (offset = _2 == null ? none_default : _2, stack) : offset;
  };
  return stack;
}

// node_modules/d3-shape/src/offset/diverging.js
function diverging_default(series, order) {
  if (!((n = series.length) > 0))
    return;
  for (var i, j = 0, d, dy, yp, yn, n, m = series[order[0]].length; j < m; ++j) {
    for (yp = yn = 0, i = 0; i < n; ++i) {
      if ((dy = (d = series[order[i]][j])[1] - d[0]) > 0) {
        d[0] = yp, d[1] = yp += dy;
      } else if (dy < 0) {
        d[1] = yn, d[0] = yn += dy;
      } else {
        d[0] = 0, d[1] = dy;
      }
    }
  }
}

// src/charts/Sunburst.svelte
function get_each_context4(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[19] = list[i];
  return child_ctx;
}
function create_each_block4(ctx2) {
  let a;
  let path2;
  let path_fill_value;
  let path_d_value;
  let a_href_value;
  let mounted;
  let dispose;
  function mouseover_handler() {
    return ctx2[13](ctx2[19]);
  }
  function focus_handler() {
    return ctx2[14](ctx2[19]);
  }
  return {
    c() {
      var _a2;
      a = svg_element("a");
      path2 = svg_element("path");
      attr(path2, "fill-rule", "evenodd");
      attr(path2, "fill", path_fill_value = ctx2[8](ctx2[19].data.account));
      attr(path2, "d", path_d_value = (_a2 = ctx2[4](ctx2[19])) != null ? _a2 : void 0);
      attr(path2, "class", "svelte-1j2l4ij");
      toggle_class(path2, "half", ctx2[2] && !ctx2[6].startsWith(ctx2[19].data.account));
      attr(a, "href", a_href_value = urlForAccount(ctx2[19].data.account));
    },
    m(target, anchor) {
      insert(target, a, anchor);
      append(a, path2);
      if (!mounted) {
        dispose = [
          listen(path2, "mouseover", mouseover_handler),
          listen(path2, "focus", focus_handler)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      var _a2;
      ctx2 = new_ctx;
      if (dirty & 384 && path_fill_value !== (path_fill_value = ctx2[8](ctx2[19].data.account))) {
        attr(path2, "fill", path_fill_value);
      }
      if (dirty & 144 && path_d_value !== (path_d_value = (_a2 = ctx2[4](ctx2[19])) != null ? _a2 : void 0)) {
        attr(path2, "d", path_d_value);
      }
      if (dirty & 196) {
        toggle_class(path2, "half", ctx2[2] && !ctx2[6].startsWith(ctx2[19].data.account));
      }
      if (dirty & 128 && a_href_value !== (a_href_value = urlForAccount(ctx2[19].data.account))) {
        attr(a, "href", a_href_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(a);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_fragment5(ctx2) {
  let g;
  let circle;
  let text0;
  let t03;
  let text1;
  let t13;
  let g_transform_value;
  let mounted;
  let dispose;
  let each_value = ctx2[7];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block4(get_each_context4(ctx2, each_value, i));
  }
  return {
    c() {
      g = svg_element("g");
      circle = svg_element("circle");
      text0 = svg_element("text");
      t03 = text(ctx2[6]);
      text1 = svg_element("text");
      t13 = text(ctx2[5]);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      set_style(circle, "opacity", "0");
      attr(circle, "r", ctx2[3]);
      attr(text0, "class", "account svelte-1j2l4ij");
      attr(text0, "text-anchor", "middle");
      attr(text1, "class", "balance svelte-1j2l4ij");
      attr(text1, "dy", "1.2em");
      attr(text1, "text-anchor", "middle");
      attr(g, "width", ctx2[0]);
      attr(g, "height", ctx2[1]);
      attr(g, "transform", g_transform_value = `translate(${ctx2[0] / 2},${ctx2[1] / 2})`);
    },
    m(target, anchor) {
      insert(target, g, anchor);
      append(g, circle);
      append(g, text0);
      append(text0, t03);
      append(g, text1);
      append(text1, t13);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(g, null);
      }
      if (!mounted) {
        dispose = listen(g, "mouseleave", ctx2[15]);
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & 8) {
        attr(circle, "r", ctx3[3]);
      }
      if (dirty & 64)
        set_data(t03, ctx3[6]);
      if (dirty & 32)
        set_data(t13, ctx3[5]);
      if (dirty & 468) {
        each_value = ctx3[7];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context4(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block4(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(g, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
      if (dirty & 1) {
        attr(g, "width", ctx3[0]);
      }
      if (dirty & 2) {
        attr(g, "height", ctx3[1]);
      }
      if (dirty & 3 && g_transform_value !== (g_transform_value = `translate(${ctx3[0] / 2},${ctx3[1] / 2})`)) {
        attr(g, "transform", g_transform_value);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(g);
      destroy_each(each_blocks, detaching);
      mounted = false;
      dispose();
    }
  };
}
function instance5($$self, $$props, $$invalidate) {
  let radius;
  let root2;
  let leaves;
  let currentAccount;
  let currentBalance;
  let y2;
  let arcShape;
  let $ctx;
  let $sunburstScale;
  component_subscribe($$self, ctx, ($$value) => $$invalidate(16, $ctx = $$value));
  component_subscribe($$self, sunburstScale, ($$value) => $$invalidate(8, $sunburstScale = $$value));
  let { data } = $$props;
  let { currency } = $$props;
  let { width } = $$props;
  let { height: height4 } = $$props;
  let current = null;
  function balanceText(d) {
    var _a2;
    const val = (_a2 = d.value) != null ? _a2 : 0;
    const rootVal = root2.value || 1;
    return `${$ctx.amount(val, currency)} (${formatPercentage(val / rootVal)})`;
  }
  const x2 = linear2().range([0, 2 * Math.PI]);
  const mouseover_handler = (d) => {
    $$invalidate(2, current = d);
  };
  const focus_handler = (d) => {
    $$invalidate(2, current = d);
  };
  const mouseleave_handler = () => {
    $$invalidate(2, current = null);
  };
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(9, data = $$props2.data);
    if ("currency" in $$props2)
      $$invalidate(10, currency = $$props2.currency);
    if ("width" in $$props2)
      $$invalidate(0, width = $$props2.width);
    if ("height" in $$props2)
      $$invalidate(1, height4 = $$props2.height);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 3) {
      $:
        $$invalidate(3, radius = Math.min(width, height4) / 2);
    }
    if ($$self.$$.dirty & 512) {
      $:
        $$invalidate(12, root2 = partition_default()(data));
    }
    if ($$self.$$.dirty & 4096) {
      $:
        $$invalidate(7, leaves = root2.descendants().filter((d) => !d.data.dummy && d.depth));
    }
    if ($$self.$$.dirty & 4096) {
      $:
        if (root2) {
          $$invalidate(2, current = null);
        }
    }
    if ($$self.$$.dirty & 4100) {
      $:
        $$invalidate(6, currentAccount = current ? current.data.account : root2.data.account);
    }
    if ($$self.$$.dirty & 4100) {
      $:
        $$invalidate(5, currentBalance = current ? balanceText(current) : balanceText(root2));
    }
    if ($$self.$$.dirty & 8) {
      $:
        $$invalidate(11, y2 = sqrt().range([0, radius]));
    }
    if ($$self.$$.dirty & 2048) {
      $:
        $$invalidate(4, arcShape = arc_default().startAngle((d) => x2(d.x0)).endAngle((d) => x2(d.x1)).innerRadius((d) => y2(d.y0)).outerRadius((d) => y2(d.y1)));
    }
  };
  return [
    width,
    height4,
    current,
    radius,
    arcShape,
    currentBalance,
    currentAccount,
    leaves,
    $sunburstScale,
    data,
    currency,
    y2,
    root2,
    mouseover_handler,
    focus_handler,
    mouseleave_handler
  ];
}
var Sunburst = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance5, create_fragment5, safe_not_equal, {
      data: 9,
      currency: 10,
      width: 0,
      height: 1
    });
  }
};
var Sunburst_default = Sunburst;

// src/charts/Treemap.svelte
function get_each_context5(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[12] = list[i];
  return child_ctx;
}
function create_each_block5(ctx2) {
  let g;
  let rect;
  let rect_fill_value;
  let rect_width_value;
  let rect_height_value;
  let a;
  let text_1;
  let t_value = (ctx2[12].data.account.split(":").pop() || "") + "";
  let t4;
  let text_1_x_value;
  let text_1_y_value;
  let setVisibility_action;
  let a_href_value;
  let g_transform_value;
  let followingTooltip_action;
  let mounted;
  let dispose;
  function followingTooltip_function() {
    return ctx2[8](ctx2[12]);
  }
  return {
    c() {
      g = svg_element("g");
      rect = svg_element("rect");
      a = svg_element("a");
      text_1 = svg_element("text");
      t4 = text(t_value);
      attr(rect, "fill", rect_fill_value = ctx2[3](ctx2[12]));
      attr(rect, "width", rect_width_value = ctx2[12].x1 - ctx2[12].x0);
      attr(rect, "height", rect_height_value = ctx2[12].y1 - ctx2[12].y0);
      attr(text_1, "dy", ".5em");
      attr(text_1, "x", text_1_x_value = (ctx2[12].x1 - ctx2[12].x0) / 2);
      attr(text_1, "y", text_1_y_value = (ctx2[12].y1 - ctx2[12].y0) / 2);
      attr(text_1, "text-anchor", "middle");
      attr(text_1, "class", "svelte-1n6q2h8");
      attr(a, "href", a_href_value = urlForAccount(ctx2[12].data.account));
      attr(g, "transform", g_transform_value = `translate(${ctx2[12].x0},${ctx2[12].y0})`);
    },
    m(target, anchor) {
      insert(target, g, anchor);
      append(g, rect);
      append(g, a);
      append(a, text_1);
      append(text_1, t4);
      if (!mounted) {
        dispose = [
          action_destroyer(setVisibility_action = setVisibility.call(null, text_1, ctx2[12])),
          action_destroyer(followingTooltip_action = followingTooltip.call(null, g, followingTooltip_function))
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & 4 && rect_fill_value !== (rect_fill_value = ctx2[3](ctx2[12]))) {
        attr(rect, "fill", rect_fill_value);
      }
      if (dirty & 4 && rect_width_value !== (rect_width_value = ctx2[12].x1 - ctx2[12].x0)) {
        attr(rect, "width", rect_width_value);
      }
      if (dirty & 4 && rect_height_value !== (rect_height_value = ctx2[12].y1 - ctx2[12].y0)) {
        attr(rect, "height", rect_height_value);
      }
      if (dirty & 4 && t_value !== (t_value = (ctx2[12].data.account.split(":").pop() || "") + ""))
        set_data(t4, t_value);
      if (dirty & 4 && text_1_x_value !== (text_1_x_value = (ctx2[12].x1 - ctx2[12].x0) / 2)) {
        attr(text_1, "x", text_1_x_value);
      }
      if (dirty & 4 && text_1_y_value !== (text_1_y_value = (ctx2[12].y1 - ctx2[12].y0) / 2)) {
        attr(text_1, "y", text_1_y_value);
      }
      if (setVisibility_action && is_function(setVisibility_action.update) && dirty & 4)
        setVisibility_action.update.call(null, ctx2[12]);
      if (dirty & 4 && a_href_value !== (a_href_value = urlForAccount(ctx2[12].data.account))) {
        attr(a, "href", a_href_value);
      }
      if (dirty & 4 && g_transform_value !== (g_transform_value = `translate(${ctx2[12].x0},${ctx2[12].y0})`)) {
        attr(g, "transform", g_transform_value);
      }
      if (followingTooltip_action && is_function(followingTooltip_action.update) && dirty & 4)
        followingTooltip_action.update.call(null, followingTooltip_function);
    },
    d(detaching) {
      if (detaching)
        detach(g);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_fragment6(ctx2) {
  let svg2;
  let each_value = ctx2[2];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block5(get_each_context5(ctx2, each_value, i));
  }
  return {
    c() {
      svg2 = svg_element("svg");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(svg2, "width", ctx2[0]);
      attr(svg2, "height", ctx2[1]);
      attr(svg2, "class", "svelte-1n6q2h8");
    },
    m(target, anchor) {
      insert(target, svg2, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(svg2, null);
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & 28) {
        each_value = ctx3[2];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context5(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block5(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(svg2, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
      if (dirty & 1) {
        attr(svg2, "width", ctx3[0]);
      }
      if (dirty & 2) {
        attr(svg2, "height", ctx3[1]);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(svg2);
      destroy_each(each_blocks, detaching);
    }
  };
}
function setVisibility(node, param) {
  function update2(d) {
    const length = node.getComputedTextLength();
    node.style.visibility = d.x1 - d.x0 > length + 4 && d.y1 - d.y0 > 14 ? "visible" : "hidden";
  }
  update2(param);
  return { update: update2 };
}
function instance6($$self, $$props, $$invalidate) {
  let height4;
  let root2;
  let leaves;
  let $ctx;
  let $treemapScale;
  component_subscribe($$self, ctx, ($$value) => $$invalidate(9, $ctx = $$value));
  component_subscribe($$self, treemapScale, ($$value) => $$invalidate(10, $treemapScale = $$value));
  let { data } = $$props;
  let { width } = $$props;
  let { currency } = $$props;
  const tree = treemap_default().paddingInner(2).round(true);
  function fill(d) {
    const node = d.data.dummy && d.parent ? d.parent : d;
    if (node.depth === 1 || !node.parent) {
      return $treemapScale(node.data.account);
    }
    return $treemapScale(node.parent.data.account);
  }
  function tooltipText(d) {
    var _a2;
    const val = (_a2 = d.value) != null ? _a2 : 0;
    const rootValue = root2.value || 1;
    return [
      domHelpers.t(`${$ctx.amount(val, currency)} (${formatPercentage(val / rootValue)})`),
      domHelpers.em(d.data.account)
    ];
  }
  const followingTooltip_function = (d) => tooltipText(d);
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(5, data = $$props2.data);
    if ("width" in $$props2)
      $$invalidate(0, width = $$props2.width);
    if ("currency" in $$props2)
      $$invalidate(6, currency = $$props2.currency);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(1, height4 = Math.min(width / 2.5, 400));
    }
    if ($$self.$$.dirty & 35) {
      $:
        $$invalidate(7, root2 = tree.size([width, height4])(data));
    }
    if ($$self.$$.dirty & 128) {
      $:
        $$invalidate(2, leaves = root2.leaves().filter((d) => d.value));
    }
  };
  return [
    width,
    height4,
    leaves,
    fill,
    tooltipText,
    data,
    currency,
    root2,
    followingTooltip_function
  ];
}
var Treemap = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance6, create_fragment6, safe_not_equal, { data: 5, width: 0, currency: 6 });
  }
};
var Treemap_default = Treemap;

// src/charts/HierarchyContainer.svelte
function get_each_context6(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[8] = list[i][0];
  child_ctx[9] = list[i][1];
  child_ctx[11] = i;
  return child_ctx;
}
function create_if_block_2(ctx2) {
  let svg2;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let svg_height_value;
  let current;
  let each_value = [...ctx2[0]];
  const get_key = (ctx3) => ctx3[2];
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context6(ctx2, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block6(key, child_ctx));
  }
  return {
    c() {
      svg2 = svg_element("svg");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(svg2, "width", ctx2[1]);
      attr(svg2, "height", svg_height_value = 500);
    },
    m(target, anchor) {
      insert(target, svg2, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(svg2, null);
      }
      current = true;
    },
    p(ctx3, dirty) {
      if (dirty & 15) {
        each_value = [...ctx3[0]];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx3, each_value, each_1_lookup, svg2, outro_and_destroy_block, create_each_block6, null, get_each_context6);
        check_outros();
      }
      if (!current || dirty & 2) {
        attr(svg2, "width", ctx3[1]);
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(svg2);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
function create_if_block_12(ctx2) {
  let treemap;
  let current;
  treemap = new Treemap_default({
    props: {
      data: ctx2[5],
      currency: ctx2[2],
      width: ctx2[1]
    }
  });
  return {
    c() {
      create_component(treemap.$$.fragment);
    },
    m(target, anchor) {
      mount_component(treemap, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const treemap_changes = {};
      if (dirty & 32)
        treemap_changes.data = ctx3[5];
      if (dirty & 4)
        treemap_changes.currency = ctx3[2];
      if (dirty & 2)
        treemap_changes.width = ctx3[1];
      treemap.$set(treemap_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(treemap.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(treemap.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(treemap, detaching);
    }
  };
}
function create_if_block2(ctx2) {
  let svg2;
  let text_1;
  let t_value = _("Chart is empty.") + "";
  let t4;
  let text_1_x_value;
  let text_1_y_value;
  return {
    c() {
      svg2 = svg_element("svg");
      text_1 = svg_element("text");
      t4 = text(t_value);
      attr(text_1, "x", text_1_x_value = ctx2[1] / 2);
      attr(text_1, "y", text_1_y_value = 80);
      attr(text_1, "text-anchor", "middle");
      attr(svg2, "width", ctx2[1]);
    },
    m(target, anchor) {
      insert(target, svg2, anchor);
      append(svg2, text_1);
      append(text_1, t4);
    },
    p(ctx3, dirty) {
      if (dirty & 2 && text_1_x_value !== (text_1_x_value = ctx3[1] / 2)) {
        attr(text_1, "x", text_1_x_value);
      }
      if (dirty & 2) {
        attr(svg2, "width", ctx3[1]);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(svg2);
    }
  };
}
function create_each_block6(key_1, ctx2) {
  let g;
  let sunburst;
  let g_transform_value;
  let current;
  sunburst = new Sunburst_default({
    props: {
      data: ctx2[9],
      currency: ctx2[8],
      width: ctx2[1] / ctx2[3].length,
      height: 500
    }
  });
  return {
    key: key_1,
    first: null,
    c() {
      g = svg_element("g");
      create_component(sunburst.$$.fragment);
      attr(g, "transform", g_transform_value = `translate(${ctx2[1] * ctx2[11] / ctx2[3].length},0)`);
      this.first = g;
    },
    m(target, anchor) {
      insert(target, g, anchor);
      mount_component(sunburst, g, null);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      const sunburst_changes = {};
      if (dirty & 1)
        sunburst_changes.data = ctx2[9];
      if (dirty & 1)
        sunburst_changes.currency = ctx2[8];
      if (dirty & 10)
        sunburst_changes.width = ctx2[1] / ctx2[3].length;
      sunburst.$set(sunburst_changes);
      if (!current || dirty & 11 && g_transform_value !== (g_transform_value = `translate(${ctx2[1] * ctx2[11] / ctx2[3].length},0)`)) {
        attr(g, "transform", g_transform_value);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(sunburst.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(sunburst.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(g);
      destroy_component(sunburst);
    }
  };
}
function create_fragment7(ctx2) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block2, create_if_block_12, create_if_block_2];
  const if_blocks = [];
  function select_block_type(ctx3, dirty) {
    if (ctx3[3].length === 0)
      return 0;
    if (ctx3[5])
      return 1;
    if (ctx3[4] === "sunburst")
      return 2;
    return -1;
  }
  if (~(current_block_type_index = select_block_type(ctx2, -1))) {
    if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
  }
  return {
    c() {
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(target, anchor);
      }
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx3, dirty);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx3, dirty);
        }
      } else {
        if (if_block) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block = if_blocks[current_block_type_index];
          if (!if_block) {
            if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx3);
            if_block.c();
          } else {
            if_block.p(ctx3, dirty);
          }
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        } else {
          if_block = null;
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d(detaching);
      }
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
function instance7($$self, $$props, $$invalidate) {
  let currencies2;
  let currency;
  let treemapData;
  let $hierarchyChartMode;
  let $chartCurrency;
  component_subscribe($$self, hierarchyChartMode, ($$value) => $$invalidate(4, $hierarchyChartMode = $$value));
  component_subscribe($$self, chartCurrency, ($$value) => $$invalidate(6, $chartCurrency = $$value));
  const context = getContext("chart-currencies");
  let { data } = $$props;
  let { width } = $$props;
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(0, data = $$props2.data);
    if ("width" in $$props2)
      $$invalidate(1, width = $$props2.width);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(3, currencies2 = [...data.keys()]);
    }
    if ($$self.$$.dirty & 72) {
      $:
        $$invalidate(2, currency = $chartCurrency || currencies2[0]);
    }
    if ($$self.$$.dirty & 8) {
      $:
        context.set(currencies2);
    }
    if ($$self.$$.dirty & 21) {
      $:
        $$invalidate(5, treemapData = $hierarchyChartMode === "treemap" && data.get(currency));
    }
  };
  return [
    data,
    width,
    currency,
    currencies2,
    $hierarchyChartMode,
    treemapData,
    $chartCurrency
  ];
}
var HierarchyContainer = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance7, create_fragment7, safe_not_equal, { data: 0, width: 1 });
  }
};
var HierarchyContainer_default = HierarchyContainer;

// node_modules/d3-quadtree/src/add.js
function add_default(d) {
  const x2 = +this._x.call(null, d), y2 = +this._y.call(null, d);
  return add2(this.cover(x2, y2), x2, y2, d);
}
function add2(tree, x2, y2, d) {
  if (isNaN(x2) || isNaN(y2))
    return tree;
  var parent2, node = tree._root, leaf2 = { data: d }, x0 = tree._x0, y0 = tree._y0, x1 = tree._x1, y1 = tree._y1, xm, ym, xp, yp, right2, bottom2, i, j;
  if (!node)
    return tree._root = leaf2, tree;
  while (node.length) {
    if (right2 = x2 >= (xm = (x0 + x1) / 2))
      x0 = xm;
    else
      x1 = xm;
    if (bottom2 = y2 >= (ym = (y0 + y1) / 2))
      y0 = ym;
    else
      y1 = ym;
    if (parent2 = node, !(node = node[i = bottom2 << 1 | right2]))
      return parent2[i] = leaf2, tree;
  }
  xp = +tree._x.call(null, node.data);
  yp = +tree._y.call(null, node.data);
  if (x2 === xp && y2 === yp)
    return leaf2.next = node, parent2 ? parent2[i] = leaf2 : tree._root = leaf2, tree;
  do {
    parent2 = parent2 ? parent2[i] = new Array(4) : tree._root = new Array(4);
    if (right2 = x2 >= (xm = (x0 + x1) / 2))
      x0 = xm;
    else
      x1 = xm;
    if (bottom2 = y2 >= (ym = (y0 + y1) / 2))
      y0 = ym;
    else
      y1 = ym;
  } while ((i = bottom2 << 1 | right2) === (j = (yp >= ym) << 1 | xp >= xm));
  return parent2[j] = node, parent2[i] = leaf2, tree;
}
function addAll(data) {
  var d, i, n = data.length, x2, y2, xz = new Array(n), yz = new Array(n), x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
  for (i = 0; i < n; ++i) {
    if (isNaN(x2 = +this._x.call(null, d = data[i])) || isNaN(y2 = +this._y.call(null, d)))
      continue;
    xz[i] = x2;
    yz[i] = y2;
    if (x2 < x0)
      x0 = x2;
    if (x2 > x1)
      x1 = x2;
    if (y2 < y0)
      y0 = y2;
    if (y2 > y1)
      y1 = y2;
  }
  if (x0 > x1 || y0 > y1)
    return this;
  this.cover(x0, y0).cover(x1, y1);
  for (i = 0; i < n; ++i) {
    add2(this, xz[i], yz[i], data[i]);
  }
  return this;
}

// node_modules/d3-quadtree/src/cover.js
function cover_default(x2, y2) {
  if (isNaN(x2 = +x2) || isNaN(y2 = +y2))
    return this;
  var x0 = this._x0, y0 = this._y0, x1 = this._x1, y1 = this._y1;
  if (isNaN(x0)) {
    x1 = (x0 = Math.floor(x2)) + 1;
    y1 = (y0 = Math.floor(y2)) + 1;
  } else {
    var z = x1 - x0 || 1, node = this._root, parent2, i;
    while (x0 > x2 || x2 >= x1 || y0 > y2 || y2 >= y1) {
      i = (y2 < y0) << 1 | x2 < x0;
      parent2 = new Array(4), parent2[i] = node, node = parent2, z *= 2;
      switch (i) {
        case 0:
          x1 = x0 + z, y1 = y0 + z;
          break;
        case 1:
          x0 = x1 - z, y1 = y0 + z;
          break;
        case 2:
          x1 = x0 + z, y0 = y1 - z;
          break;
        case 3:
          x0 = x1 - z, y0 = y1 - z;
          break;
      }
    }
    if (this._root && this._root.length)
      this._root = node;
  }
  this._x0 = x0;
  this._y0 = y0;
  this._x1 = x1;
  this._y1 = y1;
  return this;
}

// node_modules/d3-quadtree/src/data.js
function data_default2() {
  var data = [];
  this.visit(function(node) {
    if (!node.length)
      do
        data.push(node.data);
      while (node = node.next);
  });
  return data;
}

// node_modules/d3-quadtree/src/extent.js
function extent_default(_2) {
  return arguments.length ? this.cover(+_2[0][0], +_2[0][1]).cover(+_2[1][0], +_2[1][1]) : isNaN(this._x0) ? void 0 : [[this._x0, this._y0], [this._x1, this._y1]];
}

// node_modules/d3-quadtree/src/quad.js
function quad_default(node, x0, y0, x1, y1) {
  this.node = node;
  this.x0 = x0;
  this.y0 = y0;
  this.x1 = x1;
  this.y1 = y1;
}

// node_modules/d3-quadtree/src/find.js
function find_default2(x2, y2, radius) {
  var data, x0 = this._x0, y0 = this._y0, x1, y1, x22, y22, x3 = this._x1, y3 = this._y1, quads = [], node = this._root, q, i;
  if (node)
    quads.push(new quad_default(node, x0, y0, x3, y3));
  if (radius == null)
    radius = Infinity;
  else {
    x0 = x2 - radius, y0 = y2 - radius;
    x3 = x2 + radius, y3 = y2 + radius;
    radius *= radius;
  }
  while (q = quads.pop()) {
    if (!(node = q.node) || (x1 = q.x0) > x3 || (y1 = q.y0) > y3 || (x22 = q.x1) < x0 || (y22 = q.y1) < y0)
      continue;
    if (node.length) {
      var xm = (x1 + x22) / 2, ym = (y1 + y22) / 2;
      quads.push(
        new quad_default(node[3], xm, ym, x22, y22),
        new quad_default(node[2], x1, ym, xm, y22),
        new quad_default(node[1], xm, y1, x22, ym),
        new quad_default(node[0], x1, y1, xm, ym)
      );
      if (i = (y2 >= ym) << 1 | x2 >= xm) {
        q = quads[quads.length - 1];
        quads[quads.length - 1] = quads[quads.length - 1 - i];
        quads[quads.length - 1 - i] = q;
      }
    } else {
      var dx = x2 - +this._x.call(null, node.data), dy = y2 - +this._y.call(null, node.data), d2 = dx * dx + dy * dy;
      if (d2 < radius) {
        var d = Math.sqrt(radius = d2);
        x0 = x2 - d, y0 = y2 - d;
        x3 = x2 + d, y3 = y2 + d;
        data = node.data;
      }
    }
  }
  return data;
}

// node_modules/d3-quadtree/src/remove.js
function remove_default2(d) {
  if (isNaN(x2 = +this._x.call(null, d)) || isNaN(y2 = +this._y.call(null, d)))
    return this;
  var parent2, node = this._root, retainer, previous, next, x0 = this._x0, y0 = this._y0, x1 = this._x1, y1 = this._y1, x2, y2, xm, ym, right2, bottom2, i, j;
  if (!node)
    return this;
  if (node.length)
    while (true) {
      if (right2 = x2 >= (xm = (x0 + x1) / 2))
        x0 = xm;
      else
        x1 = xm;
      if (bottom2 = y2 >= (ym = (y0 + y1) / 2))
        y0 = ym;
      else
        y1 = ym;
      if (!(parent2 = node, node = node[i = bottom2 << 1 | right2]))
        return this;
      if (!node.length)
        break;
      if (parent2[i + 1 & 3] || parent2[i + 2 & 3] || parent2[i + 3 & 3])
        retainer = parent2, j = i;
    }
  while (node.data !== d)
    if (!(previous = node, node = node.next))
      return this;
  if (next = node.next)
    delete node.next;
  if (previous)
    return next ? previous.next = next : delete previous.next, this;
  if (!parent2)
    return this._root = next, this;
  next ? parent2[i] = next : delete parent2[i];
  if ((node = parent2[0] || parent2[1] || parent2[2] || parent2[3]) && node === (parent2[3] || parent2[2] || parent2[1] || parent2[0]) && !node.length) {
    if (retainer)
      retainer[j] = node;
    else
      this._root = node;
  }
  return this;
}
function removeAll(data) {
  for (var i = 0, n = data.length; i < n; ++i)
    this.remove(data[i]);
  return this;
}

// node_modules/d3-quadtree/src/root.js
function root_default() {
  return this._root;
}

// node_modules/d3-quadtree/src/size.js
function size_default2() {
  var size = 0;
  this.visit(function(node) {
    if (!node.length)
      do
        ++size;
      while (node = node.next);
  });
  return size;
}

// node_modules/d3-quadtree/src/visit.js
function visit_default(callback) {
  var quads = [], q, node = this._root, child, x0, y0, x1, y1;
  if (node)
    quads.push(new quad_default(node, this._x0, this._y0, this._x1, this._y1));
  while (q = quads.pop()) {
    if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1) && node.length) {
      var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
      if (child = node[3])
        quads.push(new quad_default(child, xm, ym, x1, y1));
      if (child = node[2])
        quads.push(new quad_default(child, x0, ym, xm, y1));
      if (child = node[1])
        quads.push(new quad_default(child, xm, y0, x1, ym));
      if (child = node[0])
        quads.push(new quad_default(child, x0, y0, xm, ym));
    }
  }
  return this;
}

// node_modules/d3-quadtree/src/visitAfter.js
function visitAfter_default(callback) {
  var quads = [], next = [], q;
  if (this._root)
    quads.push(new quad_default(this._root, this._x0, this._y0, this._x1, this._y1));
  while (q = quads.pop()) {
    var node = q.node;
    if (node.length) {
      var child, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
      if (child = node[0])
        quads.push(new quad_default(child, x0, y0, xm, ym));
      if (child = node[1])
        quads.push(new quad_default(child, xm, y0, x1, ym));
      if (child = node[2])
        quads.push(new quad_default(child, x0, ym, xm, y1));
      if (child = node[3])
        quads.push(new quad_default(child, xm, ym, x1, y1));
    }
    next.push(q);
  }
  while (q = next.pop()) {
    callback(q.node, q.x0, q.y0, q.x1, q.y1);
  }
  return this;
}

// node_modules/d3-quadtree/src/x.js
function defaultX(d) {
  return d[0];
}
function x_default(_2) {
  return arguments.length ? (this._x = _2, this) : this._x;
}

// node_modules/d3-quadtree/src/y.js
function defaultY(d) {
  return d[1];
}
function y_default(_2) {
  return arguments.length ? (this._y = _2, this) : this._y;
}

// node_modules/d3-quadtree/src/quadtree.js
function quadtree(nodes, x2, y2) {
  var tree = new Quadtree(x2 == null ? defaultX : x2, y2 == null ? defaultY : y2, NaN, NaN, NaN, NaN);
  return nodes == null ? tree : tree.addAll(nodes);
}
function Quadtree(x2, y2, x0, y0, x1, y1) {
  this._x = x2;
  this._y = y2;
  this._x0 = x0;
  this._y0 = y0;
  this._x1 = x1;
  this._y1 = y1;
  this._root = void 0;
}
function leaf_copy(leaf2) {
  var copy2 = { data: leaf2.data }, next = copy2;
  while (leaf2 = leaf2.next)
    next = next.next = { data: leaf2.data };
  return copy2;
}
var treeProto = quadtree.prototype = Quadtree.prototype;
treeProto.copy = function() {
  var copy2 = new Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1), node = this._root, nodes, child;
  if (!node)
    return copy2;
  if (!node.length)
    return copy2._root = leaf_copy(node), copy2;
  nodes = [{ source: node, target: copy2._root = new Array(4) }];
  while (node = nodes.pop()) {
    for (var i = 0; i < 4; ++i) {
      if (child = node.source[i]) {
        if (child.length)
          nodes.push({ source: child, target: node.target[i] = new Array(4) });
        else
          node.target[i] = leaf_copy(child);
      }
    }
  }
  return copy2;
};
treeProto.add = add_default;
treeProto.addAll = addAll;
treeProto.cover = cover_default;
treeProto.data = data_default2;
treeProto.extent = extent_default;
treeProto.find = find_default2;
treeProto.remove = remove_default2;
treeProto.removeAll = removeAll;
treeProto.root = root_default;
treeProto.size = size_default2;
treeProto.visit = visit_default;
treeProto.visitAfter = visitAfter_default;
treeProto.x = x_default;
treeProto.y = y_default;

// src/charts/LineChart.svelte
function get_each_context7(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[26] = list[i];
  return child_ctx;
}
function get_each_context_12(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[29] = list[i];
  return child_ctx;
}
function get_each_context_22(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[26] = list[i];
  return child_ctx;
}
function get_each_context_32(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[26] = list[i];
  return child_ctx;
}
function create_if_block_13(ctx2) {
  let g;
  let each_value_3 = ctx2[0];
  let each_blocks = [];
  for (let i = 0; i < each_value_3.length; i += 1) {
    each_blocks[i] = create_each_block_32(get_each_context_32(ctx2, each_value_3, i));
  }
  return {
    c() {
      g = svg_element("g");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(g, "class", "area svelte-1gzc8m3");
      attr(g, "filter", ctx2[6]);
    },
    m(target, anchor) {
      insert(target, g, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(g, null);
      }
    },
    p(ctx3, dirty) {
      if (dirty[0] & 545) {
        each_value_3 = ctx3[0];
        let i;
        for (i = 0; i < each_value_3.length; i += 1) {
          const child_ctx = get_each_context_32(ctx3, each_value_3, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_32(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(g, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value_3.length;
      }
      if (dirty[0] & 64) {
        attr(g, "filter", ctx3[6]);
      }
    },
    d(detaching) {
      if (detaching)
        detach(g);
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_each_block_32(ctx2) {
  let path2;
  let path_d_value;
  let path_fill_value;
  return {
    c() {
      var _a2;
      path2 = svg_element("path");
      attr(path2, "d", path_d_value = (_a2 = ctx2[9](ctx2[26].values)) != null ? _a2 : void 0);
      attr(path2, "fill", path_fill_value = ctx2[5](ctx2[26].name));
      attr(path2, "class", "svelte-1gzc8m3");
    },
    m(target, anchor) {
      insert(target, path2, anchor);
    },
    p(ctx3, dirty) {
      var _a2;
      if (dirty[0] & 513 && path_d_value !== (path_d_value = (_a2 = ctx3[9](ctx3[26].values)) != null ? _a2 : void 0)) {
        attr(path2, "d", path_d_value);
      }
      if (dirty[0] & 33 && path_fill_value !== (path_fill_value = ctx3[5](ctx3[26].name))) {
        attr(path2, "fill", path_fill_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(path2);
    }
  };
}
function create_each_block_22(ctx2) {
  let path2;
  let path_d_value;
  let path_stroke_value;
  return {
    c() {
      var _a2;
      path2 = svg_element("path");
      attr(path2, "d", path_d_value = (_a2 = ctx2[10](ctx2[26].values)) != null ? _a2 : void 0);
      attr(path2, "stroke", path_stroke_value = ctx2[5](ctx2[26].name));
      attr(path2, "class", "svelte-1gzc8m3");
    },
    m(target, anchor) {
      insert(target, path2, anchor);
    },
    p(ctx3, dirty) {
      var _a2;
      if (dirty[0] & 1025 && path_d_value !== (path_d_value = (_a2 = ctx3[10](ctx3[26].values)) != null ? _a2 : void 0)) {
        attr(path2, "d", path_d_value);
      }
      if (dirty[0] & 33 && path_stroke_value !== (path_stroke_value = ctx3[5](ctx3[26].name))) {
        attr(path2, "stroke", path_stroke_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(path2);
    }
  };
}
function create_if_block3(ctx2) {
  let g;
  let each_value = ctx2[0];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block7(get_each_context7(ctx2, each_value, i));
  }
  return {
    c() {
      g = svg_element("g");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
    },
    m(target, anchor) {
      insert(target, g, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(g, null);
      }
    },
    p(ctx3, dirty) {
      if (dirty[0] & 4141) {
        each_value = ctx3[0];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context7(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block7(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(g, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    d(detaching) {
      if (detaching)
        detach(g);
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_each_block_12(ctx2) {
  let circle;
  let circle_cx_value;
  let circle_cy_value;
  return {
    c() {
      circle = svg_element("circle");
      attr(circle, "r", "2");
      attr(circle, "cx", circle_cx_value = ctx2[3](ctx2[29].date));
      attr(circle, "cy", circle_cy_value = ctx2[2](ctx2[29].value));
      attr(circle, "class", "svelte-1gzc8m3");
      toggle_class(circle, "desaturate", ctx2[29].date > ctx2[12]);
    },
    m(target, anchor) {
      insert(target, circle, anchor);
    },
    p(ctx3, dirty) {
      if (dirty[0] & 9 && circle_cx_value !== (circle_cx_value = ctx3[3](ctx3[29].date))) {
        attr(circle, "cx", circle_cx_value);
      }
      if (dirty[0] & 5 && circle_cy_value !== (circle_cy_value = ctx3[2](ctx3[29].value))) {
        attr(circle, "cy", circle_cy_value);
      }
      if (dirty[0] & 4097) {
        toggle_class(circle, "desaturate", ctx3[29].date > ctx3[12]);
      }
    },
    d(detaching) {
      if (detaching)
        detach(circle);
    }
  };
}
function create_each_block7(ctx2) {
  let g;
  let g_fill_value;
  let each_value_1 = ctx2[26].values;
  let each_blocks = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks[i] = create_each_block_12(get_each_context_12(ctx2, each_value_1, i));
  }
  return {
    c() {
      g = svg_element("g");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(g, "fill", g_fill_value = ctx2[5](ctx2[26].name));
    },
    m(target, anchor) {
      insert(target, g, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(g, null);
      }
    },
    p(ctx3, dirty) {
      if (dirty[0] & 4109) {
        each_value_1 = ctx3[26].values;
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_12(ctx3, each_value_1, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_12(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(g, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value_1.length;
      }
      if (dirty[0] & 33 && g_fill_value !== (g_fill_value = ctx3[5](ctx3[26].name))) {
        attr(g, "fill", g_fill_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(g);
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_fragment8(ctx2) {
  let svg2;
  let filter2;
  let feColorMatrix;
  let feColorMatrix_x_value;
  let feBlend;
  let g1;
  let axis0;
  let axis1;
  let g0;
  let g1_transform_value;
  let positionedTooltip_action;
  let current;
  let mounted;
  let dispose;
  axis0 = new Axis_default({
    props: {
      x: true,
      axis: ctx2[8],
      innerHeight: ctx2[4]
    }
  });
  axis1 = new Axis_default({
    props: { y: true, axis: ctx2[7] }
  });
  let if_block0 = ctx2[11] === "area" && create_if_block_13(ctx2);
  let each_value_2 = ctx2[0];
  let each_blocks = [];
  for (let i = 0; i < each_value_2.length; i += 1) {
    each_blocks[i] = create_each_block_22(get_each_context_22(ctx2, each_value_2, i));
  }
  let if_block1 = ctx2[11] === "line" && create_if_block3(ctx2);
  return {
    c() {
      svg2 = svg_element("svg");
      filter2 = svg_element("filter");
      feColorMatrix = svg_element("feColorMatrix");
      feBlend = svg_element("feBlend");
      g1 = svg_element("g");
      create_component(axis0.$$.fragment);
      create_component(axis1.$$.fragment);
      if (if_block0)
        if_block0.c();
      g0 = svg_element("g");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      if (if_block1)
        if_block1.c();
      attr(feColorMatrix, "type", "saturate");
      attr(feColorMatrix, "values", "0.5");
      attr(feColorMatrix, "x", feColorMatrix_x_value = ctx2[3](ctx2[12]));
      attr(feBlend, "in2", "SourceGraphic");
      attr(filter2, "id", "desaturateFuture");
      attr(g0, "class", "lines svelte-1gzc8m3");
      attr(g0, "filter", ctx2[6]);
      attr(g1, "transform", g1_transform_value = `translate(${ctx2[13].left},${ctx2[13].top})`);
      attr(g1, "class", "svelte-1gzc8m3");
      attr(svg2, "width", ctx2[1]);
      attr(svg2, "height", height2);
      attr(svg2, "class", "svelte-1gzc8m3");
    },
    m(target, anchor) {
      insert(target, svg2, anchor);
      append(svg2, filter2);
      append(filter2, feColorMatrix);
      append(filter2, feBlend);
      append(svg2, g1);
      mount_component(axis0, g1, null);
      mount_component(axis1, g1, null);
      if (if_block0)
        if_block0.m(g1, null);
      append(g1, g0);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(g0, null);
      }
      if (if_block1)
        if_block1.m(g1, null);
      current = true;
      if (!mounted) {
        dispose = action_destroyer(positionedTooltip_action = positionedTooltip.call(null, g1, ctx2[14]));
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if (!current || dirty[0] & 8 && feColorMatrix_x_value !== (feColorMatrix_x_value = ctx3[3](ctx3[12]))) {
        attr(feColorMatrix, "x", feColorMatrix_x_value);
      }
      const axis0_changes = {};
      if (dirty[0] & 256)
        axis0_changes.axis = ctx3[8];
      if (dirty[0] & 16)
        axis0_changes.innerHeight = ctx3[4];
      axis0.$set(axis0_changes);
      const axis1_changes = {};
      if (dirty[0] & 128)
        axis1_changes.axis = ctx3[7];
      axis1.$set(axis1_changes);
      if (ctx3[11] === "area") {
        if (if_block0) {
          if_block0.p(ctx3, dirty);
        } else {
          if_block0 = create_if_block_13(ctx3);
          if_block0.c();
          if_block0.m(g1, g0);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (dirty[0] & 1057) {
        each_value_2 = ctx3[0];
        let i;
        for (i = 0; i < each_value_2.length; i += 1) {
          const child_ctx = get_each_context_22(ctx3, each_value_2, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_22(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(g0, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value_2.length;
      }
      if (!current || dirty[0] & 64) {
        attr(g0, "filter", ctx3[6]);
      }
      if (ctx3[11] === "line") {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
        } else {
          if_block1 = create_if_block3(ctx3);
          if_block1.c();
          if_block1.m(g1, null);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (!current || dirty[0] & 2) {
        attr(svg2, "width", ctx3[1]);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(axis0.$$.fragment, local);
      transition_in(axis1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(axis0.$$.fragment, local);
      transition_out(axis1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(svg2);
      destroy_component(axis0);
      destroy_component(axis1);
      if (if_block0)
        if_block0.d();
      destroy_each(each_blocks, detaching);
      if (if_block1)
        if_block1.d();
      mounted = false;
      dispose();
    }
  };
}
var height2 = 250;
function instance8($$self, $$props, $$invalidate) {
  let innerWidth;
  let innerHeight2;
  let allValues;
  let x2;
  let y2;
  let quad;
  let lineShape;
  let areaShape;
  let xAxis;
  let yAxis;
  let futureFilter;
  let $ctx;
  let $currenciesScale;
  let $lineChartMode;
  component_subscribe($$self, ctx, ($$value) => $$invalidate(23, $ctx = $$value));
  component_subscribe($$self, currenciesScale, ($$value) => $$invalidate(5, $currenciesScale = $$value));
  component_subscribe($$self, lineChartMode, ($$value) => $$invalidate(11, $lineChartMode = $$value));
  var _a2, _b;
  let { data } = $$props;
  let { width } = $$props;
  let { tooltipText } = $$props;
  const today = new Date();
  const margin = { top: 10, right: 10, bottom: 30, left: 40 };
  const legend = getContext("chart-legend");
  let xDomain;
  let yMin;
  let yMax;
  const tooltipFindNode = (xPos, yPos) => {
    const d = quad.find(xPos, yPos);
    return d && [x2(d.date), y2(d.value), tooltipText($ctx, d)];
  };
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(0, data = $$props2.data);
    if ("width" in $$props2)
      $$invalidate(1, width = $$props2.width);
    if ("tooltipText" in $$props2)
      $$invalidate(15, tooltipText = $$props2.tooltipText);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & 2) {
      $:
        $$invalidate(21, innerWidth = width - margin.left - margin.right);
    }
    if ($$self.$$.dirty[0] & 33) {
      $:
        legend.set(data.map((d) => d.name).sort().map((c) => [c, $currenciesScale(c)]));
    }
    if ($$self.$$.dirty[0] & 1) {
      $:
        $$invalidate(22, allValues = merge(data.map((d) => d.values)));
    }
    if ($$self.$$.dirty[0] & 196609) {
      $:
        $$invalidate(18, xDomain = [
          $$invalidate(16, _a2 = min(data, (s) => s.values[0].date)) != null ? _a2 : today,
          $$invalidate(17, _b = max(data, (s) => s.values[s.values.length - 1].date)) != null ? _b : today
        ]);
    }
    if ($$self.$$.dirty[0] & 2359296) {
      $:
        $$invalidate(3, x2 = utcTime().domain(xDomain).range([0, innerWidth]));
    }
    if ($$self.$$.dirty[0] & 4194304) {
      $:
        $$invalidate(19, [yMin = 0, yMax = 0] = extent(allValues, (v) => v.value), yMin, ($$invalidate(20, yMax), $$invalidate(22, allValues), $$invalidate(0, data)));
    }
    if ($$self.$$.dirty[0] & 1572880) {
      $:
        $$invalidate(2, y2 = linear2().domain([yMin - (yMax - yMin) * 0.05, yMax + (yMax - yMin) * 0.05]).range([innerHeight2, 0]));
    }
    if ($$self.$$.dirty[0] & 4194316) {
      $:
        quad = quadtree(allValues, (d) => x2(d.date), (d) => y2(d.value));
    }
    if ($$self.$$.dirty[0] & 12) {
      $:
        $$invalidate(10, lineShape = line_default().x((d) => x2(d.date)).y((d) => y2(d.value)).curve(stepAfter));
    }
    if ($$self.$$.dirty[0] & 28) {
      $:
        $$invalidate(9, areaShape = area_default().x((d) => x2(d.date)).y1((d) => y2(d.value)).y0(Math.min(innerHeight2, y2(0))).curve(stepAfter));
    }
    if ($$self.$$.dirty[0] & 8) {
      $:
        $$invalidate(8, xAxis = axisBottom(x2).tickSizeOuter(0));
    }
    if ($$self.$$.dirty[0] & 10485764) {
      $:
        $$invalidate(7, yAxis = axisLeft(y2).tickPadding(6).tickSize(-innerWidth).tickFormat($ctx.short));
    }
    if ($$self.$$.dirty[0] & 262144) {
      $:
        $$invalidate(6, futureFilter = xDomain[1] > today ? "url(#desaturateFuture)" : void 0);
    }
  };
  $:
    $$invalidate(4, innerHeight2 = height2 - margin.top - margin.bottom);
  return [
    data,
    width,
    y2,
    x2,
    innerHeight2,
    $currenciesScale,
    futureFilter,
    yAxis,
    xAxis,
    areaShape,
    lineShape,
    $lineChartMode,
    today,
    margin,
    tooltipFindNode,
    tooltipText,
    _a2,
    _b,
    xDomain,
    yMin,
    yMax,
    innerWidth,
    allValues,
    $ctx
  ];
}
var LineChart = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance8, create_fragment8, safe_not_equal, { data: 0, width: 1, tooltipText: 15 }, null, [-1, -1]);
  }
};
var LineChart_default = LineChart;

// src/charts/ModeSwitch.svelte
function get_each_context8(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[4] = list[i][0];
  child_ctx[5] = list[i][1];
  return child_ctx;
}
function create_each_block8(ctx2) {
  let label;
  let input;
  let input_value_value;
  let t03;
  let t1_value = ctx2[5] + "";
  let t13;
  let t22;
  let mounted;
  let dispose;
  return {
    c() {
      label = element("label");
      input = element("input");
      t03 = space();
      t13 = text(t1_value);
      t22 = space();
      attr(input, "type", "radio");
      input.__value = input_value_value = ctx2[4];
      input.value = input.__value;
      attr(input, "class", "svelte-1g16jx5");
      ctx2[3][0].push(input);
      attr(label, "class", "button svelte-1g16jx5");
      toggle_class(label, "muted", ctx2[0] !== ctx2[4]);
    },
    m(target, anchor) {
      insert(target, label, anchor);
      append(label, input);
      input.checked = input.__value === ctx2[0];
      append(label, t03);
      append(label, t13);
      append(label, t22);
      if (!mounted) {
        dispose = listen(input, "change", ctx2[2]);
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if (dirty & 2 && input_value_value !== (input_value_value = ctx3[4])) {
        input.__value = input_value_value;
        input.value = input.__value;
      }
      if (dirty & 1) {
        input.checked = input.__value === ctx3[0];
      }
      if (dirty & 2 && t1_value !== (t1_value = ctx3[5] + ""))
        set_data(t13, t1_value);
      if (dirty & 3) {
        toggle_class(label, "muted", ctx3[0] !== ctx3[4]);
      }
    },
    d(detaching) {
      if (detaching)
        detach(label);
      ctx2[3][0].splice(ctx2[3][0].indexOf(input), 1);
      mounted = false;
      dispose();
    }
  };
}
function create_fragment9(ctx2) {
  let span;
  let each_value = ctx2[1];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block8(get_each_context8(ctx2, each_value, i));
  }
  return {
    c() {
      span = element("span");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
    },
    m(target, anchor) {
      insert(target, span, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(span, null);
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & 3) {
        each_value = ctx3[1];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context8(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block8(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(span, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(span);
      destroy_each(each_blocks, detaching);
    }
  };
}
function instance9($$self, $$props, $$invalidate) {
  let { value } = $$props;
  let { options: options2 } = $$props;
  const $$binding_groups = [[]];
  function input_change_handler() {
    value = this.__value;
    $$invalidate(0, value);
  }
  $$self.$$set = ($$props2) => {
    if ("value" in $$props2)
      $$invalidate(0, value = $$props2.value);
    if ("options" in $$props2)
      $$invalidate(1, options2 = $$props2.options);
  };
  return [value, options2, input_change_handler, $$binding_groups];
}
var ModeSwitch = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance9, create_fragment9, safe_not_equal, { value: 0, options: 1 });
  }
};
var ModeSwitch_default = ModeSwitch;

// src/charts/ScatterPlot.svelte
function get_each_context9(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[14] = list[i];
  return child_ctx;
}
function create_each_block9(ctx2) {
  let circle;
  let circle_fill_value;
  let circle_cx_value;
  let circle_cy_value;
  return {
    c() {
      circle = svg_element("circle");
      attr(circle, "r", "5");
      attr(circle, "fill", circle_fill_value = scatterplotScale(ctx2[14].type));
      attr(circle, "cx", circle_cx_value = ctx2[3](ctx2[14].date));
      attr(circle, "cy", circle_cy_value = ctx2[2](ctx2[14].type));
      attr(circle, "class", "svelte-jl8ee");
      toggle_class(circle, "desaturate", ctx2[14].date > ctx2[7]);
    },
    m(target, anchor) {
      insert(target, circle, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & 1 && circle_fill_value !== (circle_fill_value = scatterplotScale(ctx3[14].type))) {
        attr(circle, "fill", circle_fill_value);
      }
      if (dirty & 9 && circle_cx_value !== (circle_cx_value = ctx3[3](ctx3[14].date))) {
        attr(circle, "cx", circle_cx_value);
      }
      if (dirty & 5 && circle_cy_value !== (circle_cy_value = ctx3[2](ctx3[14].type))) {
        attr(circle, "cy", circle_cy_value);
      }
      if (dirty & 129) {
        toggle_class(circle, "desaturate", ctx3[14].date > ctx3[7]);
      }
    },
    d(detaching) {
      if (detaching)
        detach(circle);
    }
  };
}
function create_fragment10(ctx2) {
  let svg2;
  let g1;
  let axis0;
  let axis1;
  let g0;
  let g1_transform_value;
  let positionedTooltip_action;
  let current;
  let mounted;
  let dispose;
  axis0 = new Axis_default({
    props: {
      x: true,
      axis: ctx2[6],
      innerHeight: ctx2[4]
    }
  });
  axis1 = new Axis_default({
    props: { y: true, axis: ctx2[5] }
  });
  let each_value = ctx2[0];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block9(get_each_context9(ctx2, each_value, i));
  }
  return {
    c() {
      svg2 = svg_element("svg");
      g1 = svg_element("g");
      create_component(axis0.$$.fragment);
      create_component(axis1.$$.fragment);
      g0 = svg_element("g");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(g1, "transform", g1_transform_value = `translate(${ctx2[8].left},${ctx2[8].top})`);
      attr(g1, "class", "svelte-jl8ee");
      attr(svg2, "width", ctx2[1]);
      attr(svg2, "height", height3);
      attr(svg2, "class", "svelte-jl8ee");
    },
    m(target, anchor) {
      insert(target, svg2, anchor);
      append(svg2, g1);
      mount_component(axis0, g1, null);
      mount_component(axis1, g1, null);
      append(g1, g0);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(g0, null);
      }
      current = true;
      if (!mounted) {
        dispose = action_destroyer(positionedTooltip_action = positionedTooltip.call(null, g1, ctx2[9]));
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      const axis0_changes = {};
      if (dirty & 64)
        axis0_changes.axis = ctx3[6];
      if (dirty & 16)
        axis0_changes.innerHeight = ctx3[4];
      axis0.$set(axis0_changes);
      const axis1_changes = {};
      if (dirty & 32)
        axis1_changes.axis = ctx3[5];
      axis1.$set(axis1_changes);
      if (dirty & 141) {
        each_value = ctx3[0];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context9(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block9(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(g0, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
      if (!current || dirty & 2) {
        attr(svg2, "width", ctx3[1]);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(axis0.$$.fragment, local);
      transition_in(axis1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(axis0.$$.fragment, local);
      transition_out(axis1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(svg2);
      destroy_component(axis0);
      destroy_component(axis1);
      destroy_each(each_blocks, detaching);
      mounted = false;
      dispose();
    }
  };
}
var height3 = 250;
function instance10($$self, $$props, $$invalidate) {
  let innerWidth;
  let innerHeight2;
  let dateExtent;
  let x2;
  let y2;
  let xAxis;
  let yAxis;
  let quad;
  let { data } = $$props;
  let { width } = $$props;
  const today = new Date();
  const margin = { top: 10, right: 10, bottom: 30, left: 70 };
  function tooltipText(d) {
    return [domHelpers.t(d.description), domHelpers.em(day2(d.date))];
  }
  const tooltipFindNode = (xPos, yPos) => {
    var _a2;
    const d = quad.find(xPos, yPos);
    return d && [x2(d.date), (_a2 = y2(d.type)) != null ? _a2 : 0, tooltipText(d)];
  };
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(0, data = $$props2.data);
    if ("width" in $$props2)
      $$invalidate(1, width = $$props2.width);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 2) {
      $:
        $$invalidate(10, innerWidth = width - margin.left - margin.right);
    }
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(11, dateExtent = extent(data, (d) => d.date));
    }
    if ($$self.$$.dirty & 3072) {
      $:
        $$invalidate(3, x2 = utcTime().domain(dateExtent[0] ? dateExtent : [0, 1]).range([0, innerWidth]));
    }
    if ($$self.$$.dirty & 17) {
      $:
        $$invalidate(2, y2 = point().padding(1).domain(data.map((d) => d.type)).range([innerHeight2, 0]));
    }
    if ($$self.$$.dirty & 8) {
      $:
        $$invalidate(6, xAxis = axisBottom(x2).tickSizeOuter(0));
    }
    if ($$self.$$.dirty & 1028) {
      $:
        $$invalidate(5, yAxis = axisLeft(y2).tickPadding(6).tickSize(-innerWidth).tickFormat((d) => d));
    }
    if ($$self.$$.dirty & 13) {
      $:
        quad = quadtree(data, (d) => x2(d.date), (d) => {
          var _a2;
          return (_a2 = y2(d.type)) != null ? _a2 : 0;
        });
    }
  };
  $:
    $$invalidate(4, innerHeight2 = height3 - margin.top - margin.bottom);
  return [
    data,
    width,
    y2,
    x2,
    innerHeight2,
    yAxis,
    xAxis,
    today,
    margin,
    tooltipFindNode,
    innerWidth,
    dateExtent
  ];
}
var ScatterPlot = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance10, create_fragment10, safe_not_equal, { data: 0, width: 1 });
  }
};
var ScatterPlot_default = ScatterPlot;

// src/charts/Chart.svelte
function get_each_context10(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[20] = list[i];
  return child_ctx;
}
function create_else_block(ctx2) {
  let span;
  return {
    c() {
      span = element("span");
      attr(span, "class", "spacer");
    },
    m(target, anchor) {
      insert(target, span, anchor);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(span);
    }
  };
}
function create_if_block_14(ctx2) {
  let div;
  let chartlegend;
  let t03;
  let span;
  let t13;
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  chartlegend = new ChartLegend_default({ props: { legend: ctx2[3] } });
  const if_block_creators = [create_if_block_22, create_if_block_4, create_if_block_5];
  const if_blocks = [];
  function select_block_type_1(ctx3, dirty) {
    if (ctx3[0].type === "hierarchy")
      return 0;
    if (ctx3[0].type === "linechart")
      return 1;
    if (ctx3[0].type === "barchart" && ctx3[0].data.hasStackedData)
      return 2;
    return -1;
  }
  if (~(current_block_type_index = select_block_type_1(ctx2, -1))) {
    if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
  }
  return {
    c() {
      div = element("div");
      create_component(chartlegend.$$.fragment);
      t03 = space();
      span = element("span");
      t13 = space();
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
      attr(span, "class", "spacer");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(chartlegend, div, null);
      insert(target, t03, anchor);
      insert(target, span, anchor);
      insert(target, t13, anchor);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(target, anchor);
      }
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const chartlegend_changes = {};
      if (dirty & 8)
        chartlegend_changes.legend = ctx3[3];
      chartlegend.$set(chartlegend_changes);
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type_1(ctx3, dirty);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx3, dirty);
        }
      } else {
        if (if_block) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block = if_blocks[current_block_type_index];
          if (!if_block) {
            if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx3);
            if_block.c();
          } else {
            if_block.p(ctx3, dirty);
          }
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        } else {
          if_block = null;
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(chartlegend.$$.fragment, local);
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(chartlegend.$$.fragment, local);
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      destroy_component(chartlegend);
      if (detaching)
        detach(t03);
      if (detaching)
        detach(span);
      if (detaching)
        detach(t13);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d(detaching);
      }
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
function create_if_block_5(ctx2) {
  let modeswitch;
  let updating_value;
  let current;
  function modeswitch_value_binding_2(value) {
    ctx2[17](value);
  }
  let modeswitch_props = {
    options: [["stacked", _("Stacked Bars")], ["single", _("Single Bars")]]
  };
  if (ctx2[8] !== void 0) {
    modeswitch_props.value = ctx2[8];
  }
  modeswitch = new ModeSwitch_default({ props: modeswitch_props });
  binding_callbacks.push(() => bind(modeswitch, "value", modeswitch_value_binding_2));
  return {
    c() {
      create_component(modeswitch.$$.fragment);
    },
    m(target, anchor) {
      mount_component(modeswitch, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const modeswitch_changes = {};
      if (!updating_value && dirty & 256) {
        updating_value = true;
        modeswitch_changes.value = ctx3[8];
        add_flush_callback(() => updating_value = false);
      }
      modeswitch.$set(modeswitch_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(modeswitch.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(modeswitch.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(modeswitch, detaching);
    }
  };
}
function create_if_block_4(ctx2) {
  let modeswitch;
  let updating_value;
  let current;
  function modeswitch_value_binding_1(value) {
    ctx2[16](value);
  }
  let modeswitch_props = {
    options: [["line", _("Line chart")], ["area", _("Area chart")]]
  };
  if (ctx2[7] !== void 0) {
    modeswitch_props.value = ctx2[7];
  }
  modeswitch = new ModeSwitch_default({ props: modeswitch_props });
  binding_callbacks.push(() => bind(modeswitch, "value", modeswitch_value_binding_1));
  return {
    c() {
      create_component(modeswitch.$$.fragment);
    },
    m(target, anchor) {
      mount_component(modeswitch, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const modeswitch_changes = {};
      if (!updating_value && dirty & 128) {
        updating_value = true;
        modeswitch_changes.value = ctx3[7];
        add_flush_callback(() => updating_value = false);
      }
      modeswitch.$set(modeswitch_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(modeswitch.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(modeswitch.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(modeswitch, detaching);
    }
  };
}
function create_if_block_22(ctx2) {
  let t4;
  let modeswitch;
  let updating_value;
  let current;
  let if_block = ctx2[4] === "treemap" && create_if_block_3(ctx2);
  function modeswitch_value_binding(value) {
    ctx2[15](value);
  }
  let modeswitch_props = {
    options: [["treemap", _("Treemap")], ["sunburst", _("Sunburst")]]
  };
  if (ctx2[4] !== void 0) {
    modeswitch_props.value = ctx2[4];
  }
  modeswitch = new ModeSwitch_default({ props: modeswitch_props });
  binding_callbacks.push(() => bind(modeswitch, "value", modeswitch_value_binding));
  return {
    c() {
      if (if_block)
        if_block.c();
      t4 = space();
      create_component(modeswitch.$$.fragment);
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, t4, anchor);
      mount_component(modeswitch, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      if (ctx3[4] === "treemap") {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block_3(ctx3);
          if_block.c();
          if_block.m(t4.parentNode, t4);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      const modeswitch_changes = {};
      if (!updating_value && dirty & 16) {
        updating_value = true;
        modeswitch_changes.value = ctx3[4];
        add_flush_callback(() => updating_value = false);
      }
      modeswitch.$set(modeswitch_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(modeswitch.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(modeswitch.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(t4);
      destroy_component(modeswitch, detaching);
    }
  };
}
function create_if_block_3(ctx2) {
  let select;
  let mounted;
  let dispose;
  let each_value = ctx2[6];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block10(get_each_context10(ctx2, each_value, i));
  }
  return {
    c() {
      select = element("select");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      if (ctx2[5] === void 0)
        add_render_callback(() => ctx2[14].call(select));
    },
    m(target, anchor) {
      insert(target, select, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(select, null);
      }
      select_option(select, ctx2[5]);
      if (!mounted) {
        dispose = listen(select, "change", ctx2[14]);
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if (dirty & 64) {
        each_value = ctx3[6];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context10(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block10(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(select, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
      if (dirty & 96) {
        select_option(select, ctx3[5]);
      }
    },
    d(detaching) {
      if (detaching)
        detach(select);
      destroy_each(each_blocks, detaching);
      mounted = false;
      dispose();
    }
  };
}
function create_each_block10(ctx2) {
  let option;
  let t_value = ctx2[20] + "";
  let t4;
  let option_value_value;
  return {
    c() {
      option = element("option");
      t4 = text(t_value);
      option.__value = option_value_value = ctx2[20];
      option.value = option.__value;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t4);
    },
    p(ctx3, dirty) {
      if (dirty & 64 && t_value !== (t_value = ctx3[20] + ""))
        set_data(t4, t_value);
      if (dirty & 64 && option_value_value !== (option_value_value = ctx3[20])) {
        option.__value = option_value_value;
        option.value = option.__value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
function create_if_block4(ctx2) {
  let switch_instance;
  let switch_instance_anchor;
  let current;
  var switch_value = ctx2[11][ctx2[0].type];
  function switch_props(ctx3) {
    return {
      props: {
        data: ctx3[0].data,
        tooltipText: ctx3[0].tooltipText,
        width: ctx3[1]
      }
    };
  }
  if (switch_value) {
    switch_instance = construct_svelte_component(switch_value, switch_props(ctx2));
  }
  return {
    c() {
      if (switch_instance)
        create_component(switch_instance.$$.fragment);
      switch_instance_anchor = empty();
    },
    m(target, anchor) {
      if (switch_instance)
        mount_component(switch_instance, target, anchor);
      insert(target, switch_instance_anchor, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const switch_instance_changes = {};
      if (dirty & 1)
        switch_instance_changes.data = ctx3[0].data;
      if (dirty & 1)
        switch_instance_changes.tooltipText = ctx3[0].tooltipText;
      if (dirty & 2)
        switch_instance_changes.width = ctx3[1];
      if (switch_value !== (switch_value = ctx3[11][ctx3[0].type])) {
        if (switch_instance) {
          group_outros();
          const old_component = switch_instance;
          transition_out(old_component.$$.fragment, 1, 0, () => {
            destroy_component(old_component, 1);
          });
          check_outros();
        }
        if (switch_value) {
          switch_instance = construct_svelte_component(switch_value, switch_props(ctx3));
          create_component(switch_instance.$$.fragment);
          transition_in(switch_instance.$$.fragment, 1);
          mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
        } else {
          switch_instance = null;
        }
      } else if (switch_value) {
        switch_instance.$set(switch_instance_changes);
      }
    },
    i(local) {
      if (current)
        return;
      if (switch_instance)
        transition_in(switch_instance.$$.fragment, local);
      current = true;
    },
    o(local) {
      if (switch_instance)
        transition_out(switch_instance.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(switch_instance_anchor);
      if (switch_instance)
        destroy_component(switch_instance, detaching);
    }
  };
}
function create_fragment11(ctx2) {
  let div0;
  let current_block_type_index;
  let if_block0;
  let t03;
  let t13;
  let button;
  let keyboardShortcut_action;
  let t22;
  let div1;
  let div1_hidden_value;
  let div1_resize_listener;
  let current;
  let mounted;
  let dispose;
  const if_block_creators = [create_if_block_14, create_else_block];
  const if_blocks = [];
  function select_block_type(ctx3, dirty) {
    if (ctx3[2])
      return 0;
    return 1;
  }
  current_block_type_index = select_block_type(ctx2, -1);
  if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
  const default_slot_template = ctx2[13].default;
  const default_slot = create_slot(default_slot_template, ctx2, ctx2[12], null);
  let if_block1 = ctx2[1] && create_if_block4(ctx2);
  return {
    c() {
      div0 = element("div");
      if_block0.c();
      t03 = space();
      if (default_slot)
        default_slot.c();
      t13 = space();
      button = element("button");
      t22 = space();
      div1 = element("div");
      if (if_block1)
        if_block1.c();
      attr(button, "type", "button");
      attr(button, "class", "toggle-chart svelte-gzgoh1");
      toggle_class(button, "closed", !ctx2[2]);
      attr(div0, "class", "flex-row");
      div1.hidden = div1_hidden_value = !ctx2[2];
      add_render_callback(() => ctx2[19].call(div1));
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      if_blocks[current_block_type_index].m(div0, null);
      append(div0, t03);
      if (default_slot) {
        default_slot.m(div0, null);
      }
      append(div0, t13);
      append(div0, button);
      insert(target, t22, anchor);
      insert(target, div1, anchor);
      if (if_block1)
        if_block1.m(div1, null);
      div1_resize_listener = add_resize_listener(div1, ctx2[19].bind(div1));
      current = true;
      if (!mounted) {
        dispose = [
          listen(button, "click", ctx2[18]),
          action_destroyer(keyboardShortcut_action = keyboardShortcut.call(null, button, "Control+c"))
        ];
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx3, dirty);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx3, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block0 = if_blocks[current_block_type_index];
        if (!if_block0) {
          if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx3);
          if_block0.c();
        } else {
          if_block0.p(ctx3, dirty);
        }
        transition_in(if_block0, 1);
        if_block0.m(div0, t03);
      }
      if (default_slot) {
        if (default_slot.p && (!current || dirty & 4096)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx3,
            ctx3[12],
            !current ? get_all_dirty_from_scope(ctx3[12]) : get_slot_changes(default_slot_template, ctx3[12], dirty, null),
            null
          );
        }
      }
      if (!current || dirty & 4) {
        toggle_class(button, "closed", !ctx3[2]);
      }
      if (ctx3[1]) {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
          if (dirty & 2) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block4(ctx3);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(div1, null);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      if (!current || dirty & 4 && div1_hidden_value !== (div1_hidden_value = !ctx3[2])) {
        div1.hidden = div1_hidden_value;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block0);
      transition_in(default_slot, local);
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(default_slot, local);
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div0);
      if_blocks[current_block_type_index].d();
      if (default_slot)
        default_slot.d(detaching);
      if (detaching)
        detach(t22);
      if (detaching)
        detach(div1);
      if (if_block1)
        if_block1.d();
      div1_resize_listener();
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance11($$self, $$props, $$invalidate) {
  let $showCharts;
  let $legend;
  let $hierarchyChartMode;
  let $chartCurrency;
  let $currencies;
  let $lineChartMode;
  let $barChartMode;
  component_subscribe($$self, showCharts, ($$value) => $$invalidate(2, $showCharts = $$value));
  component_subscribe($$self, hierarchyChartMode, ($$value) => $$invalidate(4, $hierarchyChartMode = $$value));
  component_subscribe($$self, chartCurrency, ($$value) => $$invalidate(5, $chartCurrency = $$value));
  component_subscribe($$self, lineChartMode, ($$value) => $$invalidate(7, $lineChartMode = $$value));
  component_subscribe($$self, barChartMode, ($$value) => $$invalidate(8, $barChartMode = $$value));
  let { $$slots: slots = {}, $$scope } = $$props;
  let { chart } = $$props;
  let width;
  const currencies2 = writable([]);
  component_subscribe($$self, currencies2, (value) => $$invalidate(6, $currencies = value));
  setContext("chart-currencies", currencies2);
  const legend = writable([]);
  component_subscribe($$self, legend, (value) => $$invalidate(3, $legend = value));
  setContext("chart-legend", legend);
  const components2 = {
    barchart: BarChart_default,
    hierarchy: HierarchyContainer_default,
    linechart: LineChart_default,
    scatterplot: ScatterPlot_default
  };
  function select_change_handler() {
    $chartCurrency = select_value(this);
    chartCurrency.set($chartCurrency);
  }
  function modeswitch_value_binding(value) {
    $hierarchyChartMode = value;
    hierarchyChartMode.set($hierarchyChartMode);
  }
  function modeswitch_value_binding_1(value) {
    $lineChartMode = value;
    lineChartMode.set($lineChartMode);
  }
  function modeswitch_value_binding_2(value) {
    $barChartMode = value;
    barChartMode.set($barChartMode);
  }
  const click_handler = () => showCharts.update((v) => !v);
  function div1_elementresize_handler() {
    width = this.clientWidth;
    $$invalidate(1, width);
  }
  $$self.$$set = ($$props2) => {
    if ("chart" in $$props2)
      $$invalidate(0, chart = $$props2.chart);
    if ("$$scope" in $$props2)
      $$invalidate(12, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 1) {
      $:
        if (chart) {
          legend.set([]);
        }
    }
  };
  return [
    chart,
    width,
    $showCharts,
    $legend,
    $hierarchyChartMode,
    $chartCurrency,
    $currencies,
    $lineChartMode,
    $barChartMode,
    currencies2,
    legend,
    components2,
    $$scope,
    slots,
    select_change_handler,
    modeswitch_value_binding,
    modeswitch_value_binding_1,
    modeswitch_value_binding_2,
    click_handler,
    div1_elementresize_handler
  ];
}
var Chart = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance11, create_fragment11, safe_not_equal, { chart: 0 });
  }
};
var Chart_default = Chart;

// src/charts/context.ts
var operatingCurrenciesWithConversion = derived(
  [operating_currency, currencies, conversion],
  ([operating_currency_val, currencies_val, conversion_val]) => currencies_val.includes(conversion_val) && !operating_currency_val.includes(conversion_val) ? [...operating_currency_val, conversion_val] : operating_currency_val
);
var chartContext = derived(
  [operatingCurrenciesWithConversion, currentDateFormat],
  ([currencies_val, dateFormat2]) => ({ currencies: currencies_val, dateFormat: dateFormat2 })
);

// src/charts/ConversionAndInterval.svelte
function get_each_context11(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[6] = list[i][0];
  child_ctx[7] = list[i][1];
  return child_ctx;
}
function get_each_context_13(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[10] = list[i][0];
  child_ctx[11] = list[i][1];
  return child_ctx;
}
function create_each_block_13(ctx2) {
  let option;
  let t_value = ctx2[11] + "";
  let t4;
  let option_value_value;
  return {
    c() {
      option = element("option");
      t4 = text(t_value);
      option.__value = option_value_value = ctx2[10];
      option.value = option.__value;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t4);
    },
    p(ctx3, dirty) {
      if (dirty & 2 && t_value !== (t_value = ctx3[11] + ""))
        set_data(t4, t_value);
      if (dirty & 2 && option_value_value !== (option_value_value = ctx3[10])) {
        option.__value = option_value_value;
        option.value = option.__value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
function create_each_block11(ctx2) {
  let option;
  let t_value = ctx2[7] + "";
  let t4;
  let option_value_value;
  return {
    c() {
      option = element("option");
      t4 = text(t_value);
      option.__value = option_value_value = ctx2[6];
      option.value = option.__value;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t4);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
function create_fragment12(ctx2) {
  let select0;
  let t4;
  let select1;
  let mounted;
  let dispose;
  let each_value_1 = ctx2[1];
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks_1[i] = create_each_block_13(get_each_context_13(ctx2, each_value_1, i));
  }
  let each_value = ctx2[3];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block11(get_each_context11(ctx2, each_value, i));
  }
  return {
    c() {
      select0 = element("select");
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t4 = space();
      select1 = element("select");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      if (ctx2[0] === void 0)
        add_render_callback(() => ctx2[4].call(select0));
      if (ctx2[2] === void 0)
        add_render_callback(() => ctx2[5].call(select1));
    },
    m(target, anchor) {
      insert(target, select0, anchor);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].m(select0, null);
      }
      select_option(select0, ctx2[0]);
      insert(target, t4, anchor);
      insert(target, select1, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(select1, null);
      }
      select_option(select1, ctx2[2]);
      if (!mounted) {
        dispose = [
          listen(select0, "change", ctx2[4]),
          listen(select1, "change", ctx2[5])
        ];
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & 2) {
        each_value_1 = ctx3[1];
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_13(ctx3, each_value_1, i);
          if (each_blocks_1[i]) {
            each_blocks_1[i].p(child_ctx, dirty);
          } else {
            each_blocks_1[i] = create_each_block_13(child_ctx);
            each_blocks_1[i].c();
            each_blocks_1[i].m(select0, null);
          }
        }
        for (; i < each_blocks_1.length; i += 1) {
          each_blocks_1[i].d(1);
        }
        each_blocks_1.length = each_value_1.length;
      }
      if (dirty & 3) {
        select_option(select0, ctx3[0]);
      }
      if (dirty & 8) {
        each_value = ctx3[3];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context11(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block11(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(select1, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
      if (dirty & 12) {
        select_option(select1, ctx3[2]);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(select0);
      destroy_each(each_blocks_1, detaching);
      if (detaching)
        detach(t4);
      if (detaching)
        detach(select1);
      destroy_each(each_blocks, detaching);
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance12($$self, $$props, $$invalidate) {
  let $conversion;
  let $conversions;
  let $interval;
  component_subscribe($$self, conversion, ($$value) => $$invalidate(0, $conversion = $$value));
  component_subscribe($$self, conversions, ($$value) => $$invalidate(1, $conversions = $$value));
  component_subscribe($$self, interval, ($$value) => $$invalidate(2, $interval = $$value));
  const intervals = [
    ["year", _("Yearly")],
    ["quarter", _("Quarterly")],
    ["month", _("Monthly")],
    ["week", _("Weekly")],
    ["day", _("Daily")]
  ];
  function select0_change_handler() {
    $conversion = select_value(this);
    conversion.set($conversion);
  }
  function select1_change_handler() {
    $interval = select_value(this);
    interval.set($interval);
    $$invalidate(3, intervals);
  }
  return [
    $conversion,
    $conversions,
    $interval,
    intervals,
    select0_change_handler,
    select1_change_handler
  ];
}
var ConversionAndInterval = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance12, create_fragment12, safe_not_equal, {});
  }
};
var ConversionAndInterval_default = ConversionAndInterval;

// src/charts/bar.ts
var bar_validator = array(
  object({
    date,
    budgets: record(number2),
    balance: record(number2),
    account_balances: record(record(number2))
  })
);
function bar(json, { currencies: currencies2, dateFormat: dateFormat2 }) {
  const res2 = bar_validator(json);
  if (!res2.success) {
    return res2;
  }
  const parsedData = res2.value;
  const bar_groups = parsedData.map((interval2) => ({
    values: currencies2.map((currency) => {
      var _a2, _b;
      return {
        currency,
        value: (_a2 = interval2.balance[currency]) != null ? _a2 : 0,
        budget: (_b = interval2.budgets[currency]) != null ? _b : 0
      };
    }),
    date: interval2.date,
    label: dateFormat2(interval2.date),
    account_balances: interval2.account_balances
  }));
  const accounts2 = Array.from(
    new Set(parsedData.map((d) => [...Object.keys(d.account_balances)]).flat(2))
  ).sort();
  const hasStackedData = accounts2.length > 1;
  const stacks = currencies2.map(
    (currency) => [
      currency,
      stack_default().keys(accounts2).value((obj, key) => {
        var _a2, _b;
        return (_b = (_a2 = obj.account_balances[key]) == null ? void 0 : _a2[currency]) != null ? _b : 0;
      }).offset(diverging_default)(bar_groups)
    ]
  );
  return ok({
    type: "barchart",
    data: { accounts: accounts2, bar_groups, stacks, hasStackedData },
    tooltipText: (c, d, e3) => {
      const content2 = [];
      if (e3 === "") {
        d.values.forEach((a) => {
          content2.push(
            domHelpers.t(
              a.budget ? `${c.amount(a.value, a.currency)} / ${c.amount(
                a.budget,
                a.currency
              )}` : c.amount(a.value, a.currency)
            )
          );
          content2.push(domHelpers.br());
        });
      } else {
        content2.push(domHelpers.em(e3));
        d.values.forEach((a) => {
          var _a2, _b;
          const value = (_b = (_a2 = d.account_balances[e3]) == null ? void 0 : _a2[a.currency]) != null ? _b : 0;
          content2.push(domHelpers.t(`${c.amount(value, a.currency)}`));
          content2.push(domHelpers.br());
        });
      }
      content2.push(domHelpers.em(d.label));
      return content2;
    }
  });
}

// src/charts/hierarchy.ts
function addInternalNodesAsLeaves(node) {
  if (node.children.length) {
    node.children.forEach(addInternalNodesAsLeaves);
    node.children.push(__spreadProps(__spreadValues({}, node), { children: [], dummy: true }));
    node.balance = {};
  }
}
var account_hierarchy_validator = object({
  account: string,
  balance: record(number2),
  children: lazy(() => array(account_hierarchy_validator))
});
var hierarchy_validator = object({
  root: account_hierarchy_validator,
  modifier: number2
});
function hierarchy2(json, { currencies: currencies2 }) {
  const res2 = hierarchy_validator(json);
  if (!res2.success) {
    return res2;
  }
  const { root: root2, modifier } = res2.value;
  addInternalNodesAsLeaves(root2);
  const data = /* @__PURE__ */ new Map();
  currencies2.forEach((currency) => {
    const currencyHierarchy = hierarchy(root2).sum((d) => {
      var _a2;
      return Math.max(((_a2 = d.balance[currency]) != null ? _a2 : 0) * modifier, 0);
    }).sort((a, b) => {
      var _a2, _b;
      return ((_a2 = b.value) != null ? _a2 : 0) - ((_b = a.value) != null ? _b : 0);
    });
    if (currencyHierarchy.value) {
      data.set(currency, currencyHierarchy);
    }
  });
  return ok({ type: "hierarchy", data });
}

// src/charts/line.ts
var balances_validator = array(object({ date, balance: record(number2) }));
function balances(json) {
  const res2 = balances_validator(json);
  if (!res2.success) {
    return res2;
  }
  const parsedData = res2.value;
  const groups2 = /* @__PURE__ */ new Map();
  for (const { date: date_, balance } of parsedData) {
    Object.entries(balance).forEach(([currency, value]) => {
      const group2 = groups2.get(currency);
      const datum2 = { date: date_, value, name: currency };
      if (group2) {
        group2.push(datum2);
      } else {
        groups2.set(currency, [datum2]);
      }
    });
  }
  const data = [...groups2.entries()].map(([name2, values]) => ({
    name: name2,
    values
  }));
  return ok({
    type: "linechart",
    data,
    tooltipText: (c, d) => [
      domHelpers.t(c.amount(d.value, d.name)),
      domHelpers.em(day2(d.date))
    ]
  });
}
var commodities_validator = object({
  quote: string,
  base: string,
  prices: array(tuple([date, number2]))
});
function commodities(json, _ctx, label) {
  const res2 = commodities_validator(json);
  if (!res2.success) {
    return res2;
  }
  const { base: base2, quote, prices } = res2.value;
  const values = prices.map((d) => ({ name: label, date: d[0], value: d[1] }));
  return ok({
    type: "linechart",
    data: [{ name: label, values }],
    tooltipText: (c, d) => [
      domHelpers.t(`1 ${base2} = ${c.amount(d.value, quote)}`),
      domHelpers.em(day2(d.date))
    ]
  });
}

// src/charts/scatterplot.ts
var scatterplot_validator = array(
  object({ type: string, date, description: string })
);
function scatterplot(json) {
  const res2 = scatterplot_validator(json);
  if (!res2.success) {
    return res2;
  }
  return ok({ type: "scatterplot", data: res2.value });
}

// src/charts/index.ts
var parsers = {
  balances,
  commodities,
  bar,
  hierarchy: hierarchy2,
  scatterplot
};
var chart_data_validator = array(
  object({ label: string, type: string, data: unknown })
);
function parseChartData(res2, ctx2) {
  if (!res2.success) {
    return res2;
  }
  const chartData = res2.value;
  const result = [];
  chartData.forEach((chart) => {
    const parser = parsers[chart.type];
    if (parser) {
      const r = parser(chart.data, ctx2, chart.label);
      if (r.success) {
        result.push(__spreadValues({ name: chart.label }, r.value));
      }
    }
  });
  return ok(result);
}

// src/charts/ChartSwitcher.svelte
function get_each_context12(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[7] = list[i];
  return child_ctx;
}
function create_if_block5(ctx2) {
  let chart;
  let t4;
  let div;
  let div_hidden_value;
  let current;
  chart = new Chart_default({
    props: {
      chart: ctx2[0],
      $$slots: { default: [create_default_slot] },
      $$scope: { ctx: ctx2 }
    }
  });
  let each_value = ctx2[1];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block12(get_each_context12(ctx2, each_value, i));
  }
  return {
    c() {
      create_component(chart.$$.fragment);
      t4 = space();
      div = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      div.hidden = div_hidden_value = !ctx2[2];
      attr(div, "class", "svelte-nc8apk");
    },
    m(target, anchor) {
      mount_component(chart, target, anchor);
      insert(target, t4, anchor);
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(div, null);
      }
      current = true;
    },
    p(ctx3, dirty) {
      const chart_changes = {};
      if (dirty & 1)
        chart_changes.chart = ctx3[0];
      if (dirty & 1024) {
        chart_changes.$$scope = { dirty, ctx: ctx3 };
      }
      chart.$set(chart_changes);
      if (dirty & 3) {
        each_value = ctx3[1];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context12(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block12(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(div, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
      if (!current || dirty & 4 && div_hidden_value !== (div_hidden_value = !ctx3[2])) {
        div.hidden = div_hidden_value;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(chart.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(chart.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(chart, detaching);
      if (detaching)
        detach(t4);
      if (detaching)
        detach(div);
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_default_slot(ctx2) {
  let conversionandinterval;
  let current;
  conversionandinterval = new ConversionAndInterval_default({});
  return {
    c() {
      create_component(conversionandinterval.$$.fragment);
    },
    m(target, anchor) {
      mount_component(conversionandinterval, target, anchor);
      current = true;
    },
    i(local) {
      if (current)
        return;
      transition_in(conversionandinterval.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(conversionandinterval.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(conversionandinterval, detaching);
    }
  };
}
function create_each_block12(ctx2) {
  let button;
  let t0_value = ctx2[7].name + "";
  let t03;
  let t13;
  let mounted;
  let dispose;
  function click_handler() {
    return ctx2[4](ctx2[7]);
  }
  return {
    c() {
      button = element("button");
      t03 = text(t0_value);
      t13 = space();
      attr(button, "type", "button");
      attr(button, "class", "svelte-nc8apk");
      toggle_class(button, "selected", ctx2[7] === ctx2[0]);
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, t03);
      append(button, t13);
      if (!mounted) {
        dispose = listen(button, "click", click_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & 2 && t0_value !== (t0_value = ctx2[7].name + ""))
        set_data(t03, t0_value);
      if (dirty & 3) {
        toggle_class(button, "selected", ctx2[7] === ctx2[0]);
      }
    },
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
function create_fragment13(ctx2) {
  let if_block_anchor;
  let current;
  let if_block = ctx2[1].length > 0 && ctx2[0] && create_if_block5(ctx2);
  return {
    c() {
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      if (ctx3[1].length > 0 && ctx3[0]) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & 3) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block5(ctx3);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
function instance13($$self, $$props, $$invalidate) {
  let $lastActiveChartName;
  let $chartContext;
  let $showCharts;
  component_subscribe($$self, lastActiveChartName, ($$value) => $$invalidate(5, $lastActiveChartName = $$value));
  component_subscribe($$self, chartContext, ($$value) => $$invalidate(6, $chartContext = $$value));
  component_subscribe($$self, showCharts, ($$value) => $$invalidate(2, $showCharts = $$value));
  let { data } = $$props;
  let charts = [];
  let active_chart = null;
  onMount(() => {
    const chartData = data ? chart_data_validator(data) : getScriptTagValue("#chart-data", chart_data_validator);
    if (!data && chartData.success && chartData.value.length) {
      notify("This page adds charts using a deprecated method which will be removed soon.", "warning");
    }
    const res2 = parseChartData(chartData, $chartContext);
    if (res2.success) {
      $$invalidate(1, charts = res2.value);
    } else {
      log_error(res2.value);
    }
    $$invalidate(0, active_chart = charts.length ? charts.find((c) => c.name === $lastActiveChartName) || charts[0] : null);
    if (!active_chart) {
      return () => {
      };
    }
    const unbind = [
      bindKey("c", () => {
        const currentIndex = charts.findIndex((e3) => e3 === active_chart);
        $$invalidate(0, active_chart = charts[(currentIndex + 1 + charts.length) % charts.length]);
      }),
      bindKey("C", () => {
        const currentIndex = charts.findIndex((e3) => e3 === active_chart);
        $$invalidate(0, active_chart = charts[(currentIndex - 1 + charts.length) % charts.length]);
      })
    ];
    return () => {
      unbind.forEach((u) => u());
    };
  });
  const click_handler = (chart) => {
    $$invalidate(0, active_chart = chart);
  };
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(3, data = $$props2.data);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 1) {
      $:
        if (active_chart) {
          set_store_value(lastActiveChartName, $lastActiveChartName = active_chart.name, $lastActiveChartName);
        }
    }
  };
  return [active_chart, charts, $showCharts, data, click_handler];
}
var ChartSwitcher = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance13, create_fragment13, safe_not_equal, { data: 3 });
  }
};
var ChartSwitcher_default = ChartSwitcher;

// src/lib/fuzzy.ts
function fuzzytest(pattern, text2) {
  const casesensitive = pattern === pattern.toLowerCase();
  const exact = casesensitive ? text2.toLowerCase().indexOf(pattern) : text2.indexOf(pattern);
  if (exact > -1) {
    return pattern.length ** 2;
  }
  let score2 = 0;
  let localScore = 0;
  let pindex = 0;
  for (let index2 = 0; index2 < text2.length; index2 += 1) {
    const char = text2[index2];
    const search = pattern[pindex];
    if (char === search || char.toLowerCase() === search) {
      pindex += 1;
      localScore += 1;
    } else {
      localScore = 0;
    }
    score2 += localScore;
  }
  return pindex === pattern.length ? score2 : 0;
}
function fuzzyfilter(pattern, suggestions) {
  if (!pattern) {
    return suggestions;
  }
  return suggestions.map((s) => [s, fuzzytest(pattern, s)]).filter(([, score2]) => score2).sort((a, b) => b[1] - a[1]).map(([s]) => s);
}
var escapeChars = {
  '"': "&quot;",
  "'": "&#39;",
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;"
};
var e = (text2) => text2.replace(/["'&<>]/g, (m) => escapeChars[m]);
function fuzzywrap(pattern, text2) {
  if (!pattern) {
    return e(text2);
  }
  const casesensitive = pattern === pattern.toLowerCase();
  const exact = casesensitive ? text2.toLowerCase().indexOf(pattern) : text2.indexOf(pattern);
  if (exact > -1) {
    const before = text2.slice(0, exact);
    const match = text2.slice(exact, exact + pattern.length);
    const after = text2.slice(exact + pattern.length);
    return `${e(before)}<span>${e(match)}</span>${e(after)}`;
  }
  let pindex = 0;
  let inMatch = false;
  const result = [];
  for (let index2 = 0; index2 < text2.length; index2 += 1) {
    const char = text2[index2];
    const search = pattern[pindex];
    if (char === search || char.toLowerCase() === search) {
      if (!inMatch) {
        result.push("<span>");
        inMatch = true;
      }
      result.push(e(char));
      pindex += 1;
    } else {
      if (inMatch) {
        result.push("</span>");
        inMatch = false;
      }
      result.push(e(char));
    }
  }
  if (pindex < pattern.length) {
    return e(text2);
  }
  if (inMatch) {
    result.push("</span>");
  }
  return result.join("");
}

// src/AutocompleteInput.svelte
function get_each_context13(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[26] = list[i].innerHTML;
  child_ctx[27] = list[i].suggestion;
  child_ctx[29] = i;
  return child_ctx;
}
function create_if_block_15(ctx2) {
  let button;
  let button_tabindex_value;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      button.textContent = "\xD7";
      attr(button, "type", "button");
      attr(button, "tabindex", button_tabindex_value = -1);
      attr(button, "class", "muted round svelte-420ct3");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (!mounted) {
        dispose = listen(button, "click", ctx2[23]);
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block6(ctx2) {
  let ul;
  let each_value = ctx2[5];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block13(get_each_context13(ctx2, each_value, i));
  }
  return {
    c() {
      ul = element("ul");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      ul.hidden = ctx2[8];
      attr(ul, "class", "svelte-420ct3");
    },
    m(target, anchor) {
      insert(target, ul, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(ul, null);
      }
    },
    p(ctx3, dirty) {
      if (dirty & 2144) {
        each_value = ctx3[5];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context13(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block13(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(ul, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
      if (dirty & 256) {
        ul.hidden = ctx3[8];
      }
    },
    d(detaching) {
      if (detaching)
        detach(ul);
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_each_block13(ctx2) {
  let li;
  let html_tag;
  let raw_value = ctx2[26] + "";
  let t4;
  let mounted;
  let dispose;
  function mousedown_handler(...args) {
    return ctx2[24](ctx2[27], ...args);
  }
  return {
    c() {
      li = element("li");
      html_tag = new HtmlTag(false);
      t4 = space();
      html_tag.a = t4;
      attr(li, "class", "svelte-420ct3");
      toggle_class(li, "selected", ctx2[29] === ctx2[6]);
    },
    m(target, anchor) {
      insert(target, li, anchor);
      html_tag.m(raw_value, li);
      append(li, t4);
      if (!mounted) {
        dispose = listen(li, "mousedown", mousedown_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & 32 && raw_value !== (raw_value = ctx2[26] + ""))
        html_tag.p(raw_value);
      if (dirty & 64) {
        toggle_class(li, "selected", ctx2[29] === ctx2[6]);
      }
    },
    d(detaching) {
      if (detaching)
        detach(li);
      mounted = false;
      dispose();
    }
  };
}
function create_fragment14(ctx2) {
  let span;
  let input_1;
  let keyboardShortcut_action;
  let t03;
  let t13;
  let span_class_value;
  let mounted;
  let dispose;
  let if_block0 = ctx2[4] && ctx2[0] && create_if_block_15(ctx2);
  let if_block1 = ctx2[5].length && create_if_block6(ctx2);
  return {
    c() {
      span = element("span");
      input_1 = element("input");
      t03 = space();
      if (if_block0)
        if_block0.c();
      t13 = space();
      if (if_block1)
        if_block1.c();
      attr(input_1, "type", "text");
      attr(input_1, "autocomplete", "off");
      attr(input_1, "placeholder", ctx2[1]);
      attr(input_1, "size", ctx2[9]);
      attr(input_1, "class", "svelte-420ct3");
      attr(span, "class", span_class_value = null_to_empty(ctx2[2]) + " svelte-420ct3");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, input_1);
      set_input_value(input_1, ctx2[0]);
      ctx2[19](input_1);
      append(span, t03);
      if (if_block0)
        if_block0.m(span, null);
      append(span, t13);
      if (if_block1)
        if_block1.m(span, null);
      if (!mounted) {
        dispose = [
          listen(input_1, "input", ctx2[18]),
          action_destroyer(keyboardShortcut_action = keyboardShortcut.call(null, input_1, ctx2[3])),
          listen(input_1, "blur", ctx2[20]),
          listen(input_1, "focus", ctx2[21]),
          listen(input_1, "input", ctx2[22]),
          listen(input_1, "keydown", ctx2[12])
        ];
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & 2) {
        attr(input_1, "placeholder", ctx3[1]);
      }
      if (dirty & 512) {
        attr(input_1, "size", ctx3[9]);
      }
      if (dirty & 1 && input_1.value !== ctx3[0]) {
        set_input_value(input_1, ctx3[0]);
      }
      if (keyboardShortcut_action && is_function(keyboardShortcut_action.update) && dirty & 8)
        keyboardShortcut_action.update.call(null, ctx3[3]);
      if (ctx3[4] && ctx3[0]) {
        if (if_block0) {
          if_block0.p(ctx3, dirty);
        } else {
          if_block0 = create_if_block_15(ctx3);
          if_block0.c();
          if_block0.m(span, t13);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (ctx3[5].length) {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
        } else {
          if_block1 = create_if_block6(ctx3);
          if_block1.c();
          if_block1.m(span, null);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (dirty & 4 && span_class_value !== (span_class_value = null_to_empty(ctx3[2]) + " svelte-420ct3")) {
        attr(span, "class", span_class_value);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(span);
      ctx2[19](null);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance14($$self, $$props, $$invalidate) {
  let size;
  const dispatch = createEventDispatcher();
  let { value } = $$props;
  let { suggestions } = $$props;
  let { placeholder: placeholder2 = "" } = $$props;
  let { valueExtractor: valueExtractor2 = null } = $$props;
  let { valueSelector: valueSelector2 = null } = $$props;
  let { setSize = false } = $$props;
  let { className = void 0 } = $$props;
  let { key = void 0 } = $$props;
  let { checkValidity = void 0 } = $$props;
  let { clearButton = false } = $$props;
  let filteredSuggestions = [];
  let hidden = true;
  let index2 = -1;
  let input;
  function select(suggestion) {
    $$invalidate(0, value = input && valueSelector2 ? valueSelector2(suggestion, input) : suggestion);
    dispatch("select", input);
    $$invalidate(8, hidden = true);
  }
  function mousedown(event, suggestion) {
    if (event.button === 0) {
      select(suggestion);
    }
  }
  function keydown2(event) {
    if (event.key === "Enter") {
      if (index2 > -1 && !hidden && filteredSuggestions[index2]) {
        event.preventDefault();
        select(filteredSuggestions[index2].suggestion);
      } else {
        dispatch("enter", input);
      }
    } else if (event.key === " " && event.ctrlKey) {
      $$invalidate(8, hidden = false);
    } else if (event.key === "Escape") {
      if (!hidden && filteredSuggestions.length > 0) {
        event.stopPropagation();
        $$invalidate(6, index2 = -1);
      }
      $$invalidate(8, hidden = true);
    } else if (event.key === "ArrowUp") {
      event.preventDefault();
      $$invalidate(6, index2 = index2 === 0 ? filteredSuggestions.length - 1 : index2 - 1);
    } else if (event.key === "ArrowDown") {
      event.preventDefault();
      $$invalidate(6, index2 = index2 === filteredSuggestions.length - 1 ? 0 : index2 + 1);
    }
  }
  function input_1_input_handler() {
    value = this.value;
    $$invalidate(0, value);
  }
  function input_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      input = $$value;
      $$invalidate(7, input);
    });
  }
  const blur_handler = () => {
    $$invalidate(8, hidden = true);
    dispatch("blur");
  };
  const focus_handler = () => {
    $$invalidate(8, hidden = false);
  };
  const input_handler = () => {
    $$invalidate(8, hidden = false);
  };
  const click_handler = () => {
    $$invalidate(0, value = "");
    dispatch("select");
  };
  const mousedown_handler = (suggestion, ev) => mousedown(ev, suggestion);
  $$self.$$set = ($$props2) => {
    if ("value" in $$props2)
      $$invalidate(0, value = $$props2.value);
    if ("suggestions" in $$props2)
      $$invalidate(13, suggestions = $$props2.suggestions);
    if ("placeholder" in $$props2)
      $$invalidate(1, placeholder2 = $$props2.placeholder);
    if ("valueExtractor" in $$props2)
      $$invalidate(14, valueExtractor2 = $$props2.valueExtractor);
    if ("valueSelector" in $$props2)
      $$invalidate(15, valueSelector2 = $$props2.valueSelector);
    if ("setSize" in $$props2)
      $$invalidate(16, setSize = $$props2.setSize);
    if ("className" in $$props2)
      $$invalidate(2, className = $$props2.className);
    if ("key" in $$props2)
      $$invalidate(3, key = $$props2.key);
    if ("checkValidity" in $$props2)
      $$invalidate(17, checkValidity = $$props2.checkValidity);
    if ("clearButton" in $$props2)
      $$invalidate(4, clearButton = $$props2.clearButton);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 65539) {
      $:
        $$invalidate(9, size = setSize ? Math.max(value.length, placeholder2.length) + 1 : void 0);
    }
    if ($$self.$$.dirty & 131201) {
      $:
        if (input && checkValidity) {
          input.setCustomValidity(checkValidity(value));
        }
    }
    if ($$self.$$.dirty & 24801) {
      $: {
        const val = input && valueExtractor2 ? valueExtractor2(value, input) : value;
        const filtered = fuzzyfilter(val, suggestions).slice(0, 30).map((suggestion) => ({
          suggestion,
          innerHTML: fuzzywrap(val, suggestion)
        }));
        $$invalidate(5, filteredSuggestions = filtered.length === 1 && filtered[0].suggestion === val ? [] : filtered);
        $$invalidate(6, index2 = Math.min(index2, filteredSuggestions.length - 1));
      }
    }
  };
  return [
    value,
    placeholder2,
    className,
    key,
    clearButton,
    filteredSuggestions,
    index2,
    input,
    hidden,
    size,
    dispatch,
    mousedown,
    keydown2,
    suggestions,
    valueExtractor2,
    valueSelector2,
    setSize,
    checkValidity,
    input_1_input_handler,
    input_1_binding,
    blur_handler,
    focus_handler,
    input_handler,
    click_handler,
    mousedown_handler
  ];
}
var AutocompleteInput = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance14, create_fragment14, safe_not_equal, {
      value: 0,
      suggestions: 13,
      placeholder: 1,
      valueExtractor: 14,
      valueSelector: 15,
      setSize: 16,
      className: 2,
      key: 3,
      checkValidity: 17,
      clearButton: 4
    });
  }
};
var AutocompleteInput_default = AutocompleteInput;

// src/entry-forms/AccountInput.svelte
function create_fragment15(ctx2) {
  let autocompleteinput;
  let updating_value;
  let current;
  function autocompleteinput_value_binding(value) {
    ctx2[8](value);
  }
  let autocompleteinput_props = {
    placeholder: _("Account"),
    className: ctx2[1],
    checkValidity: ctx2[3],
    suggestions: ctx2[2]
  };
  if (ctx2[0] !== void 0) {
    autocompleteinput_props.value = ctx2[0];
  }
  autocompleteinput = new AutocompleteInput_default({ props: autocompleteinput_props });
  binding_callbacks.push(() => bind(autocompleteinput, "value", autocompleteinput_value_binding));
  return {
    c() {
      create_component(autocompleteinput.$$.fragment);
    },
    m(target, anchor) {
      mount_component(autocompleteinput, target, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      const autocompleteinput_changes = {};
      if (dirty & 2)
        autocompleteinput_changes.className = ctx3[1];
      if (dirty & 4)
        autocompleteinput_changes.suggestions = ctx3[2];
      if (!updating_value && dirty & 1) {
        updating_value = true;
        autocompleteinput_changes.value = ctx3[0];
        add_flush_callback(() => updating_value = false);
      }
      autocompleteinput.$set(autocompleteinput_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(autocompleteinput.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(autocompleteinput.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(autocompleteinput, detaching);
    }
  };
}
function instance15($$self, $$props, $$invalidate) {
  let account_suggestions;
  let filtered_suggestions;
  let $accounts;
  let $account_details;
  component_subscribe($$self, accounts, ($$value) => $$invalidate(7, $accounts = $$value));
  component_subscribe($$self, account_details, ($$value) => $$invalidate(9, $account_details = $$value));
  let { value } = $$props;
  let { suggestions = void 0 } = $$props;
  let { date: date5 = void 0 } = $$props;
  let { className = void 0 } = $$props;
  function checkValidity(val) {
    return !$accounts.length || $accounts.includes(val) ? "" : _("Should be one of the declared accounts");
  }
  function filterSuggestions(accounts_, date_) {
    const res2 = date(date_);
    if (!res2.success) {
      return accounts_;
    }
    const entry_date = res2.value;
    return accounts_.filter((account2) => {
      const details = $account_details[account2];
      if (!details) {
        return true;
      }
      return details.close_date >= entry_date;
    });
  }
  function autocompleteinput_value_binding(value$1) {
    value = value$1;
    $$invalidate(0, value);
  }
  $$self.$$set = ($$props2) => {
    if ("value" in $$props2)
      $$invalidate(0, value = $$props2.value);
    if ("suggestions" in $$props2)
      $$invalidate(4, suggestions = $$props2.suggestions);
    if ("date" in $$props2)
      $$invalidate(5, date5 = $$props2.date);
    if ("className" in $$props2)
      $$invalidate(1, className = $$props2.className);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 144) {
      $:
        $$invalidate(6, account_suggestions = suggestions || $accounts);
    }
    if ($$self.$$.dirty & 96) {
      $:
        $$invalidate(2, filtered_suggestions = filterSuggestions(account_suggestions, date5));
    }
  };
  return [
    value,
    className,
    filtered_suggestions,
    checkValidity,
    suggestions,
    date5,
    account_suggestions,
    $accounts,
    autocompleteinput_value_binding
  ];
}
var AccountInput = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance15, create_fragment15, safe_not_equal, {
      value: 0,
      suggestions: 4,
      date: 5,
      className: 1
    });
  }
};
var AccountInput_default = AccountInput;

// src/lib/paths.ts
function basename(filename) {
  const parts = filename.split(/\/|\\/);
  return parts[parts.length - 1];
}
function ext(filename) {
  const match = /\.(\w+)$/.exec(filename);
  return match ? match[1] : "";
}
function documentHasAccount(filename, account2) {
  const accountParts = account2.split(":").reverse();
  const folders = filename.split(/\/|\\/).reverse().slice(1);
  return accountParts.every((part, index2) => part === folders[index2]);
}

// src/lib/account.ts
function parent(name2) {
  const parentEnd = name2.lastIndexOf(":");
  return parentEnd > 0 ? name2.slice(0, parentEnd) : "";
}
function leaf(name2) {
  const parentEnd = name2.lastIndexOf(":");
  return parentEnd > 0 ? name2.slice(parentEnd + 1) : name2;
}
function isDescendant(name2, of) {
  if (of === "") {
    return true;
  }
  return name2 === of || name2.startsWith(`${of}:`);
}

// src/lib/tree.ts
function stratify(data, id, init3) {
  const root2 = __spreadValues({ children: [] }, init3(""));
  const map2 = /* @__PURE__ */ new Map();
  map2.set("", root2);
  function addAccount(name2, datum2) {
    var _a2;
    const existing = map2.get(name2);
    if (existing) {
      Object.assign(existing, init3(name2, datum2));
      return existing;
    }
    const node = __spreadValues({ children: [] }, init3(name2, datum2));
    map2.set(name2, node);
    const parentName = parent(name2);
    const parentNode = (_a2 = map2.get(parentName)) != null ? _a2 : addAccount(parentName);
    parentNode.children.push(node);
    return node;
  }
  [...data].sort((a, b) => id(a).localeCompare(id(b))).forEach((datum2) => addAccount(id(datum2), datum2));
  return root2;
}

// src/lib/focus.ts
var FOCUSABLE_ELEMENTS = [
  "a[href]",
  'input:not([disabled]):not([type="hidden"]):not([aria-hidden])',
  "select:not([disabled]):not([aria-hidden])",
  "textarea:not([disabled]):not([aria-hidden])",
  "button:not([disabled]):not([aria-hidden])",
  "object",
  "[contenteditable]"
].join(", ");
function getFocusableElements(el) {
  return [...el.querySelectorAll(FOCUSABLE_ELEMENTS)];
}
function attemptFocus(el) {
  try {
    el.focus();
  } catch (e3) {
  }
  return document.activeElement === el;
}

// src/modals/ModalBase.svelte
function create_if_block7(ctx2) {
  let div2;
  let div0;
  let t03;
  let div1;
  let t13;
  let button;
  let handleFocus_action;
  let current;
  let mounted;
  let dispose;
  const default_slot_template = ctx2[5].default;
  const default_slot = create_slot(default_slot_template, ctx2, ctx2[4], null);
  return {
    c() {
      div2 = element("div");
      div0 = element("div");
      t03 = space();
      div1 = element("div");
      if (default_slot)
        default_slot.c();
      t13 = space();
      button = element("button");
      button.textContent = "x";
      attr(div0, "class", "background svelte-1bh5xrq");
      attr(div0, "aria-hidden", "true");
      attr(button, "type", "button");
      attr(button, "class", "muted close svelte-1bh5xrq");
      attr(div1, "class", "content svelte-1bh5xrq");
      attr(div1, "role", "dialog");
      attr(div1, "aria-modal", "true");
      attr(div2, "class", "overlay svelte-1bh5xrq");
    },
    m(target, anchor) {
      insert(target, div2, anchor);
      append(div2, div0);
      append(div2, t03);
      append(div2, div1);
      if (default_slot) {
        default_slot.m(div1, null);
      }
      append(div1, t13);
      append(div1, button);
      current = true;
      if (!mounted) {
        dispose = [
          listen(div0, "click", function() {
            if (is_function(ctx2[1]))
              ctx2[1].apply(this, arguments);
          }),
          listen(button, "click", function() {
            if (is_function(ctx2[1]))
              ctx2[1].apply(this, arguments);
          }),
          action_destroyer(handleFocus_action = ctx2[2].call(null, div1))
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (default_slot) {
        if (default_slot.p && (!current || dirty & 16)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            ctx2[4],
            !current ? get_all_dirty_from_scope(ctx2[4]) : get_slot_changes(default_slot_template, ctx2[4], dirty, null),
            null
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div2);
      if (default_slot)
        default_slot.d(detaching);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_fragment16(ctx2) {
  let if_block_anchor;
  let current;
  let if_block = ctx2[0] && create_if_block7(ctx2);
  return {
    c() {
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      if (ctx3[0]) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & 1) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block7(ctx3);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
function instance16($$self, $$props, $$invalidate) {
  let { $$slots: slots = {}, $$scope } = $$props;
  let { shown = false } = $$props;
  let { focus = "" } = $$props;
  let { closeHandler = closeOverlay } = $$props;
  function handleFocus(el) {
    function keydown2(ev) {
      if (ev.key === "Tab") {
        const focusable = getFocusableElements(el);
        const first = focusable[0];
        const last = focusable[focusable.length - 1];
        if (ev.shiftKey && document.activeElement === first) {
          ev.preventDefault();
          attemptFocus(last);
        } else if (!ev.shiftKey && document.activeElement === last) {
          ev.preventDefault();
          attemptFocus(first);
        }
      } else if (ev.key === "Escape") {
        ev.preventDefault();
        closeHandler();
      }
    }
    document.addEventListener("keydown", keydown2);
    const focusEl = focus && el.querySelector(focus);
    attemptFocus(focusEl || getFocusableElements(el)[0]);
    return {
      destroy: () => document.removeEventListener("keydown", keydown2)
    };
  }
  $$self.$$set = ($$props2) => {
    if ("shown" in $$props2)
      $$invalidate(0, shown = $$props2.shown);
    if ("focus" in $$props2)
      $$invalidate(3, focus = $$props2.focus);
    if ("closeHandler" in $$props2)
      $$invalidate(1, closeHandler = $$props2.closeHandler);
    if ("$$scope" in $$props2)
      $$invalidate(4, $$scope = $$props2.$$scope);
  };
  return [shown, closeHandler, handleFocus, focus, $$scope, slots];
}
var ModalBase = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance16, create_fragment16, safe_not_equal, { shown: 0, focus: 3, closeHandler: 1 });
  }
};
var ModalBase_default = ModalBase;

// src/documents/stores.ts
var selectedAccount = writable("");

// src/documents/Accounts.svelte
function get_each_context14(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[12] = list[i];
  return child_ctx;
}
function create_if_block_16(ctx2) {
  let p;
  let button0;
  let t0_value = ctx2[3] ? "\u25BE" : "\u25B8";
  let t03;
  let t13;
  let button1;
  let t2_value = leaf(ctx2[0].name) + "";
  let t22;
  let t32;
  let p_title_value;
  let p_data_account_name_value;
  let mounted;
  let dispose;
  let if_block = ctx2[0].count > 0 && create_if_block_23(ctx2);
  return {
    c() {
      p = element("p");
      button0 = element("button");
      t03 = text(t0_value);
      t13 = space();
      button1 = element("button");
      t22 = text(t2_value);
      t32 = space();
      if (if_block)
        if_block.c();
      attr(button0, "type", "button");
      attr(button0, "class", "toggle svelte-1dmmlqh");
      attr(button1, "type", "button");
      attr(button1, "class", "leaf svelte-1dmmlqh");
      attr(p, "title", p_title_value = ctx2[0].name);
      attr(p, "class", "droptarget svelte-1dmmlqh");
      attr(p, "data-account-name", p_data_account_name_value = ctx2[0].name);
      toggle_class(p, "has-children", ctx2[6]);
      toggle_class(p, "selected", ctx2[5]);
      toggle_class(p, "drag", ctx2[4]);
    },
    m(target, anchor) {
      insert(target, p, anchor);
      append(p, button0);
      append(button0, t03);
      append(p, t13);
      append(p, button1);
      append(button1, t22);
      append(p, t32);
      if (if_block)
        if_block.m(p, null);
      if (!mounted) {
        dispose = [
          listen(button0, "click", ctx2[9]),
          listen(button1, "click", ctx2[10]),
          listen(p, "dragenter", ctx2[7]),
          listen(p, "dragover", ctx2[7]),
          listen(p, "dragleave", ctx2[11]),
          listen(p, "drop", prevent_default(ctx2[8]))
        ];
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if (dirty & 8 && t0_value !== (t0_value = ctx3[3] ? "\u25BE" : "\u25B8"))
        set_data(t03, t0_value);
      if (dirty & 1 && t2_value !== (t2_value = leaf(ctx3[0].name) + ""))
        set_data(t22, t2_value);
      if (ctx3[0].count > 0) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block_23(ctx3);
          if_block.c();
          if_block.m(p, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty & 1 && p_title_value !== (p_title_value = ctx3[0].name)) {
        attr(p, "title", p_title_value);
      }
      if (dirty & 1 && p_data_account_name_value !== (p_data_account_name_value = ctx3[0].name)) {
        attr(p, "data-account-name", p_data_account_name_value);
      }
      if (dirty & 64) {
        toggle_class(p, "has-children", ctx3[6]);
      }
      if (dirty & 32) {
        toggle_class(p, "selected", ctx3[5]);
      }
      if (dirty & 16) {
        toggle_class(p, "drag", ctx3[4]);
      }
    },
    d(detaching) {
      if (detaching)
        detach(p);
      if (if_block)
        if_block.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_if_block_23(ctx2) {
  let span;
  let t_value = ctx2[0].count + "";
  let t4;
  return {
    c() {
      span = element("span");
      t4 = text(t_value);
      attr(span, "class", "count svelte-1dmmlqh");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t4);
    },
    p(ctx3, dirty) {
      if (dirty & 1 && t_value !== (t_value = ctx3[0].count + ""))
        set_data(t4, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(span);
    }
  };
}
function create_if_block8(ctx2) {
  let ul;
  let ul_hidden_value;
  let current;
  let each_value = ctx2[0].children;
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block14(get_each_context14(ctx2, each_value, i));
  }
  const out = (i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  });
  return {
    c() {
      ul = element("ul");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(ul, "class", "flex-table svelte-1dmmlqh");
      ul.hidden = ul_hidden_value = !ctx2[3];
    },
    m(target, anchor) {
      insert(target, ul, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(ul, null);
      }
      current = true;
    },
    p(ctx3, dirty) {
      if (dirty & 3) {
        each_value = ctx3[0].children;
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context14(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block14(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(ul, null);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out(i);
        }
        check_outros();
      }
      if (!current || dirty & 8 && ul_hidden_value !== (ul_hidden_value = !ctx3[3])) {
        ul.hidden = ul_hidden_value;
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(ul);
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_each_block14(ctx2) {
  let li;
  let accounts2;
  let t4;
  let current;
  accounts2 = new Accounts({
    props: {
      node: ctx2[12],
      move: ctx2[1]
    }
  });
  return {
    c() {
      li = element("li");
      create_component(accounts2.$$.fragment);
      t4 = space();
    },
    m(target, anchor) {
      insert(target, li, anchor);
      mount_component(accounts2, li, null);
      append(li, t4);
      current = true;
    },
    p(ctx3, dirty) {
      const accounts_changes = {};
      if (dirty & 1)
        accounts_changes.node = ctx3[12];
      if (dirty & 2)
        accounts_changes.move = ctx3[1];
      accounts2.$set(accounts_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(accounts2.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(accounts2.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(li);
      destroy_component(accounts2);
    }
  };
}
function create_fragment17(ctx2) {
  let t4;
  let if_block1_anchor;
  let current;
  let if_block0 = ctx2[0].name && create_if_block_16(ctx2);
  let if_block1 = ctx2[6] && create_if_block8(ctx2);
  return {
    c() {
      if (if_block0)
        if_block0.c();
      t4 = space();
      if (if_block1)
        if_block1.c();
      if_block1_anchor = empty();
    },
    m(target, anchor) {
      if (if_block0)
        if_block0.m(target, anchor);
      insert(target, t4, anchor);
      if (if_block1)
        if_block1.m(target, anchor);
      insert(target, if_block1_anchor, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      if (ctx3[0].name) {
        if (if_block0) {
          if_block0.p(ctx3, dirty);
        } else {
          if_block0 = create_if_block_16(ctx3);
          if_block0.c();
          if_block0.m(t4.parentNode, t4);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (ctx3[6]) {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
          if (dirty & 64) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block8(ctx3);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(if_block1_anchor.parentNode, if_block1_anchor);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (if_block0)
        if_block0.d(detaching);
      if (detaching)
        detach(t4);
      if (if_block1)
        if_block1.d(detaching);
      if (detaching)
        detach(if_block1_anchor);
    }
  };
}
function instance17($$self, $$props, $$invalidate) {
  let hasChildren;
  let selected;
  let $selectedAccount;
  component_subscribe($$self, selectedAccount, ($$value) => $$invalidate(2, $selectedAccount = $$value));
  let { node } = $$props;
  let { move } = $$props;
  let expanded = true;
  let drag = false;
  function dragenter(event) {
    var _a2;
    if ((_a2 = event.dataTransfer) == null ? void 0 : _a2.types.includes("fava/filename")) {
      event.preventDefault();
      $$invalidate(4, drag = true);
    }
  }
  function drop2(event) {
    var _a2;
    const filename = (_a2 = event.dataTransfer) == null ? void 0 : _a2.getData("fava/filename");
    if (filename) {
      move({ account: node.name, filename });
      $$invalidate(4, drag = false);
    }
  }
  const click_handler = (ev) => {
    $$invalidate(3, expanded = !expanded);
    ev.stopPropagation();
  };
  const click_handler_1 = () => {
    set_store_value(selectedAccount, $selectedAccount = selected ? "" : node.name, $selectedAccount);
  };
  const dragleave_handler = () => {
    $$invalidate(4, drag = false);
  };
  $$self.$$set = ($$props2) => {
    if ("node" in $$props2)
      $$invalidate(0, node = $$props2.node);
    if ("move" in $$props2)
      $$invalidate(1, move = $$props2.move);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(6, hasChildren = node.children.length > 0);
    }
    if ($$self.$$.dirty & 5) {
      $:
        $$invalidate(5, selected = $selectedAccount === node.name);
    }
  };
  return [
    node,
    move,
    $selectedAccount,
    expanded,
    drag,
    selected,
    hasChildren,
    dragenter,
    drop2,
    click_handler,
    click_handler_1,
    dragleave_handler
  ];
}
var Accounts = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance17, create_fragment17, safe_not_equal, { node: 0, move: 1 });
  }
};
var Accounts_default = Accounts;

// src/editor/DocumentPreviewEditor.svelte
function create_fragment18(ctx2) {
  let div;
  let useEditor_action;
  let mounted;
  let dispose;
  return {
    c() {
      div = element("div");
      attr(div, "class", "svelte-96o3lr");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (!mounted) {
        dispose = action_destroyer(useEditor_action = ctx2[0].call(null, div));
        mounted = true;
      }
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      dispose();
    }
  };
}
function instance18($$self, $$props, $$invalidate) {
  let { url } = $$props;
  let value = "";
  const [editor, useEditor] = initDocumentPreviewEditor(value);
  $$self.$$set = ($$props2) => {
    if ("url" in $$props2)
      $$invalidate(1, url = $$props2.url);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 2) {
      $:
        fetch(url).then(handleText).then((v) => {
          $$invalidate(2, value = v);
        }).catch(() => {
          $$invalidate(2, value = `Loading ${url} failed...`);
        });
    }
    if ($$self.$$.dirty & 4) {
      $:
        if (value !== editor.state.doc.toString()) {
          editor.dispatch({
            changes: {
              from: 0,
              to: editor.state.doc.length,
              insert: value
            }
          });
        }
    }
  };
  return [useEditor, url, value];
}
var DocumentPreviewEditor = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance18, create_fragment18, safe_not_equal, { url: 1 });
  }
};
var DocumentPreviewEditor_default = DocumentPreviewEditor;

// src/documents/DocumentPreview.svelte
function create_else_block2(ctx2) {
  let t03;
  let t13;
  let t22;
  let t32;
  let t4;
  return {
    c() {
      t03 = text("Preview for file `");
      t13 = text(ctx2[0]);
      t22 = text("` with file type `");
      t32 = text(ctx2[2]);
      t4 = text("` is not implemented");
    },
    m(target, anchor) {
      insert(target, t03, anchor);
      insert(target, t13, anchor);
      insert(target, t22, anchor);
      insert(target, t32, anchor);
      insert(target, t4, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & 1)
        set_data(t13, ctx3[0]);
      if (dirty & 4)
        set_data(t32, ctx3[2]);
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(t03);
      if (detaching)
        detach(t13);
      if (detaching)
        detach(t22);
      if (detaching)
        detach(t32);
      if (detaching)
        detach(t4);
    }
  };
}
function create_if_block_32(ctx2) {
  let iframe;
  let iframe_src_value;
  return {
    c() {
      iframe = element("iframe");
      if (!src_url_equal(iframe.src, iframe_src_value = ctx2[1]))
        attr(iframe, "src", iframe_src_value);
      attr(iframe, "title", ctx2[0]);
      attr(iframe, "sandbox", "");
      attr(iframe, "class", "svelte-586ug7");
    },
    m(target, anchor) {
      insert(target, iframe, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & 2 && !src_url_equal(iframe.src, iframe_src_value = ctx3[1])) {
        attr(iframe, "src", iframe_src_value);
      }
      if (dirty & 1) {
        attr(iframe, "title", ctx3[0]);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(iframe);
    }
  };
}
function create_if_block_24(ctx2) {
  let img;
  let img_src_value;
  return {
    c() {
      img = element("img");
      if (!src_url_equal(img.src, img_src_value = ctx2[1]))
        attr(img, "src", img_src_value);
      attr(img, "alt", ctx2[0]);
      attr(img, "class", "svelte-586ug7");
    },
    m(target, anchor) {
      insert(target, img, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & 2 && !src_url_equal(img.src, img_src_value = ctx3[1])) {
        attr(img, "src", img_src_value);
      }
      if (dirty & 1) {
        attr(img, "alt", ctx3[0]);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(img);
    }
  };
}
function create_if_block_17(ctx2) {
  let documentprevieweditor;
  let current;
  documentprevieweditor = new DocumentPreviewEditor_default({ props: { url: ctx2[1] } });
  return {
    c() {
      create_component(documentprevieweditor.$$.fragment);
    },
    m(target, anchor) {
      mount_component(documentprevieweditor, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const documentprevieweditor_changes = {};
      if (dirty & 2)
        documentprevieweditor_changes.url = ctx3[1];
      documentprevieweditor.$set(documentprevieweditor_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(documentprevieweditor.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(documentprevieweditor.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(documentprevieweditor, detaching);
    }
  };
}
function create_if_block9(ctx2) {
  let object2;
  return {
    c() {
      object2 = element("object");
      attr(object2, "title", ctx2[0]);
      attr(object2, "data", ctx2[1]);
      attr(object2, "class", "svelte-586ug7");
    },
    m(target, anchor) {
      insert(target, object2, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & 1) {
        attr(object2, "title", ctx3[0]);
      }
      if (dirty & 2) {
        attr(object2, "data", ctx3[1]);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(object2);
    }
  };
}
function create_fragment19(ctx2) {
  let show_if;
  let show_if_1;
  let show_if_2;
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [
    create_if_block9,
    create_if_block_17,
    create_if_block_24,
    create_if_block_32,
    create_else_block2
  ];
  const if_blocks = [];
  function select_block_type(ctx3, dirty) {
    if (dirty & 4)
      show_if = null;
    if (dirty & 4)
      show_if_1 = null;
    if (dirty & 4)
      show_if_2 = null;
    if (ctx3[2] === "pdf")
      return 0;
    if (show_if == null)
      show_if = !!plainTextExtensions.includes(ctx3[2]);
    if (show_if)
      return 1;
    if (show_if_1 == null)
      show_if_1 = !!imageExtensions.includes(ctx3[2]);
    if (show_if_1)
      return 2;
    if (show_if_2 == null)
      show_if_2 = !!["html", "htm"].includes(ctx3[2]);
    if (show_if_2)
      return 3;
    return 4;
  }
  current_block_type_index = select_block_type(ctx2, -1);
  if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
  return {
    c() {
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if_blocks[current_block_type_index].m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx3, dirty);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx3, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block = if_blocks[current_block_type_index];
        if (!if_block) {
          if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx3);
          if_block.c();
        } else {
          if_block.p(ctx3, dirty);
        }
        transition_in(if_block, 1);
        if_block.m(if_block_anchor.parentNode, if_block_anchor);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if_blocks[current_block_type_index].d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
var plainTextExtensions = ["csv", "txt", "qfx"];
var imageExtensions = ["gif", "jpg", "jpeg", "png", "svg", "webp", "bmp", "ico"];
function instance19($$self, $$props, $$invalidate) {
  let extension;
  let url;
  let $base_url;
  component_subscribe($$self, base_url, ($$value) => $$invalidate(3, $base_url = $$value));
  let { filename } = $$props;
  $$self.$$set = ($$props2) => {
    if ("filename" in $$props2)
      $$invalidate(0, filename = $$props2.filename);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(2, extension = ext(filename).toLowerCase());
    }
    if ($$self.$$.dirty & 9) {
      $:
        $$invalidate(1, url = `${$base_url}document/?filename=${filename}`);
    }
  };
  return [filename, url, extension, $base_url];
}
var DocumentPreview = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance19, create_fragment19, safe_not_equal, { filename: 0 });
  }
};
var DocumentPreview_default = DocumentPreview;

// src/documents/Table.svelte
function get_each_context15(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[14] = list[i].doc;
  child_ctx[15] = list[i].row;
  return child_ctx;
}
function get_each_context_14(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[18] = list[i];
  child_ctx[20] = i;
  return child_ctx;
}
function create_each_block_14(ctx2) {
  let th;
  let t0_value = ctx2[18] + "";
  let t03;
  let t13;
  let th_data_order_value;
  let mounted;
  let dispose;
  function click_handler() {
    return ctx2[9](ctx2[20]);
  }
  return {
    c() {
      th = element("th");
      t03 = text(t0_value);
      t13 = space();
      attr(th, "data-sort", "");
      attr(th, "data-order", th_data_order_value = ctx2[20] === ctx2[1] ? ctx2[2] : null);
    },
    m(target, anchor) {
      insert(target, th, anchor);
      append(th, t03);
      append(th, t13);
      if (!mounted) {
        dispose = listen(th, "click", click_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & 6 && th_data_order_value !== (th_data_order_value = ctx2[20] === ctx2[1] ? ctx2[2] : null)) {
        attr(th, "data-order", th_data_order_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(th);
      mounted = false;
      dispose();
    }
  };
}
function create_each_block15(ctx2) {
  let tr;
  let td0;
  let t0_value = ctx2[15][0] + "";
  let t03;
  let t13;
  let td1;
  let t2_value = ctx2[15][1] + "";
  let t22;
  let t32;
  let tr_draggable_value;
  let tr_title_value;
  let mounted;
  let dispose;
  function dragstart_handler(...args) {
    return ctx2[10](ctx2[14], ...args);
  }
  function click_handler_1() {
    return ctx2[11](ctx2[14]);
  }
  return {
    c() {
      tr = element("tr");
      td0 = element("td");
      t03 = text(t0_value);
      t13 = space();
      td1 = element("td");
      t22 = text(t2_value);
      t32 = space();
      attr(tr, "draggable", tr_draggable_value = true);
      attr(tr, "title", tr_title_value = ctx2[14].filename);
      attr(tr, "class", "svelte-1511gpj");
      toggle_class(tr, "selected", ctx2[0] === ctx2[14]);
    },
    m(target, anchor) {
      insert(target, tr, anchor);
      append(tr, td0);
      append(td0, t03);
      append(tr, t13);
      append(tr, td1);
      append(td1, t22);
      append(tr, t32);
      if (!mounted) {
        dispose = [
          listen(tr, "dragstart", dragstart_handler),
          listen(tr, "click", click_handler_1)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & 8 && t0_value !== (t0_value = ctx2[15][0] + ""))
        set_data(t03, t0_value);
      if (dirty & 8 && t2_value !== (t2_value = ctx2[15][1] + ""))
        set_data(t22, t2_value);
      if (dirty & 8 && tr_title_value !== (tr_title_value = ctx2[14].filename)) {
        attr(tr, "title", tr_title_value);
      }
      if (dirty & 9) {
        toggle_class(tr, "selected", ctx2[0] === ctx2[14]);
      }
    },
    d(detaching) {
      if (detaching)
        detach(tr);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_fragment20(ctx2) {
  let table_1;
  let thead;
  let tr;
  let t4;
  let tbody;
  let each_value_1 = ctx2[4];
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks_1[i] = create_each_block_14(get_each_context_14(ctx2, each_value_1, i));
  }
  let each_value = ctx2[3];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block15(get_each_context15(ctx2, each_value, i));
  }
  return {
    c() {
      table_1 = element("table");
      thead = element("thead");
      tr = element("tr");
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t4 = space();
      tbody = element("tbody");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(tr, "class", "svelte-1511gpj");
      attr(table_1, "class", "svelte-1511gpj");
    },
    m(target, anchor) {
      insert(target, table_1, anchor);
      append(table_1, thead);
      append(thead, tr);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].m(tr, null);
      }
      append(table_1, t4);
      append(table_1, tbody);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(tbody, null);
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & 54) {
        each_value_1 = ctx3[4];
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_14(ctx3, each_value_1, i);
          if (each_blocks_1[i]) {
            each_blocks_1[i].p(child_ctx, dirty);
          } else {
            each_blocks_1[i] = create_each_block_14(child_ctx);
            each_blocks_1[i].c();
            each_blocks_1[i].m(tr, null);
          }
        }
        for (; i < each_blocks_1.length; i += 1) {
          each_blocks_1[i].d(1);
        }
        each_blocks_1.length = each_value_1.length;
      }
      if (dirty & 9) {
        each_value = ctx3[3];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context15(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block15(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(tbody, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(table_1);
      destroy_each(each_blocks_1, detaching);
      destroy_each(each_blocks, detaching);
    }
  };
}
function instance20($$self, $$props, $$invalidate) {
  let table;
  let sortedTable;
  let $selectedAccount;
  component_subscribe($$self, selectedAccount, ($$value) => $$invalidate(8, $selectedAccount = $$value));
  let { data } = $$props;
  let { selected = null } = $$props;
  function name2(doc2) {
    const base2 = basename(doc2.filename);
    return `${doc2.date}` === base2.substring(0, 10) ? base2.substring(11) : base2;
  }
  const headers = [_("Date"), _("Name")];
  const rowGetter = (d) => [d.date, name2(d)];
  let sortColumn = 0;
  let sortOrder = "desc";
  function setSort(index2) {
    if (index2 === sortColumn) {
      $$invalidate(2, sortOrder = sortOrder === "asc" ? "desc" : "asc");
    } else {
      $$invalidate(2, sortOrder = "asc");
      $$invalidate(1, sortColumn = index2);
    }
  }
  const click_handler = (index2) => setSort(index2);
  const dragstart_handler = (doc2, ev) => {
    var _a2;
    (_a2 = ev.dataTransfer) == null ? void 0 : _a2.setData("fava/filename", doc2.filename);
  };
  const click_handler_1 = (doc2) => {
    $$invalidate(0, selected = doc2);
  };
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(6, data = $$props2.data);
    if ("selected" in $$props2)
      $$invalidate(0, selected = $$props2.selected);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 320) {
      $:
        $$invalidate(7, table = data.filter((doc2) => isDescendant(doc2.account, $selectedAccount)).map((doc2) => ({ doc: doc2, row: rowGetter(doc2) })));
    }
    if ($$self.$$.dirty & 134) {
      $:
        $$invalidate(3, sortedTable = table.sort(sortFunc("string", sortOrder, ({ row }) => row[sortColumn])));
    }
  };
  return [
    selected,
    sortColumn,
    sortOrder,
    sortedTable,
    headers,
    setSort,
    data,
    table,
    $selectedAccount,
    click_handler,
    dragstart_handler,
    click_handler_1
  ];
}
var Table = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance20, create_fragment20, safe_not_equal, { data: 6, selected: 0 });
  }
};
var Table_default = Table;

// src/documents/Documents.svelte
function create_if_block_18(ctx2) {
  let modalbase;
  let current;
  modalbase = new ModalBase_default({
    props: {
      shown: true,
      closeHandler: ctx2[9],
      $$slots: { default: [create_default_slot2] },
      $$scope: { ctx: ctx2 }
    }
  });
  return {
    c() {
      create_component(modalbase.$$.fragment);
    },
    m(target, anchor) {
      mount_component(modalbase, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const modalbase_changes = {};
      if (dirty & 4)
        modalbase_changes.closeHandler = ctx3[9];
      if (dirty & 2097156) {
        modalbase_changes.$$scope = { dirty, ctx: ctx3 };
      }
      modalbase.$set(modalbase_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(modalbase.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(modalbase.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(modalbase, detaching);
    }
  };
}
function create_default_slot2(ctx2) {
  let form;
  let h3;
  let t13;
  let p0;
  let code;
  let t2_value = ctx2[2].filename + "";
  let t22;
  let t32;
  let p1;
  let accountinput;
  let updating_value;
  let t4;
  let input;
  let input_size_value;
  let t5;
  let button;
  let current;
  let mounted;
  let dispose;
  function accountinput_value_binding(value) {
    ctx2[7](value);
  }
  let accountinput_props = {};
  if (ctx2[2].account !== void 0) {
    accountinput_props.value = ctx2[2].account;
  }
  accountinput = new AccountInput_default({ props: accountinput_props });
  binding_callbacks.push(() => bind(accountinput, "value", accountinput_value_binding));
  return {
    c() {
      form = element("form");
      h3 = element("h3");
      h3.textContent = `${_("Move or rename document")}`;
      t13 = space();
      p0 = element("p");
      code = element("code");
      t22 = text(t2_value);
      t32 = space();
      p1 = element("p");
      create_component(accountinput.$$.fragment);
      t4 = space();
      input = element("input");
      t5 = space();
      button = element("button");
      button.textContent = `${"Move"}`;
      attr(input, "size", input_size_value = 40);
      attr(button, "type", "submit");
    },
    m(target, anchor) {
      insert(target, form, anchor);
      append(form, h3);
      append(form, t13);
      append(form, p0);
      append(p0, code);
      append(code, t22);
      append(form, t32);
      append(form, p1);
      mount_component(accountinput, p1, null);
      append(p1, t4);
      append(p1, input);
      set_input_value(input, ctx2[2].newName);
      append(p1, t5);
      append(p1, button);
      current = true;
      if (!mounted) {
        dispose = [
          listen(input, "input", ctx2[8]),
          listen(form, "submit", prevent_default(ctx2[5]))
        ];
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if ((!current || dirty & 4) && t2_value !== (t2_value = ctx3[2].filename + ""))
        set_data(t22, t2_value);
      const accountinput_changes = {};
      if (!updating_value && dirty & 4) {
        updating_value = true;
        accountinput_changes.value = ctx3[2].account;
        add_flush_callback(() => updating_value = false);
      }
      accountinput.$set(accountinput_changes);
      if (dirty & 4 && input.value !== ctx3[2].newName) {
        set_input_value(input, ctx3[2].newName);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(accountinput.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(accountinput.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form);
      destroy_component(accountinput);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_if_block10(ctx2) {
  let documentpreview;
  let current;
  documentpreview = new DocumentPreview_default({
    props: { filename: ctx2[1].filename }
  });
  return {
    c() {
      create_component(documentpreview.$$.fragment);
    },
    m(target, anchor) {
      mount_component(documentpreview, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const documentpreview_changes = {};
      if (dirty & 2)
        documentpreview_changes.filename = ctx3[1].filename;
      documentpreview.$set(documentpreview_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(documentpreview.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(documentpreview.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(documentpreview, detaching);
    }
  };
}
function create_fragment21(ctx2) {
  let t03;
  let div1;
  let accounts2;
  let t13;
  let div0;
  let table;
  let updating_selected;
  let t22;
  let current;
  let mounted;
  let dispose;
  let if_block0 = ctx2[2] && create_if_block_18(ctx2);
  accounts2 = new Accounts_default({
    props: {
      node: ctx2[3],
      move: ctx2[10]
    }
  });
  function table_selected_binding(value) {
    ctx2[11](value);
  }
  let table_props = { data: ctx2[0] };
  if (ctx2[1] !== void 0) {
    table_props.selected = ctx2[1];
  }
  table = new Table_default({ props: table_props });
  binding_callbacks.push(() => bind(table, "selected", table_selected_binding));
  let if_block1 = ctx2[1] && create_if_block10(ctx2);
  return {
    c() {
      if (if_block0)
        if_block0.c();
      t03 = space();
      div1 = element("div");
      create_component(accounts2.$$.fragment);
      t13 = space();
      div0 = element("div");
      create_component(table.$$.fragment);
      t22 = space();
      if (if_block1)
        if_block1.c();
      attr(div1, "class", "fixed-fullsize-container svelte-11fib5h");
    },
    m(target, anchor) {
      if (if_block0)
        if_block0.m(target, anchor);
      insert(target, t03, anchor);
      insert(target, div1, anchor);
      mount_component(accounts2, div1, null);
      append(div1, t13);
      append(div1, div0);
      mount_component(table, div0, null);
      append(div1, t22);
      if (if_block1)
        if_block1.m(div1, null);
      current = true;
      if (!mounted) {
        dispose = listen(window, "keyup", ctx2[4]);
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (ctx3[2]) {
        if (if_block0) {
          if_block0.p(ctx3, dirty);
          if (dirty & 4) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_18(ctx3);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(t03.parentNode, t03);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      const accounts_changes = {};
      if (dirty & 8)
        accounts_changes.node = ctx3[3];
      if (dirty & 4)
        accounts_changes.move = ctx3[10];
      accounts2.$set(accounts_changes);
      const table_changes = {};
      if (dirty & 1)
        table_changes.data = ctx3[0];
      if (!updating_selected && dirty & 2) {
        updating_selected = true;
        table_changes.selected = ctx3[1];
        add_flush_callback(() => updating_selected = false);
      }
      table.$set(table_changes);
      if (ctx3[1]) {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
          if (dirty & 2) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block10(ctx3);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(div1, null);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block0);
      transition_in(accounts2.$$.fragment, local);
      transition_in(table.$$.fragment, local);
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(accounts2.$$.fragment, local);
      transition_out(table.$$.fragment, local);
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (if_block0)
        if_block0.d(detaching);
      if (detaching)
        detach(t03);
      if (detaching)
        detach(div1);
      destroy_component(accounts2);
      destroy_component(table);
      if (if_block1)
        if_block1.d();
      mounted = false;
      dispose();
    }
  };
}
function instance21($$self, $$props, $$invalidate) {
  let grouped;
  let node;
  var __defProp2 = Object.defineProperty;
  var __defProps2 = Object.defineProperties;
  var __getOwnPropDescs2 = Object.getOwnPropertyDescriptors;
  var __getOwnPropSymbols2 = Object.getOwnPropertySymbols;
  var __hasOwnProp2 = Object.prototype.hasOwnProperty;
  var __propIsEnum2 = Object.prototype.propertyIsEnumerable;
  var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, {
    enumerable: true,
    configurable: true,
    writable: true,
    value
  }) : obj[key] = value;
  var __spreadValues2 = (a, b) => {
    for (var prop in b || (b = {}))
      if (__hasOwnProp2.call(b, prop))
        __defNormalProp2(a, prop, b[prop]);
    if (__getOwnPropSymbols2)
      for (var prop of __getOwnPropSymbols2(b)) {
        if (__propIsEnum2.call(b, prop))
          __defNormalProp2(a, prop, b[prop]);
      }
    return a;
  };
  var __spreadProps2 = (a, b) => __defProps2(a, __getOwnPropDescs2(b));
  let { data } = $$props;
  let selected;
  let moving = null;
  function keyup(ev) {
    if (ev.key === "F2" && selected && !moving) {
      $$invalidate(2, moving = __spreadProps2(__spreadValues2({}, selected), { newName: basename(selected.filename) }));
    }
  }
  async function move() {
    const moved = moving && await moveDocument(moving.filename, moving.account, moving.newName);
    if (moved) {
      $$invalidate(2, moving = null);
      router_default.reload();
    }
  }
  function accountinput_value_binding(value) {
    if ($$self.$$.not_equal(moving.account, value)) {
      moving.account = value;
      $$invalidate(2, moving);
    }
  }
  function input_input_handler() {
    moving.newName = this.value;
    $$invalidate(2, moving);
  }
  const func = () => {
    $$invalidate(2, moving = null);
  };
  const func_1 = (arg) => {
    $$invalidate(2, moving = __spreadProps(__spreadValues({}, arg), { newName: basename(arg.filename) }));
  };
  function table_selected_binding(value) {
    selected = value;
    $$invalidate(1, selected);
  }
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(0, data = $$props2.data);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(6, grouped = group(data, (d) => d.account));
    }
    if ($$self.$$.dirty & 64) {
      $:
        $$invalidate(3, node = stratify(grouped.entries(), ([s]) => s, (name2, d) => {
          var _a2;
          return {
            name: name2,
            count: (_a2 = d == null ? void 0 : d[1].length) != null ? _a2 : 0
          };
        }));
    }
  };
  return [
    data,
    selected,
    moving,
    node,
    keyup,
    move,
    grouped,
    accountinput_value_binding,
    input_input_handler,
    func,
    func_1,
    table_selected_binding
  ];
}
var Documents = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance21, create_fragment21, safe_not_equal, { data: 0 });
  }
};
var Documents_default = Documents;

// src/codemirror/scroll-to-line.ts
function scrollToLine(cm, line) {
  const linePos = cm.state.doc.line(line);
  cm.dispatch({
    selection: __spreadProps(__spreadValues({}, linePos), { anchor: linePos.from }),
    scrollIntoView: true
  });
}

// src/editor/AppMenu.svelte
function create_fragment22(ctx2) {
  let div;
  let current;
  const default_slot_template = ctx2[1].default;
  const default_slot = create_slot(default_slot_template, ctx2, ctx2[0], null);
  return {
    c() {
      div = element("div");
      if (default_slot)
        default_slot.c();
      attr(div, "role", "menubar");
      attr(div, "class", "svelte-soh75");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (default_slot) {
        default_slot.m(div, null);
      }
      current = true;
    },
    p(ctx3, [dirty]) {
      if (default_slot) {
        if (default_slot.p && (!current || dirty & 1)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx3,
            ctx3[0],
            !current ? get_all_dirty_from_scope(ctx3[0]) : get_slot_changes(default_slot_template, ctx3[0], dirty, null),
            null
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (default_slot)
        default_slot.d(detaching);
    }
  };
}
function instance22($$self, $$props, $$invalidate) {
  let { $$slots: slots = {}, $$scope } = $$props;
  $$self.$$set = ($$props2) => {
    if ("$$scope" in $$props2)
      $$invalidate(0, $$scope = $$props2.$$scope);
  };
  return [$$scope, slots];
}
var AppMenu = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance22, create_fragment22, safe_not_equal, {});
  }
};
var AppMenu_default = AppMenu;

// src/editor/AppMenuItem.svelte
function create_fragment23(ctx2) {
  let span;
  let t03;
  let t13;
  let ul;
  let current;
  let mounted;
  let dispose;
  const default_slot_template = ctx2[3].default;
  const default_slot = create_slot(default_slot_template, ctx2, ctx2[2], null);
  return {
    c() {
      span = element("span");
      t03 = text(ctx2[0]);
      t13 = space();
      ul = element("ul");
      if (default_slot)
        default_slot.c();
      attr(ul, "role", "menu");
      attr(ul, "class", "svelte-1j138l1");
      attr(span, "tabindex", "0");
      attr(span, "role", "menuitem");
      attr(span, "class", "svelte-1j138l1");
      toggle_class(span, "open", ctx2[1]);
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t03);
      append(span, t13);
      append(span, ul);
      if (default_slot) {
        default_slot.m(ul, null);
      }
      current = true;
      if (!mounted) {
        dispose = listen(span, "keydown", ctx2[4]);
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (!current || dirty & 1)
        set_data(t03, ctx3[0]);
      if (default_slot) {
        if (default_slot.p && (!current || dirty & 4)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx3,
            ctx3[2],
            !current ? get_all_dirty_from_scope(ctx3[2]) : get_slot_changes(default_slot_template, ctx3[2], dirty, null),
            null
          );
        }
      }
      if (!current || dirty & 2) {
        toggle_class(span, "open", ctx3[1]);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(span);
      if (default_slot)
        default_slot.d(detaching);
      mounted = false;
      dispose();
    }
  };
}
function instance23($$self, $$props, $$invalidate) {
  let { $$slots: slots = {}, $$scope } = $$props;
  let { name: name2 } = $$props;
  let open = false;
  const keydown_handler = (ev) => {
    if (ev.key === "ArrowDown") {
      $$invalidate(1, open = true);
    }
  };
  $$self.$$set = ($$props2) => {
    if ("name" in $$props2)
      $$invalidate(0, name2 = $$props2.name);
    if ("$$scope" in $$props2)
      $$invalidate(2, $$scope = $$props2.$$scope);
  };
  return [name2, open, $$scope, slots, keydown_handler];
}
var AppMenuItem = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance23, create_fragment23, safe_not_equal, { name: 0 });
  }
};
var AppMenuItem_default = AppMenuItem;

// src/editor/AppMenuSubItem.svelte
var get_right_slot_changes = (dirty) => ({});
var get_right_slot_context = (ctx2) => ({});
function create_if_block11(ctx2) {
  let span;
  let current;
  const right_slot_template = ctx2[5].right;
  const right_slot = create_slot(right_slot_template, ctx2, ctx2[4], get_right_slot_context);
  return {
    c() {
      span = element("span");
      if (right_slot)
        right_slot.c();
      attr(span, "class", "svelte-485lcm");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      if (right_slot) {
        right_slot.m(span, null);
      }
      current = true;
    },
    p(ctx3, dirty) {
      if (right_slot) {
        if (right_slot.p && (!current || dirty & 16)) {
          update_slot_base(
            right_slot,
            right_slot_template,
            ctx3,
            ctx3[4],
            !current ? get_all_dirty_from_scope(ctx3[4]) : get_slot_changes(right_slot_template, ctx3[4], dirty, get_right_slot_changes),
            get_right_slot_context
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(right_slot, local);
      current = true;
    },
    o(local) {
      transition_out(right_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(span);
      if (right_slot)
        right_slot.d(detaching);
    }
  };
}
function create_fragment24(ctx2) {
  let li;
  let button;
  let t4;
  let current;
  let mounted;
  let dispose;
  const default_slot_template = ctx2[5].default;
  const default_slot = create_slot(default_slot_template, ctx2, ctx2[4], null);
  let if_block = ctx2[3].right && create_if_block11(ctx2);
  return {
    c() {
      li = element("li");
      button = element("button");
      if (default_slot)
        default_slot.c();
      t4 = space();
      if (if_block)
        if_block.c();
      attr(button, "type", "button");
      attr(button, "class", "svelte-485lcm");
      attr(li, "title", ctx2[0]);
      attr(li, "class", "svelte-485lcm");
      toggle_class(li, "selected", ctx2[1]);
    },
    m(target, anchor) {
      insert(target, li, anchor);
      append(li, button);
      if (default_slot) {
        default_slot.m(button, null);
      }
      append(button, t4);
      if (if_block)
        if_block.m(button, null);
      current = true;
      if (!mounted) {
        dispose = listen(button, "click", function() {
          if (is_function(ctx2[2]))
            ctx2[2].apply(this, arguments);
        });
        mounted = true;
      }
    },
    p(new_ctx, [dirty]) {
      ctx2 = new_ctx;
      if (default_slot) {
        if (default_slot.p && (!current || dirty & 16)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            ctx2[4],
            !current ? get_all_dirty_from_scope(ctx2[4]) : get_slot_changes(default_slot_template, ctx2[4], dirty, null),
            null
          );
        }
      }
      if (ctx2[3].right) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty & 8) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block11(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(button, null);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
      if (!current || dirty & 1) {
        attr(li, "title", ctx2[0]);
      }
      if (!current || dirty & 2) {
        toggle_class(li, "selected", ctx2[1]);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(default_slot, local);
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(li);
      if (default_slot)
        default_slot.d(detaching);
      if (if_block)
        if_block.d();
      mounted = false;
      dispose();
    }
  };
}
function instance24($$self, $$props, $$invalidate) {
  let { $$slots: slots = {}, $$scope } = $$props;
  const $$slots = compute_slots(slots);
  let { title = void 0 } = $$props;
  let { selected = false } = $$props;
  let { action } = $$props;
  $$self.$$set = ($$props2) => {
    if ("title" in $$props2)
      $$invalidate(0, title = $$props2.title);
    if ("selected" in $$props2)
      $$invalidate(1, selected = $$props2.selected);
    if ("action" in $$props2)
      $$invalidate(2, action = $$props2.action);
    if ("$$scope" in $$props2)
      $$invalidate(4, $$scope = $$props2.$$scope);
  };
  return [title, selected, action, $$slots, $$scope, slots];
}
var AppMenuSubItem = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance24, create_fragment24, safe_not_equal, { title: 0, selected: 1, action: 2 });
  }
};
var AppMenuSubItem_default = AppMenuSubItem;

// src/editor/Key.svelte
function get_each_context16(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[1] = list[i];
  child_ctx[3] = i;
  return child_ctx;
}
function create_each_block16(ctx2) {
  let kbd;
  let t0_value = ctx2[1] + "";
  let t03;
  let t1_value = ctx2[3] === ctx2[0].length - 1 ? "" : "+";
  let t13;
  return {
    c() {
      kbd = element("kbd");
      t03 = text(t0_value);
      t13 = text(t1_value);
    },
    m(target, anchor) {
      insert(target, kbd, anchor);
      append(kbd, t03);
      insert(target, t13, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & 1 && t0_value !== (t0_value = ctx3[1] + ""))
        set_data(t03, t0_value);
      if (dirty & 1 && t1_value !== (t1_value = ctx3[3] === ctx3[0].length - 1 ? "" : "+"))
        set_data(t13, t1_value);
    },
    d(detaching) {
      if (detaching)
        detach(kbd);
      if (detaching)
        detach(t13);
    }
  };
}
function create_fragment25(ctx2) {
  let each_1_anchor;
  let each_value = ctx2[0];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block16(get_each_context16(ctx2, each_value, i));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(target, anchor);
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx3, [dirty]) {
      if (dirty & 1) {
        each_value = ctx3[0];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context16(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block16(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
function instance25($$self, $$props, $$invalidate) {
  let { key } = $$props;
  $$self.$$set = ($$props2) => {
    if ("key" in $$props2)
      $$invalidate(0, key = $$props2.key);
  };
  return [key];
}
var Key = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance25, create_fragment25, safe_not_equal, { key: 0 });
  }
};
var Key_default = Key;

// src/editor/EditorMenu.svelte
function get_each_context17(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[15] = list[i];
  return child_ctx;
}
function get_each_context_15(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[18] = list[i];
  return child_ctx;
}
function create_default_slot_9(ctx2) {
  let t0_value = ctx2[18] + "";
  let t03;
  let t13;
  return {
    c() {
      t03 = text(t0_value);
      t13 = space();
    },
    m(target, anchor) {
      insert(target, t03, anchor);
      insert(target, t13, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & 8 && t0_value !== (t0_value = ctx3[18] + ""))
        set_data(t03, t0_value);
    },
    d(detaching) {
      if (detaching)
        detach(t03);
      if (detaching)
        detach(t13);
    }
  };
}
function create_each_block_15(ctx2) {
  let appmenusubitem;
  let current;
  function func() {
    return ctx2[8](ctx2[18]);
  }
  appmenusubitem = new AppMenuSubItem_default({
    props: {
      action: func,
      selected: ctx2[18] === ctx2[0],
      $$slots: { default: [create_default_slot_9] },
      $$scope: { ctx: ctx2 }
    }
  });
  return {
    c() {
      create_component(appmenusubitem.$$.fragment);
    },
    m(target, anchor) {
      mount_component(appmenusubitem, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      const appmenusubitem_changes = {};
      if (dirty & 8)
        appmenusubitem_changes.action = func;
      if (dirty & 9)
        appmenusubitem_changes.selected = ctx2[18] === ctx2[0];
      if (dirty & 16392) {
        appmenusubitem_changes.$$scope = { dirty, ctx: ctx2 };
      }
      appmenusubitem.$set(appmenusubitem_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(appmenusubitem.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(appmenusubitem.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(appmenusubitem, detaching);
    }
  };
}
function create_default_slot_8(ctx2) {
  let each_1_anchor;
  let current;
  let each_value_1 = ctx2[3];
  let each_blocks = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks[i] = create_each_block_15(get_each_context_15(ctx2, each_value_1, i));
  }
  const out = (i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  });
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(target, anchor);
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      if (dirty & 25) {
        each_value_1 = ctx3[3];
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_15(ctx3, each_value_1, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block_15(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        group_outros();
        for (i = each_value_1.length; i < each_blocks.length; i += 1) {
          out(i);
        }
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
function create_default_slot_7(ctx2) {
  let t_value = _("Align Amounts") + "";
  let t4;
  return {
    c() {
      t4 = text(t_value);
    },
    m(target, anchor) {
      insert(target, t4, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(t4);
    }
  };
}
function create_right_slot_4(ctx2) {
  let key;
  let current;
  key = new Key_default({
    props: { slot: "right", key: [modKey, "d"] }
  });
  return {
    c() {
      create_component(key.$$.fragment);
    },
    m(target, anchor) {
      mount_component(key, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current)
        return;
      transition_in(key.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(key.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(key, detaching);
    }
  };
}
function create_default_slot_6(ctx2) {
  let t_value = _("Toggle Comment (selection)") + "";
  let t4;
  return {
    c() {
      t4 = text(t_value);
    },
    m(target, anchor) {
      insert(target, t4, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(t4);
    }
  };
}
function create_right_slot_3(ctx2) {
  let key;
  let current;
  key = new Key_default({
    props: { slot: "right", key: [modKey, "/"] }
  });
  return {
    c() {
      create_component(key.$$.fragment);
    },
    m(target, anchor) {
      mount_component(key, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current)
        return;
      transition_in(key.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(key.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(key, detaching);
    }
  };
}
function create_default_slot_5(ctx2) {
  let t_value = _("Open all folds") + "";
  let t4;
  return {
    c() {
      t4 = text(t_value);
    },
    m(target, anchor) {
      insert(target, t4, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(t4);
    }
  };
}
function create_right_slot_2(ctx2) {
  let key;
  let current;
  key = new Key_default({
    props: { slot: "right", key: ["Ctrl", "Alt", "]"] }
  });
  return {
    c() {
      create_component(key.$$.fragment);
    },
    m(target, anchor) {
      mount_component(key, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current)
        return;
      transition_in(key.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(key.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(key, detaching);
    }
  };
}
function create_default_slot_4(ctx2) {
  let t_value = _("Close all folds") + "";
  let t4;
  return {
    c() {
      t4 = text(t_value);
    },
    m(target, anchor) {
      insert(target, t4, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(t4);
    }
  };
}
function create_right_slot_1(ctx2) {
  let key;
  let current;
  key = new Key_default({
    props: { slot: "right", key: ["Ctrl", "Alt", "["] }
  });
  return {
    c() {
      create_component(key.$$.fragment);
    },
    m(target, anchor) {
      mount_component(key, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current)
        return;
      transition_in(key.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(key.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(key, detaching);
    }
  };
}
function create_default_slot_3(ctx2) {
  let appmenusubitem0;
  let t03;
  let appmenusubitem1;
  let t13;
  let appmenusubitem2;
  let t22;
  let appmenusubitem3;
  let current;
  appmenusubitem0 = new AppMenuSubItem_default({
    props: {
      action: ctx2[9],
      $$slots: {
        right: [create_right_slot_4],
        default: [create_default_slot_7]
      },
      $$scope: { ctx: ctx2 }
    }
  });
  appmenusubitem1 = new AppMenuSubItem_default({
    props: {
      action: ctx2[10],
      $$slots: {
        right: [create_right_slot_3],
        default: [create_default_slot_6]
      },
      $$scope: { ctx: ctx2 }
    }
  });
  appmenusubitem2 = new AppMenuSubItem_default({
    props: {
      action: ctx2[11],
      $$slots: {
        right: [create_right_slot_2],
        default: [create_default_slot_5]
      },
      $$scope: { ctx: ctx2 }
    }
  });
  appmenusubitem3 = new AppMenuSubItem_default({
    props: {
      action: ctx2[12],
      $$slots: {
        right: [create_right_slot_1],
        default: [create_default_slot_4]
      },
      $$scope: { ctx: ctx2 }
    }
  });
  return {
    c() {
      create_component(appmenusubitem0.$$.fragment);
      t03 = space();
      create_component(appmenusubitem1.$$.fragment);
      t13 = space();
      create_component(appmenusubitem2.$$.fragment);
      t22 = space();
      create_component(appmenusubitem3.$$.fragment);
    },
    m(target, anchor) {
      mount_component(appmenusubitem0, target, anchor);
      insert(target, t03, anchor);
      mount_component(appmenusubitem1, target, anchor);
      insert(target, t13, anchor);
      mount_component(appmenusubitem2, target, anchor);
      insert(target, t22, anchor);
      mount_component(appmenusubitem3, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const appmenusubitem0_changes = {};
      if (dirty & 2)
        appmenusubitem0_changes.action = ctx3[9];
      if (dirty & 16384) {
        appmenusubitem0_changes.$$scope = { dirty, ctx: ctx3 };
      }
      appmenusubitem0.$set(appmenusubitem0_changes);
      const appmenusubitem1_changes = {};
      if (dirty & 2)
        appmenusubitem1_changes.action = ctx3[10];
      if (dirty & 16384) {
        appmenusubitem1_changes.$$scope = { dirty, ctx: ctx3 };
      }
      appmenusubitem1.$set(appmenusubitem1_changes);
      const appmenusubitem2_changes = {};
      if (dirty & 2)
        appmenusubitem2_changes.action = ctx3[11];
      if (dirty & 16384) {
        appmenusubitem2_changes.$$scope = { dirty, ctx: ctx3 };
      }
      appmenusubitem2.$set(appmenusubitem2_changes);
      const appmenusubitem3_changes = {};
      if (dirty & 2)
        appmenusubitem3_changes.action = ctx3[12];
      if (dirty & 16384) {
        appmenusubitem3_changes.$$scope = { dirty, ctx: ctx3 };
      }
      appmenusubitem3.$set(appmenusubitem3_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(appmenusubitem0.$$.fragment, local);
      transition_in(appmenusubitem1.$$.fragment, local);
      transition_in(appmenusubitem2.$$.fragment, local);
      transition_in(appmenusubitem3.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(appmenusubitem0.$$.fragment, local);
      transition_out(appmenusubitem1.$$.fragment, local);
      transition_out(appmenusubitem2.$$.fragment, local);
      transition_out(appmenusubitem3.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(appmenusubitem0, detaching);
      if (detaching)
        detach(t03);
      destroy_component(appmenusubitem1, detaching);
      if (detaching)
        detach(t13);
      destroy_component(appmenusubitem2, detaching);
      if (detaching)
        detach(t22);
      destroy_component(appmenusubitem3, detaching);
    }
  };
}
function create_if_block12(ctx2) {
  let appmenuitem;
  let current;
  appmenuitem = new AppMenuItem_default({
    props: {
      name: `'insert-entry' ${_("Options")}`,
      $$slots: { default: [create_default_slot_1] },
      $$scope: { ctx: ctx2 }
    }
  });
  return {
    c() {
      create_component(appmenuitem.$$.fragment);
    },
    m(target, anchor) {
      mount_component(appmenuitem, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const appmenuitem_changes = {};
      if (dirty & 16388) {
        appmenuitem_changes.$$scope = { dirty, ctx: ctx3 };
      }
      appmenuitem.$set(appmenuitem_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(appmenuitem.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(appmenuitem.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(appmenuitem, detaching);
    }
  };
}
function create_default_slot_2(ctx2) {
  let t0_value = ctx2[15].re + "";
  let t03;
  let t13;
  return {
    c() {
      t03 = text(t0_value);
      t13 = space();
    },
    m(target, anchor) {
      insert(target, t03, anchor);
      insert(target, t13, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & 4 && t0_value !== (t0_value = ctx3[15].re + ""))
        set_data(t03, t0_value);
    },
    d(detaching) {
      if (detaching)
        detach(t03);
      if (detaching)
        detach(t13);
    }
  };
}
function create_right_slot(ctx2) {
  let span;
  let t_value = ctx2[15].date + "";
  let t4;
  return {
    c() {
      span = element("span");
      t4 = text(t_value);
      attr(span, "slot", "right");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t4);
    },
    p(ctx3, dirty) {
      if (dirty & 4 && t_value !== (t_value = ctx3[15].date + ""))
        set_data(t4, t_value);
    },
    d(detaching) {
      if (detaching)
        detach(span);
    }
  };
}
function create_each_block17(ctx2) {
  let appmenusubitem;
  let current;
  function func_5() {
    return ctx2[13](ctx2[15]);
  }
  appmenusubitem = new AppMenuSubItem_default({
    props: {
      title: `${ctx2[15].filename}:${ctx2[15].lineno}`,
      action: func_5,
      $$slots: {
        right: [create_right_slot],
        default: [create_default_slot_2]
      },
      $$scope: { ctx: ctx2 }
    }
  });
  return {
    c() {
      create_component(appmenusubitem.$$.fragment);
    },
    m(target, anchor) {
      mount_component(appmenusubitem, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      const appmenusubitem_changes = {};
      if (dirty & 4)
        appmenusubitem_changes.title = `${ctx2[15].filename}:${ctx2[15].lineno}`;
      if (dirty & 4)
        appmenusubitem_changes.action = func_5;
      if (dirty & 16388) {
        appmenusubitem_changes.$$scope = { dirty, ctx: ctx2 };
      }
      appmenusubitem.$set(appmenusubitem_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(appmenusubitem.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(appmenusubitem.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(appmenusubitem, detaching);
    }
  };
}
function create_default_slot_1(ctx2) {
  let each_1_anchor;
  let current;
  let each_value = ctx2[2];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block17(get_each_context17(ctx2, each_value, i));
  }
  const out = (i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  });
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(target, anchor);
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      if (dirty & 20) {
        each_value = ctx3[2];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context17(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block17(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out(i);
        }
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
function create_default_slot3(ctx2) {
  let appmenuitem0;
  let t03;
  let appmenuitem1;
  let t13;
  let if_block_anchor;
  let current;
  appmenuitem0 = new AppMenuItem_default({
    props: {
      name: _("File"),
      $$slots: { default: [create_default_slot_8] },
      $$scope: { ctx: ctx2 }
    }
  });
  appmenuitem1 = new AppMenuItem_default({
    props: {
      name: _("Edit"),
      $$slots: { default: [create_default_slot_3] },
      $$scope: { ctx: ctx2 }
    }
  });
  let if_block = ctx2[2].length && create_if_block12(ctx2);
  return {
    c() {
      create_component(appmenuitem0.$$.fragment);
      t03 = space();
      create_component(appmenuitem1.$$.fragment);
      t13 = space();
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      mount_component(appmenuitem0, target, anchor);
      insert(target, t03, anchor);
      mount_component(appmenuitem1, target, anchor);
      insert(target, t13, anchor);
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const appmenuitem0_changes = {};
      if (dirty & 16393) {
        appmenuitem0_changes.$$scope = { dirty, ctx: ctx3 };
      }
      appmenuitem0.$set(appmenuitem0_changes);
      const appmenuitem1_changes = {};
      if (dirty & 16386) {
        appmenuitem1_changes.$$scope = { dirty, ctx: ctx3 };
      }
      appmenuitem1.$set(appmenuitem1_changes);
      if (ctx3[2].length) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & 4) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block12(ctx3);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(appmenuitem0.$$.fragment, local);
      transition_in(appmenuitem1.$$.fragment, local);
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(appmenuitem0.$$.fragment, local);
      transition_out(appmenuitem1.$$.fragment, local);
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      destroy_component(appmenuitem0, detaching);
      if (detaching)
        detach(t03);
      destroy_component(appmenuitem1, detaching);
      if (detaching)
        detach(t13);
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
function create_fragment26(ctx2) {
  let div;
  let appmenu;
  let t4;
  let current;
  appmenu = new AppMenu_default({
    props: {
      $$slots: { default: [create_default_slot3] },
      $$scope: { ctx: ctx2 }
    }
  });
  const default_slot_template = ctx2[7].default;
  const default_slot = create_slot(default_slot_template, ctx2, ctx2[14], null);
  return {
    c() {
      div = element("div");
      create_component(appmenu.$$.fragment);
      t4 = space();
      if (default_slot)
        default_slot.c();
      attr(div, "class", "fieldset svelte-1dybjb4");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(appmenu, div, null);
      append(div, t4);
      if (default_slot) {
        default_slot.m(div, null);
      }
      current = true;
    },
    p(ctx3, [dirty]) {
      const appmenu_changes = {};
      if (dirty & 16399) {
        appmenu_changes.$$scope = { dirty, ctx: ctx3 };
      }
      appmenu.$set(appmenu_changes);
      if (default_slot) {
        if (default_slot.p && (!current || dirty & 16384)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx3,
            ctx3[14],
            !current ? get_all_dirty_from_scope(ctx3[14]) : get_slot_changes(default_slot_template, ctx3[14], dirty, null),
            null
          );
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(appmenu.$$.fragment, local);
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(appmenu.$$.fragment, local);
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      destroy_component(appmenu);
      if (default_slot)
        default_slot.d(detaching);
    }
  };
}
function instance26($$self, $$props, $$invalidate) {
  let sources;
  let insertEntryOptions;
  let $fava_options;
  let $options;
  component_subscribe($$self, fava_options, ($$value) => $$invalidate(5, $fava_options = $$value));
  component_subscribe($$self, options, ($$value) => $$invalidate(6, $options = $$value));
  let { $$slots: slots = {}, $$scope } = $$props;
  let { file_path } = $$props;
  let { editor } = $$props;
  function goToFileAndLine(filename, line) {
    const url = urlFor("editor/", { file_path: filename, line });
    const shouldLoad = filename !== file_path;
    router_default.navigate(url, shouldLoad);
    if (!shouldLoad && line) {
      scrollToLine(editor, line);
      editor.focus();
    }
  }
  const func = (source) => goToFileAndLine(source);
  const func_1 = () => beancountFormat(editor);
  const func_2 = () => toggleComment(editor);
  const func_3 = () => unfoldAll(editor);
  const func_4 = () => foldAll(editor);
  const func_5 = (opt) => goToFileAndLine(opt.filename, opt.lineno - 1);
  $$self.$$set = ($$props2) => {
    if ("file_path" in $$props2)
      $$invalidate(0, file_path = $$props2.file_path);
    if ("editor" in $$props2)
      $$invalidate(1, editor = $$props2.editor);
    if ("$$scope" in $$props2)
      $$invalidate(14, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 64) {
      $:
        $$invalidate(3, sources = [
          $options.filename,
          ...$options.include.filter((f) => f !== $options.filename)
        ]);
    }
    if ($$self.$$.dirty & 32) {
      $:
        $$invalidate(2, insertEntryOptions = $fava_options.insert_entry);
    }
  };
  return [
    file_path,
    editor,
    insertEntryOptions,
    sources,
    goToFileAndLine,
    $fava_options,
    $options,
    slots,
    func,
    func_1,
    func_2,
    func_3,
    func_4,
    func_5,
    $$scope
  ];
}
var EditorMenu = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance26, create_fragment26, safe_not_equal, { file_path: 0, editor: 1 });
  }
};
var EditorMenu_default = EditorMenu;

// src/editor/SaveButton.svelte
function create_fragment27(ctx2) {
  let button;
  let t4;
  let button_disabled_value;
  let button_title_value;
  return {
    c() {
      button = element("button");
      t4 = text(ctx2[1]);
      attr(button, "type", "submit");
      button.disabled = button_disabled_value = !ctx2[0];
      attr(button, "title", button_title_value = `${_("Save")} (${modKey}+s)`);
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, t4);
    },
    p(ctx3, [dirty]) {
      if (dirty & 2)
        set_data(t4, ctx3[1]);
      if (dirty & 1 && button_disabled_value !== (button_disabled_value = !ctx3[0])) {
        button.disabled = button_disabled_value;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(button);
    }
  };
}
function instance27($$self, $$props, $$invalidate) {
  let buttonContent;
  let { changed } = $$props;
  let { saving } = $$props;
  $$self.$$set = ($$props2) => {
    if ("changed" in $$props2)
      $$invalidate(0, changed = $$props2.changed);
    if ("saving" in $$props2)
      $$invalidate(2, saving = $$props2.saving);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 4) {
      $:
        $$invalidate(1, buttonContent = saving ? _("Saving...") : _("Save"));
    }
  };
  return [changed, buttonContent, saving];
}
var SaveButton = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance27, create_fragment27, safe_not_equal, { changed: 0, saving: 2 });
  }
};
var SaveButton_default = SaveButton;

// src/editor/SourceEditor.svelte
function create_default_slot4(ctx2) {
  let savebutton;
  let current;
  savebutton = new SaveButton_default({
    props: {
      changed: ctx2[1],
      saving: ctx2[2]
    }
  });
  return {
    c() {
      create_component(savebutton.$$.fragment);
    },
    m(target, anchor) {
      mount_component(savebutton, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const savebutton_changes = {};
      if (dirty & 2)
        savebutton_changes.changed = ctx3[1];
      if (dirty & 4)
        savebutton_changes.saving = ctx3[2];
      savebutton.$set(savebutton_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(savebutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(savebutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(savebutton, detaching);
    }
  };
}
function create_fragment28(ctx2) {
  let form;
  let editormenu;
  let t4;
  let div;
  let useEditor_action;
  let current;
  let mounted;
  let dispose;
  editormenu = new EditorMenu_default({
    props: {
      file_path: ctx2[0].file_path,
      editor: ctx2[4],
      $$slots: { default: [create_default_slot4] },
      $$scope: { ctx: ctx2 }
    }
  });
  return {
    c() {
      form = element("form");
      create_component(editormenu.$$.fragment);
      t4 = space();
      div = element("div");
      attr(div, "class", "svelte-zn7rvj");
      attr(form, "class", "fixed-fullsize-container svelte-zn7rvj");
    },
    m(target, anchor) {
      insert(target, form, anchor);
      mount_component(editormenu, form, null);
      append(form, t4);
      append(form, div);
      current = true;
      if (!mounted) {
        dispose = [
          action_destroyer(useEditor_action = ctx2[5].call(null, div)),
          listen(form, "submit", prevent_default(ctx2[6]))
        ];
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      const editormenu_changes = {};
      if (dirty & 1)
        editormenu_changes.file_path = ctx3[0].file_path;
      if (dirty & 2054) {
        editormenu_changes.$$scope = { dirty, ctx: ctx3 };
      }
      editormenu.$set(editormenu_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(editormenu.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(editormenu.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form);
      destroy_component(editormenu);
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance28($$self, $$props, $$invalidate) {
  let $fava_options;
  component_subscribe($$self, fava_options, ($$value) => $$invalidate(8, $fava_options = $$value));
  let { data } = $$props;
  let changed = false;
  const onDocChanges = () => {
    $$invalidate(1, changed = true);
  };
  let sha256sum = "";
  let saving = false;
  async function save(cm) {
    $$invalidate(2, saving = true);
    try {
      sha256sum = await put("source", {
        file_path: data.file_path,
        source: cm.state.doc.toString(),
        sha256sum
      });
      $$invalidate(1, changed = false);
      cm.focus();
      get("errors").then((count2) => errorCount.set(count2), log_error);
    } catch (error) {
      if (error instanceof Error) {
        notify(error.message, "error");
      }
    } finally {
      $$invalidate(2, saving = false);
    }
  }
  const [editor, useEditor] = initBeancountEditor(data.source, onDocChanges, [
    {
      key: "Control-s",
      mac: "Meta-s",
      run: () => {
        save(editor).catch(() => {
        });
        return true;
      }
    }
  ]);
  function checkEditorChanges() {
    return changed ? "There are unsaved changes. Are you sure you want to leave?" : null;
  }
  onMount(() => router_default.addInteruptHandler(checkEditorChanges));
  onMount(() => {
    var _a2;
    sha256sum = data.sha256sum;
    const unbind = [
      bindKey({ key: "Control+s", mac: "Meta+s" }, (event) => {
        event.preventDefault();
        save(editor).catch(() => {
        });
      }),
      bindKey({ key: "Control+d", mac: "Meta+d" }, (event) => {
        event.preventDefault();
        beancountFormat(editor);
      })
    ];
    editor.focus();
    const opts = $fava_options.insert_entry.filter((f) => f.filename === data.file_path);
    const line = parseInt(
      (_a2 = new URLSearchParams(window.location.search).get("line")) != null ? _a2 : "0",
      10
    );
    if (line > 0) {
      scrollToLine(editor, line);
    } else if (opts.length > 0) {
      const last = opts[opts.length - 1];
      scrollToLine(editor, last.lineno - 1);
    } else {
      scrollToLine(editor, editor.state.doc.lines);
    }
    return () => {
      unbind.forEach((u) => u());
    };
  });
  const submit_handler = () => save(editor);
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(0, data = $$props2.data);
  };
  return [data, changed, saving, save, editor, useEditor, submit_handler];
}
var SourceEditor = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance28, create_fragment28, safe_not_equal, { data: 0 });
  }
};
var SourceEditor_default = SourceEditor;

// src/header/FilterForm.svelte
function create_fragment29(ctx2) {
  let form;
  let autocompleteinput0;
  let updating_value;
  let t03;
  let autocompleteinput1;
  let updating_value_1;
  let t13;
  let autocompleteinput2;
  let updating_value_2;
  let t22;
  let button;
  let current;
  let mounted;
  let dispose;
  function autocompleteinput0_value_binding(value) {
    ctx2[10](value);
  }
  let autocompleteinput0_props = {
    placeholder: _("Time"),
    suggestions: ctx2[4],
    key: "f t",
    clearButton: true,
    setSize: true
  };
  if (ctx2[2] !== void 0) {
    autocompleteinput0_props.value = ctx2[2];
  }
  autocompleteinput0 = new AutocompleteInput_default({ props: autocompleteinput0_props });
  binding_callbacks.push(() => bind(autocompleteinput0, "value", autocompleteinput0_value_binding));
  autocompleteinput0.$on("blur", ctx2[6]);
  autocompleteinput0.$on("select", ctx2[6]);
  function autocompleteinput1_value_binding(value) {
    ctx2[11](value);
  }
  let autocompleteinput1_props = {
    placeholder: _("Account"),
    suggestions: ctx2[5],
    key: "f a",
    clearButton: true,
    setSize: true
  };
  if (ctx2[0] !== void 0) {
    autocompleteinput1_props.value = ctx2[0];
  }
  autocompleteinput1 = new AutocompleteInput_default({ props: autocompleteinput1_props });
  binding_callbacks.push(() => bind(autocompleteinput1, "value", autocompleteinput1_value_binding));
  autocompleteinput1.$on("blur", ctx2[6]);
  autocompleteinput1.$on("select", ctx2[6]);
  function autocompleteinput2_value_binding(value) {
    ctx2[12](value);
  }
  let autocompleteinput2_props = {
    placeholder: _("Filter by tag, payee, ..."),
    suggestions: ctx2[3],
    key: "f f",
    clearButton: true,
    setSize: true,
    valueExtractor,
    valueSelector
  };
  if (ctx2[1] !== void 0) {
    autocompleteinput2_props.value = ctx2[1];
  }
  autocompleteinput2 = new AutocompleteInput_default({ props: autocompleteinput2_props });
  binding_callbacks.push(() => bind(autocompleteinput2, "value", autocompleteinput2_value_binding));
  autocompleteinput2.$on("blur", ctx2[6]);
  autocompleteinput2.$on("select", ctx2[6]);
  return {
    c() {
      form = element("form");
      create_component(autocompleteinput0.$$.fragment);
      t03 = space();
      create_component(autocompleteinput1.$$.fragment);
      t13 = space();
      create_component(autocompleteinput2.$$.fragment);
      t22 = space();
      button = element("button");
      attr(button, "type", "submit");
      attr(button, "class", "svelte-1k9a59j");
      attr(form, "class", "svelte-1k9a59j");
    },
    m(target, anchor) {
      insert(target, form, anchor);
      mount_component(autocompleteinput0, form, null);
      append(form, t03);
      mount_component(autocompleteinput1, form, null);
      append(form, t13);
      mount_component(autocompleteinput2, form, null);
      append(form, t22);
      append(form, button);
      current = true;
      if (!mounted) {
        dispose = listen(form, "submit", prevent_default(ctx2[6]));
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      const autocompleteinput0_changes = {};
      if (dirty & 16)
        autocompleteinput0_changes.suggestions = ctx3[4];
      if (!updating_value && dirty & 4) {
        updating_value = true;
        autocompleteinput0_changes.value = ctx3[2];
        add_flush_callback(() => updating_value = false);
      }
      autocompleteinput0.$set(autocompleteinput0_changes);
      const autocompleteinput1_changes = {};
      if (dirty & 32)
        autocompleteinput1_changes.suggestions = ctx3[5];
      if (!updating_value_1 && dirty & 1) {
        updating_value_1 = true;
        autocompleteinput1_changes.value = ctx3[0];
        add_flush_callback(() => updating_value_1 = false);
      }
      autocompleteinput1.$set(autocompleteinput1_changes);
      const autocompleteinput2_changes = {};
      if (dirty & 8)
        autocompleteinput2_changes.suggestions = ctx3[3];
      if (!updating_value_2 && dirty & 2) {
        updating_value_2 = true;
        autocompleteinput2_changes.value = ctx3[1];
        add_flush_callback(() => updating_value_2 = false);
      }
      autocompleteinput2.$set(autocompleteinput2_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(autocompleteinput0.$$.fragment, local);
      transition_in(autocompleteinput1.$$.fragment, local);
      transition_in(autocompleteinput2.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(autocompleteinput0.$$.fragment, local);
      transition_out(autocompleteinput1.$$.fragment, local);
      transition_out(autocompleteinput2.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form);
      destroy_component(autocompleteinput0);
      destroy_component(autocompleteinput1);
      destroy_component(autocompleteinput2);
      mounted = false;
      dispose();
    }
  };
}
function valueExtractor(value, input) {
  const match = value.slice(0, input.selectionStart || void 0).match(/\S*$/);
  return match ? match[0] : value;
}
function valueSelector(value, input) {
  var _a2;
  const selectionStart = (_a2 = input.selectionStart) != null ? _a2 : 0;
  const match = input.value.slice(0, selectionStart).match(/\S*$/);
  return match ? `${input.value.slice(0, selectionStart - match[0].length)}${value}${input.value.slice(selectionStart)}` : value;
}
function instance29($$self, $$props, $$invalidate) {
  let fql_filter_suggestions;
  let $payees;
  let $links;
  let $tags;
  let $years;
  let $accounts;
  component_subscribe($$self, payees, ($$value) => $$invalidate(7, $payees = $$value));
  component_subscribe($$self, links, ($$value) => $$invalidate(8, $links = $$value));
  component_subscribe($$self, tags, ($$value) => $$invalidate(9, $tags = $$value));
  component_subscribe($$self, years2, ($$value) => $$invalidate(4, $years = $$value));
  component_subscribe($$self, accounts, ($$value) => $$invalidate(5, $accounts = $$value));
  let account_filter_value = "";
  let fql_filter_value = "";
  let time_filter_value = "";
  account_filter.subscribe((v) => {
    $$invalidate(0, account_filter_value = v);
  });
  fql_filter.subscribe((v) => {
    $$invalidate(1, fql_filter_value = v);
  });
  time_filter.subscribe((v) => {
    $$invalidate(2, time_filter_value = v);
  });
  function submit() {
    account_filter.set(account_filter_value);
    fql_filter.set(fql_filter_value);
    time_filter.set(time_filter_value);
  }
  function autocompleteinput0_value_binding(value) {
    time_filter_value = value;
    $$invalidate(2, time_filter_value);
  }
  function autocompleteinput1_value_binding(value) {
    account_filter_value = value;
    $$invalidate(0, account_filter_value);
  }
  function autocompleteinput2_value_binding(value) {
    fql_filter_value = value;
    $$invalidate(1, fql_filter_value);
  }
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 896) {
      $:
        $$invalidate(3, fql_filter_suggestions = [
          ...$tags.map((tag2) => `#${tag2}`),
          ...$links.map((link2) => `^${link2}`),
          ...$payees.map((payee) => `payee:"${payee}"`)
        ]);
    }
  };
  return [
    account_filter_value,
    fql_filter_value,
    time_filter_value,
    fql_filter_suggestions,
    $years,
    $accounts,
    submit,
    $payees,
    $links,
    $tags,
    autocompleteinput0_value_binding,
    autocompleteinput1_value_binding,
    autocompleteinput2_value_binding
  ];
}
var FilterForm = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance29, create_fragment29, safe_not_equal, {});
  }
};
var FilterForm_default = FilterForm;

// src/entry-forms/AddMetadataButton.svelte
function create_fragment30(ctx2) {
  let button;
  let t4;
  let button_tabindex_value;
  let button_title_value;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      t4 = text("m");
      attr(button, "type", "button");
      attr(button, "class", "muted round");
      attr(button, "tabindex", button_tabindex_value = -1);
      attr(button, "title", button_title_value = _("Add metadata"));
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, t4);
      if (!mounted) {
        dispose = listen(button, "click", ctx2[0]);
        mounted = true;
      }
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
function instance30($$self, $$props, $$invalidate) {
  let { meta: meta3 } = $$props;
  function addMetadata() {
    $$invalidate(1, meta3[""] = "", meta3);
    $$invalidate(1, meta3);
  }
  $$self.$$set = ($$props2) => {
    if ("meta" in $$props2)
      $$invalidate(1, meta3 = $$props2.meta);
  };
  return [addMetadata, meta3];
}
var AddMetadataButton = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance30, create_fragment30, safe_not_equal, { meta: 1 });
  }
};
var AddMetadataButton_default = AddMetadataButton;

// src/entry-forms/metadata.ts
function metaValueToString(value) {
  if (typeof value === "boolean") {
    return value ? "TRUE" : "FALSE";
  }
  return typeof value === "string" ? value : value.toString();
}
function stringToMetaValue(s) {
  if (s === "TRUE") {
    return true;
  }
  if (s === "FALSE") {
    return false;
  }
  return s;
}

// src/entry-forms/EntryMetadata.svelte
function get_each_context18(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[8] = list[i];
  child_ctx[10] = i;
  return child_ctx;
}
function create_if_block13(ctx2) {
  let button;
  let t4;
  let button_title_value;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      t4 = text("+");
      attr(button, "type", "button");
      attr(button, "class", "muted round");
      attr(button, "title", button_title_value = _("Add metadata"));
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, t4);
      if (!mounted) {
        dispose = listen(button, "click", ctx2[4]);
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
function create_each_block18(ctx2) {
  let div;
  let button;
  let button_tabindex_value;
  let t13;
  let input0;
  let input0_placeholder_value;
  let input0_value_value;
  let t22;
  let input1;
  let input1_placeholder_value;
  let input1_value_value;
  let t32;
  let t4;
  let mounted;
  let dispose;
  function click_handler() {
    return ctx2[5](ctx2[8]);
  }
  function change_handler(...args) {
    return ctx2[6](ctx2[8], ...args);
  }
  function change_handler_1(...args) {
    return ctx2[7](ctx2[8], ...args);
  }
  let if_block = ctx2[10] === ctx2[1].length - 1 && create_if_block13(ctx2);
  return {
    c() {
      div = element("div");
      button = element("button");
      button.textContent = "\xD7";
      t13 = space();
      input0 = element("input");
      t22 = space();
      input1 = element("input");
      t32 = space();
      if (if_block)
        if_block.c();
      t4 = space();
      attr(button, "type", "button");
      attr(button, "class", "muted round remove-row");
      attr(button, "tabindex", button_tabindex_value = -1);
      attr(input0, "type", "text");
      attr(input0, "class", "key svelte-1v6bu4l");
      attr(input0, "placeholder", input0_placeholder_value = _("Key"));
      input0.value = input0_value_value = ctx2[8];
      input0.required = true;
      attr(input1, "type", "text");
      attr(input1, "class", "value svelte-1v6bu4l");
      attr(input1, "placeholder", input1_placeholder_value = _("Value"));
      input1.value = input1_value_value = metaValueToString(ctx2[0][ctx2[8]]);
      attr(div, "class", "flex-row svelte-1v6bu4l");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, button);
      append(div, t13);
      append(div, input0);
      append(div, t22);
      append(div, input1);
      append(div, t32);
      if (if_block)
        if_block.m(div, null);
      append(div, t4);
      if (!mounted) {
        dispose = [
          listen(button, "click", click_handler),
          listen(input0, "change", change_handler),
          listen(input1, "change", change_handler_1)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & 2 && input0_value_value !== (input0_value_value = ctx2[8]) && input0.value !== input0_value_value) {
        input0.value = input0_value_value;
      }
      if (dirty & 3 && input1_value_value !== (input1_value_value = metaValueToString(ctx2[0][ctx2[8]])) && input1.value !== input1_value_value) {
        input1.value = input1_value_value;
      }
      if (ctx2[10] === ctx2[1].length - 1) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block13(ctx2);
          if_block.c();
          if_block.m(div, t4);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (if_block)
        if_block.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_fragment31(ctx2) {
  let each_1_anchor;
  let each_value = ctx2[1];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block18(get_each_context18(ctx2, each_value, i));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(target, anchor);
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx3, [dirty]) {
      if (dirty & 31) {
        each_value = ctx3[1];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context18(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block18(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
function instance31($$self, $$props, $$invalidate) {
  let metakeys;
  let { meta: meta3 } = $$props;
  function removeMetadata(metakey) {
    delete meta3[metakey];
    $$invalidate(0, meta3);
  }
  function updateMetakey(currentKey, newKey) {
    $$invalidate(0, meta3 = Object.keys(meta3).reduce(
      (m, key) => {
        if (key === currentKey) {
          m[newKey] = meta3[currentKey];
        } else {
          m[key] = meta3[key];
        }
        return m;
      },
      {}
    ));
  }
  function addMetadata() {
    $$invalidate(0, meta3[""] = "", meta3);
    $$invalidate(0, meta3);
  }
  const click_handler = (metakey) => removeMetadata(metakey);
  const change_handler = (metakey, event) => {
    updateMetakey(metakey, event.currentTarget.value);
  };
  const change_handler_1 = (metakey, event) => {
    $$invalidate(0, meta3[metakey] = stringToMetaValue(event.currentTarget.value), meta3);
  };
  $$self.$$set = ($$props2) => {
    if ("meta" in $$props2)
      $$invalidate(0, meta3 = $$props2.meta);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(1, metakeys = Object.keys(meta3).filter((key) => !key.startsWith("_") && key !== "filename" && key !== "lineno"));
    }
  };
  return [
    meta3,
    metakeys,
    removeMetadata,
    updateMetakey,
    addMetadata,
    click_handler,
    change_handler,
    change_handler_1
  ];
}
var EntryMetadata = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance31, create_fragment31, safe_not_equal, { meta: 0 });
  }
};
var EntryMetadata_default = EntryMetadata;

// src/entry-forms/Balance.svelte
function create_fragment32(ctx2) {
  let div1;
  let div0;
  let input0;
  let t03;
  let h4;
  let t22;
  let accountinput;
  let updating_value;
  let t32;
  let input1;
  let input1_placeholder_value;
  let input1_size_value;
  let t4;
  let autocompleteinput;
  let updating_value_1;
  let t5;
  let addmetadatabutton;
  let updating_meta;
  let t6;
  let entrymetadata;
  let updating_meta_1;
  let current;
  let mounted;
  let dispose;
  function accountinput_value_binding(value) {
    ctx2[3](value);
  }
  let accountinput_props = {
    className: "grow",
    date: ctx2[0].date
  };
  if (ctx2[0].account !== void 0) {
    accountinput_props.value = ctx2[0].account;
  }
  accountinput = new AccountInput_default({ props: accountinput_props });
  binding_callbacks.push(() => bind(accountinput, "value", accountinput_value_binding));
  function autocompleteinput_value_binding(value) {
    ctx2[5](value);
  }
  let autocompleteinput_props = {
    className: "currency",
    placeholder: _("Currency"),
    suggestions: ctx2[1]
  };
  if (ctx2[0].amount.currency !== void 0) {
    autocompleteinput_props.value = ctx2[0].amount.currency;
  }
  autocompleteinput = new AutocompleteInput_default({ props: autocompleteinput_props });
  binding_callbacks.push(() => bind(autocompleteinput, "value", autocompleteinput_value_binding));
  function addmetadatabutton_meta_binding(value) {
    ctx2[6](value);
  }
  let addmetadatabutton_props = {};
  if (ctx2[0].meta !== void 0) {
    addmetadatabutton_props.meta = ctx2[0].meta;
  }
  addmetadatabutton = new AddMetadataButton_default({ props: addmetadatabutton_props });
  binding_callbacks.push(() => bind(addmetadatabutton, "meta", addmetadatabutton_meta_binding));
  function entrymetadata_meta_binding(value) {
    ctx2[7](value);
  }
  let entrymetadata_props = {};
  if (ctx2[0].meta !== void 0) {
    entrymetadata_props.meta = ctx2[0].meta;
  }
  entrymetadata = new EntryMetadata_default({ props: entrymetadata_props });
  binding_callbacks.push(() => bind(entrymetadata, "meta", entrymetadata_meta_binding));
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      input0 = element("input");
      t03 = space();
      h4 = element("h4");
      h4.textContent = `${_("Balance")}`;
      t22 = space();
      create_component(accountinput.$$.fragment);
      t32 = space();
      input1 = element("input");
      t4 = space();
      create_component(autocompleteinput.$$.fragment);
      t5 = space();
      create_component(addmetadatabutton.$$.fragment);
      t6 = space();
      create_component(entrymetadata.$$.fragment);
      attr(input0, "type", "date");
      input0.required = true;
      attr(input1, "type", "tel");
      attr(input1, "pattern", "-?[0-9.,]*");
      attr(input1, "placeholder", input1_placeholder_value = _("Number"));
      attr(input1, "size", input1_size_value = 10);
      attr(div0, "class", "flex-row svelte-unorr4");
      attr(div1, "class", "svelte-unorr4");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      append(div0, input0);
      set_input_value(input0, ctx2[0].date);
      append(div0, t03);
      append(div0, h4);
      append(div0, t22);
      mount_component(accountinput, div0, null);
      append(div0, t32);
      append(div0, input1);
      set_input_value(input1, ctx2[0].amount.number);
      append(div0, t4);
      mount_component(autocompleteinput, div0, null);
      append(div0, t5);
      mount_component(addmetadatabutton, div0, null);
      append(div1, t6);
      mount_component(entrymetadata, div1, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(input0, "input", ctx2[2]),
          listen(input1, "input", ctx2[4])
        ];
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & 1) {
        set_input_value(input0, ctx3[0].date);
      }
      const accountinput_changes = {};
      if (dirty & 1)
        accountinput_changes.date = ctx3[0].date;
      if (!updating_value && dirty & 1) {
        updating_value = true;
        accountinput_changes.value = ctx3[0].account;
        add_flush_callback(() => updating_value = false);
      }
      accountinput.$set(accountinput_changes);
      if (dirty & 1) {
        set_input_value(input1, ctx3[0].amount.number);
      }
      const autocompleteinput_changes = {};
      if (dirty & 2)
        autocompleteinput_changes.suggestions = ctx3[1];
      if (!updating_value_1 && dirty & 1) {
        updating_value_1 = true;
        autocompleteinput_changes.value = ctx3[0].amount.currency;
        add_flush_callback(() => updating_value_1 = false);
      }
      autocompleteinput.$set(autocompleteinput_changes);
      const addmetadatabutton_changes = {};
      if (!updating_meta && dirty & 1) {
        updating_meta = true;
        addmetadatabutton_changes.meta = ctx3[0].meta;
        add_flush_callback(() => updating_meta = false);
      }
      addmetadatabutton.$set(addmetadatabutton_changes);
      const entrymetadata_changes = {};
      if (!updating_meta_1 && dirty & 1) {
        updating_meta_1 = true;
        entrymetadata_changes.meta = ctx3[0].meta;
        add_flush_callback(() => updating_meta_1 = false);
      }
      entrymetadata.$set(entrymetadata_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(accountinput.$$.fragment, local);
      transition_in(autocompleteinput.$$.fragment, local);
      transition_in(addmetadatabutton.$$.fragment, local);
      transition_in(entrymetadata.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(accountinput.$$.fragment, local);
      transition_out(autocompleteinput.$$.fragment, local);
      transition_out(addmetadatabutton.$$.fragment, local);
      transition_out(entrymetadata.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div1);
      destroy_component(accountinput);
      destroy_component(autocompleteinput);
      destroy_component(addmetadatabutton);
      destroy_component(entrymetadata);
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance32($$self, $$props, $$invalidate) {
  let $currencies;
  component_subscribe($$self, currencies, ($$value) => $$invalidate(1, $currencies = $$value));
  let { entry } = $$props;
  function input0_input_handler() {
    entry.date = this.value;
    $$invalidate(0, entry);
  }
  function accountinput_value_binding(value) {
    if ($$self.$$.not_equal(entry.account, value)) {
      entry.account = value;
      $$invalidate(0, entry);
    }
  }
  function input1_input_handler() {
    entry.amount.number = this.value;
    $$invalidate(0, entry);
  }
  function autocompleteinput_value_binding(value) {
    if ($$self.$$.not_equal(entry.amount.currency, value)) {
      entry.amount.currency = value;
      $$invalidate(0, entry);
    }
  }
  function addmetadatabutton_meta_binding(value) {
    if ($$self.$$.not_equal(entry.meta, value)) {
      entry.meta = value;
      $$invalidate(0, entry);
    }
  }
  function entrymetadata_meta_binding(value) {
    if ($$self.$$.not_equal(entry.meta, value)) {
      entry.meta = value;
      $$invalidate(0, entry);
    }
  }
  $$self.$$set = ($$props2) => {
    if ("entry" in $$props2)
      $$invalidate(0, entry = $$props2.entry);
  };
  return [
    entry,
    $currencies,
    input0_input_handler,
    accountinput_value_binding,
    input1_input_handler,
    autocompleteinput_value_binding,
    addmetadatabutton_meta_binding,
    entrymetadata_meta_binding
  ];
}
var Balance2 = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance32, create_fragment32, safe_not_equal, { entry: 0 });
  }
};
var Balance_default = Balance2;

// src/entry-forms/Note.svelte
function create_fragment33(ctx2) {
  let div1;
  let div0;
  let input;
  let t03;
  let h4;
  let t22;
  let accountinput;
  let updating_value;
  let t32;
  let addmetadatabutton;
  let updating_meta;
  let t4;
  let textarea;
  let textarea_rows_value;
  let t5;
  let entrymetadata;
  let updating_meta_1;
  let current;
  let mounted;
  let dispose;
  function accountinput_value_binding(value) {
    ctx2[2](value);
  }
  let accountinput_props = {
    className: "grow",
    date: ctx2[0].date
  };
  if (ctx2[0].account !== void 0) {
    accountinput_props.value = ctx2[0].account;
  }
  accountinput = new AccountInput_default({ props: accountinput_props });
  binding_callbacks.push(() => bind(accountinput, "value", accountinput_value_binding));
  function addmetadatabutton_meta_binding(value) {
    ctx2[3](value);
  }
  let addmetadatabutton_props = {};
  if (ctx2[0].meta !== void 0) {
    addmetadatabutton_props.meta = ctx2[0].meta;
  }
  addmetadatabutton = new AddMetadataButton_default({ props: addmetadatabutton_props });
  binding_callbacks.push(() => bind(addmetadatabutton, "meta", addmetadatabutton_meta_binding));
  function entrymetadata_meta_binding(value) {
    ctx2[5](value);
  }
  let entrymetadata_props = {};
  if (ctx2[0].meta !== void 0) {
    entrymetadata_props.meta = ctx2[0].meta;
  }
  entrymetadata = new EntryMetadata_default({ props: entrymetadata_props });
  binding_callbacks.push(() => bind(entrymetadata, "meta", entrymetadata_meta_binding));
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      input = element("input");
      t03 = space();
      h4 = element("h4");
      h4.textContent = `${_("Note")}`;
      t22 = space();
      create_component(accountinput.$$.fragment);
      t32 = space();
      create_component(addmetadatabutton.$$.fragment);
      t4 = space();
      textarea = element("textarea");
      t5 = space();
      create_component(entrymetadata.$$.fragment);
      attr(input, "type", "date");
      attr(input, "name", "date");
      input.required = true;
      attr(div0, "class", "flex-row");
      attr(textarea, "name", "comment");
      attr(textarea, "rows", textarea_rows_value = 2);
      attr(textarea, "class", "svelte-s9o1z4");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      append(div0, input);
      set_input_value(input, ctx2[0].date);
      append(div0, t03);
      append(div0, h4);
      append(div0, t22);
      mount_component(accountinput, div0, null);
      append(div0, t32);
      mount_component(addmetadatabutton, div0, null);
      append(div1, t4);
      append(div1, textarea);
      set_input_value(textarea, ctx2[0].comment);
      append(div1, t5);
      mount_component(entrymetadata, div1, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(input, "input", ctx2[1]),
          listen(textarea, "input", ctx2[4])
        ];
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & 1) {
        set_input_value(input, ctx3[0].date);
      }
      const accountinput_changes = {};
      if (dirty & 1)
        accountinput_changes.date = ctx3[0].date;
      if (!updating_value && dirty & 1) {
        updating_value = true;
        accountinput_changes.value = ctx3[0].account;
        add_flush_callback(() => updating_value = false);
      }
      accountinput.$set(accountinput_changes);
      const addmetadatabutton_changes = {};
      if (!updating_meta && dirty & 1) {
        updating_meta = true;
        addmetadatabutton_changes.meta = ctx3[0].meta;
        add_flush_callback(() => updating_meta = false);
      }
      addmetadatabutton.$set(addmetadatabutton_changes);
      if (dirty & 1) {
        set_input_value(textarea, ctx3[0].comment);
      }
      const entrymetadata_changes = {};
      if (!updating_meta_1 && dirty & 1) {
        updating_meta_1 = true;
        entrymetadata_changes.meta = ctx3[0].meta;
        add_flush_callback(() => updating_meta_1 = false);
      }
      entrymetadata.$set(entrymetadata_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(accountinput.$$.fragment, local);
      transition_in(addmetadatabutton.$$.fragment, local);
      transition_in(entrymetadata.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(accountinput.$$.fragment, local);
      transition_out(addmetadatabutton.$$.fragment, local);
      transition_out(entrymetadata.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div1);
      destroy_component(accountinput);
      destroy_component(addmetadatabutton);
      destroy_component(entrymetadata);
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance33($$self, $$props, $$invalidate) {
  let { entry } = $$props;
  function input_input_handler() {
    entry.date = this.value;
    $$invalidate(0, entry);
  }
  function accountinput_value_binding(value) {
    if ($$self.$$.not_equal(entry.account, value)) {
      entry.account = value;
      $$invalidate(0, entry);
    }
  }
  function addmetadatabutton_meta_binding(value) {
    if ($$self.$$.not_equal(entry.meta, value)) {
      entry.meta = value;
      $$invalidate(0, entry);
    }
  }
  function textarea_input_handler() {
    entry.comment = this.value;
    $$invalidate(0, entry);
  }
  function entrymetadata_meta_binding(value) {
    if ($$self.$$.not_equal(entry.meta, value)) {
      entry.meta = value;
      $$invalidate(0, entry);
    }
  }
  $$self.$$set = ($$props2) => {
    if ("entry" in $$props2)
      $$invalidate(0, entry = $$props2.entry);
  };
  return [
    entry,
    input_input_handler,
    accountinput_value_binding,
    addmetadatabutton_meta_binding,
    textarea_input_handler,
    entrymetadata_meta_binding
  ];
}
var Note2 = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance33, create_fragment33, safe_not_equal, { entry: 0 });
  }
};
var Note_default = Note2;

// src/entry-forms/Posting.svelte
function create_fragment34(ctx2) {
  let div;
  let button0;
  let button0_tabindex_value;
  let t13;
  let accountinput;
  let updating_value;
  let t22;
  let autocompleteinput;
  let updating_value_1;
  let t32;
  let button1;
  let t4;
  let button1_title_value;
  let current;
  let mounted;
  let dispose;
  function accountinput_value_binding(value) {
    ctx2[17](value);
  }
  let accountinput_props = {
    className: "grow",
    suggestions: ctx2[1],
    date: ctx2[2]
  };
  if (ctx2[0].account !== void 0) {
    accountinput_props.value = ctx2[0].account;
  }
  accountinput = new AccountInput_default({ props: accountinput_props });
  binding_callbacks.push(() => bind(accountinput, "value", accountinput_value_binding));
  function autocompleteinput_value_binding(value) {
    ctx2[18](value);
  }
  let autocompleteinput_props = {
    className: "amount",
    placeholder: _("Amount"),
    suggestions: ctx2[7]
  };
  if (ctx2[0].amount !== void 0) {
    autocompleteinput_props.value = ctx2[0].amount;
  }
  autocompleteinput = new AutocompleteInput_default({ props: autocompleteinput_props });
  binding_callbacks.push(() => bind(autocompleteinput, "value", autocompleteinput_value_binding));
  return {
    c() {
      div = element("div");
      button0 = element("button");
      button0.textContent = "\xD7";
      t13 = space();
      create_component(accountinput.$$.fragment);
      t22 = space();
      create_component(autocompleteinput.$$.fragment);
      t32 = space();
      button1 = element("button");
      t4 = text("+");
      attr(button0, "type", "button");
      attr(button0, "class", "muted round remove-row svelte-1yh40ui");
      attr(button0, "tabindex", button0_tabindex_value = -1);
      attr(button1, "type", "button");
      attr(button1, "class", "muted round add-row svelte-1yh40ui");
      attr(button1, "title", button1_title_value = _("Add posting"));
      attr(div, "class", "flex-row svelte-1yh40ui");
      attr(div, "draggable", ctx2[6]);
      toggle_class(div, "drag", ctx2[5]);
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, button0);
      append(div, t13);
      mount_component(accountinput, div, null);
      append(div, t22);
      mount_component(autocompleteinput, div, null);
      append(div, t32);
      append(div, button1);
      append(button1, t4);
      current = true;
      if (!mounted) {
        dispose = [
          listen(button0, "click", function() {
            if (is_function(ctx2[3]))
              ctx2[3].apply(this, arguments);
          }),
          listen(button1, "click", function() {
            if (is_function(ctx2[4]))
              ctx2[4].apply(this, arguments);
          }),
          listen(div, "mousemove", ctx2[8]),
          listen(div, "dragstart", ctx2[9]),
          listen(div, "dragenter", ctx2[10]),
          listen(div, "dragover", ctx2[10]),
          listen(div, "dragleave", ctx2[11]),
          listen(div, "drop", prevent_default(ctx2[12]))
        ];
        mounted = true;
      }
    },
    p(new_ctx, [dirty]) {
      ctx2 = new_ctx;
      const accountinput_changes = {};
      if (dirty & 2)
        accountinput_changes.suggestions = ctx2[1];
      if (dirty & 4)
        accountinput_changes.date = ctx2[2];
      if (!updating_value && dirty & 1) {
        updating_value = true;
        accountinput_changes.value = ctx2[0].account;
        add_flush_callback(() => updating_value = false);
      }
      accountinput.$set(accountinput_changes);
      const autocompleteinput_changes = {};
      if (dirty & 128)
        autocompleteinput_changes.suggestions = ctx2[7];
      if (!updating_value_1 && dirty & 1) {
        updating_value_1 = true;
        autocompleteinput_changes.value = ctx2[0].amount;
        add_flush_callback(() => updating_value_1 = false);
      }
      autocompleteinput.$set(autocompleteinput_changes);
      if (!current || dirty & 64) {
        attr(div, "draggable", ctx2[6]);
      }
      if (!current || dirty & 32) {
        toggle_class(div, "drag", ctx2[5]);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(accountinput.$$.fragment, local);
      transition_in(autocompleteinput.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(accountinput.$$.fragment, local);
      transition_out(autocompleteinput.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      destroy_component(accountinput);
      destroy_component(autocompleteinput);
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance34($$self, $$props, $$invalidate) {
  let amount_number;
  let amountSuggestions;
  let $currencies;
  component_subscribe($$self, currencies, ($$value) => $$invalidate(16, $currencies = $$value));
  let { posting } = $$props;
  let { index: index2 } = $$props;
  let { suggestions } = $$props;
  let { date: date5 } = $$props;
  let { move } = $$props;
  let { remove: remove3 } = $$props;
  let { add: add3 } = $$props;
  let drag = false;
  let draggable = true;
  function mousemove(event) {
    $$invalidate(6, draggable = !(event.target instanceof HTMLInputElement));
  }
  function dragstart(event) {
    var _a2;
    (_a2 = event.dataTransfer) == null ? void 0 : _a2.setData("fava/posting", `${index2}`);
  }
  function dragenter(event) {
    var _a2;
    if ((_a2 = event.dataTransfer) == null ? void 0 : _a2.types.includes("fava/posting")) {
      event.preventDefault();
      $$invalidate(5, drag = true);
    }
  }
  function dragleave2() {
    $$invalidate(5, drag = false);
  }
  function drop2(event) {
    var _a2;
    const from = (_a2 = event.dataTransfer) == null ? void 0 : _a2.getData("fava/posting");
    if (from) {
      move({ from: +from, to: index2 });
      $$invalidate(5, drag = false);
    }
  }
  function accountinput_value_binding(value) {
    if ($$self.$$.not_equal(posting.account, value)) {
      posting.account = value;
      $$invalidate(0, posting);
    }
  }
  function autocompleteinput_value_binding(value) {
    if ($$self.$$.not_equal(posting.amount, value)) {
      posting.amount = value;
      $$invalidate(0, posting);
    }
  }
  $$self.$$set = ($$props2) => {
    if ("posting" in $$props2)
      $$invalidate(0, posting = $$props2.posting);
    if ("index" in $$props2)
      $$invalidate(13, index2 = $$props2.index);
    if ("suggestions" in $$props2)
      $$invalidate(1, suggestions = $$props2.suggestions);
    if ("date" in $$props2)
      $$invalidate(2, date5 = $$props2.date);
    if ("move" in $$props2)
      $$invalidate(14, move = $$props2.move);
    if ("remove" in $$props2)
      $$invalidate(3, remove3 = $$props2.remove);
    if ("add" in $$props2)
      $$invalidate(4, add3 = $$props2.add);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(15, amount_number = posting.amount.replace(/[^\-?0-9.]/g, ""));
    }
    if ($$self.$$.dirty & 98304) {
      $:
        $$invalidate(7, amountSuggestions = $currencies.map((c) => `${amount_number} ${c}`));
    }
  };
  return [
    posting,
    suggestions,
    date5,
    remove3,
    add3,
    drag,
    draggable,
    amountSuggestions,
    mousemove,
    dragstart,
    dragenter,
    dragleave2,
    drop2,
    index2,
    move,
    amount_number,
    $currencies,
    accountinput_value_binding,
    autocompleteinput_value_binding
  ];
}
var Posting = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance34, create_fragment34, safe_not_equal, {
      posting: 0,
      index: 13,
      suggestions: 1,
      date: 2,
      move: 14,
      remove: 3,
      add: 4
    });
  }
};
var Posting_default = Posting;

// src/entry-forms/Transaction.svelte
function get_each_context19(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[17] = list[i];
  child_ctx[18] = list;
  child_ctx[19] = i;
  return child_ctx;
}
function create_each_block19(ctx2) {
  let postingsvelte;
  let updating_posting;
  let current;
  function func() {
    return ctx2[15](ctx2[17]);
  }
  function postingsvelte_posting_binding(value) {
    ctx2[16](value, ctx2[17], ctx2[18], ctx2[19]);
  }
  let postingsvelte_props = {
    index: ctx2[19],
    suggestions: ctx2[2],
    date: ctx2[0].date,
    add: ctx2[5],
    move: ctx2[8],
    remove: func
  };
  if (ctx2[17] !== void 0) {
    postingsvelte_props.posting = ctx2[17];
  }
  postingsvelte = new Posting_default({ props: postingsvelte_props });
  binding_callbacks.push(() => bind(postingsvelte, "posting", postingsvelte_posting_binding));
  return {
    c() {
      create_component(postingsvelte.$$.fragment);
    },
    m(target, anchor) {
      mount_component(postingsvelte, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      const postingsvelte_changes = {};
      if (dirty & 4)
        postingsvelte_changes.suggestions = ctx2[2];
      if (dirty & 1)
        postingsvelte_changes.date = ctx2[0].date;
      if (dirty & 1)
        postingsvelte_changes.remove = func;
      if (!updating_posting && dirty & 1) {
        updating_posting = true;
        postingsvelte_changes.posting = ctx2[17];
        add_flush_callback(() => updating_posting = false);
      }
      postingsvelte.$set(postingsvelte_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(postingsvelte.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(postingsvelte.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(postingsvelte, detaching);
    }
  };
}
function create_fragment35(ctx2) {
  let div2;
  let div0;
  let input0;
  let t03;
  let input1;
  let t13;
  let label0;
  let span0;
  let t4;
  let autocompleteinput;
  let updating_value;
  let t5;
  let label1;
  let span1;
  let t8;
  let input2;
  let input2_placeholder_value;
  let t9;
  let addmetadatabutton;
  let updating_meta;
  let t10;
  let button;
  let t11;
  let button_title_value;
  let button_tabindex_value;
  let t122;
  let entrymetadata;
  let updating_meta_1;
  let t132;
  let div1;
  let span3;
  let span2;
  let t16;
  let current;
  let mounted;
  let dispose;
  function autocompleteinput_value_binding(value) {
    ctx2[12](value);
  }
  let autocompleteinput_props = {
    className: "payee",
    placeholder: _("Payee"),
    suggestions: ctx2[1]
  };
  if (ctx2[0].payee !== void 0) {
    autocompleteinput_props.value = ctx2[0].payee;
  }
  autocompleteinput = new AutocompleteInput_default({ props: autocompleteinput_props });
  binding_callbacks.push(() => bind(autocompleteinput, "value", autocompleteinput_value_binding));
  autocompleteinput.$on("select", ctx2[7]);
  function addmetadatabutton_meta_binding(value) {
    ctx2[13](value);
  }
  let addmetadatabutton_props = {};
  if (ctx2[0].meta !== void 0) {
    addmetadatabutton_props.meta = ctx2[0].meta;
  }
  addmetadatabutton = new AddMetadataButton_default({ props: addmetadatabutton_props });
  binding_callbacks.push(() => bind(addmetadatabutton, "meta", addmetadatabutton_meta_binding));
  function entrymetadata_meta_binding(value) {
    ctx2[14](value);
  }
  let entrymetadata_props = {};
  if (ctx2[0].meta !== void 0) {
    entrymetadata_props.meta = ctx2[0].meta;
  }
  entrymetadata = new EntryMetadata_default({ props: entrymetadata_props });
  binding_callbacks.push(() => bind(entrymetadata, "meta", entrymetadata_meta_binding));
  let each_value = ctx2[0].postings;
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block19(get_each_context19(ctx2, each_value, i));
  }
  const out = (i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  });
  return {
    c() {
      div2 = element("div");
      div0 = element("div");
      input0 = element("input");
      t03 = space();
      input1 = element("input");
      t13 = space();
      label0 = element("label");
      span0 = element("span");
      span0.textContent = `${_("Payee")}:`;
      t4 = space();
      create_component(autocompleteinput.$$.fragment);
      t5 = space();
      label1 = element("label");
      span1 = element("span");
      span1.textContent = `${_("Narration")}:`;
      t8 = space();
      input2 = element("input");
      t9 = space();
      create_component(addmetadatabutton.$$.fragment);
      t10 = space();
      button = element("button");
      t11 = text("p");
      t122 = space();
      create_component(entrymetadata.$$.fragment);
      t132 = space();
      div1 = element("div");
      span3 = element("span");
      span2 = element("span");
      span2.textContent = `${_("Postings")}:`;
      t16 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(input0, "type", "date");
      input0.required = true;
      attr(input1, "type", "text");
      attr(input1, "name", "flag");
      input1.required = true;
      attr(input1, "class", "svelte-12mv83z");
      attr(span0, "class", "svelte-12mv83z");
      attr(label0, "class", "svelte-12mv83z");
      attr(span1, "class", "svelte-12mv83z");
      attr(input2, "type", "text");
      attr(input2, "name", "narration");
      attr(input2, "placeholder", input2_placeholder_value = _("Narration"));
      input2.value = ctx2[3];
      attr(input2, "class", "svelte-12mv83z");
      attr(label1, "class", "svelte-12mv83z");
      attr(button, "type", "button");
      attr(button, "class", "muted round");
      attr(button, "title", button_title_value = _("Add posting"));
      attr(button, "tabindex", button_tabindex_value = -1);
      attr(div0, "class", "flex-row svelte-12mv83z");
      attr(span2, "class", "svelte-12mv83z");
      attr(span3, "class", "label svelte-12mv83z");
      attr(div1, "class", "flex-row svelte-12mv83z");
      attr(div2, "class", "svelte-12mv83z");
    },
    m(target, anchor) {
      insert(target, div2, anchor);
      append(div2, div0);
      append(div0, input0);
      set_input_value(input0, ctx2[0].date);
      append(div0, t03);
      append(div0, input1);
      set_input_value(input1, ctx2[0].flag);
      append(div0, t13);
      append(div0, label0);
      append(label0, span0);
      append(label0, t4);
      mount_component(autocompleteinput, label0, null);
      append(div0, t5);
      append(div0, label1);
      append(label1, span1);
      append(label1, t8);
      append(label1, input2);
      append(label1, t9);
      mount_component(addmetadatabutton, label1, null);
      append(div0, t10);
      append(div0, button);
      append(button, t11);
      append(div2, t122);
      mount_component(entrymetadata, div2, null);
      append(div2, t132);
      append(div2, div1);
      append(div1, span3);
      append(span3, span2);
      append(div2, t16);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(div2, null);
      }
      current = true;
      if (!mounted) {
        dispose = [
          listen(input0, "input", ctx2[10]),
          listen(input1, "input", ctx2[11]),
          listen(input2, "change", ctx2[6]),
          listen(button, "click", ctx2[5])
        ];
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & 1) {
        set_input_value(input0, ctx3[0].date);
      }
      if (dirty & 1 && input1.value !== ctx3[0].flag) {
        set_input_value(input1, ctx3[0].flag);
      }
      const autocompleteinput_changes = {};
      if (dirty & 2)
        autocompleteinput_changes.suggestions = ctx3[1];
      if (!updating_value && dirty & 1) {
        updating_value = true;
        autocompleteinput_changes.value = ctx3[0].payee;
        add_flush_callback(() => updating_value = false);
      }
      autocompleteinput.$set(autocompleteinput_changes);
      if (!current || dirty & 8 && input2.value !== ctx3[3]) {
        input2.value = ctx3[3];
      }
      const addmetadatabutton_changes = {};
      if (!updating_meta && dirty & 1) {
        updating_meta = true;
        addmetadatabutton_changes.meta = ctx3[0].meta;
        add_flush_callback(() => updating_meta = false);
      }
      addmetadatabutton.$set(addmetadatabutton_changes);
      const entrymetadata_changes = {};
      if (!updating_meta_1 && dirty & 1) {
        updating_meta_1 = true;
        entrymetadata_changes.meta = ctx3[0].meta;
        add_flush_callback(() => updating_meta_1 = false);
      }
      entrymetadata.$set(entrymetadata_changes);
      if (dirty & 309) {
        each_value = ctx3[0].postings;
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context19(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block19(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(div2, null);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out(i);
        }
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(autocompleteinput.$$.fragment, local);
      transition_in(addmetadatabutton.$$.fragment, local);
      transition_in(entrymetadata.$$.fragment, local);
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      transition_out(autocompleteinput.$$.fragment, local);
      transition_out(addmetadatabutton.$$.fragment, local);
      transition_out(entrymetadata.$$.fragment, local);
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div2);
      destroy_component(autocompleteinput);
      destroy_component(addmetadatabutton);
      destroy_component(entrymetadata);
      destroy_each(each_blocks, detaching);
      mounted = false;
      run_all(dispose);
    }
  };
}
var TAGS_RE = /(?:^|\s)#([A-Za-z0-9\-_/.]+)/g;
var LINKS_RE = /(?:^|\s)\^([A-Za-z0-9\-_/.]+)/g;
function combineNarrationTagsLinks(e3) {
  let val = e3.narration;
  if (e3.tags.length) {
    val += ` ${e3.tags.map((t4) => `#${t4}`).join(" ")}`;
  }
  if (e3.links.length) {
    val += ` ${e3.links.map((t4) => `^${t4}`).join(" ")}`;
  }
  return val;
}
function instance35($$self, $$props, $$invalidate) {
  let payee;
  let narration;
  let $payees;
  component_subscribe($$self, payees, ($$value) => $$invalidate(1, $payees = $$value));
  let { entry } = $$props;
  let suggestions;
  function removePosting(posting) {
    $$invalidate(0, entry.postings = entry.postings.filter((p) => p !== posting), entry);
  }
  function addPosting() {
    $$invalidate(0, entry.postings = entry.postings.concat(emptyPosting()), entry);
  }
  function onNarrationChange({ currentTarget }) {
    const { value } = currentTarget;
    $$invalidate(0, entry.tags = [...value.matchAll(TAGS_RE)].map((a) => a[1]), entry);
    $$invalidate(0, entry.links = [...value.matchAll(LINKS_RE)].map((a) => a[1]), entry);
    $$invalidate(0, entry.narration = value.replaceAll(TAGS_RE, "").replaceAll(LINKS_RE, "").trim(), entry);
  }
  async function autocompleteSelectPayee() {
    if (entry.narration || !entry.postings.every((p) => !p.account)) {
      return;
    }
    const data = await get("payee_transaction", { payee: entry.payee });
    $$invalidate(0, entry = Object.assign(new Transaction(), data, { date: entry.date }));
  }
  function movePosting({ from, to }) {
    const moved = entry.postings[from];
    entry.postings.splice(from, 1);
    entry.postings.splice(to, 0, moved);
    $$invalidate(0, entry);
  }
  function input0_input_handler() {
    entry.date = this.value;
    $$invalidate(0, entry);
  }
  function input1_input_handler() {
    entry.flag = this.value;
    $$invalidate(0, entry);
  }
  function autocompleteinput_value_binding(value) {
    if ($$self.$$.not_equal(entry.payee, value)) {
      entry.payee = value;
      $$invalidate(0, entry);
    }
  }
  function addmetadatabutton_meta_binding(value) {
    if ($$self.$$.not_equal(entry.meta, value)) {
      entry.meta = value;
      $$invalidate(0, entry);
    }
  }
  function entrymetadata_meta_binding(value) {
    if ($$self.$$.not_equal(entry.meta, value)) {
      entry.meta = value;
      $$invalidate(0, entry);
    }
  }
  const func = (posting) => removePosting(posting);
  function postingsvelte_posting_binding(value, posting, each_value, index2) {
    each_value[index2] = value;
    $$invalidate(0, entry);
  }
  $$self.$$set = ($$props2) => {
    if ("entry" in $$props2)
      $$invalidate(0, entry = $$props2.entry);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(9, payee = entry.payee);
    }
    if ($$self.$$.dirty & 514) {
      $:
        if (payee) {
          $$invalidate(2, suggestions = void 0);
          if ($payees.includes(payee)) {
            get("payee_accounts", { payee }).then((s) => {
              $$invalidate(2, suggestions = s);
            }).catch((error) => {
              if (error instanceof Error) {
                notify(`Fetching account suggestions for payee ${payee} failed: ${error.message}`, "error");
              }
            });
          }
        }
    }
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(3, narration = combineNarrationTagsLinks(entry));
    }
  };
  return [
    entry,
    $payees,
    suggestions,
    narration,
    removePosting,
    addPosting,
    onNarrationChange,
    autocompleteSelectPayee,
    movePosting,
    payee,
    input0_input_handler,
    input1_input_handler,
    autocompleteinput_value_binding,
    addmetadatabutton_meta_binding,
    entrymetadata_meta_binding,
    func,
    postingsvelte_posting_binding
  ];
}
var Transaction_1 = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance35, create_fragment35, safe_not_equal, { entry: 0 });
  }
};
var Transaction_default = Transaction_1;

// src/entry-forms/Entry.svelte
function create_fragment36(ctx2) {
  let switch_instance;
  let updating_entry;
  let switch_instance_anchor;
  let current;
  function switch_instance_entry_binding(value) {
    ctx2[2](value);
  }
  var switch_value = ctx2[1];
  function switch_props(ctx3) {
    let switch_instance_props = {};
    if (ctx3[0] !== void 0) {
      switch_instance_props.entry = ctx3[0];
    }
    return { props: switch_instance_props };
  }
  if (switch_value) {
    switch_instance = construct_svelte_component(switch_value, switch_props(ctx2));
    binding_callbacks.push(() => bind(switch_instance, "entry", switch_instance_entry_binding));
  }
  return {
    c() {
      if (switch_instance)
        create_component(switch_instance.$$.fragment);
      switch_instance_anchor = empty();
    },
    m(target, anchor) {
      if (switch_instance)
        mount_component(switch_instance, target, anchor);
      insert(target, switch_instance_anchor, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      const switch_instance_changes = {};
      if (!updating_entry && dirty & 1) {
        updating_entry = true;
        switch_instance_changes.entry = ctx3[0];
        add_flush_callback(() => updating_entry = false);
      }
      if (switch_value !== (switch_value = ctx3[1])) {
        if (switch_instance) {
          group_outros();
          const old_component = switch_instance;
          transition_out(old_component.$$.fragment, 1, 0, () => {
            destroy_component(old_component, 1);
          });
          check_outros();
        }
        if (switch_value) {
          switch_instance = construct_svelte_component(switch_value, switch_props(ctx3));
          binding_callbacks.push(() => bind(switch_instance, "entry", switch_instance_entry_binding));
          create_component(switch_instance.$$.fragment);
          transition_in(switch_instance.$$.fragment, 1);
          mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
        } else {
          switch_instance = null;
        }
      } else if (switch_value) {
        switch_instance.$set(switch_instance_changes);
      }
    },
    i(local) {
      if (current)
        return;
      if (switch_instance)
        transition_in(switch_instance.$$.fragment, local);
      current = true;
    },
    o(local) {
      if (switch_instance)
        transition_out(switch_instance.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(switch_instance_anchor);
      if (switch_instance)
        destroy_component(switch_instance, detaching);
    }
  };
}
function instance36($$self, $$props, $$invalidate) {
  let component;
  let { entry } = $$props;
  const components2 = { Balance: Balance_default, Note: Note_default, Transaction: Transaction_default };
  function switch_instance_entry_binding(value) {
    entry = value;
    $$invalidate(0, entry);
  }
  $$self.$$set = ($$props2) => {
    if ("entry" in $$props2)
      $$invalidate(0, entry = $$props2.entry);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(1, component = components2[entry.type]);
    }
  };
  return [entry, component, switch_instance_entry_binding];
}
var Entry = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance36, create_fragment36, safe_not_equal, { entry: 0 });
  }
};
var Entry_default = Entry;

// src/import/helpers.ts
function isDuplicate(e3) {
  return !!e3.meta.__duplicate__;
}
function newFilename(date5, basename2) {
  if (/^\d{4}-\d{2}-\d{2}/.test(basename2)) {
    return basename2;
  }
  if (!date5 || !basename2) {
    return "";
  }
  return `${date5} ${basename2}`;
}
function preprocessData(arr) {
  const today = todayAsString();
  return arr.map((file) => {
    const importers = file.importers.map(
      ({ account: account2, importer_name, date: date5, name: name2 }) => ({
        account: account2,
        importer_name,
        newName: newFilename(date5, name2)
      })
    );
    if (importers.length === 0) {
      const newName = newFilename(today, file.basename);
      importers.push({ account: "", newName, importer_name: "" });
    }
    return __spreadProps(__spreadValues({}, file), { importers });
  });
}

// src/import/Extract.svelte
function create_if_block14(ctx2) {
  let div0;
  let h3;
  let t03;
  let t1_value = ctx2[2] + 1 + "";
  let t13;
  let t22;
  let t3_value = ctx2[0].length + "";
  let t32;
  let t4;
  let t5_value = ctx2[0].length - ctx2[4] + "";
  let t5;
  let t6;
  let t7;
  let span0;
  let t8;
  let label;
  let input;
  let t9;
  let t10;
  let div1;
  let entry_1;
  let updating_entry;
  let t11;
  let div2;
  let t122;
  let span1;
  let t132;
  let t14;
  let hr;
  let t15;
  let if_block2_anchor;
  let current;
  let mounted;
  let dispose;
  function entry_1_entry_binding(value) {
    ctx2[11](value);
  }
  let entry_1_props = {};
  if (ctx2[3] !== void 0) {
    entry_1_props.entry = ctx2[3];
  }
  entry_1 = new Entry_default({ props: entry_1_props });
  binding_callbacks.push(() => bind(entry_1, "entry", entry_1_entry_binding));
  let if_block0 = ctx2[2] > 0 && create_if_block_42(ctx2);
  function select_block_type(ctx3, dirty) {
    if (ctx3[2] < ctx3[0].length - 1)
      return create_if_block_33;
    return create_else_block3;
  }
  let current_block_type = select_block_type(ctx2, -1);
  let if_block1 = current_block_type(ctx2);
  let if_block2 = ctx2[3].meta.__source__ && create_if_block_19(ctx2);
  return {
    c() {
      div0 = element("div");
      h3 = element("h3");
      t03 = text("Entry\n          ");
      t13 = text(t1_value);
      t22 = text("\n          of\n          ");
      t32 = text(t3_value);
      t4 = text("\n          (");
      t5 = text(t5_value);
      t6 = text("\n          to import):");
      t7 = space();
      span0 = element("span");
      t8 = space();
      label = element("label");
      input = element("input");
      t9 = text("\n          ignore duplicate");
      t10 = space();
      div1 = element("div");
      create_component(entry_1.$$.fragment);
      t11 = space();
      div2 = element("div");
      if (if_block0)
        if_block0.c();
      t122 = space();
      span1 = element("span");
      t132 = space();
      if_block1.c();
      t14 = space();
      hr = element("hr");
      t15 = space();
      if (if_block2)
        if_block2.c();
      if_block2_anchor = empty();
      attr(span0, "class", "spacer");
      attr(input, "type", "checkbox");
      input.checked = ctx2[5];
      attr(label, "class", "button muted");
      attr(div0, "class", "flex-row");
      attr(div1, "class", "svelte-kordbm");
      toggle_class(div1, "duplicate", ctx2[5]);
      attr(span1, "class", "spacer");
      attr(div2, "class", "flex-row");
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      append(div0, h3);
      append(h3, t03);
      append(h3, t13);
      append(h3, t22);
      append(h3, t32);
      append(h3, t4);
      append(h3, t5);
      append(h3, t6);
      append(div0, t7);
      append(div0, span0);
      append(div0, t8);
      append(div0, label);
      append(label, input);
      append(label, t9);
      insert(target, t10, anchor);
      insert(target, div1, anchor);
      mount_component(entry_1, div1, null);
      insert(target, t11, anchor);
      insert(target, div2, anchor);
      if (if_block0)
        if_block0.m(div2, null);
      append(div2, t122);
      append(div2, span1);
      append(div2, t132);
      if_block1.m(div2, null);
      insert(target, t14, anchor);
      insert(target, hr, anchor);
      insert(target, t15, anchor);
      if (if_block2)
        if_block2.m(target, anchor);
      insert(target, if_block2_anchor, anchor);
      current = true;
      if (!mounted) {
        dispose = listen(input, "click", ctx2[9]);
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if ((!current || dirty & 4) && t1_value !== (t1_value = ctx3[2] + 1 + ""))
        set_data(t13, t1_value);
      if ((!current || dirty & 1) && t3_value !== (t3_value = ctx3[0].length + ""))
        set_data(t32, t3_value);
      if ((!current || dirty & 17) && t5_value !== (t5_value = ctx3[0].length - ctx3[4] + ""))
        set_data(t5, t5_value);
      if (!current || dirty & 32) {
        input.checked = ctx3[5];
      }
      const entry_1_changes = {};
      if (!updating_entry && dirty & 8) {
        updating_entry = true;
        entry_1_changes.entry = ctx3[3];
        add_flush_callback(() => updating_entry = false);
      }
      entry_1.$set(entry_1_changes);
      if (!current || dirty & 32) {
        toggle_class(div1, "duplicate", ctx3[5]);
      }
      if (ctx3[2] > 0) {
        if (if_block0) {
          if_block0.p(ctx3, dirty);
        } else {
          if_block0 = create_if_block_42(ctx3);
          if_block0.c();
          if_block0.m(div2, t122);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (current_block_type === (current_block_type = select_block_type(ctx3, dirty)) && if_block1) {
        if_block1.p(ctx3, dirty);
      } else {
        if_block1.d(1);
        if_block1 = current_block_type(ctx3);
        if (if_block1) {
          if_block1.c();
          if_block1.m(div2, null);
        }
      }
      if (ctx3[3].meta.__source__) {
        if (if_block2) {
          if_block2.p(ctx3, dirty);
        } else {
          if_block2 = create_if_block_19(ctx3);
          if_block2.c();
          if_block2.m(if_block2_anchor.parentNode, if_block2_anchor);
        }
      } else if (if_block2) {
        if_block2.d(1);
        if_block2 = null;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(entry_1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(entry_1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div0);
      if (detaching)
        detach(t10);
      if (detaching)
        detach(div1);
      destroy_component(entry_1);
      if (detaching)
        detach(t11);
      if (detaching)
        detach(div2);
      if (if_block0)
        if_block0.d();
      if_block1.d();
      if (detaching)
        detach(t14);
      if (detaching)
        detach(hr);
      if (detaching)
        detach(t15);
      if (if_block2)
        if_block2.d(detaching);
      if (detaching)
        detach(if_block2_anchor);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_42(ctx2) {
  let button0;
  let t13;
  let button1;
  let mounted;
  let dispose;
  return {
    c() {
      button0 = element("button");
      button0.textContent = "\u23EE";
      t13 = space();
      button1 = element("button");
      button1.textContent = `${_("Previous")}`;
      attr(button0, "type", "button");
      attr(button0, "class", "muted");
      attr(button1, "type", "button");
      attr(button1, "class", "muted");
    },
    m(target, anchor) {
      insert(target, button0, anchor);
      insert(target, t13, anchor);
      insert(target, button1, anchor);
      if (!mounted) {
        dispose = [
          listen(button0, "click", ctx2[12]),
          listen(button1, "click", ctx2[8])
        ];
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(button0);
      if (detaching)
        detach(t13);
      if (detaching)
        detach(button1);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_else_block3(ctx2) {
  let button;
  return {
    c() {
      button = element("button");
      button.textContent = `${_("Save")}`;
      attr(button, "type", "submit");
    },
    m(target, anchor) {
      insert(target, button, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(button);
    }
  };
}
function create_if_block_33(ctx2) {
  let button0;
  let t13;
  let button1;
  let mounted;
  let dispose;
  return {
    c() {
      button0 = element("button");
      button0.textContent = `${_("Next")}`;
      t13 = space();
      button1 = element("button");
      button1.textContent = "\u23ED";
      attr(button0, "type", "submit");
      attr(button1, "type", "button");
      attr(button1, "class", "muted");
    },
    m(target, anchor) {
      insert(target, button0, anchor);
      insert(target, t13, anchor);
      insert(target, button1, anchor);
      if (!mounted) {
        dispose = listen(button1, "click", ctx2[13]);
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(button0);
      if (detaching)
        detach(t13);
      if (detaching)
        detach(button1);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_19(ctx2) {
  let h3;
  let t0_value = _("Source") + "";
  let t03;
  let t13;
  let t22;
  let pre;
  let t3_value = ctx2[3].meta.__source__ + "";
  let t32;
  let if_block = ctx2[3].meta.lineno && create_if_block_25(ctx2);
  return {
    c() {
      h3 = element("h3");
      t03 = text(t0_value);
      t13 = space();
      if (if_block)
        if_block.c();
      t22 = space();
      pre = element("pre");
      t32 = text(t3_value);
      attr(pre, "class", "svelte-kordbm");
    },
    m(target, anchor) {
      insert(target, h3, anchor);
      append(h3, t03);
      append(h3, t13);
      if (if_block)
        if_block.m(h3, null);
      insert(target, t22, anchor);
      insert(target, pre, anchor);
      append(pre, t32);
    },
    p(ctx3, dirty) {
      if (ctx3[3].meta.lineno) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block_25(ctx3);
          if_block.c();
          if_block.m(h3, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty & 8 && t3_value !== (t3_value = ctx3[3].meta.__source__ + ""))
        set_data(t32, t3_value);
    },
    d(detaching) {
      if (detaching)
        detach(h3);
      if (if_block)
        if_block.d();
      if (detaching)
        detach(t22);
      if (detaching)
        detach(pre);
    }
  };
}
function create_if_block_25(ctx2) {
  let t03;
  let t1_value = _("Line") + "";
  let t13;
  let t22;
  let t3_value = ctx2[3].meta.lineno + "";
  let t32;
  let t4;
  return {
    c() {
      t03 = text("(");
      t13 = text(t1_value);
      t22 = text(": ");
      t32 = text(t3_value);
      t4 = text(")");
    },
    m(target, anchor) {
      insert(target, t03, anchor);
      insert(target, t13, anchor);
      insert(target, t22, anchor);
      insert(target, t32, anchor);
      insert(target, t4, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & 8 && t3_value !== (t3_value = ctx3[3].meta.lineno + ""))
        set_data(t32, t3_value);
    },
    d(detaching) {
      if (detaching)
        detach(t03);
      if (detaching)
        detach(t13);
      if (detaching)
        detach(t22);
      if (detaching)
        detach(t32);
      if (detaching)
        detach(t4);
    }
  };
}
function create_default_slot5(ctx2) {
  let form;
  let h3;
  let t13;
  let current;
  let mounted;
  let dispose;
  let if_block = ctx2[3] && create_if_block14(ctx2);
  return {
    c() {
      form = element("form");
      h3 = element("h3");
      h3.textContent = `${_("Import")}`;
      t13 = space();
      if (if_block)
        if_block.c();
      form.noValidate = ctx2[5];
    },
    m(target, anchor) {
      insert(target, form, anchor);
      append(form, h3);
      append(form, t13);
      if (if_block)
        if_block.m(form, null);
      current = true;
      if (!mounted) {
        dispose = listen(form, "submit", prevent_default(ctx2[7]));
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if (ctx3[3]) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & 8) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block14(ctx3);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(form, null);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
      if (!current || dirty & 32) {
        form.noValidate = ctx3[5];
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form);
      if (if_block)
        if_block.d();
      mounted = false;
      dispose();
    }
  };
}
function create_fragment37(ctx2) {
  let modalbase;
  let current;
  modalbase = new ModalBase_default({
    props: {
      shown: ctx2[6],
      closeHandler: ctx2[1],
      $$slots: { default: [create_default_slot5] },
      $$scope: { ctx: ctx2 }
    }
  });
  return {
    c() {
      create_component(modalbase.$$.fragment);
    },
    m(target, anchor) {
      mount_component(modalbase, target, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      const modalbase_changes = {};
      if (dirty & 64)
        modalbase_changes.shown = ctx3[6];
      if (dirty & 2)
        modalbase_changes.closeHandler = ctx3[1];
      if (dirty & 16445) {
        modalbase_changes.$$scope = { dirty, ctx: ctx3 };
      }
      modalbase.$set(modalbase_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(modalbase.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(modalbase.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(modalbase, detaching);
    }
  };
}
function instance37($$self, $$props, $$invalidate) {
  let shown;
  let entry;
  let duplicate;
  let duplicates;
  let { entries } = $$props;
  let { save } = $$props;
  let { close } = $$props;
  let currentIndex = 0;
  function submitOrNext() {
    if (currentIndex < entries.length - 1) {
      $$invalidate(2, currentIndex += 1);
    } else {
      save();
    }
  }
  function previousEntry() {
    $$invalidate(2, currentIndex = Math.max(currentIndex - 1, 0));
  }
  function toggleDuplicate() {
    $$invalidate(3, entry.meta.__duplicate__ = !entry.meta.__duplicate__, entry);
  }
  function entry_1_entry_binding(value) {
    entry = value;
    $$invalidate(3, entry), $$invalidate(0, entries), $$invalidate(2, currentIndex);
  }
  const click_handler = () => {
    $$invalidate(2, currentIndex = 0);
  };
  const click_handler_1 = () => {
    $$invalidate(2, currentIndex = entries.length - 1);
  };
  $$self.$$set = ($$props2) => {
    if ("entries" in $$props2)
      $$invalidate(0, entries = $$props2.entries);
    if ("save" in $$props2)
      $$invalidate(10, save = $$props2.save);
    if ("close" in $$props2)
      $$invalidate(1, close = $$props2.close);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(6, shown = entries.length > 0);
    }
    if ($$self.$$.dirty & 5) {
      $:
        if (entries.length > 0 && currentIndex >= entries.length) {
          $$invalidate(2, currentIndex = 0);
        }
    }
    if ($$self.$$.dirty & 5) {
      $:
        $$invalidate(3, entry = entries[currentIndex]);
    }
    if ($$self.$$.dirty & 8) {
      $:
        $$invalidate(5, duplicate = entry && isDuplicate(entry));
    }
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(4, duplicates = entries.filter((e3) => isDuplicate(e3)).length);
    }
  };
  return [
    entries,
    close,
    currentIndex,
    entry,
    duplicates,
    duplicate,
    shown,
    submitOrNext,
    previousEntry,
    toggleDuplicate,
    save,
    entry_1_entry_binding,
    click_handler,
    click_handler_1
  ];
}
var Extract = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance37, create_fragment37, safe_not_equal, { entries: 0, save: 10, close: 1 });
  }
};
var Extract_default = Extract;

// src/import/FileList.svelte
function get_each_context20(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[13] = list[i];
  return child_ctx;
}
function get_each_context_16(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[16] = list[i];
  child_ctx[17] = list;
  child_ctx[18] = i;
  return child_ctx;
}
function create_if_block15(ctx2) {
  let button;
  let t0_value = (ctx2[1].get(`${ctx2[13].name}:${ctx2[16].importer_name}`) ? _("Continue") : _("Extract")) + "";
  let t03;
  let button_title_value;
  let t13;
  let show_if = ctx2[1].get(`${ctx2[13].name}:${ctx2[16].importer_name}`);
  let t22;
  let t3_value = ctx2[16].importer_name + "";
  let t32;
  let mounted;
  let dispose;
  function click_handler_3() {
    return ctx2[11](ctx2[13], ctx2[16]);
  }
  let if_block = show_if && create_if_block_110(ctx2);
  return {
    c() {
      button = element("button");
      t03 = text(t0_value);
      t13 = space();
      if (if_block)
        if_block.c();
      t22 = space();
      t32 = text(t3_value);
      attr(button, "type", "button");
      attr(button, "title", button_title_value = _("Extract") + " with importer " + ctx2[16].importer_name);
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, t03);
      insert(target, t13, anchor);
      if (if_block)
        if_block.m(target, anchor);
      insert(target, t22, anchor);
      insert(target, t32, anchor);
      if (!mounted) {
        dispose = listen(button, "click", click_handler_3);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & 3 && t0_value !== (t0_value = (ctx2[1].get(`${ctx2[13].name}:${ctx2[16].importer_name}`) ? _("Continue") : _("Extract")) + ""))
        set_data(t03, t0_value);
      if (dirty & 1 && button_title_value !== (button_title_value = _("Extract") + " with importer " + ctx2[16].importer_name)) {
        attr(button, "title", button_title_value);
      }
      if (dirty & 3)
        show_if = ctx2[1].get(`${ctx2[13].name}:${ctx2[16].importer_name}`);
      if (show_if) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_110(ctx2);
          if_block.c();
          if_block.m(t22.parentNode, t22);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty & 1 && t3_value !== (t3_value = ctx2[16].importer_name + ""))
        set_data(t32, t3_value);
    },
    d(detaching) {
      if (detaching)
        detach(button);
      if (detaching)
        detach(t13);
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(t22);
      if (detaching)
        detach(t32);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_110(ctx2) {
  let button;
  let mounted;
  let dispose;
  function click_handler_4() {
    return ctx2[12](ctx2[13], ctx2[16]);
  }
  return {
    c() {
      button = element("button");
      button.textContent = `${_("Clear")}`;
      attr(button, "type", "button");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (!mounted) {
        dispose = listen(button, "click", click_handler_4);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
    },
    d(detaching) {
      if (detaching)
        detach(button);
      mounted = false;
      dispose();
    }
  };
}
function create_each_block_16(ctx2) {
  let div;
  let accountinput;
  let updating_value;
  let t03;
  let input;
  let input_size_value;
  let t13;
  let button;
  let t32;
  let t4;
  let current;
  let mounted;
  let dispose;
  function accountinput_value_binding(value) {
    ctx2[8](value, ctx2[16]);
  }
  let accountinput_props = {};
  if (ctx2[16].account !== void 0) {
    accountinput_props.value = ctx2[16].account;
  }
  accountinput = new AccountInput_default({ props: accountinput_props });
  binding_callbacks.push(() => bind(accountinput, "value", accountinput_value_binding));
  function input_input_handler() {
    ctx2[9].call(input, ctx2[17], ctx2[18]);
  }
  function click_handler_2() {
    return ctx2[10](ctx2[13], ctx2[16]);
  }
  let if_block = ctx2[16].importer_name && create_if_block15(ctx2);
  return {
    c() {
      div = element("div");
      create_component(accountinput.$$.fragment);
      t03 = space();
      input = element("input");
      t13 = space();
      button = element("button");
      button.textContent = `${"Move"}`;
      t32 = space();
      if (if_block)
        if_block.c();
      t4 = space();
      attr(input, "size", input_size_value = 40);
      attr(button, "type", "button");
      attr(div, "class", "flex-row");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(accountinput, div, null);
      append(div, t03);
      append(div, input);
      set_input_value(input, ctx2[16].newName);
      append(div, t13);
      append(div, button);
      append(div, t32);
      if (if_block)
        if_block.m(div, null);
      append(div, t4);
      current = true;
      if (!mounted) {
        dispose = [
          listen(input, "input", input_input_handler),
          listen(button, "click", click_handler_2)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      const accountinput_changes = {};
      if (!updating_value && dirty & 1) {
        updating_value = true;
        accountinput_changes.value = ctx2[16].account;
        add_flush_callback(() => updating_value = false);
      }
      accountinput.$set(accountinput_changes);
      if (dirty & 1 && input.value !== ctx2[16].newName) {
        set_input_value(input, ctx2[16].newName);
      }
      if (ctx2[16].importer_name) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block15(ctx2);
          if_block.c();
          if_block.m(div, t4);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(accountinput.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(accountinput.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      destroy_component(accountinput);
      if (if_block)
        if_block.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_each_block20(ctx2) {
  let div;
  let button0;
  let t0_value = ctx2[13].basename + "";
  let t03;
  let t13;
  let button1;
  let t22;
  let button1_title_value;
  let button1_tabindex_value;
  let div_title_value;
  let t32;
  let each_1_anchor;
  let current;
  let mounted;
  let dispose;
  function click_handler() {
    return ctx2[6](ctx2[13]);
  }
  function click_handler_1() {
    return ctx2[7](ctx2[13]);
  }
  let each_value_1 = ctx2[13].importers;
  let each_blocks = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks[i] = create_each_block_16(get_each_context_16(ctx2, each_value_1, i));
  }
  const out = (i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  });
  return {
    c() {
      div = element("div");
      button0 = element("button");
      t03 = text(t0_value);
      t13 = space();
      button1 = element("button");
      t22 = text("\xD7");
      t32 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
      attr(button0, "type", "button");
      attr(button0, "class", "svelte-4bh69f");
      attr(button1, "type", "button");
      attr(button1, "class", "round svelte-4bh69f");
      attr(button1, "title", button1_title_value = _("Delete"));
      attr(button1, "tabindex", button1_tabindex_value = -1);
      attr(div, "class", "header svelte-4bh69f");
      attr(div, "title", div_title_value = ctx2[13].name);
      toggle_class(div, "selected", ctx2[2] === ctx2[13].name);
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, button0);
      append(button0, t03);
      append(div, t13);
      append(div, button1);
      append(button1, t22);
      insert(target, t32, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(target, anchor);
      }
      insert(target, each_1_anchor, anchor);
      current = true;
      if (!mounted) {
        dispose = [
          listen(button0, "click", click_handler),
          listen(button1, "click", click_handler_1)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if ((!current || dirty & 1) && t0_value !== (t0_value = ctx2[13].basename + ""))
        set_data(t03, t0_value);
      if (!current || dirty & 1 && div_title_value !== (div_title_value = ctx2[13].name)) {
        attr(div, "title", div_title_value);
      }
      if (!current || dirty & 5) {
        toggle_class(div, "selected", ctx2[2] === ctx2[13].name);
      }
      if (dirty & 51) {
        each_value_1 = ctx2[13].importers;
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_16(ctx2, each_value_1, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block_16(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        group_outros();
        for (i = each_value_1.length; i < each_blocks.length; i += 1) {
          out(i);
        }
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      if (detaching)
        detach(t32);
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(each_1_anchor);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_fragment38(ctx2) {
  let each_1_anchor;
  let current;
  let each_value = ctx2[0];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block20(get_each_context20(ctx2, each_value, i));
  }
  const out = (i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  });
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(target, anchor);
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      if (dirty & 63) {
        each_value = ctx3[0];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context20(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block20(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out(i);
        }
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      destroy_each(each_blocks, detaching);
      if (detaching)
        detach(each_1_anchor);
    }
  };
}
function instance38($$self, $$props, $$invalidate) {
  let { files: files2 } = $$props;
  let { extractCache } = $$props;
  let { selected } = $$props;
  let { remove: remove3 } = $$props;
  let { move } = $$props;
  let { extract } = $$props;
  const click_handler = (file) => {
    $$invalidate(2, selected = selected === file.name ? null : file.name);
  };
  const click_handler_1 = (file) => remove3(file.name);
  function accountinput_value_binding(value, info) {
    if ($$self.$$.not_equal(info.account, value)) {
      info.account = value;
      $$invalidate(0, files2);
    }
  }
  function input_input_handler(each_value_1, info_index) {
    each_value_1[info_index].newName = this.value;
    $$invalidate(0, files2);
  }
  const click_handler_2 = (file, info) => move(file.name, info.account, info.newName);
  const click_handler_3 = (file, info) => extract(file.name, info.importer_name);
  const click_handler_4 = (file, info) => {
    extractCache.delete(`${file.name}:${info.importer_name}`);
    $$invalidate(1, extractCache);
  };
  $$self.$$set = ($$props2) => {
    if ("files" in $$props2)
      $$invalidate(0, files2 = $$props2.files);
    if ("extractCache" in $$props2)
      $$invalidate(1, extractCache = $$props2.extractCache);
    if ("selected" in $$props2)
      $$invalidate(2, selected = $$props2.selected);
    if ("remove" in $$props2)
      $$invalidate(3, remove3 = $$props2.remove);
    if ("move" in $$props2)
      $$invalidate(4, move = $$props2.move);
    if ("extract" in $$props2)
      $$invalidate(5, extract = $$props2.extract);
  };
  return [
    files2,
    extractCache,
    selected,
    remove3,
    move,
    extract,
    click_handler,
    click_handler_1,
    accountinput_value_binding,
    input_input_handler,
    click_handler_2,
    click_handler_3,
    click_handler_4
  ];
}
var FileList = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance38, create_fragment38, safe_not_equal, {
      files: 0,
      extractCache: 1,
      selected: 2,
      remove: 3,
      move: 4,
      extract: 5
    });
  }
};
var FileList_default = FileList;

// src/import/Import.svelte
function create_if_block_34(ctx2) {
  let p;
  return {
    c() {
      p = element("p");
      p.textContent = `${_("No files were found for import.")}`;
    },
    m(target, anchor) {
      insert(target, p, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(p);
    }
  };
}
function create_if_block_26(ctx2) {
  let div;
  let h2;
  let t13;
  let filelist;
  let updating_selected;
  let t22;
  let hr;
  let current;
  function filelist_selected_binding(value) {
    ctx2[12](value);
  }
  let filelist_props = {
    files: ctx2[5],
    extractCache: ctx2[3],
    move: ctx2[6],
    remove: ctx2[7],
    extract: ctx2[8]
  };
  if (ctx2[2] !== void 0) {
    filelist_props.selected = ctx2[2];
  }
  filelist = new FileList_default({ props: filelist_props });
  binding_callbacks.push(() => bind(filelist, "selected", filelist_selected_binding));
  return {
    c() {
      div = element("div");
      h2 = element("h2");
      h2.textContent = `${_("Importable Files")}`;
      t13 = space();
      create_component(filelist.$$.fragment);
      t22 = space();
      hr = element("hr");
      attr(hr, "class", "svelte-9ktust");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, h2);
      append(div, t13);
      mount_component(filelist, div, null);
      insert(target, t22, anchor);
      insert(target, hr, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const filelist_changes = {};
      if (dirty & 32)
        filelist_changes.files = ctx3[5];
      if (dirty & 8)
        filelist_changes.extractCache = ctx3[3];
      if (!updating_selected && dirty & 4) {
        updating_selected = true;
        filelist_changes.selected = ctx3[2];
        add_flush_callback(() => updating_selected = false);
      }
      filelist.$set(filelist_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(filelist.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(filelist.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      destroy_component(filelist);
      if (detaching)
        detach(t22);
      if (detaching)
        detach(hr);
    }
  };
}
function create_if_block_111(ctx2) {
  let details;
  let summary;
  let t13;
  let filelist;
  let updating_selected;
  let details_open_value;
  let current;
  function filelist_selected_binding_1(value) {
    ctx2[13](value);
  }
  let filelist_props = {
    files: ctx2[4],
    extractCache: ctx2[3],
    move: ctx2[6],
    remove: ctx2[7],
    extract: ctx2[8]
  };
  if (ctx2[2] !== void 0) {
    filelist_props.selected = ctx2[2];
  }
  filelist = new FileList_default({ props: filelist_props });
  binding_callbacks.push(() => bind(filelist, "selected", filelist_selected_binding_1));
  return {
    c() {
      details = element("details");
      summary = element("summary");
      summary.textContent = `${_("Non-importable Files")}`;
      t13 = space();
      create_component(filelist.$$.fragment);
      details.open = details_open_value = ctx2[5].length === 0;
    },
    m(target, anchor) {
      insert(target, details, anchor);
      append(details, summary);
      append(details, t13);
      mount_component(filelist, details, null);
      current = true;
    },
    p(ctx3, dirty) {
      const filelist_changes = {};
      if (dirty & 16)
        filelist_changes.files = ctx3[4];
      if (dirty & 8)
        filelist_changes.extractCache = ctx3[3];
      if (!updating_selected && dirty & 4) {
        updating_selected = true;
        filelist_changes.selected = ctx3[2];
        add_flush_callback(() => updating_selected = false);
      }
      filelist.$set(filelist_changes);
      if (!current || dirty & 32 && details_open_value !== (details_open_value = ctx3[5].length === 0)) {
        details.open = details_open_value;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(filelist.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(filelist.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(details);
      destroy_component(filelist);
    }
  };
}
function create_if_block16(ctx2) {
  let div;
  let documentpreview;
  let current;
  documentpreview = new DocumentPreview_default({ props: { filename: ctx2[2] } });
  return {
    c() {
      div = element("div");
      create_component(documentpreview.$$.fragment);
      attr(div, "class", "svelte-9ktust");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(documentpreview, div, null);
      current = true;
    },
    p(ctx3, dirty) {
      const documentpreview_changes = {};
      if (dirty & 4)
        documentpreview_changes.filename = ctx3[2];
      documentpreview.$set(documentpreview_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(documentpreview.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(documentpreview.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      destroy_component(documentpreview);
    }
  };
}
function create_fragment39(ctx2) {
  let extract_1;
  let t03;
  let div1;
  let div0;
  let t13;
  let t22;
  let t32;
  let current;
  extract_1 = new Extract_default({
    props: {
      entries: ctx2[1],
      close: ctx2[11],
      save: ctx2[9]
    }
  });
  let if_block0 = ctx2[0].length === 0 && create_if_block_34(ctx2);
  let if_block1 = ctx2[5].length > 0 && create_if_block_26(ctx2);
  let if_block2 = ctx2[4].length > 0 && create_if_block_111(ctx2);
  let if_block3 = ctx2[2] && create_if_block16(ctx2);
  return {
    c() {
      create_component(extract_1.$$.fragment);
      t03 = space();
      div1 = element("div");
      div0 = element("div");
      if (if_block0)
        if_block0.c();
      t13 = space();
      if (if_block1)
        if_block1.c();
      t22 = space();
      if (if_block2)
        if_block2.c();
      t32 = space();
      if (if_block3)
        if_block3.c();
      attr(div0, "class", "filelist svelte-9ktust");
      attr(div1, "class", "fixed-fullsize-container svelte-9ktust");
    },
    m(target, anchor) {
      mount_component(extract_1, target, anchor);
      insert(target, t03, anchor);
      insert(target, div1, anchor);
      append(div1, div0);
      if (if_block0)
        if_block0.m(div0, null);
      append(div0, t13);
      if (if_block1)
        if_block1.m(div0, null);
      append(div0, t22);
      if (if_block2)
        if_block2.m(div0, null);
      append(div1, t32);
      if (if_block3)
        if_block3.m(div1, null);
      current = true;
    },
    p(ctx3, [dirty]) {
      const extract_1_changes = {};
      if (dirty & 2)
        extract_1_changes.entries = ctx3[1];
      if (dirty & 2)
        extract_1_changes.close = ctx3[11];
      extract_1.$set(extract_1_changes);
      if (ctx3[0].length === 0) {
        if (if_block0) {
          if_block0.p(ctx3, dirty);
        } else {
          if_block0 = create_if_block_34(ctx3);
          if_block0.c();
          if_block0.m(div0, t13);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (ctx3[5].length > 0) {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
          if (dirty & 32) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_26(ctx3);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(div0, t22);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      if (ctx3[4].length > 0) {
        if (if_block2) {
          if_block2.p(ctx3, dirty);
          if (dirty & 16) {
            transition_in(if_block2, 1);
          }
        } else {
          if_block2 = create_if_block_111(ctx3);
          if_block2.c();
          transition_in(if_block2, 1);
          if_block2.m(div0, null);
        }
      } else if (if_block2) {
        group_outros();
        transition_out(if_block2, 1, 1, () => {
          if_block2 = null;
        });
        check_outros();
      }
      if (ctx3[2]) {
        if (if_block3) {
          if_block3.p(ctx3, dirty);
          if (dirty & 4) {
            transition_in(if_block3, 1);
          }
        } else {
          if_block3 = create_if_block16(ctx3);
          if_block3.c();
          transition_in(if_block3, 1);
          if_block3.m(div1, null);
        }
      } else if (if_block3) {
        group_outros();
        transition_out(if_block3, 1, 1, () => {
          if_block3 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(extract_1.$$.fragment, local);
      transition_in(if_block1);
      transition_in(if_block2);
      transition_in(if_block3);
      current = true;
    },
    o(local) {
      transition_out(extract_1.$$.fragment, local);
      transition_out(if_block1);
      transition_out(if_block2);
      transition_out(if_block3);
      current = false;
    },
    d(detaching) {
      destroy_component(extract_1, detaching);
      if (detaching)
        detach(t03);
      if (detaching)
        detach(div1);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      if (if_block2)
        if_block2.d();
      if (if_block3)
        if_block3.d();
    }
  };
}
function instance39($$self, $$props, $$invalidate) {
  let importableFiles;
  let otherFiles;
  let { data } = $$props;
  let entries = [];
  let selected = null;
  let files2 = [];
  let extractCache = /* @__PURE__ */ new Map();
  function preventNavigation() {
    return extractCache.size > 0 ? "There are unfinished imports, are you sure you want to continue?" : null;
  }
  onMount(() => router_default.addInteruptHandler(preventNavigation));
  onMount(() => {
    $$invalidate(0, files2 = preprocessData(data));
  });
  async function move(filename, account2, newName) {
    const moved = await moveDocument(filename, account2, newName);
    if (moved) {
      $$invalidate(0, files2 = files2.filter((item) => item.name !== filename));
    }
  }
  async function remove3(filename) {
    if (!window.confirm(_("Delete this file?"))) {
      return;
    }
    const removed = await deleteDocument(filename);
    if (removed) {
      $$invalidate(0, files2 = files2.filter((item) => item.name !== filename));
    }
  }
  async function extract(filename, importer) {
    const extractCacheKey = `${filename}:${importer}`;
    let cached = extractCache.get(extractCacheKey);
    if (!cached) {
      cached = await get("extract", { filename, importer });
      if (!cached.length) {
        notify("No entries to import from this file.", "warning");
        return;
      }
      extractCache.set(extractCacheKey, cached);
      $$invalidate(3, extractCache);
    }
    $$invalidate(1, entries = cached);
  }
  async function save() {
    var _a2;
    const withoutDuplicates = entries.filter((e3) => !isDuplicate(e3));
    const key = (_a2 = [...extractCache].find(([, e3]) => e3 === entries)) == null ? void 0 : _a2[0];
    if (key) {
      extractCache.delete(key);
      $$invalidate(3, extractCache);
    }
    $$invalidate(1, entries = []);
    await saveEntries(withoutDuplicates);
  }
  const func = () => {
    $$invalidate(1, entries = []);
  };
  function filelist_selected_binding(value) {
    selected = value;
    $$invalidate(2, selected);
  }
  function filelist_selected_binding_1(value) {
    selected = value;
    $$invalidate(2, selected);
  }
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(10, data = $$props2.data);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(5, importableFiles = files2.filter((i) => i.importers[0].importer_name !== ""));
    }
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(4, otherFiles = files2.filter((i) => i.importers[0].importer_name === ""));
    }
  };
  return [
    files2,
    entries,
    selected,
    extractCache,
    otherFiles,
    importableFiles,
    move,
    remove3,
    extract,
    save,
    data,
    func,
    filelist_selected_binding,
    filelist_selected_binding_1
  ];
}
var Import = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance39, create_fragment39, safe_not_equal, { data: 10 });
  }
};
var Import_default = Import;

// src/modals/AddEntry.svelte
function get_each_context21(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[8] = list[i][0];
  child_ctx[9] = list[i][1];
  return child_ctx;
}
function create_each_block21(ctx2) {
  let button;
  let t0_value = ctx2[9] + "";
  let t03;
  let t13;
  let t2_value = " ";
  let t22;
  let mounted;
  let dispose;
  function click_handler() {
    return ctx2[6](ctx2[8]);
  }
  return {
    c() {
      button = element("button");
      t03 = text(t0_value);
      t13 = space();
      t22 = text(t2_value);
      attr(button, "type", "button");
      toggle_class(button, "muted", ctx2[0].type !== ctx2[8]);
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, t03);
      insert(target, t13, anchor);
      insert(target, t22, anchor);
      if (!mounted) {
        dispose = listen(button, "click", click_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & 5) {
        toggle_class(button, "muted", ctx2[0].type !== ctx2[8]);
      }
    },
    d(detaching) {
      if (detaching)
        detach(button);
      if (detaching)
        detach(t13);
      if (detaching)
        detach(t22);
      mounted = false;
      dispose();
    }
  };
}
function create_default_slot6(ctx2) {
  let form;
  let h3;
  let t0_value = _("Add") + "";
  let t03;
  let t13;
  let t22;
  let entry_1;
  let updating_entry;
  let t32;
  let div;
  let span;
  let t4;
  let button0;
  let t6;
  let button1;
  let current;
  let mounted;
  let dispose;
  let each_value = ctx2[2];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block21(get_each_context21(ctx2, each_value, i));
  }
  function entry_1_entry_binding(value) {
    ctx2[7](value);
  }
  let entry_1_props = {};
  if (ctx2[0] !== void 0) {
    entry_1_props.entry = ctx2[0];
  }
  entry_1 = new Entry_default({ props: entry_1_props });
  binding_callbacks.push(() => bind(entry_1, "entry", entry_1_entry_binding));
  return {
    c() {
      form = element("form");
      h3 = element("h3");
      t03 = text(t0_value);
      t13 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t22 = space();
      create_component(entry_1.$$.fragment);
      t32 = space();
      div = element("div");
      span = element("span");
      t4 = space();
      button0 = element("button");
      button0.textContent = `${_("Save and add new")}`;
      t6 = space();
      button1 = element("button");
      button1.textContent = `${_("Save")}`;
      attr(span, "class", "spacer");
      attr(button0, "type", "submit");
      attr(button0, "class", "muted");
      attr(button1, "type", "submit");
      attr(div, "class", "flex-row");
    },
    m(target, anchor) {
      insert(target, form, anchor);
      append(form, h3);
      append(h3, t03);
      append(h3, t13);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(h3, null);
      }
      append(form, t22);
      mount_component(entry_1, form, null);
      append(form, t32);
      append(form, div);
      append(div, span);
      append(div, t4);
      append(div, button0);
      append(div, t6);
      append(div, button1);
      current = true;
      if (!mounted) {
        dispose = [
          listen(button0, "click", prevent_default(ctx2[3])),
          listen(form, "submit", prevent_default(ctx2[4]))
        ];
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if (dirty & 5) {
        each_value = ctx3[2];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context21(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block21(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(h3, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
      const entry_1_changes = {};
      if (!updating_entry && dirty & 1) {
        updating_entry = true;
        entry_1_changes.entry = ctx3[0];
        add_flush_callback(() => updating_entry = false);
      }
      entry_1.$set(entry_1_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(entry_1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(entry_1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form);
      destroy_each(each_blocks, detaching);
      destroy_component(entry_1);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_fragment40(ctx2) {
  let modalbase;
  let current;
  modalbase = new ModalBase_default({
    props: {
      shown: ctx2[1],
      focus: ".payee input",
      $$slots: { default: [create_default_slot6] },
      $$scope: { ctx: ctx2 }
    }
  });
  return {
    c() {
      create_component(modalbase.$$.fragment);
    },
    m(target, anchor) {
      mount_component(modalbase, target, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      const modalbase_changes = {};
      if (dirty & 2)
        modalbase_changes.shown = ctx3[1];
      if (dirty & 4097) {
        modalbase_changes.$$scope = { dirty, ctx: ctx3 };
      }
      modalbase.$set(modalbase_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(modalbase.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(modalbase.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(modalbase, detaching);
    }
  };
}
function instance40($$self, $$props, $$invalidate) {
  let shown;
  let $urlHash;
  component_subscribe($$self, urlHash, ($$value) => $$invalidate(5, $urlHash = $$value));
  const entryTypes = [
    ["Transaction", _("Transaction")],
    ["Balance", _("Balance")],
    ["Note", _("Note")]
  ];
  let entry = create("Transaction");
  async function submitAndNew({ currentTarget }) {
    var _a2;
    if ((_a2 = currentTarget.form) == null ? void 0 : _a2.reportValidity()) {
      await saveEntries([entry]);
      $$invalidate(0, entry = create(entry.type));
    }
  }
  async function submit() {
    await saveEntries([entry]);
    $$invalidate(0, entry = create(entry.type));
    closeOverlay();
  }
  const click_handler = (type) => {
    $$invalidate(0, entry = create(type));
  };
  function entry_1_entry_binding(value) {
    entry = value;
    $$invalidate(0, entry);
  }
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 32) {
      $:
        $$invalidate(1, shown = $urlHash === "add-transaction");
    }
  };
  return [
    entry,
    shown,
    entryTypes,
    submitAndNew,
    submit,
    $urlHash,
    click_handler,
    entry_1_entry_binding
  ];
}
var AddEntry = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance40, create_fragment40, safe_not_equal, {});
  }
};
var AddEntry_default = AddEntry;

// src/editor/SliceEditor.svelte
function create_fragment41(ctx2) {
  let form;
  let div;
  let useEditor_action;
  let t4;
  let savebutton;
  let current;
  let mounted;
  let dispose;
  savebutton = new SaveButton_default({
    props: {
      changed: ctx2[1],
      saving: ctx2[0]
    }
  });
  return {
    c() {
      form = element("form");
      div = element("div");
      t4 = space();
      create_component(savebutton.$$.fragment);
      attr(div, "class", "svelte-1t1lmj4");
    },
    m(target, anchor) {
      insert(target, form, anchor);
      append(form, div);
      append(form, t4);
      mount_component(savebutton, form, null);
      current = true;
      if (!mounted) {
        dispose = [
          action_destroyer(useEditor_action = ctx2[3].call(null, div)),
          listen(form, "submit", prevent_default(ctx2[2]))
        ];
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      const savebutton_changes = {};
      if (dirty & 2)
        savebutton_changes.changed = ctx3[1];
      if (dirty & 1)
        savebutton_changes.saving = ctx3[0];
      savebutton.$set(savebutton_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(savebutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(savebutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form);
      destroy_component(savebutton);
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance41($$self, $$props, $$invalidate) {
  let changed;
  let { slice: slice2 } = $$props;
  let { entry_hash } = $$props;
  let { sha256sum } = $$props;
  let currentSlice = slice2;
  let saving = false;
  async function save() {
    $$invalidate(0, saving = true);
    try {
      $$invalidate(4, sha256sum = await put("source_slice", {
        entry_hash,
        source: currentSlice,
        sha256sum
      }));
      router_default.reload();
      closeOverlay();
    } catch (error) {
      if (error instanceof Error) {
        notify(error.message, "error");
      }
    } finally {
      $$invalidate(0, saving = false);
    }
  }
  const [, useEditor] = initBeancountEditor(
    slice2,
    (state) => {
      $$invalidate(7, currentSlice = state.doc.toString());
    },
    [
      {
        key: "Control-s",
        mac: "Meta-s",
        run: () => {
          save().catch(() => {
          });
          return true;
        }
      }
    ]
  );
  $$self.$$set = ($$props2) => {
    if ("slice" in $$props2)
      $$invalidate(5, slice2 = $$props2.slice);
    if ("entry_hash" in $$props2)
      $$invalidate(6, entry_hash = $$props2.entry_hash);
    if ("sha256sum" in $$props2)
      $$invalidate(4, sha256sum = $$props2.sha256sum);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 160) {
      $:
        $$invalidate(1, changed = currentSlice !== slice2);
    }
  };
  return [saving, changed, save, useEditor, sha256sum, slice2, entry_hash, currentSlice];
}
var SliceEditor = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance41, create_fragment41, safe_not_equal, { slice: 5, entry_hash: 6, sha256sum: 4 });
  }
};
var SliceEditor_default = SliceEditor;

// src/modals/EntryContext.svelte
function get_each_context22(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[3] = list[i][0];
  child_ctx[4] = list[i][1];
  return child_ctx;
}
function get_each_context_17(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[7] = list[i];
  return child_ctx;
}
function get_each_context_23(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[3] = list[i][0];
  child_ctx[4] = list[i][1];
  return child_ctx;
}
function get_each_context_33(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[7] = list[i];
  return child_ctx;
}
function create_if_block17(ctx2) {
  let details;
  let summary;
  let span;
  let t13;
  let div;
  let table0;
  let thead0;
  let tr0;
  let th0;
  let t32;
  let tbody0;
  let t4;
  let table1;
  let thead1;
  let tr1;
  let th1;
  let t6;
  let tbody1;
  let each_value_2 = Object.entries(ctx2[1]);
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_2.length; i += 1) {
    each_blocks_1[i] = create_each_block_23(get_each_context_23(ctx2, each_value_2, i));
  }
  let each_value = Object.entries(ctx2[2]);
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block22(get_each_context22(ctx2, each_value, i));
  }
  return {
    c() {
      details = element("details");
      summary = element("summary");
      span = element("span");
      span.textContent = `${_("Context")}`;
      t13 = space();
      div = element("div");
      table0 = element("table");
      thead0 = element("thead");
      tr0 = element("tr");
      th0 = element("th");
      th0.textContent = `${_("Balances before entry")}`;
      t32 = space();
      tbody0 = element("tbody");
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t4 = space();
      table1 = element("table");
      thead1 = element("thead");
      tr1 = element("tr");
      th1 = element("th");
      th1.textContent = `${_("Balances after entry")}`;
      t6 = space();
      tbody1 = element("tbody");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(th0, "colspan", "2");
      attr(th1, "colspan", "2");
    },
    m(target, anchor) {
      insert(target, details, anchor);
      append(details, summary);
      append(summary, span);
      append(details, t13);
      append(details, div);
      append(div, table0);
      append(table0, thead0);
      append(thead0, tr0);
      append(tr0, th0);
      append(table0, t32);
      append(table0, tbody0);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].m(tbody0, null);
      }
      append(div, t4);
      append(div, table1);
      append(table1, thead1);
      append(thead1, tr1);
      append(tr1, th1);
      append(table1, t6);
      append(table1, tbody1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(tbody1, null);
      }
    },
    p(ctx3, dirty) {
      if (dirty & 2) {
        each_value_2 = Object.entries(ctx3[1]);
        let i;
        for (i = 0; i < each_value_2.length; i += 1) {
          const child_ctx = get_each_context_23(ctx3, each_value_2, i);
          if (each_blocks_1[i]) {
            each_blocks_1[i].p(child_ctx, dirty);
          } else {
            each_blocks_1[i] = create_each_block_23(child_ctx);
            each_blocks_1[i].c();
            each_blocks_1[i].m(tbody0, null);
          }
        }
        for (; i < each_blocks_1.length; i += 1) {
          each_blocks_1[i].d(1);
        }
        each_blocks_1.length = each_value_2.length;
      }
      if (dirty & 4) {
        each_value = Object.entries(ctx3[2]);
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context22(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block22(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(tbody1, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    d(detaching) {
      if (detaching)
        detach(details);
      destroy_each(each_blocks_1, detaching);
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_each_block_33(ctx2) {
  let t0_value = ctx2[7] + "";
  let t03;
  let t13;
  let br;
  return {
    c() {
      t03 = text(t0_value);
      t13 = space();
      br = element("br");
    },
    m(target, anchor) {
      insert(target, t03, anchor);
      insert(target, t13, anchor);
      insert(target, br, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & 2 && t0_value !== (t0_value = ctx3[7] + ""))
        set_data(t03, t0_value);
    },
    d(detaching) {
      if (detaching)
        detach(t03);
      if (detaching)
        detach(t13);
      if (detaching)
        detach(br);
    }
  };
}
function create_each_block_23(ctx2) {
  let tr;
  let td0;
  let a;
  let t0_value = ctx2[3] + "";
  let t03;
  let a_href_value;
  let t13;
  let td1;
  let t22;
  let each_value_3 = ctx2[4];
  let each_blocks = [];
  for (let i = 0; i < each_value_3.length; i += 1) {
    each_blocks[i] = create_each_block_33(get_each_context_33(ctx2, each_value_3, i));
  }
  return {
    c() {
      tr = element("tr");
      td0 = element("td");
      a = element("a");
      t03 = text(t0_value);
      t13 = space();
      td1 = element("td");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t22 = space();
      attr(a, "href", a_href_value = urlForAccount(ctx2[3]));
    },
    m(target, anchor) {
      insert(target, tr, anchor);
      append(tr, td0);
      append(td0, a);
      append(a, t03);
      append(tr, t13);
      append(tr, td1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(td1, null);
      }
      append(tr, t22);
    },
    p(ctx3, dirty) {
      if (dirty & 2 && t0_value !== (t0_value = ctx3[3] + ""))
        set_data(t03, t0_value);
      if (dirty & 2 && a_href_value !== (a_href_value = urlForAccount(ctx3[3]))) {
        attr(a, "href", a_href_value);
      }
      if (dirty & 2) {
        each_value_3 = ctx3[4];
        let i;
        for (i = 0; i < each_value_3.length; i += 1) {
          const child_ctx = get_each_context_33(ctx3, each_value_3, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_33(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(td1, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value_3.length;
      }
    },
    d(detaching) {
      if (detaching)
        detach(tr);
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_each_block_17(ctx2) {
  let t0_value = ctx2[7] + "";
  let t03;
  let t13;
  let br;
  return {
    c() {
      t03 = text(t0_value);
      t13 = space();
      br = element("br");
    },
    m(target, anchor) {
      insert(target, t03, anchor);
      insert(target, t13, anchor);
      insert(target, br, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & 4 && t0_value !== (t0_value = ctx3[7] + ""))
        set_data(t03, t0_value);
    },
    d(detaching) {
      if (detaching)
        detach(t03);
      if (detaching)
        detach(t13);
      if (detaching)
        detach(br);
    }
  };
}
function create_each_block22(ctx2) {
  let tr;
  let td0;
  let a;
  let t0_value = ctx2[3] + "";
  let t03;
  let a_href_value;
  let t13;
  let td1;
  let t22;
  let each_value_1 = ctx2[4];
  let each_blocks = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks[i] = create_each_block_17(get_each_context_17(ctx2, each_value_1, i));
  }
  return {
    c() {
      tr = element("tr");
      td0 = element("td");
      a = element("a");
      t03 = text(t0_value);
      t13 = space();
      td1 = element("td");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t22 = space();
      attr(a, "href", a_href_value = urlForAccount(ctx2[3]));
    },
    m(target, anchor) {
      insert(target, tr, anchor);
      append(tr, td0);
      append(td0, a);
      append(a, t03);
      append(tr, t13);
      append(tr, td1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(td1, null);
      }
      append(tr, t22);
    },
    p(ctx3, dirty) {
      if (dirty & 4 && t0_value !== (t0_value = ctx3[3] + ""))
        set_data(t03, t0_value);
      if (dirty & 4 && a_href_value !== (a_href_value = urlForAccount(ctx3[3]))) {
        attr(a, "href", a_href_value);
      }
      if (dirty & 4) {
        each_value_1 = ctx3[4];
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_17(ctx3, each_value_1, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_17(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(td1, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value_1.length;
      }
    },
    d(detaching) {
      if (detaching)
        detach(tr);
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_fragment42(ctx2) {
  let p;
  let t0_value = _("Location") + "";
  let t03;
  let t13;
  let code;
  let a;
  let t2_value = ctx2[0].meta.filename + "";
  let t22;
  let t32;
  let t4_value = ctx2[0].meta.lineno + "";
  let t4;
  let a_href_value;
  let t5;
  let if_block_anchor;
  let if_block = ctx2[1] && ctx2[2] && create_if_block17(ctx2);
  return {
    c() {
      p = element("p");
      t03 = text(t0_value);
      t13 = text(":\n  ");
      code = element("code");
      a = element("a");
      t22 = text(t2_value);
      t32 = text(":");
      t4 = text(t4_value);
      t5 = space();
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
      attr(a, "href", a_href_value = urlForSource(ctx2[0]));
    },
    m(target, anchor) {
      insert(target, p, anchor);
      append(p, t03);
      append(p, t13);
      append(p, code);
      append(code, a);
      append(a, t22);
      append(a, t32);
      append(a, t4);
      insert(target, t5, anchor);
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx3, [dirty]) {
      if (dirty & 1 && t2_value !== (t2_value = ctx3[0].meta.filename + ""))
        set_data(t22, t2_value);
      if (dirty & 1 && t4_value !== (t4_value = ctx3[0].meta.lineno + ""))
        set_data(t4, t4_value);
      if (dirty & 1 && a_href_value !== (a_href_value = urlForSource(ctx3[0]))) {
        attr(a, "href", a_href_value);
      }
      if (ctx3[1] && ctx3[2]) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block17(ctx3);
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(p);
      if (detaching)
        detach(t5);
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
function instance42($$self, $$props, $$invalidate) {
  let { entry } = $$props;
  let { balances_before } = $$props;
  let { balances_after } = $$props;
  $$self.$$set = ($$props2) => {
    if ("entry" in $$props2)
      $$invalidate(0, entry = $$props2.entry);
    if ("balances_before" in $$props2)
      $$invalidate(1, balances_before = $$props2.balances_before);
    if ("balances_after" in $$props2)
      $$invalidate(2, balances_after = $$props2.balances_after);
  };
  return [entry, balances_before, balances_after];
}
var EntryContext = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance42, create_fragment42, safe_not_equal, {
      entry: 0,
      balances_before: 1,
      balances_after: 2
    });
  }
};
var EntryContext_default = EntryContext;

// src/modals/Context.svelte
function create_catch_block(ctx2) {
  let t4;
  return {
    c() {
      t4 = text("Loading entry context failed...");
    },
    m(target, anchor) {
      insert(target, t4, anchor);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(t4);
    }
  };
}
function create_then_block(ctx2) {
  let if_block_anchor;
  let current;
  let if_block = ctx2[4] && create_if_block18(ctx2);
  return {
    c() {
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      if (ctx3[4]) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & 4) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block18(ctx3);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
function create_if_block18(ctx2) {
  let entrycontext;
  let t4;
  let sliceeditor;
  let current;
  entrycontext = new EntryContext_default({
    props: {
      entry: ctx2[4].entry,
      balances_before: ctx2[4].balances_before,
      balances_after: ctx2[4].balances_after
    }
  });
  sliceeditor = new SliceEditor_default({
    props: {
      entry_hash: ctx2[0],
      slice: ctx2[4].slice,
      sha256sum: ctx2[4].sha256sum
    }
  });
  return {
    c() {
      create_component(entrycontext.$$.fragment);
      t4 = space();
      create_component(sliceeditor.$$.fragment);
    },
    m(target, anchor) {
      mount_component(entrycontext, target, anchor);
      insert(target, t4, anchor);
      mount_component(sliceeditor, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const entrycontext_changes = {};
      if (dirty & 4)
        entrycontext_changes.entry = ctx3[4].entry;
      if (dirty & 4)
        entrycontext_changes.balances_before = ctx3[4].balances_before;
      if (dirty & 4)
        entrycontext_changes.balances_after = ctx3[4].balances_after;
      entrycontext.$set(entrycontext_changes);
      const sliceeditor_changes = {};
      if (dirty & 1)
        sliceeditor_changes.entry_hash = ctx3[0];
      if (dirty & 4)
        sliceeditor_changes.slice = ctx3[4].slice;
      if (dirty & 4)
        sliceeditor_changes.sha256sum = ctx3[4].sha256sum;
      sliceeditor.$set(sliceeditor_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(entrycontext.$$.fragment, local);
      transition_in(sliceeditor.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(entrycontext.$$.fragment, local);
      transition_out(sliceeditor.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(entrycontext, detaching);
      if (detaching)
        detach(t4);
      destroy_component(sliceeditor, detaching);
    }
  };
}
function create_pending_block(ctx2) {
  let t4;
  return {
    c() {
      t4 = text("Loading entry context...");
    },
    m(target, anchor) {
      insert(target, t4, anchor);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(t4);
    }
  };
}
function create_default_slot7(ctx2) {
  let div;
  let promise;
  let current;
  let info = {
    ctx: ctx2,
    current: null,
    token: null,
    hasCatch: true,
    pending: create_pending_block,
    then: create_then_block,
    catch: create_catch_block,
    value: 4,
    blocks: [, , ,]
  };
  handle_promise(promise = ctx2[2], info);
  return {
    c() {
      div = element("div");
      info.block.c();
      attr(div, "class", "content");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      info.block.m(div, info.anchor = null);
      info.mount = () => div;
      info.anchor = null;
      current = true;
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      info.ctx = ctx2;
      if (dirty & 4 && promise !== (promise = ctx2[2]) && handle_promise(promise, info)) {
      } else {
        update_await_block_branch(info, ctx2, dirty);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(info.block);
      current = true;
    },
    o(local) {
      for (let i = 0; i < 3; i += 1) {
        const block = info.blocks[i];
        transition_out(block);
      }
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(div);
      info.block.d();
      info.token = null;
      info = null;
    }
  };
}
function create_fragment43(ctx2) {
  let modalbase;
  let current;
  modalbase = new ModalBase_default({
    props: {
      shown: ctx2[1],
      $$slots: { default: [create_default_slot7] },
      $$scope: { ctx: ctx2 }
    }
  });
  return {
    c() {
      create_component(modalbase.$$.fragment);
    },
    m(target, anchor) {
      mount_component(modalbase, target, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      const modalbase_changes = {};
      if (dirty & 2)
        modalbase_changes.shown = ctx3[1];
      if (dirty & 37) {
        modalbase_changes.$$scope = { dirty, ctx: ctx3 };
      }
      modalbase.$set(modalbase_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(modalbase.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(modalbase.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(modalbase, detaching);
    }
  };
}
function instance43($$self, $$props, $$invalidate) {
  let shown;
  let entry_hash;
  let content2;
  let $urlHash;
  component_subscribe($$self, urlHash, ($$value) => $$invalidate(3, $urlHash = $$value));
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 8) {
      $:
        $$invalidate(1, shown = $urlHash.startsWith("context"));
    }
    if ($$self.$$.dirty & 10) {
      $:
        $$invalidate(0, entry_hash = shown ? $urlHash.slice(8) : "");
    }
    if ($$self.$$.dirty & 3) {
      $:
        $$invalidate(2, content2 = shown ? get("context", { entry_hash }) : null);
    }
  };
  return [entry_hash, shown, content2, $urlHash];
}
var Context = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance43, create_fragment43, safe_not_equal, {});
  }
};
var Context_default = Context;

// src/document-upload.ts
function dragover(event, closestTarget) {
  var _a2, _b;
  if (((_a2 = event.dataTransfer) == null ? void 0 : _a2.types.includes("Files")) || ((_b = event.dataTransfer) == null ? void 0 : _b.types.includes("text/uri-list"))) {
    closestTarget.classList.add("dragover");
    event.preventDefault();
  }
}
delegate(document, "dragenter", ".droptarget", dragover);
delegate(document, "dragover", ".droptarget", dragover);
function dragleave(event, closestTarget) {
  closestTarget.classList.remove("dragover");
  event.preventDefault();
}
delegate(document, "dragleave", ".droptarget", dragleave);
var account = writable("");
var hash = writable("");
var files = writable([]);
function drop(event, target) {
  var _a2;
  target.classList.remove("dragover");
  event.preventDefault();
  event.stopPropagation();
  if (!event.dataTransfer) {
    return;
  }
  const targetAccount = target.getAttribute("data-account-name");
  const targetEntry = target.getAttribute("data-entry");
  if (event.dataTransfer.types.includes("Files")) {
    const date5 = (_a2 = target.getAttribute("data-entry-date")) != null ? _a2 : todayAsString();
    const uploadedFiles = [];
    for (const dataTransferFile of event.dataTransfer.files) {
      let { name: name2 } = dataTransferFile;
      if (!/^\d{4}-\d{2}-\d{2}/.test(name2)) {
        name2 = `${date5} ${name2}`;
      }
      uploadedFiles.push({ dataTransferFile, name: name2 });
    }
    account.set(targetAccount != null ? targetAccount : "");
    hash.set(targetEntry != null ? targetEntry : "");
    files.set(uploadedFiles);
  } else if (event.dataTransfer.types.includes("text/uri-list")) {
    const url = event.dataTransfer.getData("URL");
    let filename = new URL(url).searchParams.get("filename");
    if (filename && targetEntry) {
      if (targetAccount && documentHasAccount(filename, targetAccount)) {
        filename = basename(filename);
      }
      put("attach_document", { filename, entry_hash: targetEntry }).then(
        notify,
        (error) => {
          if (error instanceof Error) {
            notify(error.message, "error");
          }
        }
      );
    }
  }
}
delegate(document, "drop", ".droptarget", drop);

// src/modals/DocumentUpload.svelte
function get_each_context23(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[12] = list[i];
  return child_ctx;
}
function get_each_context_18(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[15] = list[i];
  child_ctx[16] = list;
  child_ctx[17] = i;
  return child_ctx;
}
function create_each_block_18(ctx2) {
  let div;
  let input;
  let mounted;
  let dispose;
  function input_input_handler() {
    ctx2[8].call(input, ctx2[16], ctx2[17]);
  }
  return {
    c() {
      div = element("div");
      input = element("input");
      attr(input, "class", "file svelte-18pvuji");
      attr(div, "class", "fieldset svelte-18pvuji");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, input);
      set_input_value(input, ctx2[15].name);
      if (!mounted) {
        dispose = listen(input, "input", input_input_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & 1 && input.value !== ctx2[15].name) {
        set_input_value(input, ctx2[15].name);
      }
    },
    d(detaching) {
      if (detaching)
        detach(div);
      mounted = false;
      dispose();
    }
  };
}
function create_each_block23(ctx2) {
  let option;
  let t_value = ctx2[12] + "";
  let t4;
  let option_value_value;
  return {
    c() {
      option = element("option");
      t4 = text(t_value);
      option.__value = option_value_value = ctx2[12];
      option.value = option.__value;
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t4);
    },
    p(ctx3, dirty) {
      if (dirty & 4 && t_value !== (t_value = ctx3[12] + ""))
        set_data(t4, t_value);
      if (dirty & 4 && option_value_value !== (option_value_value = ctx3[12])) {
        option.__value = option_value_value;
        option.value = option.__value;
      }
    },
    d(detaching) {
      if (detaching)
        detach(option);
    }
  };
}
function create_default_slot8(ctx2) {
  let form;
  let h3;
  let t22;
  let t32;
  let div0;
  let label0;
  let span0;
  let t6;
  let select;
  let t7;
  let div1;
  let label1;
  let span1;
  let t10;
  let accountinput;
  let updating_value;
  let t11;
  let button;
  let current;
  let mounted;
  let dispose;
  let each_value_1 = ctx2[0];
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks_1[i] = create_each_block_18(get_each_context_18(ctx2, each_value_1, i));
  }
  let each_value = ctx2[2];
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block23(get_each_context23(ctx2, each_value, i));
  }
  function accountinput_value_binding(value) {
    ctx2[10](value);
  }
  let accountinput_props = {};
  if (ctx2[4] !== void 0) {
    accountinput_props.value = ctx2[4];
  }
  accountinput = new AccountInput_default({ props: accountinput_props });
  binding_callbacks.push(() => bind(accountinput, "value", accountinput_value_binding));
  return {
    c() {
      form = element("form");
      h3 = element("h3");
      h3.textContent = `${_("Upload file(s)")}:`;
      t22 = space();
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t32 = space();
      div0 = element("div");
      label0 = element("label");
      span0 = element("span");
      span0.textContent = `${_("Documents folder")}:`;
      t6 = space();
      select = element("select");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t7 = space();
      div1 = element("div");
      label1 = element("label");
      span1 = element("span");
      span1.textContent = `${_("Account")}:`;
      t10 = space();
      create_component(accountinput.$$.fragment);
      t11 = space();
      button = element("button");
      button.textContent = `${_("Upload")}`;
      if (ctx2[1] === void 0)
        add_render_callback(() => ctx2[9].call(select));
      attr(div0, "class", "fieldset svelte-18pvuji");
      attr(div1, "class", "fieldset account svelte-18pvuji");
      attr(button, "type", "submit");
    },
    m(target, anchor) {
      insert(target, form, anchor);
      append(form, h3);
      append(form, t22);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].m(form, null);
      }
      append(form, t32);
      append(form, div0);
      append(div0, label0);
      append(label0, span0);
      append(label0, t6);
      append(label0, select);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(select, null);
      }
      select_option(select, ctx2[1]);
      append(form, t7);
      append(form, div1);
      append(div1, label1);
      append(label1, span1);
      append(label1, t10);
      mount_component(accountinput, label1, null);
      append(form, t11);
      append(form, button);
      current = true;
      if (!mounted) {
        dispose = [
          listen(select, "change", ctx2[9]),
          listen(form, "submit", prevent_default(ctx2[6]))
        ];
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if (dirty & 1) {
        each_value_1 = ctx3[0];
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_18(ctx3, each_value_1, i);
          if (each_blocks_1[i]) {
            each_blocks_1[i].p(child_ctx, dirty);
          } else {
            each_blocks_1[i] = create_each_block_18(child_ctx);
            each_blocks_1[i].c();
            each_blocks_1[i].m(form, t32);
          }
        }
        for (; i < each_blocks_1.length; i += 1) {
          each_blocks_1[i].d(1);
        }
        each_blocks_1.length = each_value_1.length;
      }
      if (dirty & 4) {
        each_value = ctx3[2];
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context23(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block23(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(select, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
      if (dirty & 6) {
        select_option(select, ctx3[1]);
      }
      const accountinput_changes = {};
      if (!updating_value && dirty & 16) {
        updating_value = true;
        accountinput_changes.value = ctx3[4];
        add_flush_callback(() => updating_value = false);
      }
      accountinput.$set(accountinput_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(accountinput.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(accountinput.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(form);
      destroy_each(each_blocks_1, detaching);
      destroy_each(each_blocks, detaching);
      destroy_component(accountinput);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_fragment44(ctx2) {
  let modalbase;
  let current;
  modalbase = new ModalBase_default({
    props: {
      shown: ctx2[3],
      closeHandler: ctx2[5],
      $$slots: { default: [create_default_slot8] },
      $$scope: { ctx: ctx2 }
    }
  });
  return {
    c() {
      create_component(modalbase.$$.fragment);
    },
    m(target, anchor) {
      mount_component(modalbase, target, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      const modalbase_changes = {};
      if (dirty & 8)
        modalbase_changes.shown = ctx3[3];
      if (dirty & 262167) {
        modalbase_changes.$$scope = { dirty, ctx: ctx3 };
      }
      modalbase.$set(modalbase_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(modalbase.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(modalbase.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(modalbase, detaching);
    }
  };
}
function instance44($$self, $$props, $$invalidate) {
  let shown;
  let documents;
  let $hash;
  let $account;
  let $files;
  let $options;
  component_subscribe($$self, hash, ($$value) => $$invalidate(11, $hash = $$value));
  component_subscribe($$self, account, ($$value) => $$invalidate(4, $account = $$value));
  component_subscribe($$self, files, ($$value) => $$invalidate(0, $files = $$value));
  component_subscribe($$self, options, ($$value) => $$invalidate(7, $options = $$value));
  let documents_folder = "";
  function closeHandler() {
    set_store_value(files, $files = [], $files);
    set_store_value(account, $account = "", $account);
    set_store_value(hash, $hash = "", $hash);
  }
  async function submit() {
    await Promise.all($files.map(({ dataTransferFile, name: name2 }) => {
      const formData = new FormData();
      formData.append("account", $account);
      formData.append("hash", $hash);
      formData.append("folder", documents_folder);
      formData.append("file", dataTransferFile, name2);
      return put("add_document", formData).then(notify, (error) => {
        if (error instanceof Error) {
          notify(`Upload error: ${error.message}`, "error");
        }
      });
    }));
    closeHandler();
    router_default.reload();
  }
  function input_input_handler(each_value_1, file_index) {
    each_value_1[file_index].name = this.value;
    files.set($files);
  }
  function select_change_handler() {
    documents_folder = select_value(this);
    $$invalidate(1, documents_folder);
    $$invalidate(2, documents), $$invalidate(7, $options);
  }
  function accountinput_value_binding(value) {
    $account = value;
    account.set($account);
  }
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 1) {
      $:
        $$invalidate(3, shown = !!$files.length);
    }
    if ($$self.$$.dirty & 128) {
      $:
        $$invalidate(2, documents = $options.documents);
    }
  };
  return [
    $files,
    documents_folder,
    documents,
    shown,
    $account,
    closeHandler,
    submit,
    $options,
    input_input_handler,
    select_change_handler,
    accountinput_value_binding
  ];
}
var DocumentUpload = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance44, create_fragment44, safe_not_equal, {});
  }
};
var DocumentUpload_default = DocumentUpload;

// src/modals/Export.svelte
function create_if_block19(ctx2) {
  let div;
  let h3;
  let t22;
  let a;
  let t3_value = _("Download currently filtered entries as a Beancount file") + "";
  let t32;
  let a_href_value;
  return {
    c() {
      div = element("div");
      h3 = element("h3");
      h3.textContent = `${_("Export")}:`;
      t22 = space();
      a = element("a");
      t32 = text(t3_value);
      attr(a, "href", a_href_value = urlFor("download-journal"));
      attr(a, "data-remote", "");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, h3);
      append(div, t22);
      append(div, a);
      append(a, t32);
    },
    p: noop,
    d(detaching) {
      if (detaching)
        detach(div);
    }
  };
}
function create_default_slot9(ctx2) {
  let if_block_anchor;
  let if_block = ctx2[0] && create_if_block19(ctx2);
  return {
    c() {
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx3, dirty) {
      if (ctx3[0]) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block19(ctx3);
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    d(detaching) {
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(if_block_anchor);
    }
  };
}
function create_fragment45(ctx2) {
  let modalbase;
  let current;
  modalbase = new ModalBase_default({
    props: {
      shown: ctx2[0],
      $$slots: { default: [create_default_slot9] },
      $$scope: { ctx: ctx2 }
    }
  });
  return {
    c() {
      create_component(modalbase.$$.fragment);
    },
    m(target, anchor) {
      mount_component(modalbase, target, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      const modalbase_changes = {};
      if (dirty & 1)
        modalbase_changes.shown = ctx3[0];
      if (dirty & 5) {
        modalbase_changes.$$scope = { dirty, ctx: ctx3 };
      }
      modalbase.$set(modalbase_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(modalbase.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(modalbase.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(modalbase, detaching);
    }
  };
}
function instance45($$self, $$props, $$invalidate) {
  let shown;
  let $urlHash;
  component_subscribe($$self, urlHash, ($$value) => $$invalidate(1, $urlHash = $$value));
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 2) {
      $:
        $$invalidate(0, shown = $urlHash === "export");
    }
  };
  return [shown, $urlHash];
}
var Export = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance45, create_fragment45, safe_not_equal, {});
  }
};
var Export_default = Export;

// src/modals/Modals.svelte
function create_fragment46(ctx2) {
  let addentry;
  let t03;
  let context;
  let t13;
  let documentupload;
  let t22;
  let export_1;
  let current;
  addentry = new AddEntry_default({});
  context = new Context_default({});
  documentupload = new DocumentUpload_default({});
  export_1 = new Export_default({});
  return {
    c() {
      create_component(addentry.$$.fragment);
      t03 = space();
      create_component(context.$$.fragment);
      t13 = space();
      create_component(documentupload.$$.fragment);
      t22 = space();
      create_component(export_1.$$.fragment);
    },
    m(target, anchor) {
      mount_component(addentry, target, anchor);
      insert(target, t03, anchor);
      mount_component(context, target, anchor);
      insert(target, t13, anchor);
      mount_component(documentupload, target, anchor);
      insert(target, t22, anchor);
      mount_component(export_1, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current)
        return;
      transition_in(addentry.$$.fragment, local);
      transition_in(context.$$.fragment, local);
      transition_in(documentupload.$$.fragment, local);
      transition_in(export_1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(addentry.$$.fragment, local);
      transition_out(context.$$.fragment, local);
      transition_out(documentupload.$$.fragment, local);
      transition_out(export_1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(addentry, detaching);
      if (detaching)
        detach(t03);
      destroy_component(context, detaching);
      if (detaching)
        detach(t13);
      destroy_component(documentupload, detaching);
      if (detaching)
        detach(t22);
      destroy_component(export_1, detaching);
    }
  };
}
var Modals = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, null, create_fragment46, safe_not_equal, {});
  }
};
var Modals_default = Modals;

// src/charts/query-charts.ts
var grouped_chart_validator = array(
  object({ group: string, balance: record(number2) })
);
function parseGroupedQueryChart(json, { currencies: currencies2 }) {
  const grouped = grouped_chart_validator(json);
  if (!grouped.success) {
    return err("No grouped query data");
  }
  const root2 = stratify(
    grouped.value,
    (d) => d.group,
    (account2, d) => {
      var _a2;
      return { account: account2, balance: (_a2 = d == null ? void 0 : d.balance) != null ? _a2 : {} };
    }
  );
  root2.account = "(root)";
  const data = /* @__PURE__ */ new Map();
  currencies2.forEach((currency) => {
    const currencyHierarchy = hierarchy(root2).sum((d) => {
      var _a2;
      return (_a2 = d.balance[currency]) != null ? _a2 : 0;
    }).sort((a, b) => {
      var _a2, _b;
      return ((_a2 = b.value) != null ? _a2 : 0) - ((_b = a.value) != null ? _b : 0);
    });
    if (currencyHierarchy.value !== void 0) {
      data.set(currency, currencyHierarchy);
    }
  });
  return ok({ type: "hierarchy", data });
}
function parseQueryChart(json, ctx2) {
  const tree = parseGroupedQueryChart(json, ctx2);
  if (tree.success) {
    return tree;
  }
  const dated = array(unknown)(json);
  if (dated.success) {
    const bal = balances(dated.value);
    if (bal.success) {
      return bal;
    }
  }
  return err("No query chart found.");
}

// src/stores/query.ts
var query_shell_history = localStorageSyncedStore(
  "query-history",
  array(string),
  () => []
);
function addToHistory(query) {
  if (query) {
    query_shell_history.update((hist) => {
      hist.unshift(query);
      return [...new Set(hist)];
    });
  }
}
function clearHistory() {
  query_shell_history.set([]);
}

// src/query/QueryEditor.svelte
function create_fragment47(ctx2) {
  let form;
  let div;
  let useEditor_action;
  let t03;
  let button;
  let keyboardShortcut_action;
  let mounted;
  let dispose;
  return {
    c() {
      form = element("form");
      div = element("div");
      t03 = space();
      button = element("button");
      button.textContent = `${_("Submit")}`;
      attr(div, "class", "svelte-1wk8z7p");
      attr(button, "type", "submit");
      attr(button, "class", "svelte-1wk8z7p");
      attr(form, "class", "svelte-1wk8z7p");
    },
    m(target, anchor) {
      insert(target, form, anchor);
      append(form, div);
      append(form, t03);
      append(form, button);
      if (!mounted) {
        dispose = [
          action_destroyer(useEditor_action = ctx2[1].call(null, div)),
          action_destroyer(keyboardShortcut_action = keyboardShortcut.call(null, button, "Control+Enter")),
          listen(form, "submit", prevent_default(function() {
            if (is_function(ctx2[0]))
              ctx2[0].apply(this, arguments);
          }))
        ];
        mounted = true;
      }
    },
    p(new_ctx, [dirty]) {
      ctx2 = new_ctx;
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(form);
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance46($$self, $$props, $$invalidate) {
  let { value } = $$props;
  let { submit } = $$props;
  const [editor, useEditor] = initQueryEditor(
    value,
    (s) => {
      $$invalidate(2, value = s.doc.toString());
    },
    _("...enter a BQL query. 'help' to list available commands."),
    submit
  );
  $$self.$$set = ($$props2) => {
    if ("value" in $$props2)
      $$invalidate(2, value = $$props2.value);
    if ("submit" in $$props2)
      $$invalidate(0, submit = $$props2.submit);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 4) {
      $:
        if (value !== editor.state.doc.toString()) {
          editor.dispatch({
            changes: {
              from: 0,
              to: editor.state.doc.length,
              insert: value
            }
          });
        }
    }
  };
  return [submit, useEditor, value];
}
var QueryEditor = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance46, create_fragment47, safe_not_equal, { value: 2, submit: 0 });
  }
};
var QueryEditor_default = QueryEditor;

// src/query/QueryLinks.svelte
function create_if_block20(ctx2) {
  let t03;
  let a0;
  let t13;
  let a0_href_value;
  let t22;
  let a1;
  let t32;
  let a1_href_value;
  let t4;
  let a2;
  let t5;
  let a2_href_value;
  return {
    c() {
      t03 = text(",\n    ");
      a0 = element("a");
      t13 = text("XLS");
      t22 = text("\n    ,\n    ");
      a1 = element("a");
      t32 = text("XLSX");
      t4 = text("\n    , or\n    ");
      a2 = element("a");
      t5 = text("ODS");
      attr(a0, "href", a0_href_value = ctx2[2](ctx2[0], "xls"));
      attr(a0, "data-remote", "");
      attr(a1, "href", a1_href_value = ctx2[2](ctx2[0], "xlsx"));
      attr(a1, "data-remote", "");
      attr(a2, "href", a2_href_value = ctx2[2](ctx2[0], "ods"));
      attr(a2, "data-remote", "");
    },
    m(target, anchor) {
      insert(target, t03, anchor);
      insert(target, a0, anchor);
      append(a0, t13);
      insert(target, t22, anchor);
      insert(target, a1, anchor);
      append(a1, t32);
      insert(target, t4, anchor);
      insert(target, a2, anchor);
      append(a2, t5);
    },
    p(ctx3, dirty) {
      if (dirty & 1 && a0_href_value !== (a0_href_value = ctx3[2](ctx3[0], "xls"))) {
        attr(a0, "href", a0_href_value);
      }
      if (dirty & 1 && a1_href_value !== (a1_href_value = ctx3[2](ctx3[0], "xlsx"))) {
        attr(a1, "href", a1_href_value);
      }
      if (dirty & 1 && a2_href_value !== (a2_href_value = ctx3[2](ctx3[0], "ods"))) {
        attr(a2, "href", a2_href_value);
      }
    },
    d(detaching) {
      if (detaching)
        detach(t03);
      if (detaching)
        detach(a0);
      if (detaching)
        detach(t22);
      if (detaching)
        detach(a1);
      if (detaching)
        detach(t4);
      if (detaching)
        detach(a2);
    }
  };
}
function create_fragment48(ctx2) {
  let span;
  let t03;
  let t1_value = _("Download as") + "";
  let t13;
  let t22;
  let a;
  let t32;
  let a_href_value;
  let t4;
  let t5;
  let if_block = ctx2[1] && create_if_block20(ctx2);
  return {
    c() {
      span = element("span");
      t03 = text("(");
      t13 = text(t1_value);
      t22 = space();
      a = element("a");
      t32 = text("CSV");
      t4 = space();
      if (if_block)
        if_block.c();
      t5 = text("\n  )");
      attr(a, "href", a_href_value = ctx2[2](ctx2[0], "csv"));
      attr(a, "data-remote", "");
      attr(span, "class", "svelte-bt1doq");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t03);
      append(span, t13);
      append(span, t22);
      append(span, a);
      append(a, t32);
      append(span, t4);
      if (if_block)
        if_block.m(span, null);
      append(span, t5);
    },
    p(ctx3, [dirty]) {
      if (dirty & 1 && a_href_value !== (a_href_value = ctx3[2](ctx3[0], "csv"))) {
        attr(a, "href", a_href_value);
      }
      if (ctx3[1]) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block20(ctx3);
          if_block.c();
          if_block.m(span, t5);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(span);
      if (if_block)
        if_block.d();
    }
  };
}
function instance47($$self, $$props, $$invalidate) {
  let $HAVE_EXCEL;
  component_subscribe($$self, HAVE_EXCEL, ($$value) => $$invalidate(1, $HAVE_EXCEL = $$value));
  let { query } = $$props;
  function queryUrl(query_string, format3) {
    return urlFor(`download-query/query_result.${format3}`, { query_string });
  }
  $$self.$$set = ($$props2) => {
    if ("query" in $$props2)
      $$invalidate(0, query = $$props2.query);
  };
  return [query, $HAVE_EXCEL, queryUrl];
}
var QueryLinks = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance47, create_fragment48, safe_not_equal, { query: 0 });
  }
};
var QueryLinks_default = QueryLinks;

// src/query/ReadonlyQueryEditor.svelte
function create_fragment49(ctx2) {
  let pre;
  let useEditor_action;
  let mounted;
  let dispose;
  return {
    c() {
      pre = element("pre");
    },
    m(target, anchor) {
      insert(target, pre, anchor);
      if (!mounted) {
        dispose = action_destroyer(useEditor_action = ctx2[0].call(null, pre));
        mounted = true;
      }
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(pre);
      mounted = false;
      dispose();
    }
  };
}
function instance48($$self, $$props, $$invalidate) {
  let { value } = $$props;
  const [, useEditor] = initReadonlyQueryEditor(value);
  $$self.$$set = ($$props2) => {
    if ("value" in $$props2)
      $$invalidate(1, value = $$props2.value);
  };
  return [useEditor, value];
}
var ReadonlyQueryEditor = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance48, create_fragment49, safe_not_equal, { value: 1 });
  }
};
var ReadonlyQueryEditor_default = ReadonlyQueryEditor;

// src/query/Query.svelte
function get_each_context24(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[19] = list[i][0];
  child_ctx[20] = list[i][1].result;
  child_ctx[21] = list[i][1].error;
  child_ctx[22] = list;
  child_ctx[23] = i;
  return child_ctx;
}
function create_if_block_35(ctx2) {
  let span;
  let t4;
  let querylinks;
  let current;
  querylinks = new QueryLinks_default({
    props: { query: ctx2[19] }
  });
  return {
    c() {
      span = element("span");
      t4 = space();
      create_component(querylinks.$$.fragment);
      attr(span, "class", "spacer");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      insert(target, t4, anchor);
      mount_component(querylinks, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const querylinks_changes = {};
      if (dirty & 4)
        querylinks_changes.query = ctx3[19];
      querylinks.$set(querylinks_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(querylinks.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(querylinks.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(span);
      if (detaching)
        detach(t4);
      destroy_component(querylinks, detaching);
    }
  };
}
function create_if_block_27(ctx2) {
  let t_value = ctx2[21] + "";
  let t4;
  return {
    c() {
      t4 = text(t_value);
    },
    m(target, anchor) {
      insert(target, t4, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & 4 && t_value !== (t_value = ctx3[21] + ""))
        set_data(t4, t_value);
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching)
        detach(t4);
    }
  };
}
function create_if_block21(ctx2) {
  let t4;
  let html_tag;
  let raw_value = ctx2[20].table + "";
  let html_anchor;
  let current;
  let if_block = ctx2[20].chart && create_if_block_112(ctx2);
  return {
    c() {
      if (if_block)
        if_block.c();
      t4 = space();
      html_tag = new HtmlTag(false);
      html_anchor = empty();
      html_tag.a = html_anchor;
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, t4, anchor);
      html_tag.m(raw_value, target, anchor);
      insert(target, html_anchor, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      if (ctx3[20].chart) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & 4) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_112(ctx3);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(t4.parentNode, t4);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
      if ((!current || dirty & 4) && raw_value !== (raw_value = ctx3[20].table + ""))
        html_tag.p(raw_value);
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (if_block)
        if_block.d(detaching);
      if (detaching)
        detach(t4);
      if (detaching)
        detach(html_anchor);
      if (detaching)
        html_tag.d();
    }
  };
}
function create_if_block_112(ctx2) {
  let chart;
  let current;
  chart = new Chart_default({
    props: { chart: ctx2[20].chart }
  });
  return {
    c() {
      create_component(chart.$$.fragment);
    },
    m(target, anchor) {
      mount_component(chart, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const chart_changes = {};
      if (dirty & 4)
        chart_changes.chart = ctx3[20].chart;
      chart.$set(chart_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(chart.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(chart.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(chart, detaching);
    }
  };
}
function create_each_block24(key_1, ctx2) {
  let details;
  let summary;
  let readonlyqueryeditor;
  let t03;
  let t13;
  let div;
  let current_block_type_index;
  let if_block1;
  let t22;
  let history_item = ctx2[19];
  let current;
  let mounted;
  let dispose;
  readonlyqueryeditor = new ReadonlyQueryEditor_default({
    props: { value: ctx2[19] }
  });
  let if_block0 = ctx2[20] && create_if_block_35(ctx2);
  function click_handler() {
    return ctx2[8](ctx2[19]);
  }
  const if_block_creators = [create_if_block21, create_if_block_27];
  const if_blocks = [];
  function select_block_type(ctx3, dirty) {
    if (ctx3[20])
      return 0;
    if (ctx3[21])
      return 1;
    return -1;
  }
  if (~(current_block_type_index = select_block_type(ctx2, -1))) {
    if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
  }
  const assign_details = () => ctx2[9](details, history_item);
  const unassign_details = () => ctx2[9](null, history_item);
  return {
    key: key_1,
    first: null,
    c() {
      details = element("details");
      summary = element("summary");
      create_component(readonlyqueryeditor.$$.fragment);
      t03 = space();
      if (if_block0)
        if_block0.c();
      t13 = space();
      div = element("div");
      if (if_block1)
        if_block1.c();
      t22 = space();
      attr(div, "class", "svelte-1kdrm0n");
      attr(details, "class", "svelte-1kdrm0n");
      toggle_class(details, "error", ctx2[21]);
      this.first = details;
    },
    m(target, anchor) {
      insert(target, details, anchor);
      append(details, summary);
      mount_component(readonlyqueryeditor, summary, null);
      append(summary, t03);
      if (if_block0)
        if_block0.m(summary, null);
      append(details, t13);
      append(details, div);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(div, null);
      }
      append(details, t22);
      assign_details();
      current = true;
      if (!mounted) {
        dispose = listen(summary, "click", click_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      const readonlyqueryeditor_changes = {};
      if (dirty & 4)
        readonlyqueryeditor_changes.value = ctx2[19];
      readonlyqueryeditor.$set(readonlyqueryeditor_changes);
      if (ctx2[20]) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty & 4) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_35(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(summary, null);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2, dirty);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        }
      } else {
        if (if_block1) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block1 = if_blocks[current_block_type_index];
          if (!if_block1) {
            if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block1.c();
          } else {
            if_block1.p(ctx2, dirty);
          }
          transition_in(if_block1, 1);
          if_block1.m(div, null);
        } else {
          if_block1 = null;
        }
      }
      if (history_item !== ctx2[19]) {
        unassign_details();
        history_item = ctx2[19];
        assign_details();
      }
      if (!current || dirty & 4) {
        toggle_class(details, "error", ctx2[21]);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(readonlyqueryeditor.$$.fragment, local);
      transition_in(if_block0);
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(readonlyqueryeditor.$$.fragment, local);
      transition_out(if_block0);
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (detaching)
        detach(details);
      destroy_component(readonlyqueryeditor);
      if (if_block0)
        if_block0.d();
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d();
      }
      unassign_details();
      mounted = false;
      dispose();
    }
  };
}
function create_fragment50(ctx2) {
  let queryeditor;
  let updating_value;
  let t4;
  let div;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let current;
  function queryeditor_value_binding(value) {
    ctx2[7](value);
  }
  let queryeditor_props = { submit: ctx2[3] };
  if (ctx2[0] !== void 0) {
    queryeditor_props.value = ctx2[0];
  }
  queryeditor = new QueryEditor_default({ props: queryeditor_props });
  binding_callbacks.push(() => bind(queryeditor, "value", queryeditor_value_binding));
  let each_value = ctx2[2];
  const get_key = (ctx3) => ctx3[19];
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context24(ctx2, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block24(key, child_ctx));
  }
  return {
    c() {
      create_component(queryeditor.$$.fragment);
      t4 = space();
      div = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(div, "class", "svelte-1kdrm0n");
    },
    m(target, anchor) {
      mount_component(queryeditor, target, anchor);
      insert(target, t4, anchor);
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].m(div, null);
      }
      current = true;
    },
    p(ctx3, [dirty]) {
      const queryeditor_changes = {};
      if (!updating_value && dirty & 1) {
        updating_value = true;
        queryeditor_changes.value = ctx3[0];
        add_flush_callback(() => updating_value = false);
      }
      queryeditor.$set(queryeditor_changes);
      if (dirty & 22) {
        each_value = ctx3[2];
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx3, each_value, each_1_lookup, div, outro_and_destroy_block, create_each_block24, null, get_each_context24);
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(queryeditor.$$.fragment, local);
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      transition_out(queryeditor.$$.fragment, local);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      destroy_component(queryeditor, detaching);
      if (detaching)
        detach(t4);
      if (detaching)
        detach(div);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
function instance49($$self, $$props, $$invalidate) {
  let query_result_array;
  let $chartContext;
  let $query_shell_history;
  component_subscribe($$self, chartContext, ($$value) => $$invalidate(10, $chartContext = $$value));
  component_subscribe($$self, query_shell_history, ($$value) => $$invalidate(6, $query_shell_history = $$value));
  var __defProp2 = Object.defineProperty;
  var __getOwnPropSymbols2 = Object.getOwnPropertySymbols;
  var __hasOwnProp2 = Object.prototype.hasOwnProperty;
  var __propIsEnum2 = Object.prototype.propertyIsEnumerable;
  var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, {
    enumerable: true,
    configurable: true,
    writable: true,
    value
  }) : obj[key] = value;
  var __spreadValues2 = (a, b) => {
    for (var prop in b || (b = {}))
      if (__hasOwnProp2.call(b, prop))
        __defNormalProp2(a, prop, b[prop]);
    if (__getOwnPropSymbols2)
      for (var prop of __getOwnPropSymbols2(b)) {
        if (__propIsEnum2.call(b, prop))
          __defNormalProp2(a, prop, b[prop]);
      }
    return a;
  };
  let query_string = "";
  const resultElems = {};
  const query_results = {};
  async function setResult(query, res2) {
    addToHistory(query);
    $$invalidate(5, query_results[query] = res2, query_results);
    await tick();
    const url = new URL(window.location.href);
    url.searchParams.set("query_string", query);
    window.history.replaceState(null, "", url.toString());
    resultElems[query].setAttribute("open", "true");
  }
  async function clearResults() {
    clearHistory();
    await tick();
    const url = new URL(window.location.href);
    $$invalidate(0, query_string = "");
    url.searchParams.set("query_string", query_string);
    window.history.replaceState(null, "", url.toString());
  }
  function submit() {
    const query = query_string;
    if (!query) {
      return;
    }
    if (query.trim().toUpperCase() === "CLEAR") {
      clearResults().catch(log_error);
      return;
    }
    get("query_result", __spreadValues2({ query_string: query }, getFilterParams())).then(
      (res2) => {
        const r = parseQueryChart(res2.chart, $chartContext);
        const chart = r.success ? r.value : null;
        setResult(query, { result: { chart, table: res2.table } }).catch(log_error);
      },
      (error) => {
        if (typeof error === "string") {
          setResult(query, { error }).catch(log_error);
        } else {
          setResult(query, {
            error: "Received invalid data as query error."
          }).catch(log_error);
        }
      }
    );
  }
  function click(query) {
    if (!query_results[query]) {
      $$invalidate(0, query_string = query);
      submit();
    }
  }
  onMount(() => {
    const url = new URL(window.location.href);
    $$invalidate(0, query_string = url.searchParams.get("query_string") || "");
    if (query_string) {
      submit();
    }
  });
  function queryeditor_value_binding(value) {
    query_string = value;
    $$invalidate(0, query_string);
  }
  const click_handler = (history_item) => click(history_item);
  function details_binding($$value, history_item) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      resultElems[history_item] = $$value;
      $$invalidate(1, resultElems);
    });
  }
  $$self.$$.update = () => {
    if ($$self.$$.dirty & 96) {
      $:
        $$invalidate(2, query_result_array = $query_shell_history.map((item) => [item, query_results[item] || {}]));
    }
  };
  return [
    query_string,
    resultElems,
    query_result_array,
    submit,
    click,
    query_results,
    $query_shell_history,
    queryeditor_value_binding,
    click_handler,
    details_binding
  ];
}
var Query = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance49, create_fragment50, safe_not_equal, {});
  }
};
var Query_default = Query;

// src/sidebar/AccountSelector.svelte
function create_fragment51(ctx2) {
  let autocompleteinput;
  let updating_value;
  let current;
  function autocompleteinput_value_binding(value) {
    ctx2[3](value);
  }
  let autocompleteinput_props = {
    placeholder: _("Go to account"),
    suggestions: ctx2[1],
    className: "account-selector",
    key: "g a"
  };
  if (ctx2[0] !== void 0) {
    autocompleteinput_props.value = ctx2[0];
  }
  autocompleteinput = new AutocompleteInput_default({ props: autocompleteinput_props });
  binding_callbacks.push(() => bind(autocompleteinput, "value", autocompleteinput_value_binding));
  autocompleteinput.$on("select", ctx2[2]);
  autocompleteinput.$on("enter", ctx2[2]);
  return {
    c() {
      create_component(autocompleteinput.$$.fragment);
    },
    m(target, anchor) {
      mount_component(autocompleteinput, target, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      const autocompleteinput_changes = {};
      if (dirty & 2)
        autocompleteinput_changes.suggestions = ctx3[1];
      if (!updating_value && dirty & 1) {
        updating_value = true;
        autocompleteinput_changes.value = ctx3[0];
        add_flush_callback(() => updating_value = false);
      }
      autocompleteinput.$set(autocompleteinput_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(autocompleteinput.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(autocompleteinput.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(autocompleteinput, detaching);
    }
  };
}
function instance50($$self, $$props, $$invalidate) {
  let $accounts;
  component_subscribe($$self, accounts, ($$value) => $$invalidate(1, $accounts = $$value));
  let value = "";
  function select(ev) {
    if (value) {
      router_default.navigate(urlForAccount(value));
      ev.detail.blur();
      $$invalidate(0, value = "");
    }
  }
  function autocompleteinput_value_binding(value$1) {
    value = value$1;
    $$invalidate(0, value);
  }
  return [value, $accounts, select, autocompleteinput_value_binding];
}
var AccountSelector = class extends SvelteComponent {
  constructor(options2) {
    super();
    init(this, options2, instance50, create_fragment51, safe_not_equal, {});
  }
};
var AccountSelector_default = AccountSelector;

// src/svelte-custom-elements.ts
var components = /* @__PURE__ */ new Map([
  ["charts", ChartSwitcher_default],
  ["documents", Documents_default],
  ["editor", SourceEditor_default],
  ["import", Import_default],
  ["query", Query_default],
  ["account-selector", AccountSelector_default],
  ["filter-form", FilterForm_default],
  ["modals", Modals_default],
  ["conversion-and-interval", ConversionAndInterval_default]
]);
var SvelteCustomElement = class extends HTMLElement {
  connectedCallback() {
    if (this.component) {
      return;
    }
    const type = this.getAttribute("type");
    if (!type) {
      throw new Error("Component is missing type");
    }
    const Cls = components.get(type);
    if (!Cls) {
      throw new Error("Invalid component");
    }
    const props = {};
    const script = this.querySelector("script");
    if (script && script.type === "application/json") {
      props.data = JSON.parse(script.innerHTML);
    }
    this.component = new Cls({ target: this, props });
  }
  disconnectedCallback() {
    var _a2;
    (_a2 = this.component) == null ? void 0 : _a2.$destroy();
    this.component = void 0;
  }
};

// src/tree-table.ts
var TreeTable = class extends HTMLElement {
  constructor() {
    super();
    const expandAllLink = this.querySelector(".expand-all");
    expandAllLink == null ? void 0 : expandAllLink.addEventListener("click", () => {
      expandAllLink.classList.add("hidden");
      this.querySelectorAll(".toggled").forEach((el) => {
        el.classList.remove("toggled");
      });
    });
    delegate(this, "click", "span.has-children", (event) => {
      const { target } = event;
      if (!(target instanceof HTMLElement) || target instanceof HTMLAnchorElement) {
        return;
      }
      const row = target.closest("li");
      if (!row) {
        return;
      }
      const willShow = row.classList.contains("toggled");
      if (event.shiftKey) {
        this.querySelectorAll("li").forEach((el) => {
          el.classList.toggle("toggled", !willShow);
        });
      }
      if (event.ctrlKey || event.metaKey) {
        this.querySelectorAll("li").forEach((el) => {
          el.classList.toggle("toggled", willShow);
        });
      }
      row.classList.toggle("toggled");
      expandAllLink == null ? void 0 : expandAllLink.classList.toggle(
        "hidden",
        !this.querySelectorAll(".toggled").length
      );
    });
  }
};

// src/main.ts
function defineCustomElements() {
  customElements.define("beancount-textarea", BeancountTextarea, {
    extends: "textarea"
  });
  customElements.define("copyable-text", CopyableText);
  customElements.define("fava-journal", FavaJournal);
  customElements.define("sortable-table", SortableTable, { extends: "table" });
  customElements.define("tree-table", TreeTable);
  customElements.define("svelte-component", SvelteCustomElement);
}
var page_title_validator = object({
  documentTitle: string,
  pageTitle: string
});
function updatePageTitle() {
  const v = getScriptTagValue("#page-title", page_title_validator);
  if (v.success) {
    document.title = v.value.documentTitle;
    const pageTitle = document.querySelector("h1 strong");
    if (pageTitle) {
      pageTitle.innerHTML = v.value.pageTitle;
    }
  } else {
    log_error(`Loading page title failed: ${v.value}`);
  }
}
router_default.on("page-loaded", () => {
  var _a2, _b, _c;
  rawLedgerData.set((_b = (_a2 = document.getElementById("ledger-data")) == null ? void 0 : _a2.innerHTML) != null ? _b : "");
  updatePageTitle();
  initCurrentKeyboardShortcuts();
  (_c = document.getElementById("reload-page")) == null ? void 0 : _c.classList.add("hidden");
  updateSidebar();
});
function doPoll() {
  get("changed").then((changed) => {
    var _a2;
    if (changed) {
      if (get_store_value(fava_options).auto_reload) {
        router_default.reload();
      } else {
        (_a2 = document.getElementById("reload-page")) == null ? void 0 : _a2.classList.remove("hidden");
        get("errors").then((count2) => errorCount.set(count2), log_error);
        notify(_("File change detected. Click to reload."), "warning", () => {
          router_default.reload();
        });
      }
    }
  }, log_error);
}
function init2() {
  var _a2, _b, _c;
  rawLedgerData.set((_b = (_a2 = document.getElementById("ledger-data")) == null ? void 0 : _a2.innerHTML) != null ? _b : "");
  router_default.init();
  setStoreValuesFromURL();
  syncStoreValuesToURL();
  initSidebar();
  initGlobalKeyboardShortcuts();
  defineCustomElements();
  setInterval(doPoll, 5e3);
  (_c = document.getElementById("reload-page")) == null ? void 0 : _c.addEventListener("click", () => {
    router_default.reload();
  });
  ledgerData.subscribe((val) => {
    errorCount.set(val.errors);
  });
  router_default.trigger("page-loaded");
}
init2();
/*! (c) Andrea Giammarchi - ISC */
/*! (c) Andrea Giammarchi @webreflection ISC */
