var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x2)(function(x2) {
  if (typeof require !== "undefined")
    return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x2 + '" is not supported');
});
var __commonJS = (cb, mod) => function __require2() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key2 of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key2) && key2 !== except)
        __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));

// node_modules/web-tree-sitter/tree-sitter.js
var require_tree_sitter = __commonJS({
  "node_modules/web-tree-sitter/tree-sitter.js"(exports, module) {
    var Module = void 0 !== Module ? Module : {};
    var TreeSitter = function() {
      var initPromise, document = "object" == typeof window ? { currentScript: window.document.currentScript } : null;
      class Parser {
        constructor() {
          this.initialize();
        }
        initialize() {
          throw new Error("cannot construct a Parser before calling `init()`");
        }
        static init(moduleOptions) {
          return initPromise || (Module = Object.assign({}, Module, moduleOptions), initPromise = new Promise((resolveInitPromise) => {
            var moduleOverrides = Object.assign({}, Module), arguments_ = [], thisProgram = "./this.program", quit_ = (e3, t4) => {
              throw t4;
            }, ENVIRONMENT_IS_WEB = "object" == typeof window, ENVIRONMENT_IS_WORKER = "function" == typeof importScripts, ENVIRONMENT_IS_NODE = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, scriptDirectory = "", read_, readAsync, readBinary, setWindowTitle;
            function locateFile(e3) {
              return Module.locateFile ? Module.locateFile(e3, scriptDirectory) : scriptDirectory + e3;
            }
            if (ENVIRONMENT_IS_NODE) {
              var fs = __require("fs"), nodePath = __require("path");
              scriptDirectory = ENVIRONMENT_IS_WORKER ? nodePath.dirname(scriptDirectory) + "/" : __dirname + "/", read_ = (e3, t4) => (e3 = isFileURI(e3) ? new URL(e3) : nodePath.normalize(e3), fs.readFileSync(e3, t4 ? void 0 : "utf8")), readBinary = (e3) => {
                var t4 = read_(e3, true);
                return t4.buffer || (t4 = new Uint8Array(t4)), t4;
              }, readAsync = (e3, t4, r, _2 = true) => {
                e3 = isFileURI(e3) ? new URL(e3) : nodePath.normalize(e3), fs.readFile(e3, _2 ? void 0 : "utf8", (e4, s) => {
                  e4 ? r(e4) : t4(_2 ? s.buffer : s);
                });
              }, !Module.thisProgram && process.argv.length > 1 && (thisProgram = process.argv[1].replace(/\\/g, "/")), arguments_ = process.argv.slice(2), "undefined" != typeof module && (module.exports = Module), quit_ = (e3, t4) => {
                throw process.exitCode = e3, t4;
              }, Module.inspect = () => "[Emscripten Module object]";
            } else
              (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) && (ENVIRONMENT_IS_WORKER ? scriptDirectory = self.location.href : void 0 !== document && document.currentScript && (scriptDirectory = document.currentScript.src), scriptDirectory = 0 !== scriptDirectory.indexOf("blob:") ? scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1) : "", read_ = (e3) => {
                var t4 = new XMLHttpRequest();
                return t4.open("GET", e3, false), t4.send(null), t4.responseText;
              }, ENVIRONMENT_IS_WORKER && (readBinary = (e3) => {
                var t4 = new XMLHttpRequest();
                return t4.open("GET", e3, false), t4.responseType = "arraybuffer", t4.send(null), new Uint8Array(t4.response);
              }), readAsync = (e3, t4, r) => {
                var _2 = new XMLHttpRequest();
                _2.open("GET", e3, true), _2.responseType = "arraybuffer", _2.onload = () => {
                  200 == _2.status || 0 == _2.status && _2.response ? t4(_2.response) : r();
                }, _2.onerror = r, _2.send(null);
              }, setWindowTitle = (e3) => document.title = e3);
            var out = Module.print || console.log.bind(console), err = Module.printErr || console.warn.bind(console);
            Object.assign(Module, moduleOverrides), moduleOverrides = null, Module.arguments && (arguments_ = Module.arguments), Module.thisProgram && (thisProgram = Module.thisProgram), Module.quit && (quit_ = Module.quit);
            var dynamicLibraries = Module.dynamicLibraries || [], wasmBinary;
            Module.wasmBinary && (wasmBinary = Module.wasmBinary);
            var noExitRuntime = Module.noExitRuntime || true, wasmMemory;
            "object" != typeof WebAssembly && abort("no native wasm support detected");
            var ABORT = false, EXITSTATUS, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
            function assert(e3, t4) {
              e3 || abort(t4);
            }
            function updateMemoryViews() {
              var e3 = wasmMemory.buffer;
              Module.HEAP8 = HEAP8 = new Int8Array(e3), Module.HEAP16 = HEAP16 = new Int16Array(e3), Module.HEAP32 = HEAP32 = new Int32Array(e3), Module.HEAPU8 = HEAPU8 = new Uint8Array(e3), Module.HEAPU16 = HEAPU16 = new Uint16Array(e3), Module.HEAPU32 = HEAPU32 = new Uint32Array(e3), Module.HEAPF32 = HEAPF32 = new Float32Array(e3), Module.HEAPF64 = HEAPF64 = new Float64Array(e3);
            }
            var INITIAL_MEMORY = Module.INITIAL_MEMORY || 33554432;
            assert(INITIAL_MEMORY >= 65536, "INITIAL_MEMORY should be larger than STACK_SIZE, was " + INITIAL_MEMORY + "! (STACK_SIZE=65536)"), wasmMemory = Module.wasmMemory ? Module.wasmMemory : new WebAssembly.Memory({ initial: INITIAL_MEMORY / 65536, maximum: 32768 }), updateMemoryViews(), INITIAL_MEMORY = wasmMemory.buffer.byteLength;
            var wasmTable = new WebAssembly.Table({ initial: 25, element: "anyfunc" }), __ATPRERUN__ = [], __ATINIT__ = [], __ATMAIN__ = [], __ATPOSTRUN__ = [], __RELOC_FUNCS__ = [], runtimeInitialized = false, runtimeKeepaliveCounter = 0;
            function keepRuntimeAlive() {
              return noExitRuntime || runtimeKeepaliveCounter > 0;
            }
            function preRun() {
              if (Module.preRun)
                for ("function" == typeof Module.preRun && (Module.preRun = [Module.preRun]); Module.preRun.length; )
                  addOnPreRun(Module.preRun.shift());
              callRuntimeCallbacks(__ATPRERUN__);
            }
            function initRuntime() {
              runtimeInitialized = true, callRuntimeCallbacks(__RELOC_FUNCS__), callRuntimeCallbacks(__ATINIT__);
            }
            function preMain() {
              callRuntimeCallbacks(__ATMAIN__);
            }
            function postRun() {
              if (Module.postRun)
                for ("function" == typeof Module.postRun && (Module.postRun = [Module.postRun]); Module.postRun.length; )
                  addOnPostRun(Module.postRun.shift());
              callRuntimeCallbacks(__ATPOSTRUN__);
            }
            function addOnPreRun(e3) {
              __ATPRERUN__.unshift(e3);
            }
            function addOnInit(e3) {
              __ATINIT__.unshift(e3);
            }
            function addOnPostRun(e3) {
              __ATPOSTRUN__.unshift(e3);
            }
            var runDependencies = 0, runDependencyWatcher = null, dependenciesFulfilled = null;
            function getUniqueRunDependency(e3) {
              return e3;
            }
            function addRunDependency(e3) {
              runDependencies++, Module.monitorRunDependencies && Module.monitorRunDependencies(runDependencies);
            }
            function removeRunDependency(e3) {
              if (runDependencies--, Module.monitorRunDependencies && Module.monitorRunDependencies(runDependencies), 0 == runDependencies && (null !== runDependencyWatcher && (clearInterval(runDependencyWatcher), runDependencyWatcher = null), dependenciesFulfilled)) {
                var t4 = dependenciesFulfilled;
                dependenciesFulfilled = null, t4();
              }
            }
            function abort(e3) {
              throw Module.onAbort && Module.onAbort(e3), err(e3 = "Aborted(" + e3 + ")"), ABORT = true, EXITSTATUS = 1, e3 += ". Build with -sASSERTIONS for more info.", new WebAssembly.RuntimeError(e3);
            }
            var dataURIPrefix = "data:application/octet-stream;base64,", wasmBinaryFile, tempDouble, tempI64;
            function isDataURI(e3) {
              return e3.startsWith(dataURIPrefix);
            }
            function isFileURI(e3) {
              return e3.startsWith("file://");
            }
            function getBinary(e3) {
              try {
                if (e3 == wasmBinaryFile && wasmBinary)
                  return new Uint8Array(wasmBinary);
                if (readBinary)
                  return readBinary(e3);
                throw "both async and sync fetching of the wasm failed";
              } catch (e4) {
                abort(e4);
              }
            }
            function getBinaryPromise(e3) {
              if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) {
                if ("function" == typeof fetch && !isFileURI(e3))
                  return fetch(e3, { credentials: "same-origin" }).then((t4) => {
                    if (!t4.ok)
                      throw "failed to load wasm binary file at '" + e3 + "'";
                    return t4.arrayBuffer();
                  }).catch(() => getBinary(e3));
                if (readAsync)
                  return new Promise((t4, r) => {
                    readAsync(e3, (e4) => t4(new Uint8Array(e4)), r);
                  });
              }
              return Promise.resolve().then(() => getBinary(e3));
            }
            function instantiateArrayBuffer(e3, t4, r) {
              return getBinaryPromise(e3).then((e4) => WebAssembly.instantiate(e4, t4)).then((e4) => e4).then(r, (e4) => {
                err("failed to asynchronously prepare wasm: " + e4), abort(e4);
              });
            }
            function instantiateAsync(e3, t4, r, _2) {
              return e3 || "function" != typeof WebAssembly.instantiateStreaming || isDataURI(t4) || isFileURI(t4) || ENVIRONMENT_IS_NODE || "function" != typeof fetch ? instantiateArrayBuffer(t4, r, _2) : fetch(t4, { credentials: "same-origin" }).then((e4) => WebAssembly.instantiateStreaming(e4, r).then(_2, function(e6) {
                return err("wasm streaming compile failed: " + e6), err("falling back to ArrayBuffer instantiation"), instantiateArrayBuffer(t4, r, _2);
              }));
            }
            function createWasm() {
              var e3 = { env: wasmImports, wasi_snapshot_preview1: wasmImports, "GOT.mem": new Proxy(wasmImports, GOTHandler), "GOT.func": new Proxy(wasmImports, GOTHandler) };
              function t4(e4, t5) {
                var r = e4.exports;
                r = relocateExports(r, 1024);
                var _2 = getDylinkMetadata(t5);
                return _2.neededDynlibs && (dynamicLibraries = _2.neededDynlibs.concat(dynamicLibraries)), mergeLibSymbols(r, "main"), Module.asm = r, addOnInit(Module.asm.__wasm_call_ctors), __RELOC_FUNCS__.push(Module.asm.__wasm_apply_data_relocs), removeRunDependency("wasm-instantiate"), r;
              }
              if (addRunDependency("wasm-instantiate"), Module.instantiateWasm)
                try {
                  return Module.instantiateWasm(e3, t4);
                } catch (e4) {
                  return err("Module.instantiateWasm callback failed with error: " + e4), false;
                }
              return instantiateAsync(wasmBinary, wasmBinaryFile, e3, function(e4) {
                t4(e4.instance, e4.module);
              }), {};
            }
            wasmBinaryFile = "tree-sitter.wasm", isDataURI(wasmBinaryFile) || (wasmBinaryFile = locateFile(wasmBinaryFile));
            var ASM_CONSTS = {};
            function ExitStatus(e3) {
              this.name = "ExitStatus", this.message = "Program terminated with exit(" + e3 + ")", this.status = e3;
            }
            var GOT = {}, currentModuleWeakSymbols = /* @__PURE__ */ new Set([]), GOTHandler = { get: function(e3, t4) {
              var r = GOT[t4];
              return r || (r = GOT[t4] = new WebAssembly.Global({ value: "i32", mutable: true })), currentModuleWeakSymbols.has(t4) || (r.required = true), r;
            } };
            function callRuntimeCallbacks(e3) {
              for (; e3.length > 0; )
                e3.shift()(Module);
            }
            var UTF8Decoder = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0;
            function UTF8ArrayToString(e3, t4, r) {
              for (var _2 = t4 + r, s = t4; e3[s] && !(s >= _2); )
                ++s;
              if (s - t4 > 16 && e3.buffer && UTF8Decoder)
                return UTF8Decoder.decode(e3.subarray(t4, s));
              for (var n = ""; t4 < s; ) {
                var a = e3[t4++];
                if (128 & a) {
                  var o = 63 & e3[t4++];
                  if (192 != (224 & a)) {
                    var l = 63 & e3[t4++];
                    if ((a = 224 == (240 & a) ? (15 & a) << 12 | o << 6 | l : (7 & a) << 18 | o << 12 | l << 6 | 63 & e3[t4++]) < 65536)
                      n += String.fromCharCode(a);
                    else {
                      var i = a - 65536;
                      n += String.fromCharCode(55296 | i >> 10, 56320 | 1023 & i);
                    }
                  } else
                    n += String.fromCharCode((31 & a) << 6 | o);
                } else
                  n += String.fromCharCode(a);
              }
              return n;
            }
            function getDylinkMetadata(e3) {
              var t4 = 0, r = 0;
              function _2() {
                for (var r2 = 0, _3 = 1; ; ) {
                  var s2 = e3[t4++];
                  if (r2 += (127 & s2) * _3, _3 *= 128, !(128 & s2))
                    break;
                }
                return r2;
              }
              function s() {
                var r2 = _2();
                return UTF8ArrayToString(e3, (t4 += r2) - r2, r2);
              }
              function n(e4, t5) {
                if (e4)
                  throw new Error(t5);
              }
              var a = "dylink.0";
              if (e3 instanceof WebAssembly.Module) {
                var o = WebAssembly.Module.customSections(e3, a);
                0 === o.length && (a = "dylink", o = WebAssembly.Module.customSections(e3, a)), n(0 === o.length, "need dylink section"), r = (e3 = new Uint8Array(o[0])).length;
              } else {
                n(!(1836278016 == new Uint32Array(new Uint8Array(e3.subarray(0, 24)).buffer)[0]), "need to see wasm magic number"), n(0 !== e3[8], "need the dylink section to be first"), t4 = 9;
                var l = _2();
                r = t4 + l, a = s();
              }
              var i = { neededDynlibs: [], tlsExports: /* @__PURE__ */ new Set(), weakImports: /* @__PURE__ */ new Set() };
              if ("dylink" == a) {
                i.memorySize = _2(), i.memoryAlign = _2(), i.tableSize = _2(), i.tableAlign = _2();
                for (var u = _2(), d = 0; d < u; ++d) {
                  var m = s();
                  i.neededDynlibs.push(m);
                }
              } else {
                n("dylink.0" !== a);
                for (; t4 < r; ) {
                  var c = e3[t4++], p = _2();
                  if (1 === c)
                    i.memorySize = _2(), i.memoryAlign = _2(), i.tableSize = _2(), i.tableAlign = _2();
                  else if (2 === c)
                    for (u = _2(), d = 0; d < u; ++d)
                      m = s(), i.neededDynlibs.push(m);
                  else if (3 === c)
                    for (var h = _2(); h--; ) {
                      var f = s();
                      256 & _2() && i.tlsExports.add(f);
                    }
                  else if (4 === c)
                    for (h = _2(); h--; ) {
                      s(), f = s();
                      1 == (3 & _2()) && i.weakImports.add(f);
                    }
                  else
                    t4 += p;
                }
              }
              return i;
            }
            function getValue(e3, t4 = "i8") {
              switch (t4.endsWith("*") && (t4 = "*"), t4) {
                case "i1":
                case "i8":
                  return HEAP8[e3 >> 0];
                case "i16":
                  return HEAP16[e3 >> 1];
                case "i32":
                case "i64":
                  return HEAP32[e3 >> 2];
                case "float":
                  return HEAPF32[e3 >> 2];
                case "double":
                  return HEAPF64[e3 >> 3];
                case "*":
                  return HEAPU32[e3 >> 2];
                default:
                  abort("invalid type for getValue: " + t4);
              }
            }
            function newDSO(e3, t4, r) {
              var _2 = { refcount: 1 / 0, name: e3, exports: r, global: true };
              return LDSO.loadedLibsByName[e3] = _2, null != t4 && (LDSO.loadedLibsByHandle[t4] = _2), _2;
            }
            var LDSO = { loadedLibsByName: {}, loadedLibsByHandle: {}, init: () => newDSO("__main__", 0, wasmImports) }, ___heap_base = 78144;
            function zeroMemory(e3, t4) {
              return HEAPU8.fill(0, e3, e3 + t4), e3;
            }
            function getMemory(e3) {
              if (runtimeInitialized)
                return zeroMemory(_malloc(e3), e3);
              var t4 = ___heap_base, r = t4 + e3 + 15 & -16;
              return ___heap_base = r, GOT.__heap_base.value = r, t4;
            }
            function isInternalSym(e3) {
              return ["__cpp_exception", "__c_longjmp", "__wasm_apply_data_relocs", "__dso_handle", "__tls_size", "__tls_align", "__set_stack_limits", "_emscripten_tls_init", "__wasm_init_tls", "__wasm_call_ctors", "__start_em_asm", "__stop_em_asm"].includes(e3);
            }
            function uleb128Encode(e3, t4) {
              e3 < 128 ? t4.push(e3) : t4.push(e3 % 128 | 128, e3 >> 7);
            }
            function sigToWasmTypes(e3) {
              for (var t4 = { i: "i32", j: "i32", f: "f32", d: "f64", p: "i32" }, r = { parameters: [], results: "v" == e3[0] ? [] : [t4[e3[0]]] }, _2 = 1; _2 < e3.length; ++_2)
                r.parameters.push(t4[e3[_2]]), "j" === e3[_2] && r.parameters.push("i32");
              return r;
            }
            function generateFuncType(e3, t4) {
              var r = e3.slice(0, 1), _2 = e3.slice(1), s = { i: 127, p: 127, j: 126, f: 125, d: 124 };
              t4.push(96), uleb128Encode(_2.length, t4);
              for (var n = 0; n < _2.length; ++n)
                t4.push(s[_2[n]]);
              "v" == r ? t4.push(0) : t4.push(1, s[r]);
            }
            function convertJsFunctionToWasm(e3, t4) {
              if ("function" == typeof WebAssembly.Function)
                return new WebAssembly.Function(sigToWasmTypes(t4), e3);
              var r = [1];
              generateFuncType(t4, r);
              var _2 = [0, 97, 115, 109, 1, 0, 0, 0, 1];
              uleb128Encode(r.length, _2), _2.push.apply(_2, r), _2.push(2, 7, 1, 1, 101, 1, 102, 0, 0, 7, 5, 1, 1, 102, 0, 0);
              var s = new WebAssembly.Module(new Uint8Array(_2));
              return new WebAssembly.Instance(s, { e: { f: e3 } }).exports.f;
            }
            var wasmTableMirror = [];
            function getWasmTableEntry(e3) {
              var t4 = wasmTableMirror[e3];
              return t4 || (e3 >= wasmTableMirror.length && (wasmTableMirror.length = e3 + 1), wasmTableMirror[e3] = t4 = wasmTable.get(e3)), t4;
            }
            function updateTableMap(e3, t4) {
              if (functionsInTableMap)
                for (var r = e3; r < e3 + t4; r++) {
                  var _2 = getWasmTableEntry(r);
                  _2 && functionsInTableMap.set(_2, r);
                }
            }
            var functionsInTableMap = void 0;
            function getFunctionAddress(e3) {
              return functionsInTableMap || (functionsInTableMap = /* @__PURE__ */ new WeakMap(), updateTableMap(0, wasmTable.length)), functionsInTableMap.get(e3) || 0;
            }
            var freeTableIndexes = [];
            function getEmptyTableSlot() {
              if (freeTableIndexes.length)
                return freeTableIndexes.pop();
              try {
                wasmTable.grow(1);
              } catch (e3) {
                if (!(e3 instanceof RangeError))
                  throw e3;
                throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.";
              }
              return wasmTable.length - 1;
            }
            function setWasmTableEntry(e3, t4) {
              wasmTable.set(e3, t4), wasmTableMirror[e3] = wasmTable.get(e3);
            }
            function addFunction(e3, t4) {
              var r = getFunctionAddress(e3);
              if (r)
                return r;
              var _2 = getEmptyTableSlot();
              try {
                setWasmTableEntry(_2, e3);
              } catch (r2) {
                if (!(r2 instanceof TypeError))
                  throw r2;
                setWasmTableEntry(_2, convertJsFunctionToWasm(e3, t4));
              }
              return functionsInTableMap.set(e3, _2), _2;
            }
            function updateGOT(e3, t4) {
              for (var r in e3)
                if (!isInternalSym(r)) {
                  var _2 = e3[r];
                  r.startsWith("orig$") && (r = r.split("$")[1], t4 = true), GOT[r] || (GOT[r] = new WebAssembly.Global({ value: "i32", mutable: true })), (t4 || 0 == GOT[r].value) && ("function" == typeof _2 ? GOT[r].value = addFunction(_2) : "number" == typeof _2 ? GOT[r].value = _2 : err("unhandled export type for `" + r + "`: " + typeof _2));
                }
            }
            function relocateExports(e3, t4, r) {
              var _2 = {};
              for (var s in e3) {
                var n = e3[s];
                "object" == typeof n && (n = n.value), "number" == typeof n && (n += t4), _2[s] = n;
              }
              return updateGOT(_2, r), _2;
            }
            function isSymbolDefined(e3) {
              var t4 = wasmImports[e3];
              return !(!t4 || t4.stub);
            }
            function resolveGlobalSymbol(e3, t4 = false) {
              var r;
              return t4 && "orig$" + e3 in wasmImports && (e3 = "orig$" + e3), isSymbolDefined(e3) ? r = wasmImports[e3] : e3.startsWith("invoke_") && (r = wasmImports[e3] = createInvokeFunction(e3.split("_")[1])), { sym: r, name: e3 };
            }
            function alignMemory(e3, t4) {
              return Math.ceil(e3 / t4) * t4;
            }
            function dynCallLegacy(e3, t4, r) {
              var _2 = Module["dynCall_" + e3];
              return r && r.length ? _2.apply(null, [t4].concat(r)) : _2.call(null, t4);
            }
            function dynCall(e3, t4, r) {
              return e3.includes("j") ? dynCallLegacy(e3, t4, r) : getWasmTableEntry(t4).apply(null, r);
            }
            function createInvokeFunction(e3) {
              return function() {
                var t4 = stackSave();
                try {
                  return dynCall(e3, arguments[0], Array.prototype.slice.call(arguments, 1));
                } catch (e4) {
                  if (stackRestore(t4), e4 !== e4 + 0)
                    throw e4;
                  _setThrew(1, 0);
                }
              };
            }
            function UTF8ToString(e3, t4) {
              return e3 ? UTF8ArrayToString(HEAPU8, e3, t4) : "";
            }
            function loadWebAssemblyModule(binary, flags, localScope, handle) {
              var metadata = getDylinkMetadata(binary);
              function loadModule() {
                var firstLoad = !handle || !HEAP8[handle + 8 >> 0];
                if (firstLoad) {
                  var memAlign = Math.pow(2, metadata.memoryAlign);
                  memAlign = Math.max(memAlign, 16);
                  var memoryBase = metadata.memorySize ? alignMemory(getMemory(metadata.memorySize + memAlign), memAlign) : 0, tableBase = metadata.tableSize ? wasmTable.length : 0;
                  handle && (HEAP8[handle + 8 >> 0] = 1, HEAPU32[handle + 12 >> 2] = memoryBase, HEAP32[handle + 16 >> 2] = metadata.memorySize, HEAPU32[handle + 20 >> 2] = tableBase, HEAP32[handle + 24 >> 2] = metadata.tableSize);
                } else
                  memoryBase = HEAPU32[handle + 12 >> 2], tableBase = HEAPU32[handle + 20 >> 2];
                var tableGrowthNeeded = tableBase + metadata.tableSize - wasmTable.length, moduleExports;
                function resolveSymbol(e3) {
                  var t4 = resolveGlobalSymbol(e3).sym;
                  return !t4 && localScope && (t4 = localScope[e3]), t4 || (t4 = moduleExports[e3]), t4;
                }
                tableGrowthNeeded > 0 && wasmTable.grow(tableGrowthNeeded);
                var proxyHandler = { get: function(e3, t4) {
                  switch (t4) {
                    case "__memory_base":
                      return memoryBase;
                    case "__table_base":
                      return tableBase;
                  }
                  if (t4 in wasmImports && !wasmImports[t4].stub)
                    return wasmImports[t4];
                  var r;
                  t4 in e3 || (e3[t4] = function() {
                    return r || (r = resolveSymbol(t4)), r.apply(null, arguments);
                  });
                  return e3[t4];
                } }, proxy = new Proxy({}, proxyHandler), info = { "GOT.mem": new Proxy({}, GOTHandler), "GOT.func": new Proxy({}, GOTHandler), env: proxy, wasi_snapshot_preview1: proxy };
                function postInstantiation(instance) {
                  function addEmAsm(addr, body) {
                    for (var args = [], arity = 0; arity < 16 && -1 != body.indexOf("$" + arity); arity++)
                      args.push("$" + arity);
                    args = args.join(",");
                    var func = "(" + args + " ) => { " + body + "};";
                    ASM_CONSTS[start] = eval(func);
                  }
                  if (updateTableMap(tableBase, metadata.tableSize), moduleExports = relocateExports(instance.exports, memoryBase), flags.allowUndefined || reportUndefinedSymbols(), "__start_em_asm" in moduleExports)
                    for (var start = moduleExports.__start_em_asm, stop = moduleExports.__stop_em_asm; start < stop; ) {
                      var jsString = UTF8ToString(start);
                      addEmAsm(start, jsString), start = HEAPU8.indexOf(0, start) + 1;
                    }
                  var applyRelocs = moduleExports.__wasm_apply_data_relocs;
                  applyRelocs && (runtimeInitialized ? applyRelocs() : __RELOC_FUNCS__.push(applyRelocs));
                  var init = moduleExports.__wasm_call_ctors;
                  return init && (runtimeInitialized ? init() : __ATINIT__.push(init)), moduleExports;
                }
                if (flags.loadAsync) {
                  if (binary instanceof WebAssembly.Module) {
                    var instance = new WebAssembly.Instance(binary, info);
                    return Promise.resolve(postInstantiation(instance));
                  }
                  return WebAssembly.instantiate(binary, info).then((e3) => postInstantiation(e3.instance));
                }
                var module = binary instanceof WebAssembly.Module ? binary : new WebAssembly.Module(binary), instance = new WebAssembly.Instance(module, info);
                return postInstantiation(instance);
              }
              return currentModuleWeakSymbols = metadata.weakImports, flags.loadAsync ? metadata.neededDynlibs.reduce((e3, t4) => e3.then(() => loadDynamicLibrary(t4, flags)), Promise.resolve()).then(loadModule) : (metadata.neededDynlibs.forEach((e3) => loadDynamicLibrary(e3, flags, localScope)), loadModule());
            }
            function mergeLibSymbols(e3, t4) {
              for (var r in e3) {
                if (!e3.hasOwnProperty(r))
                  continue;
                const t5 = (t6) => {
                  isSymbolDefined(t6) || (wasmImports[t6] = e3[r]);
                };
                t5(r);
                const _2 = "__main_argc_argv";
                "main" == r && t5(_2), r == _2 && t5("main"), r.startsWith("dynCall_") && !Module.hasOwnProperty(r) && (Module[r] = e3[r]);
              }
            }
            function asyncLoad(e3, t4, r, _2) {
              var s = _2 ? "" : getUniqueRunDependency("al " + e3);
              readAsync(e3, (r2) => {
                assert(r2, 'Loading data file "' + e3 + '" failed (no arrayBuffer).'), t4(new Uint8Array(r2)), s && removeRunDependency(s);
              }, (t5) => {
                if (!r)
                  throw 'Loading data file "' + e3 + '" failed.';
                r();
              }), s && addRunDependency(s);
            }
            function loadDynamicLibrary(e3, t4 = { global: true, nodelete: true }, r, _2) {
              var s = LDSO.loadedLibsByName[e3];
              if (s)
                return t4.global && !s.global && (s.global = true, "loading" !== s.exports && mergeLibSymbols(s.exports, e3)), t4.nodelete && s.refcount !== 1 / 0 && (s.refcount = 1 / 0), s.refcount++, _2 && (LDSO.loadedLibsByHandle[_2] = s), !t4.loadAsync || Promise.resolve(true);
              function n() {
                if (t4.fs && t4.fs.findObject(e3)) {
                  var r2 = t4.fs.readFile(e3, { encoding: "binary" });
                  return r2 instanceof Uint8Array || (r2 = new Uint8Array(r2)), t4.loadAsync ? Promise.resolve(r2) : r2;
                }
                var _3 = locateFile(e3);
                if (t4.loadAsync)
                  return new Promise(function(e4, t5) {
                    asyncLoad(_3, (t6) => e4(t6), t5);
                  });
                if (!readBinary)
                  throw new Error(_3 + ": file not found, and synchronous loading of external files is not available");
                return readBinary(_3);
              }
              function a() {
                if ("undefined" != typeof preloadedWasm && preloadedWasm[e3]) {
                  var s2 = preloadedWasm[e3];
                  return t4.loadAsync ? Promise.resolve(s2) : s2;
                }
                return t4.loadAsync ? n().then((e4) => loadWebAssemblyModule(e4, t4, r, _2)) : loadWebAssemblyModule(n(), t4, r, _2);
              }
              function o(t5) {
                s.global ? mergeLibSymbols(t5, e3) : r && Object.assign(r, t5), s.exports = t5;
              }
              return (s = newDSO(e3, _2, "loading")).refcount = t4.nodelete ? 1 / 0 : 1, s.global = t4.global, t4.loadAsync ? a().then((e4) => (o(e4), true)) : (o(a()), true);
            }
            function reportUndefinedSymbols() {
              for (var e3 in GOT)
                if (0 == GOT[e3].value) {
                  var t4 = resolveGlobalSymbol(e3, true).sym;
                  if (!t4 && !GOT[e3].required)
                    continue;
                  if ("function" == typeof t4)
                    GOT[e3].value = addFunction(t4, t4.sig);
                  else {
                    if ("number" != typeof t4)
                      throw new Error("bad export type for `" + e3 + "`: " + typeof t4);
                    GOT[e3].value = t4;
                  }
                }
            }
            function loadDylibs() {
              dynamicLibraries.length ? (addRunDependency("loadDylibs"), dynamicLibraries.reduce((e3, t4) => e3.then(() => loadDynamicLibrary(t4, { loadAsync: true, global: true, nodelete: true, allowUndefined: true })), Promise.resolve()).then(() => {
                reportUndefinedSymbols(), removeRunDependency("loadDylibs");
              })) : reportUndefinedSymbols();
            }
            function setValue(e3, t4, r = "i8") {
              switch (r.endsWith("*") && (r = "*"), r) {
                case "i1":
                case "i8":
                  HEAP8[e3 >> 0] = t4;
                  break;
                case "i16":
                  HEAP16[e3 >> 1] = t4;
                  break;
                case "i32":
                  HEAP32[e3 >> 2] = t4;
                  break;
                case "i64":
                  tempI64 = [t4 >>> 0, (tempDouble = t4, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[e3 >> 2] = tempI64[0], HEAP32[e3 + 4 >> 2] = tempI64[1];
                  break;
                case "float":
                  HEAPF32[e3 >> 2] = t4;
                  break;
                case "double":
                  HEAPF64[e3 >> 3] = t4;
                  break;
                case "*":
                  HEAPU32[e3 >> 2] = t4;
                  break;
                default:
                  abort("invalid type for setValue: " + r);
              }
            }
            var ___memory_base = new WebAssembly.Global({ value: "i32", mutable: false }, 1024), ___stack_pointer = new WebAssembly.Global({ value: "i32", mutable: true }, 78144), ___table_base = new WebAssembly.Global({ value: "i32", mutable: false }, 1), nowIsMonotonic = true, _emscripten_get_now;
            function __emscripten_get_now_is_monotonic() {
              return nowIsMonotonic;
            }
            function _abort() {
              abort("");
            }
            function _emscripten_date_now() {
              return Date.now();
            }
            function _emscripten_memcpy_big(e3, t4, r) {
              HEAPU8.copyWithin(e3, t4, t4 + r);
            }
            function getHeapMax() {
              return 2147483648;
            }
            function emscripten_realloc_buffer(e3) {
              var t4 = wasmMemory.buffer;
              try {
                return wasmMemory.grow(e3 - t4.byteLength + 65535 >>> 16), updateMemoryViews(), 1;
              } catch (e4) {
              }
            }
            function _emscripten_resize_heap(e3) {
              var t4 = HEAPU8.length;
              e3 >>>= 0;
              var r = getHeapMax();
              if (e3 > r)
                return false;
              for (var _2 = 1; _2 <= 4; _2 *= 2) {
                var s = t4 * (1 + 0.2 / _2);
                if (s = Math.min(s, e3 + 100663296), emscripten_realloc_buffer(Math.min(r, (n = Math.max(e3, s)) + ((a = 65536) - n % a) % a)))
                  return true;
              }
              var n, a;
              return false;
            }
            __emscripten_get_now_is_monotonic.sig = "i", _abort.sig = "v", _emscripten_date_now.sig = "d", _emscripten_get_now = ENVIRONMENT_IS_NODE ? () => {
              var e3 = process.hrtime();
              return 1e3 * e3[0] + e3[1] / 1e6;
            } : () => performance.now(), _emscripten_get_now.sig = "d", _emscripten_memcpy_big.sig = "vppp", _emscripten_resize_heap.sig = "ip";
            var SYSCALLS = { DEFAULT_POLLMASK: 5, calculateAt: function(e3, t4, r) {
              if (PATH.isAbs(t4))
                return t4;
              var _2;
              -100 === e3 ? _2 = FS.cwd() : _2 = SYSCALLS.getStreamFromFD(e3).path;
              if (0 == t4.length) {
                if (!r)
                  throw new FS.ErrnoError(44);
                return _2;
              }
              return PATH.join2(_2, t4);
            }, doStat: function(e3, t4, r) {
              try {
                var _2 = e3(t4);
              } catch (e4) {
                if (e4 && e4.node && PATH.normalize(t4) !== PATH.normalize(FS.getPath(e4.node)))
                  return -54;
                throw e4;
              }
              HEAP32[r >> 2] = _2.dev, HEAP32[r + 8 >> 2] = _2.ino, HEAP32[r + 12 >> 2] = _2.mode, HEAPU32[r + 16 >> 2] = _2.nlink, HEAP32[r + 20 >> 2] = _2.uid, HEAP32[r + 24 >> 2] = _2.gid, HEAP32[r + 28 >> 2] = _2.rdev, tempI64 = [_2.size >>> 0, (tempDouble = _2.size, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[r + 40 >> 2] = tempI64[0], HEAP32[r + 44 >> 2] = tempI64[1], HEAP32[r + 48 >> 2] = 4096, HEAP32[r + 52 >> 2] = _2.blocks;
              var s = _2.atime.getTime(), n = _2.mtime.getTime(), a = _2.ctime.getTime();
              return tempI64 = [Math.floor(s / 1e3) >>> 0, (tempDouble = Math.floor(s / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[r + 56 >> 2] = tempI64[0], HEAP32[r + 60 >> 2] = tempI64[1], HEAPU32[r + 64 >> 2] = s % 1e3 * 1e3, tempI64 = [Math.floor(n / 1e3) >>> 0, (tempDouble = Math.floor(n / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[r + 72 >> 2] = tempI64[0], HEAP32[r + 76 >> 2] = tempI64[1], HEAPU32[r + 80 >> 2] = n % 1e3 * 1e3, tempI64 = [Math.floor(a / 1e3) >>> 0, (tempDouble = Math.floor(a / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[r + 88 >> 2] = tempI64[0], HEAP32[r + 92 >> 2] = tempI64[1], HEAPU32[r + 96 >> 2] = a % 1e3 * 1e3, tempI64 = [_2.ino >>> 0, (tempDouble = _2.ino, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[r + 104 >> 2] = tempI64[0], HEAP32[r + 108 >> 2] = tempI64[1], 0;
            }, doMsync: function(e3, t4, r, _2, s) {
              if (!FS.isFile(t4.node.mode))
                throw new FS.ErrnoError(43);
              if (2 & _2)
                return 0;
              var n = HEAPU8.slice(e3, e3 + r);
              FS.msync(t4, n, s, r, _2);
            }, varargs: void 0, get: function() {
              return SYSCALLS.varargs += 4, HEAP32[SYSCALLS.varargs - 4 >> 2];
            }, getStr: function(e3) {
              return UTF8ToString(e3);
            }, getStreamFromFD: function(e3) {
              var t4 = FS.getStream(e3);
              if (!t4)
                throw new FS.ErrnoError(8);
              return t4;
            } };
            function _fd_close(e3) {
              try {
                var t4 = SYSCALLS.getStreamFromFD(e3);
                return FS.close(t4), 0;
              } catch (e4) {
                if ("undefined" == typeof FS || "ErrnoError" !== e4.name)
                  throw e4;
                return e4.errno;
              }
            }
            function convertI32PairToI53Checked(e3, t4) {
              return t4 + 2097152 >>> 0 < 4194305 - !!e3 ? (e3 >>> 0) + 4294967296 * t4 : NaN;
            }
            function _fd_seek(e3, t4, r, _2, s) {
              try {
                var n = convertI32PairToI53Checked(t4, r);
                if (isNaN(n))
                  return 61;
                var a = SYSCALLS.getStreamFromFD(e3);
                return FS.llseek(a, n, _2), tempI64 = [a.position >>> 0, (tempDouble = a.position, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[s >> 2] = tempI64[0], HEAP32[s + 4 >> 2] = tempI64[1], a.getdents && 0 === n && 0 === _2 && (a.getdents = null), 0;
              } catch (e4) {
                if ("undefined" == typeof FS || "ErrnoError" !== e4.name)
                  throw e4;
                return e4.errno;
              }
            }
            function doWritev(e3, t4, r, _2) {
              for (var s = 0, n = 0; n < r; n++) {
                var a = HEAPU32[t4 >> 2], o = HEAPU32[t4 + 4 >> 2];
                t4 += 8;
                var l = FS.write(e3, HEAP8, a, o, _2);
                if (l < 0)
                  return -1;
                s += l, void 0 !== _2 && (_2 += l);
              }
              return s;
            }
            function _fd_write(e3, t4, r, _2) {
              try {
                var s = doWritev(SYSCALLS.getStreamFromFD(e3), t4, r);
                return HEAPU32[_2 >> 2] = s, 0;
              } catch (e4) {
                if ("undefined" == typeof FS || "ErrnoError" !== e4.name)
                  throw e4;
                return e4.errno;
              }
            }
            function _tree_sitter_log_callback(e3, t4) {
              if (currentLogCallback) {
                const r = UTF8ToString(t4);
                currentLogCallback(r, 0 !== e3);
              }
            }
            function _tree_sitter_parse_callback(e3, t4, r, _2, s) {
              const n = currentParseCallback(t4, { row: r, column: _2 });
              "string" == typeof n ? (setValue(s, n.length, "i32"), stringToUTF16(n, e3, 10240)) : setValue(s, 0, "i32");
            }
            function _proc_exit(e3) {
              EXITSTATUS = e3, keepRuntimeAlive() || (Module.onExit && Module.onExit(e3), ABORT = true), quit_(e3, new ExitStatus(e3));
            }
            function exitJS(e3, t4) {
              EXITSTATUS = e3, _proc_exit(e3);
            }
            function handleException(e3) {
              if (e3 instanceof ExitStatus || "unwind" == e3)
                return EXITSTATUS;
              quit_(1, e3);
            }
            function lengthBytesUTF8(e3) {
              for (var t4 = 0, r = 0; r < e3.length; ++r) {
                var _2 = e3.charCodeAt(r);
                _2 <= 127 ? t4++ : _2 <= 2047 ? t4 += 2 : _2 >= 55296 && _2 <= 57343 ? (t4 += 4, ++r) : t4 += 3;
              }
              return t4;
            }
            function stringToUTF8Array(e3, t4, r, _2) {
              if (!(_2 > 0))
                return 0;
              for (var s = r, n = r + _2 - 1, a = 0; a < e3.length; ++a) {
                var o = e3.charCodeAt(a);
                if (o >= 55296 && o <= 57343)
                  o = 65536 + ((1023 & o) << 10) | 1023 & e3.charCodeAt(++a);
                if (o <= 127) {
                  if (r >= n)
                    break;
                  t4[r++] = o;
                } else if (o <= 2047) {
                  if (r + 1 >= n)
                    break;
                  t4[r++] = 192 | o >> 6, t4[r++] = 128 | 63 & o;
                } else if (o <= 65535) {
                  if (r + 2 >= n)
                    break;
                  t4[r++] = 224 | o >> 12, t4[r++] = 128 | o >> 6 & 63, t4[r++] = 128 | 63 & o;
                } else {
                  if (r + 3 >= n)
                    break;
                  t4[r++] = 240 | o >> 18, t4[r++] = 128 | o >> 12 & 63, t4[r++] = 128 | o >> 6 & 63, t4[r++] = 128 | 63 & o;
                }
              }
              return t4[r] = 0, r - s;
            }
            function stringToUTF8(e3, t4, r) {
              return stringToUTF8Array(e3, HEAPU8, t4, r);
            }
            function stringToUTF8OnStack(e3) {
              var t4 = lengthBytesUTF8(e3) + 1, r = stackAlloc(t4);
              return stringToUTF8(e3, r, t4), r;
            }
            function stringToUTF16(e3, t4, r) {
              if (void 0 === r && (r = 2147483647), r < 2)
                return 0;
              for (var _2 = t4, s = (r -= 2) < 2 * e3.length ? r / 2 : e3.length, n = 0; n < s; ++n) {
                var a = e3.charCodeAt(n);
                HEAP16[t4 >> 1] = a, t4 += 2;
              }
              return HEAP16[t4 >> 1] = 0, t4 - _2;
            }
            function AsciiToString(e3) {
              for (var t4 = ""; ; ) {
                var r = HEAPU8[e3++ >> 0];
                if (!r)
                  return t4;
                t4 += String.fromCharCode(r);
              }
            }
            _fd_close.sig = "ii", _fd_seek.sig = "iijip", _fd_write.sig = "iippp", _proc_exit.sig = "vi";
            var wasmImports = { __heap_base: ___heap_base, __indirect_function_table: wasmTable, __memory_base: ___memory_base, __stack_pointer: ___stack_pointer, __table_base: ___table_base, _emscripten_get_now_is_monotonic: __emscripten_get_now_is_monotonic, abort: _abort, emscripten_get_now: _emscripten_get_now, emscripten_memcpy_big: _emscripten_memcpy_big, emscripten_resize_heap: _emscripten_resize_heap, fd_close: _fd_close, fd_seek: _fd_seek, fd_write: _fd_write, memory: wasmMemory, tree_sitter_log_callback: _tree_sitter_log_callback, tree_sitter_parse_callback: _tree_sitter_parse_callback }, asm = createWasm(), ___wasm_call_ctors = function() {
              return (___wasm_call_ctors = Module.asm.__wasm_call_ctors).apply(null, arguments);
            }, ___wasm_apply_data_relocs = Module.___wasm_apply_data_relocs = function() {
              return (___wasm_apply_data_relocs = Module.___wasm_apply_data_relocs = Module.asm.__wasm_apply_data_relocs).apply(null, arguments);
            }, _malloc = Module._malloc = function() {
              return (_malloc = Module._malloc = Module.asm.malloc).apply(null, arguments);
            }, _calloc = Module._calloc = function() {
              return (_calloc = Module._calloc = Module.asm.calloc).apply(null, arguments);
            }, _realloc = Module._realloc = function() {
              return (_realloc = Module._realloc = Module.asm.realloc).apply(null, arguments);
            }, _free = Module._free = function() {
              return (_free = Module._free = Module.asm.free).apply(null, arguments);
            }, _ts_language_symbol_count = Module._ts_language_symbol_count = function() {
              return (_ts_language_symbol_count = Module._ts_language_symbol_count = Module.asm.ts_language_symbol_count).apply(null, arguments);
            }, _ts_language_state_count = Module._ts_language_state_count = function() {
              return (_ts_language_state_count = Module._ts_language_state_count = Module.asm.ts_language_state_count).apply(null, arguments);
            }, _ts_language_version = Module._ts_language_version = function() {
              return (_ts_language_version = Module._ts_language_version = Module.asm.ts_language_version).apply(null, arguments);
            }, _ts_language_field_count = Module._ts_language_field_count = function() {
              return (_ts_language_field_count = Module._ts_language_field_count = Module.asm.ts_language_field_count).apply(null, arguments);
            }, _ts_language_next_state = Module._ts_language_next_state = function() {
              return (_ts_language_next_state = Module._ts_language_next_state = Module.asm.ts_language_next_state).apply(null, arguments);
            }, _ts_language_symbol_name = Module._ts_language_symbol_name = function() {
              return (_ts_language_symbol_name = Module._ts_language_symbol_name = Module.asm.ts_language_symbol_name).apply(null, arguments);
            }, _ts_language_symbol_for_name = Module._ts_language_symbol_for_name = function() {
              return (_ts_language_symbol_for_name = Module._ts_language_symbol_for_name = Module.asm.ts_language_symbol_for_name).apply(null, arguments);
            }, _ts_language_symbol_type = Module._ts_language_symbol_type = function() {
              return (_ts_language_symbol_type = Module._ts_language_symbol_type = Module.asm.ts_language_symbol_type).apply(null, arguments);
            }, _ts_language_field_name_for_id = Module._ts_language_field_name_for_id = function() {
              return (_ts_language_field_name_for_id = Module._ts_language_field_name_for_id = Module.asm.ts_language_field_name_for_id).apply(null, arguments);
            }, _ts_lookahead_iterator_new = Module._ts_lookahead_iterator_new = function() {
              return (_ts_lookahead_iterator_new = Module._ts_lookahead_iterator_new = Module.asm.ts_lookahead_iterator_new).apply(null, arguments);
            }, _ts_lookahead_iterator_delete = Module._ts_lookahead_iterator_delete = function() {
              return (_ts_lookahead_iterator_delete = Module._ts_lookahead_iterator_delete = Module.asm.ts_lookahead_iterator_delete).apply(null, arguments);
            }, _ts_lookahead_iterator_reset_state = Module._ts_lookahead_iterator_reset_state = function() {
              return (_ts_lookahead_iterator_reset_state = Module._ts_lookahead_iterator_reset_state = Module.asm.ts_lookahead_iterator_reset_state).apply(null, arguments);
            }, _ts_lookahead_iterator_reset = Module._ts_lookahead_iterator_reset = function() {
              return (_ts_lookahead_iterator_reset = Module._ts_lookahead_iterator_reset = Module.asm.ts_lookahead_iterator_reset).apply(null, arguments);
            }, _ts_lookahead_iterator_next = Module._ts_lookahead_iterator_next = function() {
              return (_ts_lookahead_iterator_next = Module._ts_lookahead_iterator_next = Module.asm.ts_lookahead_iterator_next).apply(null, arguments);
            }, _ts_lookahead_iterator_current_symbol = Module._ts_lookahead_iterator_current_symbol = function() {
              return (_ts_lookahead_iterator_current_symbol = Module._ts_lookahead_iterator_current_symbol = Module.asm.ts_lookahead_iterator_current_symbol).apply(null, arguments);
            }, _memset = Module._memset = function() {
              return (_memset = Module._memset = Module.asm.memset).apply(null, arguments);
            }, _memcpy = Module._memcpy = function() {
              return (_memcpy = Module._memcpy = Module.asm.memcpy).apply(null, arguments);
            }, _ts_parser_delete = Module._ts_parser_delete = function() {
              return (_ts_parser_delete = Module._ts_parser_delete = Module.asm.ts_parser_delete).apply(null, arguments);
            }, _ts_parser_reset = Module._ts_parser_reset = function() {
              return (_ts_parser_reset = Module._ts_parser_reset = Module.asm.ts_parser_reset).apply(null, arguments);
            }, _ts_parser_set_language = Module._ts_parser_set_language = function() {
              return (_ts_parser_set_language = Module._ts_parser_set_language = Module.asm.ts_parser_set_language).apply(null, arguments);
            }, _ts_parser_timeout_micros = Module._ts_parser_timeout_micros = function() {
              return (_ts_parser_timeout_micros = Module._ts_parser_timeout_micros = Module.asm.ts_parser_timeout_micros).apply(null, arguments);
            }, _ts_parser_set_timeout_micros = Module._ts_parser_set_timeout_micros = function() {
              return (_ts_parser_set_timeout_micros = Module._ts_parser_set_timeout_micros = Module.asm.ts_parser_set_timeout_micros).apply(null, arguments);
            }, _memmove = Module._memmove = function() {
              return (_memmove = Module._memmove = Module.asm.memmove).apply(null, arguments);
            }, _memcmp = Module._memcmp = function() {
              return (_memcmp = Module._memcmp = Module.asm.memcmp).apply(null, arguments);
            }, _ts_query_new = Module._ts_query_new = function() {
              return (_ts_query_new = Module._ts_query_new = Module.asm.ts_query_new).apply(null, arguments);
            }, _ts_query_delete = Module._ts_query_delete = function() {
              return (_ts_query_delete = Module._ts_query_delete = Module.asm.ts_query_delete).apply(null, arguments);
            }, _iswspace = Module._iswspace = function() {
              return (_iswspace = Module._iswspace = Module.asm.iswspace).apply(null, arguments);
            }, _iswalnum = Module._iswalnum = function() {
              return (_iswalnum = Module._iswalnum = Module.asm.iswalnum).apply(null, arguments);
            }, _ts_query_pattern_count = Module._ts_query_pattern_count = function() {
              return (_ts_query_pattern_count = Module._ts_query_pattern_count = Module.asm.ts_query_pattern_count).apply(null, arguments);
            }, _ts_query_capture_count = Module._ts_query_capture_count = function() {
              return (_ts_query_capture_count = Module._ts_query_capture_count = Module.asm.ts_query_capture_count).apply(null, arguments);
            }, _ts_query_string_count = Module._ts_query_string_count = function() {
              return (_ts_query_string_count = Module._ts_query_string_count = Module.asm.ts_query_string_count).apply(null, arguments);
            }, _ts_query_capture_name_for_id = Module._ts_query_capture_name_for_id = function() {
              return (_ts_query_capture_name_for_id = Module._ts_query_capture_name_for_id = Module.asm.ts_query_capture_name_for_id).apply(null, arguments);
            }, _ts_query_string_value_for_id = Module._ts_query_string_value_for_id = function() {
              return (_ts_query_string_value_for_id = Module._ts_query_string_value_for_id = Module.asm.ts_query_string_value_for_id).apply(null, arguments);
            }, _ts_query_predicates_for_pattern = Module._ts_query_predicates_for_pattern = function() {
              return (_ts_query_predicates_for_pattern = Module._ts_query_predicates_for_pattern = Module.asm.ts_query_predicates_for_pattern).apply(null, arguments);
            }, _ts_tree_copy = Module._ts_tree_copy = function() {
              return (_ts_tree_copy = Module._ts_tree_copy = Module.asm.ts_tree_copy).apply(null, arguments);
            }, _ts_tree_delete = Module._ts_tree_delete = function() {
              return (_ts_tree_delete = Module._ts_tree_delete = Module.asm.ts_tree_delete).apply(null, arguments);
            }, _ts_init = Module._ts_init = function() {
              return (_ts_init = Module._ts_init = Module.asm.ts_init).apply(null, arguments);
            }, _ts_parser_new_wasm = Module._ts_parser_new_wasm = function() {
              return (_ts_parser_new_wasm = Module._ts_parser_new_wasm = Module.asm.ts_parser_new_wasm).apply(null, arguments);
            }, _ts_parser_enable_logger_wasm = Module._ts_parser_enable_logger_wasm = function() {
              return (_ts_parser_enable_logger_wasm = Module._ts_parser_enable_logger_wasm = Module.asm.ts_parser_enable_logger_wasm).apply(null, arguments);
            }, _ts_parser_parse_wasm = Module._ts_parser_parse_wasm = function() {
              return (_ts_parser_parse_wasm = Module._ts_parser_parse_wasm = Module.asm.ts_parser_parse_wasm).apply(null, arguments);
            }, _ts_language_type_is_named_wasm = Module._ts_language_type_is_named_wasm = function() {
              return (_ts_language_type_is_named_wasm = Module._ts_language_type_is_named_wasm = Module.asm.ts_language_type_is_named_wasm).apply(null, arguments);
            }, _ts_language_type_is_visible_wasm = Module._ts_language_type_is_visible_wasm = function() {
              return (_ts_language_type_is_visible_wasm = Module._ts_language_type_is_visible_wasm = Module.asm.ts_language_type_is_visible_wasm).apply(null, arguments);
            }, _ts_tree_root_node_wasm = Module._ts_tree_root_node_wasm = function() {
              return (_ts_tree_root_node_wasm = Module._ts_tree_root_node_wasm = Module.asm.ts_tree_root_node_wasm).apply(null, arguments);
            }, _ts_tree_edit_wasm = Module._ts_tree_edit_wasm = function() {
              return (_ts_tree_edit_wasm = Module._ts_tree_edit_wasm = Module.asm.ts_tree_edit_wasm).apply(null, arguments);
            }, _ts_tree_get_changed_ranges_wasm = Module._ts_tree_get_changed_ranges_wasm = function() {
              return (_ts_tree_get_changed_ranges_wasm = Module._ts_tree_get_changed_ranges_wasm = Module.asm.ts_tree_get_changed_ranges_wasm).apply(null, arguments);
            }, _ts_tree_cursor_new_wasm = Module._ts_tree_cursor_new_wasm = function() {
              return (_ts_tree_cursor_new_wasm = Module._ts_tree_cursor_new_wasm = Module.asm.ts_tree_cursor_new_wasm).apply(null, arguments);
            }, _ts_tree_cursor_delete_wasm = Module._ts_tree_cursor_delete_wasm = function() {
              return (_ts_tree_cursor_delete_wasm = Module._ts_tree_cursor_delete_wasm = Module.asm.ts_tree_cursor_delete_wasm).apply(null, arguments);
            }, _ts_tree_cursor_reset_wasm = Module._ts_tree_cursor_reset_wasm = function() {
              return (_ts_tree_cursor_reset_wasm = Module._ts_tree_cursor_reset_wasm = Module.asm.ts_tree_cursor_reset_wasm).apply(null, arguments);
            }, _ts_tree_cursor_reset_to_wasm = Module._ts_tree_cursor_reset_to_wasm = function() {
              return (_ts_tree_cursor_reset_to_wasm = Module._ts_tree_cursor_reset_to_wasm = Module.asm.ts_tree_cursor_reset_to_wasm).apply(null, arguments);
            }, _ts_tree_cursor_goto_first_child_wasm = Module._ts_tree_cursor_goto_first_child_wasm = function() {
              return (_ts_tree_cursor_goto_first_child_wasm = Module._ts_tree_cursor_goto_first_child_wasm = Module.asm.ts_tree_cursor_goto_first_child_wasm).apply(null, arguments);
            }, _ts_tree_cursor_goto_last_child_wasm = Module._ts_tree_cursor_goto_last_child_wasm = function() {
              return (_ts_tree_cursor_goto_last_child_wasm = Module._ts_tree_cursor_goto_last_child_wasm = Module.asm.ts_tree_cursor_goto_last_child_wasm).apply(null, arguments);
            }, _ts_tree_cursor_goto_next_sibling_wasm = Module._ts_tree_cursor_goto_next_sibling_wasm = function() {
              return (_ts_tree_cursor_goto_next_sibling_wasm = Module._ts_tree_cursor_goto_next_sibling_wasm = Module.asm.ts_tree_cursor_goto_next_sibling_wasm).apply(null, arguments);
            }, _ts_tree_cursor_goto_previous_sibling_wasm = Module._ts_tree_cursor_goto_previous_sibling_wasm = function() {
              return (_ts_tree_cursor_goto_previous_sibling_wasm = Module._ts_tree_cursor_goto_previous_sibling_wasm = Module.asm.ts_tree_cursor_goto_previous_sibling_wasm).apply(null, arguments);
            }, _ts_tree_cursor_goto_parent_wasm = Module._ts_tree_cursor_goto_parent_wasm = function() {
              return (_ts_tree_cursor_goto_parent_wasm = Module._ts_tree_cursor_goto_parent_wasm = Module.asm.ts_tree_cursor_goto_parent_wasm).apply(null, arguments);
            }, _ts_tree_cursor_current_node_type_id_wasm = Module._ts_tree_cursor_current_node_type_id_wasm = function() {
              return (_ts_tree_cursor_current_node_type_id_wasm = Module._ts_tree_cursor_current_node_type_id_wasm = Module.asm.ts_tree_cursor_current_node_type_id_wasm).apply(null, arguments);
            }, _ts_tree_cursor_current_node_state_id_wasm = Module._ts_tree_cursor_current_node_state_id_wasm = function() {
              return (_ts_tree_cursor_current_node_state_id_wasm = Module._ts_tree_cursor_current_node_state_id_wasm = Module.asm.ts_tree_cursor_current_node_state_id_wasm).apply(null, arguments);
            }, _ts_tree_cursor_current_node_is_named_wasm = Module._ts_tree_cursor_current_node_is_named_wasm = function() {
              return (_ts_tree_cursor_current_node_is_named_wasm = Module._ts_tree_cursor_current_node_is_named_wasm = Module.asm.ts_tree_cursor_current_node_is_named_wasm).apply(null, arguments);
            }, _ts_tree_cursor_current_node_is_missing_wasm = Module._ts_tree_cursor_current_node_is_missing_wasm = function() {
              return (_ts_tree_cursor_current_node_is_missing_wasm = Module._ts_tree_cursor_current_node_is_missing_wasm = Module.asm.ts_tree_cursor_current_node_is_missing_wasm).apply(null, arguments);
            }, _ts_tree_cursor_current_node_id_wasm = Module._ts_tree_cursor_current_node_id_wasm = function() {
              return (_ts_tree_cursor_current_node_id_wasm = Module._ts_tree_cursor_current_node_id_wasm = Module.asm.ts_tree_cursor_current_node_id_wasm).apply(null, arguments);
            }, _ts_tree_cursor_start_position_wasm = Module._ts_tree_cursor_start_position_wasm = function() {
              return (_ts_tree_cursor_start_position_wasm = Module._ts_tree_cursor_start_position_wasm = Module.asm.ts_tree_cursor_start_position_wasm).apply(null, arguments);
            }, _ts_tree_cursor_end_position_wasm = Module._ts_tree_cursor_end_position_wasm = function() {
              return (_ts_tree_cursor_end_position_wasm = Module._ts_tree_cursor_end_position_wasm = Module.asm.ts_tree_cursor_end_position_wasm).apply(null, arguments);
            }, _ts_tree_cursor_start_index_wasm = Module._ts_tree_cursor_start_index_wasm = function() {
              return (_ts_tree_cursor_start_index_wasm = Module._ts_tree_cursor_start_index_wasm = Module.asm.ts_tree_cursor_start_index_wasm).apply(null, arguments);
            }, _ts_tree_cursor_end_index_wasm = Module._ts_tree_cursor_end_index_wasm = function() {
              return (_ts_tree_cursor_end_index_wasm = Module._ts_tree_cursor_end_index_wasm = Module.asm.ts_tree_cursor_end_index_wasm).apply(null, arguments);
            }, _ts_tree_cursor_current_field_id_wasm = Module._ts_tree_cursor_current_field_id_wasm = function() {
              return (_ts_tree_cursor_current_field_id_wasm = Module._ts_tree_cursor_current_field_id_wasm = Module.asm.ts_tree_cursor_current_field_id_wasm).apply(null, arguments);
            }, _ts_tree_cursor_current_node_wasm = Module._ts_tree_cursor_current_node_wasm = function() {
              return (_ts_tree_cursor_current_node_wasm = Module._ts_tree_cursor_current_node_wasm = Module.asm.ts_tree_cursor_current_node_wasm).apply(null, arguments);
            }, _ts_node_symbol_wasm = Module._ts_node_symbol_wasm = function() {
              return (_ts_node_symbol_wasm = Module._ts_node_symbol_wasm = Module.asm.ts_node_symbol_wasm).apply(null, arguments);
            }, _ts_node_field_name_for_child_wasm = Module._ts_node_field_name_for_child_wasm = function() {
              return (_ts_node_field_name_for_child_wasm = Module._ts_node_field_name_for_child_wasm = Module.asm.ts_node_field_name_for_child_wasm).apply(null, arguments);
            }, _ts_node_grammar_symbol_wasm = Module._ts_node_grammar_symbol_wasm = function() {
              return (_ts_node_grammar_symbol_wasm = Module._ts_node_grammar_symbol_wasm = Module.asm.ts_node_grammar_symbol_wasm).apply(null, arguments);
            }, _ts_node_child_count_wasm = Module._ts_node_child_count_wasm = function() {
              return (_ts_node_child_count_wasm = Module._ts_node_child_count_wasm = Module.asm.ts_node_child_count_wasm).apply(null, arguments);
            }, _ts_node_named_child_count_wasm = Module._ts_node_named_child_count_wasm = function() {
              return (_ts_node_named_child_count_wasm = Module._ts_node_named_child_count_wasm = Module.asm.ts_node_named_child_count_wasm).apply(null, arguments);
            }, _ts_node_child_wasm = Module._ts_node_child_wasm = function() {
              return (_ts_node_child_wasm = Module._ts_node_child_wasm = Module.asm.ts_node_child_wasm).apply(null, arguments);
            }, _ts_node_named_child_wasm = Module._ts_node_named_child_wasm = function() {
              return (_ts_node_named_child_wasm = Module._ts_node_named_child_wasm = Module.asm.ts_node_named_child_wasm).apply(null, arguments);
            }, _ts_node_child_by_field_id_wasm = Module._ts_node_child_by_field_id_wasm = function() {
              return (_ts_node_child_by_field_id_wasm = Module._ts_node_child_by_field_id_wasm = Module.asm.ts_node_child_by_field_id_wasm).apply(null, arguments);
            }, _ts_node_next_sibling_wasm = Module._ts_node_next_sibling_wasm = function() {
              return (_ts_node_next_sibling_wasm = Module._ts_node_next_sibling_wasm = Module.asm.ts_node_next_sibling_wasm).apply(null, arguments);
            }, _ts_node_prev_sibling_wasm = Module._ts_node_prev_sibling_wasm = function() {
              return (_ts_node_prev_sibling_wasm = Module._ts_node_prev_sibling_wasm = Module.asm.ts_node_prev_sibling_wasm).apply(null, arguments);
            }, _ts_node_next_named_sibling_wasm = Module._ts_node_next_named_sibling_wasm = function() {
              return (_ts_node_next_named_sibling_wasm = Module._ts_node_next_named_sibling_wasm = Module.asm.ts_node_next_named_sibling_wasm).apply(null, arguments);
            }, _ts_node_prev_named_sibling_wasm = Module._ts_node_prev_named_sibling_wasm = function() {
              return (_ts_node_prev_named_sibling_wasm = Module._ts_node_prev_named_sibling_wasm = Module.asm.ts_node_prev_named_sibling_wasm).apply(null, arguments);
            }, _ts_node_parent_wasm = Module._ts_node_parent_wasm = function() {
              return (_ts_node_parent_wasm = Module._ts_node_parent_wasm = Module.asm.ts_node_parent_wasm).apply(null, arguments);
            }, _ts_node_descendant_for_index_wasm = Module._ts_node_descendant_for_index_wasm = function() {
              return (_ts_node_descendant_for_index_wasm = Module._ts_node_descendant_for_index_wasm = Module.asm.ts_node_descendant_for_index_wasm).apply(null, arguments);
            }, _ts_node_named_descendant_for_index_wasm = Module._ts_node_named_descendant_for_index_wasm = function() {
              return (_ts_node_named_descendant_for_index_wasm = Module._ts_node_named_descendant_for_index_wasm = Module.asm.ts_node_named_descendant_for_index_wasm).apply(null, arguments);
            }, _ts_node_descendant_for_position_wasm = Module._ts_node_descendant_for_position_wasm = function() {
              return (_ts_node_descendant_for_position_wasm = Module._ts_node_descendant_for_position_wasm = Module.asm.ts_node_descendant_for_position_wasm).apply(null, arguments);
            }, _ts_node_named_descendant_for_position_wasm = Module._ts_node_named_descendant_for_position_wasm = function() {
              return (_ts_node_named_descendant_for_position_wasm = Module._ts_node_named_descendant_for_position_wasm = Module.asm.ts_node_named_descendant_for_position_wasm).apply(null, arguments);
            }, _ts_node_start_point_wasm = Module._ts_node_start_point_wasm = function() {
              return (_ts_node_start_point_wasm = Module._ts_node_start_point_wasm = Module.asm.ts_node_start_point_wasm).apply(null, arguments);
            }, _ts_node_end_point_wasm = Module._ts_node_end_point_wasm = function() {
              return (_ts_node_end_point_wasm = Module._ts_node_end_point_wasm = Module.asm.ts_node_end_point_wasm).apply(null, arguments);
            }, _ts_node_start_index_wasm = Module._ts_node_start_index_wasm = function() {
              return (_ts_node_start_index_wasm = Module._ts_node_start_index_wasm = Module.asm.ts_node_start_index_wasm).apply(null, arguments);
            }, _ts_node_end_index_wasm = Module._ts_node_end_index_wasm = function() {
              return (_ts_node_end_index_wasm = Module._ts_node_end_index_wasm = Module.asm.ts_node_end_index_wasm).apply(null, arguments);
            }, _ts_node_to_string_wasm = Module._ts_node_to_string_wasm = function() {
              return (_ts_node_to_string_wasm = Module._ts_node_to_string_wasm = Module.asm.ts_node_to_string_wasm).apply(null, arguments);
            }, _ts_node_children_wasm = Module._ts_node_children_wasm = function() {
              return (_ts_node_children_wasm = Module._ts_node_children_wasm = Module.asm.ts_node_children_wasm).apply(null, arguments);
            }, _ts_node_named_children_wasm = Module._ts_node_named_children_wasm = function() {
              return (_ts_node_named_children_wasm = Module._ts_node_named_children_wasm = Module.asm.ts_node_named_children_wasm).apply(null, arguments);
            }, _ts_node_descendants_of_type_wasm = Module._ts_node_descendants_of_type_wasm = function() {
              return (_ts_node_descendants_of_type_wasm = Module._ts_node_descendants_of_type_wasm = Module.asm.ts_node_descendants_of_type_wasm).apply(null, arguments);
            }, _ts_node_is_named_wasm = Module._ts_node_is_named_wasm = function() {
              return (_ts_node_is_named_wasm = Module._ts_node_is_named_wasm = Module.asm.ts_node_is_named_wasm).apply(null, arguments);
            }, _ts_node_has_changes_wasm = Module._ts_node_has_changes_wasm = function() {
              return (_ts_node_has_changes_wasm = Module._ts_node_has_changes_wasm = Module.asm.ts_node_has_changes_wasm).apply(null, arguments);
            }, _ts_node_has_error_wasm = Module._ts_node_has_error_wasm = function() {
              return (_ts_node_has_error_wasm = Module._ts_node_has_error_wasm = Module.asm.ts_node_has_error_wasm).apply(null, arguments);
            }, _ts_node_is_error_wasm = Module._ts_node_is_error_wasm = function() {
              return (_ts_node_is_error_wasm = Module._ts_node_is_error_wasm = Module.asm.ts_node_is_error_wasm).apply(null, arguments);
            }, _ts_node_is_missing_wasm = Module._ts_node_is_missing_wasm = function() {
              return (_ts_node_is_missing_wasm = Module._ts_node_is_missing_wasm = Module.asm.ts_node_is_missing_wasm).apply(null, arguments);
            }, _ts_node_parse_state_wasm = Module._ts_node_parse_state_wasm = function() {
              return (_ts_node_parse_state_wasm = Module._ts_node_parse_state_wasm = Module.asm.ts_node_parse_state_wasm).apply(null, arguments);
            }, _ts_node_next_parse_state_wasm = Module._ts_node_next_parse_state_wasm = function() {
              return (_ts_node_next_parse_state_wasm = Module._ts_node_next_parse_state_wasm = Module.asm.ts_node_next_parse_state_wasm).apply(null, arguments);
            }, _ts_query_matches_wasm = Module._ts_query_matches_wasm = function() {
              return (_ts_query_matches_wasm = Module._ts_query_matches_wasm = Module.asm.ts_query_matches_wasm).apply(null, arguments);
            }, _ts_query_captures_wasm = Module._ts_query_captures_wasm = function() {
              return (_ts_query_captures_wasm = Module._ts_query_captures_wasm = Module.asm.ts_query_captures_wasm).apply(null, arguments);
            }, ___errno_location = function() {
              return (___errno_location = Module.asm.__errno_location).apply(null, arguments);
            }, _iswdigit = Module._iswdigit = function() {
              return (_iswdigit = Module._iswdigit = Module.asm.iswdigit).apply(null, arguments);
            }, _iswalpha = Module._iswalpha = function() {
              return (_iswalpha = Module._iswalpha = Module.asm.iswalpha).apply(null, arguments);
            }, _iswblank = Module._iswblank = function() {
              return (_iswblank = Module._iswblank = Module.asm.iswblank).apply(null, arguments);
            }, _iswlower = Module._iswlower = function() {
              return (_iswlower = Module._iswlower = Module.asm.iswlower).apply(null, arguments);
            }, _iswupper = Module._iswupper = function() {
              return (_iswupper = Module._iswupper = Module.asm.iswupper).apply(null, arguments);
            }, _iswxdigit = Module._iswxdigit = function() {
              return (_iswxdigit = Module._iswxdigit = Module.asm.iswxdigit).apply(null, arguments);
            }, _memchr = Module._memchr = function() {
              return (_memchr = Module._memchr = Module.asm.memchr).apply(null, arguments);
            }, _strlen = Module._strlen = function() {
              return (_strlen = Module._strlen = Module.asm.strlen).apply(null, arguments);
            }, _strcmp = Module._strcmp = function() {
              return (_strcmp = Module._strcmp = Module.asm.strcmp).apply(null, arguments);
            }, _strncpy = Module._strncpy = function() {
              return (_strncpy = Module._strncpy = Module.asm.strncpy).apply(null, arguments);
            }, _towlower = Module._towlower = function() {
              return (_towlower = Module._towlower = Module.asm.towlower).apply(null, arguments);
            }, _towupper = Module._towupper = function() {
              return (_towupper = Module._towupper = Module.asm.towupper).apply(null, arguments);
            }, _setThrew = function() {
              return (_setThrew = Module.asm.setThrew).apply(null, arguments);
            }, stackSave = function() {
              return (stackSave = Module.asm.stackSave).apply(null, arguments);
            }, stackRestore = function() {
              return (stackRestore = Module.asm.stackRestore).apply(null, arguments);
            }, stackAlloc = function() {
              return (stackAlloc = Module.asm.stackAlloc).apply(null, arguments);
            }, dynCall_jiji = Module.dynCall_jiji = function() {
              return (dynCall_jiji = Module.dynCall_jiji = Module.asm.dynCall_jiji).apply(null, arguments);
            }, _orig$ts_parser_timeout_micros = Module._orig$ts_parser_timeout_micros = function() {
              return (_orig$ts_parser_timeout_micros = Module._orig$ts_parser_timeout_micros = Module.asm.orig$ts_parser_timeout_micros).apply(null, arguments);
            }, _orig$ts_parser_set_timeout_micros = Module._orig$ts_parser_set_timeout_micros = function() {
              return (_orig$ts_parser_set_timeout_micros = Module._orig$ts_parser_set_timeout_micros = Module.asm.orig$ts_parser_set_timeout_micros).apply(null, arguments);
            }, calledRun;
            function callMain(e3 = []) {
              var t4 = resolveGlobalSymbol("main").sym;
              if (t4) {
                e3.unshift(thisProgram);
                var r = e3.length, _2 = stackAlloc(4 * (r + 1)), s = _2 >> 2;
                e3.forEach((e4) => {
                  HEAP32[s++] = stringToUTF8OnStack(e4);
                }), HEAP32[s] = 0;
                try {
                  var n = t4(r, _2);
                  return exitJS(n, true), n;
                } catch (e4) {
                  return handleException(e4);
                }
              }
            }
            Module.AsciiToString = AsciiToString, Module.stringToUTF16 = stringToUTF16, dependenciesFulfilled = function e3() {
              calledRun || run(), calledRun || (dependenciesFulfilled = e3);
            };
            var dylibsLoaded = false;
            function run(e3 = arguments_) {
              function t4() {
                calledRun || (calledRun = true, Module.calledRun = true, ABORT || (initRuntime(), preMain(), Module.onRuntimeInitialized && Module.onRuntimeInitialized(), shouldRunNow && callMain(e3), postRun()));
              }
              runDependencies > 0 || !dylibsLoaded && (loadDylibs(), dylibsLoaded = true, runDependencies > 0) || (preRun(), runDependencies > 0 || (Module.setStatus ? (Module.setStatus("Running..."), setTimeout(function() {
                setTimeout(function() {
                  Module.setStatus("");
                }, 1), t4();
              }, 1)) : t4()));
            }
            if (LDSO.init(), Module.preInit)
              for ("function" == typeof Module.preInit && (Module.preInit = [Module.preInit]); Module.preInit.length > 0; )
                Module.preInit.pop()();
            var shouldRunNow = true;
            Module.noInitialRun && (shouldRunNow = false), run();
            const C = Module, INTERNAL = {}, SIZE_OF_INT = 4, SIZE_OF_CURSOR = 3 * SIZE_OF_INT, SIZE_OF_NODE = 5 * SIZE_OF_INT, SIZE_OF_POINT = 2 * SIZE_OF_INT, SIZE_OF_RANGE = 2 * SIZE_OF_INT + 2 * SIZE_OF_POINT, ZERO_POINT = { row: 0, column: 0 }, QUERY_WORD_REGEX = /[\w-.]*/g, PREDICATE_STEP_TYPE_CAPTURE = 1, PREDICATE_STEP_TYPE_STRING = 2, LANGUAGE_FUNCTION_REGEX = /^_?tree_sitter_\w+/;
            let VERSION, MIN_COMPATIBLE_VERSION, TRANSFER_BUFFER, currentParseCallback, currentLogCallback;
            class ParserImpl {
              static init() {
                TRANSFER_BUFFER = C._ts_init(), VERSION = getValue(TRANSFER_BUFFER, "i32"), MIN_COMPATIBLE_VERSION = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
              }
              initialize() {
                C._ts_parser_new_wasm(), this[0] = getValue(TRANSFER_BUFFER, "i32"), this[1] = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
              }
              delete() {
                C._ts_parser_delete(this[0]), C._free(this[1]), this[0] = 0, this[1] = 0;
              }
              setLanguage(e3) {
                let t4;
                if (e3) {
                  if (e3.constructor !== Language)
                    throw new Error("Argument must be a Language");
                  {
                    t4 = e3[0];
                    const r = C._ts_language_version(t4);
                    if (r < MIN_COMPATIBLE_VERSION || VERSION < r)
                      throw new Error(`Incompatible language version ${r}. Compatibility range ${MIN_COMPATIBLE_VERSION} through ${VERSION}.`);
                  }
                } else
                  t4 = 0, e3 = null;
                return this.language = e3, C._ts_parser_set_language(this[0], t4), this;
              }
              getLanguage() {
                return this.language;
              }
              parse(e3, t4, r) {
                if ("string" == typeof e3)
                  currentParseCallback = (t5, r2, _3) => e3.slice(t5, _3);
                else {
                  if ("function" != typeof e3)
                    throw new Error("Argument must be a string or a function");
                  currentParseCallback = e3;
                }
                this.logCallback ? (currentLogCallback = this.logCallback, C._ts_parser_enable_logger_wasm(this[0], 1)) : (currentLogCallback = null, C._ts_parser_enable_logger_wasm(this[0], 0));
                let _2 = 0, s = 0;
                if (r && r.includedRanges) {
                  _2 = r.includedRanges.length, s = C._calloc(_2, SIZE_OF_RANGE);
                  let e4 = s;
                  for (let t5 = 0; t5 < _2; t5++)
                    marshalRange(e4, r.includedRanges[t5]), e4 += SIZE_OF_RANGE;
                }
                const n = C._ts_parser_parse_wasm(this[0], this[1], t4 ? t4[0] : 0, s, _2);
                if (!n)
                  throw currentParseCallback = null, currentLogCallback = null, new Error("Parsing failed");
                const a = new Tree(INTERNAL, n, this.language, currentParseCallback);
                return currentParseCallback = null, currentLogCallback = null, a;
              }
              reset() {
                C._ts_parser_reset(this[0]);
              }
              setTimeoutMicros(e3) {
                C._ts_parser_set_timeout_micros(this[0], e3);
              }
              getTimeoutMicros() {
                return C._ts_parser_timeout_micros(this[0]);
              }
              setLogger(e3) {
                if (e3) {
                  if ("function" != typeof e3)
                    throw new Error("Logger callback must be a function");
                } else
                  e3 = null;
                return this.logCallback = e3, this;
              }
              getLogger() {
                return this.logCallback;
              }
            }
            class Tree {
              constructor(e3, t4, r, _2) {
                assertInternal(e3), this[0] = t4, this.language = r, this.textCallback = _2;
              }
              copy() {
                const e3 = C._ts_tree_copy(this[0]);
                return new Tree(INTERNAL, e3, this.language, this.textCallback);
              }
              delete() {
                C._ts_tree_delete(this[0]), this[0] = 0;
              }
              edit(e3) {
                marshalEdit(e3), C._ts_tree_edit_wasm(this[0]);
              }
              get rootNode() {
                return C._ts_tree_root_node_wasm(this[0]), unmarshalNode(this);
              }
              getLanguage() {
                return this.language;
              }
              walk() {
                return this.rootNode.walk();
              }
              getChangedRanges(e3) {
                if (e3.constructor !== Tree)
                  throw new TypeError("Argument must be a Tree");
                C._ts_tree_get_changed_ranges_wasm(this[0], e3[0]);
                const t4 = getValue(TRANSFER_BUFFER, "i32"), r = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32"), _2 = new Array(t4);
                if (t4 > 0) {
                  let e4 = r;
                  for (let r2 = 0; r2 < t4; r2++)
                    _2[r2] = unmarshalRange(e4), e4 += SIZE_OF_RANGE;
                  C._free(r);
                }
                return _2;
              }
            }
            class Node {
              constructor(e3, t4) {
                assertInternal(e3), this.tree = t4;
              }
              get typeId() {
                return marshalNode(this), C._ts_node_symbol_wasm(this.tree[0]);
              }
              get grammarId() {
                return marshalNode(this), C._ts_node_grammar_symbol_wasm(this.tree[0]);
              }
              get type() {
                return this.tree.language.types[this.typeId] || "ERROR";
              }
              get grammarType() {
                return this.tree.language.types[this.grammarId] || "ERROR";
              }
              get endPosition() {
                return marshalNode(this), C._ts_node_end_point_wasm(this.tree[0]), unmarshalPoint(TRANSFER_BUFFER);
              }
              get endIndex() {
                return marshalNode(this), C._ts_node_end_index_wasm(this.tree[0]);
              }
              get text() {
                return getText(this.tree, this.startIndex, this.endIndex);
              }
              get parseState() {
                return marshalNode(this), C._ts_node_parse_state_wasm(this.tree[0]);
              }
              get nextParseState() {
                return marshalNode(this), C._ts_node_next_parse_state_wasm(this.tree[0]);
              }
              isNamed() {
                return marshalNode(this), 1 === C._ts_node_is_named_wasm(this.tree[0]);
              }
              hasError() {
                return marshalNode(this), 1 === C._ts_node_has_error_wasm(this.tree[0]);
              }
              hasChanges() {
                return marshalNode(this), 1 === C._ts_node_has_changes_wasm(this.tree[0]);
              }
              isError() {
                return marshalNode(this), 1 === C._ts_node_is_error_wasm(this.tree[0]);
              }
              isMissing() {
                return marshalNode(this), 1 === C._ts_node_is_missing_wasm(this.tree[0]);
              }
              equals(e3) {
                return this.id === e3.id;
              }
              child(e3) {
                return marshalNode(this), C._ts_node_child_wasm(this.tree[0], e3), unmarshalNode(this.tree);
              }
              fieldNameForChild(e3) {
                marshalNode(this);
                const t4 = C._ts_node_field_name_for_child_wasm(this.tree[0], e3);
                if (!t4)
                  return null;
                return AsciiToString(t4);
              }
              namedChild(e3) {
                return marshalNode(this), C._ts_node_named_child_wasm(this.tree[0], e3), unmarshalNode(this.tree);
              }
              childForFieldId(e3) {
                return marshalNode(this), C._ts_node_child_by_field_id_wasm(this.tree[0], e3), unmarshalNode(this.tree);
              }
              childForFieldName(e3) {
                const t4 = this.tree.language.fields.indexOf(e3);
                if (-1 !== t4)
                  return this.childForFieldId(t4);
              }
              get childCount() {
                return marshalNode(this), C._ts_node_child_count_wasm(this.tree[0]);
              }
              get namedChildCount() {
                return marshalNode(this), C._ts_node_named_child_count_wasm(this.tree[0]);
              }
              get firstChild() {
                return this.child(0);
              }
              get firstNamedChild() {
                return this.namedChild(0);
              }
              get lastChild() {
                return this.child(this.childCount - 1);
              }
              get lastNamedChild() {
                return this.namedChild(this.namedChildCount - 1);
              }
              get children() {
                if (!this._children) {
                  marshalNode(this), C._ts_node_children_wasm(this.tree[0]);
                  const e3 = getValue(TRANSFER_BUFFER, "i32"), t4 = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
                  if (this._children = new Array(e3), e3 > 0) {
                    let r = t4;
                    for (let t5 = 0; t5 < e3; t5++)
                      this._children[t5] = unmarshalNode(this.tree, r), r += SIZE_OF_NODE;
                    C._free(t4);
                  }
                }
                return this._children;
              }
              get namedChildren() {
                if (!this._namedChildren) {
                  marshalNode(this), C._ts_node_named_children_wasm(this.tree[0]);
                  const e3 = getValue(TRANSFER_BUFFER, "i32"), t4 = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
                  if (this._namedChildren = new Array(e3), e3 > 0) {
                    let r = t4;
                    for (let t5 = 0; t5 < e3; t5++)
                      this._namedChildren[t5] = unmarshalNode(this.tree, r), r += SIZE_OF_NODE;
                    C._free(t4);
                  }
                }
                return this._namedChildren;
              }
              descendantsOfType(e3, t4, r) {
                Array.isArray(e3) || (e3 = [e3]), t4 || (t4 = ZERO_POINT), r || (r = ZERO_POINT);
                const _2 = [], s = this.tree.language.types;
                for (let t5 = 0, r2 = s.length; t5 < r2; t5++)
                  e3.includes(s[t5]) && _2.push(t5);
                const n = C._malloc(SIZE_OF_INT * _2.length);
                for (let e4 = 0, t5 = _2.length; e4 < t5; e4++)
                  setValue(n + e4 * SIZE_OF_INT, _2[e4], "i32");
                marshalNode(this), C._ts_node_descendants_of_type_wasm(this.tree[0], n, _2.length, t4.row, t4.column, r.row, r.column);
                const a = getValue(TRANSFER_BUFFER, "i32"), o = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32"), l = new Array(a);
                if (a > 0) {
                  let e4 = o;
                  for (let t5 = 0; t5 < a; t5++)
                    l[t5] = unmarshalNode(this.tree, e4), e4 += SIZE_OF_NODE;
                }
                return C._free(o), C._free(n), l;
              }
              get nextSibling() {
                return marshalNode(this), C._ts_node_next_sibling_wasm(this.tree[0]), unmarshalNode(this.tree);
              }
              get previousSibling() {
                return marshalNode(this), C._ts_node_prev_sibling_wasm(this.tree[0]), unmarshalNode(this.tree);
              }
              get nextNamedSibling() {
                return marshalNode(this), C._ts_node_next_named_sibling_wasm(this.tree[0]), unmarshalNode(this.tree);
              }
              get previousNamedSibling() {
                return marshalNode(this), C._ts_node_prev_named_sibling_wasm(this.tree[0]), unmarshalNode(this.tree);
              }
              get parent() {
                return marshalNode(this), C._ts_node_parent_wasm(this.tree[0]), unmarshalNode(this.tree);
              }
              descendantForIndex(e3, t4 = e3) {
                if ("number" != typeof e3 || "number" != typeof t4)
                  throw new Error("Arguments must be numbers");
                marshalNode(this);
                const r = TRANSFER_BUFFER + SIZE_OF_NODE;
                return setValue(r, e3, "i32"), setValue(r + SIZE_OF_INT, t4, "i32"), C._ts_node_descendant_for_index_wasm(this.tree[0]), unmarshalNode(this.tree);
              }
              namedDescendantForIndex(e3, t4 = e3) {
                if ("number" != typeof e3 || "number" != typeof t4)
                  throw new Error("Arguments must be numbers");
                marshalNode(this);
                const r = TRANSFER_BUFFER + SIZE_OF_NODE;
                return setValue(r, e3, "i32"), setValue(r + SIZE_OF_INT, t4, "i32"), C._ts_node_named_descendant_for_index_wasm(this.tree[0]), unmarshalNode(this.tree);
              }
              descendantForPosition(e3, t4 = e3) {
                if (!isPoint(e3) || !isPoint(t4))
                  throw new Error("Arguments must be {row, column} objects");
                marshalNode(this);
                const r = TRANSFER_BUFFER + SIZE_OF_NODE;
                return marshalPoint(r, e3), marshalPoint(r + SIZE_OF_POINT, t4), C._ts_node_descendant_for_position_wasm(this.tree[0]), unmarshalNode(this.tree);
              }
              namedDescendantForPosition(e3, t4 = e3) {
                if (!isPoint(e3) || !isPoint(t4))
                  throw new Error("Arguments must be {row, column} objects");
                marshalNode(this);
                const r = TRANSFER_BUFFER + SIZE_OF_NODE;
                return marshalPoint(r, e3), marshalPoint(r + SIZE_OF_POINT, t4), C._ts_node_named_descendant_for_position_wasm(this.tree[0]), unmarshalNode(this.tree);
              }
              walk() {
                return marshalNode(this), C._ts_tree_cursor_new_wasm(this.tree[0]), new TreeCursor(INTERNAL, this.tree);
              }
              toString() {
                marshalNode(this);
                const e3 = C._ts_node_to_string_wasm(this.tree[0]), t4 = AsciiToString(e3);
                return C._free(e3), t4;
              }
            }
            class TreeCursor {
              constructor(e3, t4) {
                assertInternal(e3), this.tree = t4, unmarshalTreeCursor(this);
              }
              delete() {
                marshalTreeCursor(this), C._ts_tree_cursor_delete_wasm(this.tree[0]), this[0] = this[1] = this[2] = 0;
              }
              reset(e3) {
                marshalNode(e3), marshalTreeCursor(this, TRANSFER_BUFFER + SIZE_OF_NODE), C._ts_tree_cursor_reset_wasm(this.tree[0]), unmarshalTreeCursor(this);
              }
              resetTo(e3) {
                marshalTreeCursor(this, TRANSFER_BUFFER), marshalTreeCursor(e3, TRANSFER_BUFFER + SIZE_OF_CURSOR), C._ts_tree_cursor_reset_to_wasm(this.tree[0], e3.tree[0]), unmarshalTreeCursor(this);
              }
              get nodeType() {
                return this.tree.language.types[this.nodeTypeId] || "ERROR";
              }
              get nodeTypeId() {
                return marshalTreeCursor(this), C._ts_tree_cursor_current_node_type_id_wasm(this.tree[0]);
              }
              get nodeStateId() {
                return marshalTreeCursor(this), C._ts_tree_cursor_current_node_state_id_wasm(this.tree[0]);
              }
              get nodeId() {
                return marshalTreeCursor(this), C._ts_tree_cursor_current_node_id_wasm(this.tree[0]);
              }
              get nodeIsNamed() {
                return marshalTreeCursor(this), 1 === C._ts_tree_cursor_current_node_is_named_wasm(this.tree[0]);
              }
              get nodeIsMissing() {
                return marshalTreeCursor(this), 1 === C._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0]);
              }
              get nodeText() {
                marshalTreeCursor(this);
                const e3 = C._ts_tree_cursor_start_index_wasm(this.tree[0]), t4 = C._ts_tree_cursor_end_index_wasm(this.tree[0]);
                return getText(this.tree, e3, t4);
              }
              get startPosition() {
                return marshalTreeCursor(this), C._ts_tree_cursor_start_position_wasm(this.tree[0]), unmarshalPoint(TRANSFER_BUFFER);
              }
              get endPosition() {
                return marshalTreeCursor(this), C._ts_tree_cursor_end_position_wasm(this.tree[0]), unmarshalPoint(TRANSFER_BUFFER);
              }
              get startIndex() {
                return marshalTreeCursor(this), C._ts_tree_cursor_start_index_wasm(this.tree[0]);
              }
              get endIndex() {
                return marshalTreeCursor(this), C._ts_tree_cursor_end_index_wasm(this.tree[0]);
              }
              currentNode() {
                return marshalTreeCursor(this), C._ts_tree_cursor_current_node_wasm(this.tree[0]), unmarshalNode(this.tree);
              }
              currentFieldId() {
                return marshalTreeCursor(this), C._ts_tree_cursor_current_field_id_wasm(this.tree[0]);
              }
              currentFieldName() {
                return this.tree.language.fields[this.currentFieldId()];
              }
              gotoFirstChild() {
                marshalTreeCursor(this);
                const e3 = C._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);
                return unmarshalTreeCursor(this), 1 === e3;
              }
              gotoLastChild() {
                marshalTreeCursor(this);
                const e3 = C._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);
                return unmarshalTreeCursor(this), 1 === e3;
              }
              gotoNextSibling() {
                marshalTreeCursor(this);
                const e3 = C._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);
                return unmarshalTreeCursor(this), 1 === e3;
              }
              gotoPreviousSibling() {
                marshalTreeCursor(this);
                const e3 = C._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);
                return unmarshalTreeCursor(this), 1 === e3;
              }
              gotoParent() {
                marshalTreeCursor(this);
                const e3 = C._ts_tree_cursor_goto_parent_wasm(this.tree[0]);
                return unmarshalTreeCursor(this), 1 === e3;
              }
            }
            class Language {
              constructor(e3, t4) {
                assertInternal(e3), this[0] = t4, this.types = new Array(C._ts_language_symbol_count(this[0]));
                for (let e4 = 0, t5 = this.types.length; e4 < t5; e4++)
                  C._ts_language_symbol_type(this[0], e4) < 2 && (this.types[e4] = UTF8ToString(C._ts_language_symbol_name(this[0], e4)));
                this.fields = new Array(C._ts_language_field_count(this[0]) + 1);
                for (let e4 = 0, t5 = this.fields.length; e4 < t5; e4++) {
                  const t6 = C._ts_language_field_name_for_id(this[0], e4);
                  this.fields[e4] = 0 !== t6 ? UTF8ToString(t6) : null;
                }
              }
              get version() {
                return C._ts_language_version(this[0]);
              }
              get fieldCount() {
                return this.fields.length - 1;
              }
              get stateCount() {
                return C._ts_language_state_count(this[0]);
              }
              fieldIdForName(e3) {
                const t4 = this.fields.indexOf(e3);
                return -1 !== t4 ? t4 : null;
              }
              fieldNameForId(e3) {
                return this.fields[e3] || null;
              }
              idForNodeType(e3, t4) {
                const r = lengthBytesUTF8(e3), _2 = C._malloc(r + 1);
                stringToUTF8(e3, _2, r + 1);
                const s = C._ts_language_symbol_for_name(this[0], _2, r, t4);
                return C._free(_2), s || null;
              }
              get nodeTypeCount() {
                return C._ts_language_symbol_count(this[0]);
              }
              nodeTypeForId(e3) {
                const t4 = C._ts_language_symbol_name(this[0], e3);
                return t4 ? UTF8ToString(t4) : null;
              }
              nodeTypeIsNamed(e3) {
                return !!C._ts_language_type_is_named_wasm(this[0], e3);
              }
              nodeTypeIsVisible(e3) {
                return !!C._ts_language_type_is_visible_wasm(this[0], e3);
              }
              nextState(e3, t4) {
                return C._ts_language_next_state(this[0], e3, t4);
              }
              lookaheadIterator(e3) {
                const t4 = C._ts_lookahead_iterator_new(this[0], e3);
                if (t4)
                  return new LookaheadIterable(INTERNAL, t4, this);
              }
              query(e3) {
                const t4 = lengthBytesUTF8(e3), r = C._malloc(t4 + 1);
                stringToUTF8(e3, r, t4 + 1);
                const _2 = C._ts_query_new(this[0], r, t4, TRANSFER_BUFFER, TRANSFER_BUFFER + SIZE_OF_INT);
                if (!_2) {
                  const t5 = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32"), _3 = UTF8ToString(r, getValue(TRANSFER_BUFFER, "i32")).length, s2 = e3.substr(_3, 100).split("\n")[0];
                  let n2, a2 = s2.match(QUERY_WORD_REGEX)[0];
                  switch (t5) {
                    case 2:
                      n2 = new RangeError(`Bad node name '${a2}'`);
                      break;
                    case 3:
                      n2 = new RangeError(`Bad field name '${a2}'`);
                      break;
                    case 4:
                      n2 = new RangeError(`Bad capture name @${a2}`);
                      break;
                    case 5:
                      n2 = new TypeError(`Bad pattern structure at offset ${_3}: '${s2}'...`), a2 = "";
                      break;
                    default:
                      n2 = new SyntaxError(`Bad syntax at offset ${_3}: '${s2}'...`), a2 = "";
                  }
                  throw n2.index = _3, n2.length = a2.length, C._free(r), n2;
                }
                const s = C._ts_query_string_count(_2), n = C._ts_query_capture_count(_2), a = C._ts_query_pattern_count(_2), o = new Array(n), l = new Array(s);
                for (let e4 = 0; e4 < n; e4++) {
                  const t5 = C._ts_query_capture_name_for_id(_2, e4, TRANSFER_BUFFER), r2 = getValue(TRANSFER_BUFFER, "i32");
                  o[e4] = UTF8ToString(t5, r2);
                }
                for (let e4 = 0; e4 < s; e4++) {
                  const t5 = C._ts_query_string_value_for_id(_2, e4, TRANSFER_BUFFER), r2 = getValue(TRANSFER_BUFFER, "i32");
                  l[e4] = UTF8ToString(t5, r2);
                }
                const i = new Array(a), u = new Array(a), d = new Array(a), m = new Array(a), c = new Array(a);
                for (let e4 = 0; e4 < a; e4++) {
                  const t5 = C._ts_query_predicates_for_pattern(_2, e4, TRANSFER_BUFFER), r2 = getValue(TRANSFER_BUFFER, "i32");
                  m[e4] = [], c[e4] = [];
                  const s2 = [];
                  let n2 = t5;
                  for (let t6 = 0; t6 < r2; t6++) {
                    const t7 = getValue(n2, "i32");
                    n2 += SIZE_OF_INT;
                    const r3 = getValue(n2, "i32");
                    if (n2 += SIZE_OF_INT, t7 === PREDICATE_STEP_TYPE_CAPTURE)
                      s2.push({ type: "capture", name: o[r3] });
                    else if (t7 === PREDICATE_STEP_TYPE_STRING)
                      s2.push({ type: "string", value: l[r3] });
                    else if (s2.length > 0) {
                      if ("string" !== s2[0].type)
                        throw new Error("Predicates must begin with a literal value");
                      const t8 = s2[0].value;
                      let r4, _3 = true, n3 = true;
                      switch (t8) {
                        case "any-not-eq?":
                        case "not-eq?":
                          _3 = false;
                        case "any-eq?":
                        case "eq?":
                          if (3 !== s2.length)
                            throw new Error(`Wrong number of arguments to \`#${t8}\` predicate. Expected 2, got ${s2.length - 1}`);
                          if ("capture" !== s2[1].type)
                            throw new Error(`First argument of \`#${t8}\` predicate must be a capture. Got "${s2[1].value}"`);
                          if (n3 = !t8.startsWith("any-"), "capture" === s2[2].type) {
                            const t9 = s2[1].name, r5 = s2[2].name;
                            c[e4].push(function(e6) {
                              const s3 = [], a3 = [];
                              for (const _4 of e6)
                                _4.name === t9 && s3.push(_4.node), _4.name === r5 && a3.push(_4.node);
                              const o3 = (e7, t10, r6) => r6 ? e7.text === t10.text : e7.text !== t10.text;
                              return n3 ? s3.every((e7) => a3.some((t10) => o3(e7, t10, _3))) : s3.some((e7) => a3.some((t10) => o3(e7, t10, _3)));
                            });
                          } else {
                            r4 = s2[1].name;
                            const t9 = s2[2].value, a3 = (e6) => e6.text === t9, o3 = (e6) => e6.text !== t9;
                            c[e4].push(function(e6) {
                              const t10 = [];
                              for (const _4 of e6)
                                _4.name === r4 && t10.push(_4.node);
                              const s3 = _3 ? a3 : o3;
                              return n3 ? t10.every(s3) : t10.some(s3);
                            });
                          }
                          break;
                        case "any-not-match?":
                        case "not-match?":
                          _3 = false;
                        case "any-match?":
                        case "match?":
                          if (3 !== s2.length)
                            throw new Error(`Wrong number of arguments to \`#${t8}\` predicate. Expected 2, got ${s2.length - 1}.`);
                          if ("capture" !== s2[1].type)
                            throw new Error(`First argument of \`#${t8}\` predicate must be a capture. Got "${s2[1].value}".`);
                          if ("string" !== s2[2].type)
                            throw new Error(`Second argument of \`#${t8}\` predicate must be a string. Got @${s2[2].value}.`);
                          r4 = s2[1].name;
                          const a2 = new RegExp(s2[2].value);
                          n3 = !t8.startsWith("any-"), c[e4].push(function(e6) {
                            const t9 = [];
                            for (const _4 of e6)
                              _4.name === r4 && t9.push(_4.node.text);
                            const s3 = (e7, t10) => t10 ? a2.test(e7) : !a2.test(e7);
                            return 0 === t9.length ? !_3 : n3 ? t9.every((e7) => s3(e7, _3)) : t9.some((e7) => s3(e7, _3));
                          });
                          break;
                        case "set!":
                          if (s2.length < 2 || s2.length > 3)
                            throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${s2.length - 1}.`);
                          if (s2.some((e6) => "string" !== e6.type))
                            throw new Error('Arguments to `#set!` predicate must be a strings.".');
                          i[e4] || (i[e4] = {}), i[e4][s2[1].value] = s2[2] ? s2[2].value : null;
                          break;
                        case "is?":
                        case "is-not?":
                          if (s2.length < 2 || s2.length > 3)
                            throw new Error(`Wrong number of arguments to \`#${t8}\` predicate. Expected 1 or 2. Got ${s2.length - 1}.`);
                          if (s2.some((e6) => "string" !== e6.type))
                            throw new Error(`Arguments to \`#${t8}\` predicate must be a strings.".`);
                          const o2 = "is?" === t8 ? u : d;
                          o2[e4] || (o2[e4] = {}), o2[e4][s2[1].value] = s2[2] ? s2[2].value : null;
                          break;
                        case "not-any-of?":
                          _3 = false;
                        case "any-of?":
                          if (s2.length < 2)
                            throw new Error(`Wrong number of arguments to \`#${t8}\` predicate. Expected at least 1. Got ${s2.length - 1}.`);
                          if ("capture" !== s2[1].type)
                            throw new Error(`First argument of \`#${t8}\` predicate must be a capture. Got "${s2[1].value}".`);
                          for (let e6 = 2; e6 < s2.length; e6++)
                            if ("string" !== s2[e6].type)
                              throw new Error(`Arguments to \`#${t8}\` predicate must be a strings.".`);
                          r4 = s2[1].name;
                          const l2 = s2.slice(2).map((e6) => e6.value);
                          c[e4].push(function(e6) {
                            const t9 = [];
                            for (const _4 of e6)
                              _4.name === r4 && t9.push(_4.node.text);
                            return 0 === t9.length ? !_3 : t9.every((e7) => l2.includes(e7)) === _3;
                          });
                          break;
                        default:
                          m[e4].push({ operator: t8, operands: s2.slice(1) });
                      }
                      s2.length = 0;
                    }
                  }
                  Object.freeze(i[e4]), Object.freeze(u[e4]), Object.freeze(d[e4]);
                }
                return C._free(r), new Query(INTERNAL, _2, o, c, m, Object.freeze(i), Object.freeze(u), Object.freeze(d));
              }
              static load(e3) {
                let t4;
                if (e3 instanceof Uint8Array)
                  t4 = Promise.resolve(e3);
                else {
                  const r = e3;
                  if ("undefined" != typeof process && process.versions && process.versions.node) {
                    const e4 = __require("fs");
                    t4 = Promise.resolve(e4.readFileSync(r));
                  } else
                    t4 = fetch(r).then((e4) => e4.arrayBuffer().then((t5) => {
                      if (e4.ok)
                        return new Uint8Array(t5);
                      {
                        const r2 = new TextDecoder("utf-8").decode(t5);
                        throw new Error(`Language.load failed with status ${e4.status}.

${r2}`);
                      }
                    }));
                }
                return t4.then((e4) => loadWebAssemblyModule(e4, { loadAsync: true })).then((e4) => {
                  const t5 = Object.keys(e4), r = t5.find((e6) => LANGUAGE_FUNCTION_REGEX.test(e6) && !e6.includes("external_scanner_"));
                  r || console.log(`Couldn't find language function in WASM file. Symbols:
${JSON.stringify(t5, null, 2)}`);
                  const _2 = e4[r]();
                  return new Language(INTERNAL, _2);
                });
              }
            }
            class LookaheadIterable {
              constructor(e3, t4, r) {
                assertInternal(e3), this[0] = t4, this.language = r;
              }
              get currentTypeId() {
                return C._ts_lookahead_iterator_current_symbol(this[0]);
              }
              get currentType() {
                return this.language.types[this.currentTypeId] || "ERROR";
              }
              delete() {
                C._ts_lookahead_iterator_delete(this[0]), this[0] = 0;
              }
              resetState(e3) {
                return C._ts_lookahead_iterator_reset_state(this[0], e3);
              }
              reset(e3, t4) {
                return !!C._ts_lookahead_iterator_reset(this[0], e3[0], t4) && (this.language = e3, true);
              }
              [Symbol.iterator]() {
                const e3 = this;
                return { next: () => C._ts_lookahead_iterator_next(e3[0]) ? { done: false, value: e3.currentType } : { done: true, value: "" } };
              }
            }
            class Query {
              constructor(e3, t4, r, _2, s, n, a, o) {
                assertInternal(e3), this[0] = t4, this.captureNames = r, this.textPredicates = _2, this.predicates = s, this.setProperties = n, this.assertedProperties = a, this.refutedProperties = o, this.exceededMatchLimit = false;
              }
              delete() {
                C._ts_query_delete(this[0]), this[0] = 0;
              }
              matches(e3, t4, r, _2) {
                t4 || (t4 = ZERO_POINT), r || (r = ZERO_POINT), _2 || (_2 = {});
                let s = _2.matchLimit;
                if (void 0 === s)
                  s = 0;
                else if ("number" != typeof s)
                  throw new Error("Arguments must be numbers");
                marshalNode(e3), C._ts_query_matches_wasm(this[0], e3.tree[0], t4.row, t4.column, r.row, r.column, s);
                const n = getValue(TRANSFER_BUFFER, "i32"), a = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32"), o = getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32"), l = new Array(n);
                this.exceededMatchLimit = !!o;
                let i = 0, u = a;
                for (let t5 = 0; t5 < n; t5++) {
                  const t6 = getValue(u, "i32");
                  u += SIZE_OF_INT;
                  const r2 = getValue(u, "i32");
                  u += SIZE_OF_INT;
                  const _3 = new Array(r2);
                  if (u = unmarshalCaptures(this, e3.tree, u, _3), this.textPredicates[t6].every((e4) => e4(_3))) {
                    l[i] = { pattern: t6, captures: _3 };
                    const e4 = this.setProperties[t6];
                    e4 && (l[i].setProperties = e4);
                    const r3 = this.assertedProperties[t6];
                    r3 && (l[i].assertedProperties = r3);
                    const s2 = this.refutedProperties[t6];
                    s2 && (l[i].refutedProperties = s2), i++;
                  }
                }
                return l.length = i, C._free(a), l;
              }
              captures(e3, t4, r, _2) {
                t4 || (t4 = ZERO_POINT), r || (r = ZERO_POINT), _2 || (_2 = {});
                let s = _2.matchLimit;
                if (void 0 === s)
                  s = 0;
                else if ("number" != typeof s)
                  throw new Error("Arguments must be numbers");
                marshalNode(e3), C._ts_query_captures_wasm(this[0], e3.tree[0], t4.row, t4.column, r.row, r.column, s);
                const n = getValue(TRANSFER_BUFFER, "i32"), a = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32"), o = getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32"), l = [];
                this.exceededMatchLimit = !!o;
                const i = [];
                let u = a;
                for (let t5 = 0; t5 < n; t5++) {
                  const t6 = getValue(u, "i32");
                  u += SIZE_OF_INT;
                  const r2 = getValue(u, "i32");
                  u += SIZE_OF_INT;
                  const _3 = getValue(u, "i32");
                  if (u += SIZE_OF_INT, i.length = r2, u = unmarshalCaptures(this, e3.tree, u, i), this.textPredicates[t6].every((e4) => e4(i))) {
                    const e4 = i[_3], r3 = this.setProperties[t6];
                    r3 && (e4.setProperties = r3);
                    const s2 = this.assertedProperties[t6];
                    s2 && (e4.assertedProperties = s2);
                    const n2 = this.refutedProperties[t6];
                    n2 && (e4.refutedProperties = n2), l.push(e4);
                  }
                }
                return C._free(a), l;
              }
              predicatesForPattern(e3) {
                return this.predicates[e3];
              }
              didExceedMatchLimit() {
                return this.exceededMatchLimit;
              }
            }
            function getText(e3, t4, r) {
              const _2 = r - t4;
              let s = e3.textCallback(t4, null, r);
              for (t4 += s.length; t4 < r; ) {
                const _3 = e3.textCallback(t4, null, r);
                if (!(_3 && _3.length > 0))
                  break;
                t4 += _3.length, s += _3;
              }
              return t4 > r && (s = s.slice(0, _2)), s;
            }
            function unmarshalCaptures(e3, t4, r, _2) {
              for (let s = 0, n = _2.length; s < n; s++) {
                const n2 = getValue(r, "i32"), a = unmarshalNode(t4, r += SIZE_OF_INT);
                r += SIZE_OF_NODE, _2[s] = { name: e3.captureNames[n2], node: a };
              }
              return r;
            }
            function assertInternal(e3) {
              if (e3 !== INTERNAL)
                throw new Error("Illegal constructor");
            }
            function isPoint(e3) {
              return e3 && "number" == typeof e3.row && "number" == typeof e3.column;
            }
            function marshalNode(e3) {
              let t4 = TRANSFER_BUFFER;
              setValue(t4, e3.id, "i32"), t4 += SIZE_OF_INT, setValue(t4, e3.startIndex, "i32"), t4 += SIZE_OF_INT, setValue(t4, e3.startPosition.row, "i32"), t4 += SIZE_OF_INT, setValue(t4, e3.startPosition.column, "i32"), t4 += SIZE_OF_INT, setValue(t4, e3[0], "i32");
            }
            function unmarshalNode(e3, t4 = TRANSFER_BUFFER) {
              const r = getValue(t4, "i32");
              if (0 === r)
                return null;
              const _2 = getValue(t4 += SIZE_OF_INT, "i32"), s = getValue(t4 += SIZE_OF_INT, "i32"), n = getValue(t4 += SIZE_OF_INT, "i32"), a = getValue(t4 += SIZE_OF_INT, "i32"), o = new Node(INTERNAL, e3);
              return o.id = r, o.startIndex = _2, o.startPosition = { row: s, column: n }, o[0] = a, o;
            }
            function marshalTreeCursor(e3, t4 = TRANSFER_BUFFER) {
              setValue(t4 + 0 * SIZE_OF_INT, e3[0], "i32"), setValue(t4 + 1 * SIZE_OF_INT, e3[1], "i32"), setValue(t4 + 2 * SIZE_OF_INT, e3[2], "i32");
            }
            function unmarshalTreeCursor(e3) {
              e3[0] = getValue(TRANSFER_BUFFER + 0 * SIZE_OF_INT, "i32"), e3[1] = getValue(TRANSFER_BUFFER + 1 * SIZE_OF_INT, "i32"), e3[2] = getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
            }
            function marshalPoint(e3, t4) {
              setValue(e3, t4.row, "i32"), setValue(e3 + SIZE_OF_INT, t4.column, "i32");
            }
            function unmarshalPoint(e3) {
              return { row: getValue(e3, "i32"), column: getValue(e3 + SIZE_OF_INT, "i32") };
            }
            function marshalRange(e3, t4) {
              marshalPoint(e3, t4.startPosition), marshalPoint(e3 += SIZE_OF_POINT, t4.endPosition), setValue(e3 += SIZE_OF_POINT, t4.startIndex, "i32"), setValue(e3 += SIZE_OF_INT, t4.endIndex, "i32"), e3 += SIZE_OF_INT;
            }
            function unmarshalRange(e3) {
              const t4 = {};
              return t4.startPosition = unmarshalPoint(e3), e3 += SIZE_OF_POINT, t4.endPosition = unmarshalPoint(e3), e3 += SIZE_OF_POINT, t4.startIndex = getValue(e3, "i32"), e3 += SIZE_OF_INT, t4.endIndex = getValue(e3, "i32"), t4;
            }
            function marshalEdit(e3) {
              let t4 = TRANSFER_BUFFER;
              marshalPoint(t4, e3.startPosition), t4 += SIZE_OF_POINT, marshalPoint(t4, e3.oldEndPosition), t4 += SIZE_OF_POINT, marshalPoint(t4, e3.newEndPosition), t4 += SIZE_OF_POINT, setValue(t4, e3.startIndex, "i32"), t4 += SIZE_OF_INT, setValue(t4, e3.oldEndIndex, "i32"), t4 += SIZE_OF_INT, setValue(t4, e3.newEndIndex, "i32"), t4 += SIZE_OF_INT;
            }
            for (const e3 of Object.getOwnPropertyNames(ParserImpl.prototype))
              Object.defineProperty(Parser.prototype, e3, { value: ParserImpl.prototype[e3], enumerable: false, writable: false });
            Parser.Language = Language, Module.onRuntimeInitialized = () => {
              ParserImpl.init(), resolveInitPromise();
            };
          }));
        }
      }
      return Parser;
    }();
    "object" == typeof exports && (module.exports = TreeSitter);
  }
});

// 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, err3;
    return {
      s: function() {
        it = it.call(o);
      },
      n: function() {
        var step = it.next();
        normalCompletion = step.done;
        return step;
      },
      e: function(e3) {
        didErr = true;
        err3 = e3;
      },
      f: function() {
        try {
          if (!normalCompletion && it.return != null)
            it.return();
        } finally {
          if (didErr)
            throw err3;
        }
      }
    };
  }
  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 loop2 = function loop3(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)
              loop3(node[QSA$1](selectors), selectors, added, removed, connected, TRUE);
          }
        }
      } catch (err3) {
        _iterator.e(err3);
      } 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;
            loop2(removedNodes, selectors, added, removed, FALSE, FALSE);
            loop2(addedNodes, selectors, added, removed, TRUE, FALSE);
          }
        } catch (err3) {
          _iterator2.e(err3);
        } 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(options3) {
    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);
              options3.handle(element2, connected, q);
            }
          }
        }
      } else if (live.has(element2)) {
        selectors = live.get(element2);
        live["delete"](element2);
        selectors.forEach(function(q2) {
          options3.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 = options3.query;
    var root2 = options3.root || document$2;
    var observer = notify2(notifier, root2, MutationObserver$2, query2);
    var attachShadow2 = Element$1.prototype.attachShadow;
    if (attachShadow2)
      Element$1.prototype.attachShadow = function(init4) {
        var shadowRoot = attachShadow2.call(this, init4);
        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, Error3 = _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 key2 = keys(element2);
    var value = [];
    var ignore = new Set$1();
    var length = key2.length;
    for (var i = 0; i < length; i++) {
      value[i] = element2[key2[i]];
      try {
        delete element2[key2[i]];
      } catch (SafariTP) {
        ignore.add(i);
      }
    }
    return function() {
      for (var _i = 0; _i < length; _i++)
        ignore.has(_i) || (element2[key2[_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 handle2 = function handle3(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: handle2
    }), 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);
    self.customElements = {
      define: function define2(is2, Class) {
        if (registry.has(is2))
          throw new Error3('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
    });
    self.HTMLElement = HTMLBuiltIn;
    document$1.createElement = function(name2, options3) {
      var is2 = options3 && options3.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-br");
    if (legacy) {
      try {
        var BR = function BR2() {
          return self.Reflect.construct(HTMLBRElement, [], BR2);
        };
        BR.prototype = HTMLLIElement.prototype;
        var is = "extends-br";
        self.customElements.define("extends-br", BR, {
          "extends": "br"
        });
        legacy = document$1.createElement("br", {
          is
        }).outerHTML.indexOf(is) < 0;
        var _self$customElements = self.customElements, get2 = _self$customElements.get, _whenDefined = _self$customElements.whenDefined;
        self.customElements.whenDefined = function(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 handle3(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(init4) {
        var root2 = attachShadow.call(this, init4);
        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, tag = _classes$get.tag;
        if (is2) {
          if (_override)
            return _augment(_override, is2);
          var element2 = _createElement.call(document$1, tag);
          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
      });
    });
    document$1.createElement = function(name2, options3) {
      var is2 = options3 && options3.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;
    };
    customElements2.get = getCE;
    customElements2.whenDefined = _whenDefined2;
    customElements2.upgrade = function(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);
    };
    customElements2.define = function(is2, Class, options3) {
      if (getCE(is2))
        throw new Error3("'".concat(is2, "' has already been defined as a custom element"));
      var selector;
      var tag = options3 && options3["extends"];
      _classes.set(Class, tag ? {
        is: is2,
        tag
      } : {
        is: "",
        tag: is2
      });
      if (tag) {
        selector = "".concat(tag, '[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 (tag) {
          _parse(document$1.querySelectorAll(selector));
          shadows.forEach(_parseShadow, [selector]);
        } else
          parseShadowed(document$1.querySelectorAll(selector));
      });
      _defined.get(is2)._(Class);
    };
  }
})();

// node_modules/svelte/src/runtime/internal/utils.js
function noop() {
}
function assign(tar, src) {
  for (const k in src)
    tar[k] = src[k];
  return (
    /** @type {T & S} */
    tar
  );
}
function is_promise(value) {
  return !!value && (typeof value === "object" || typeof value === "function") && typeof /** @type {any} */
  value.then === "function";
}
function run2(fn) {
  return fn();
}
function blank_object() {
  return /* @__PURE__ */ Object.create(null);
}
function run_all(fns) {
  fns.forEach(run2);
}
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 (element_src === url)
    return true;
  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) {
    for (const callback of callbacks) {
      callback(void 0);
    }
    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 key2 in slots) {
    result[key2] = 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;
}

// node_modules/svelte/src/runtime/internal/globals.js
var globals = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : (
  // @ts-ignore Node typings have this
  global
);

// node_modules/svelte/src/runtime/internal/ResizeObserverSingleton.js
var ResizeObserverSingleton = class _ResizeObserverSingleton {
  /**
   * @private
   * @readonly
   * @type {WeakMap<Element, import('./private.js').Listener>}
   */
  _listeners = "WeakMap" in globals ? /* @__PURE__ */ new WeakMap() : void 0;
  /**
   * @private
   * @type {ResizeObserver}
   */
  _observer = void 0;
  /** @type {ResizeObserverOptions} */
  options;
  /** @param {ResizeObserverOptions} options */
  constructor(options3) {
    this.options = options3;
  }
  /**
   * @param {Element} element
   * @param {import('./private.js').Listener} listener
   * @returns {() => void}
   */
  observe(element2, listener) {
    this._listeners.set(element2, listener);
    this._getObserver().observe(element2, this.options);
    return () => {
      this._listeners.delete(element2);
      this._observer.unobserve(element2);
    };
  }
  /**
   * @private
   */
  _getObserver() {
    return this._observer ?? (this._observer = new ResizeObserver((entries) => {
      for (const entry of entries) {
        _ResizeObserverSingleton.entries.set(entry.target, entry);
        this._listeners.get(entry.target)?.(entry);
      }
    }));
  }
};
ResizeObserverSingleton.entries = "WeakMap" in globals ? /* @__PURE__ */ new WeakMap() : void 0;

// node_modules/svelte/src/runtime/internal/dom.js
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) {
  if (node.parentNode) {
    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, options3) {
  node.addEventListener(event, handler, options3);
  return () => node.removeEventListener(event, handler, options3);
}
function prevent_default(fn) {
  return function(event) {
    event.preventDefault();
    return fn.call(this, event);
  };
}
function stop_propagation(fn) {
  return function(event) {
    event.stopPropagation();
    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 set_custom_element_data(node, prop, value) {
  const lower2 = prop.toLowerCase();
  if (lower2 in node) {
    node[lower2] = typeof node[lower2] === "boolean" && value === "" ? true : value;
  } else if (prop in node) {
    node[prop] = typeof node[prop] === "boolean" && value === "" ? true : value;
  } else {
    attr(node, prop, value);
  }
}
function init_binding_group(group2) {
  let _inputs;
  return {
    /* push */
    p(...inputs) {
      _inputs = inputs;
      _inputs.forEach((input) => group2.push(input));
    },
    /* remove */
    r() {
      _inputs.forEach((input) => group2.splice(group2.indexOf(input), 1));
    }
  };
}
function children(element2) {
  return Array.from(element2.childNodes);
}
function set_data(text2, data) {
  data = "" + data;
  if (text2.data === data)
    return;
  text2.data = /** @type {string} */
  data;
}
function set_input_value(input, value) {
  input.value = value == null ? "" : value;
}
function set_style(node, key2, value, important) {
  if (value == null) {
    node.style.removeProperty(key2);
  } else {
    node.style.setProperty(key2, value, important ? "important" : "");
  }
}
function select_option(select, value, mounting) {
  for (let i = 0; i < select.options.length; i += 1) {
    const option = select.options[i];
    if (option.__value === value) {
      option.selected = true;
      return;
    }
  }
  if (!mounting || value !== void 0) {
    select.selectedIndex = -1;
  }
}
function select_value(select) {
  const selected_option = select.querySelector(":checked");
  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 (error2) {
      crossorigin = true;
    }
  }
  return crossorigin;
}
function add_iframe_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",
      /** @param {MessageEvent} event */
      (event) => {
        if (event.source === iframe.contentWindow)
          fn();
      }
    );
  } else {
    iframe.src = "about:blank";
    iframe.onload = () => {
      unsubscribe = listen(iframe.contentWindow, "resize", fn);
      fn();
    };
  }
  append(node, iframe);
  return () => {
    if (crossorigin2) {
      unsubscribe();
    } else if (unsubscribe && iframe.contentWindow) {
      unsubscribe();
    }
    detach(iframe);
  };
}
function toggle_class(element2, name2, toggle2) {
  element2.classList.toggle(name2, !!toggle2);
}
function custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {
  return new CustomEvent(type, { detail, bubbles, cancelable });
}
var HtmlTag = class {
  /**
   * @private
   * @default false
   */
  is_svg = false;
  /** parent for creating node */
  e = void 0;
  /** html tag nodes */
  n = void 0;
  /** target */
  t = void 0;
  /** anchor */
  a = void 0;
  constructor(is_svg = false) {
    this.is_svg = is_svg;
    this.e = this.n = null;
  }
  /**
   * @param {string} html
   * @returns {void}
   */
  c(html) {
    this.h(html);
  }
  /**
   * @param {string} html
   * @param {HTMLElement | SVGElement} target
   * @param {HTMLElement | SVGElement} anchor
   * @returns {void}
   */
  m(html, target, anchor = null) {
    if (!this.e) {
      if (this.is_svg)
        this.e = svg_element(
          /** @type {keyof SVGElementTagNameMap} */
          target.nodeName
        );
      else
        this.e = element(
          /** @type {keyof HTMLElementTagNameMap} */
          target.nodeType === 11 ? "TEMPLATE" : target.nodeName
        );
      this.t = target.tagName !== "TEMPLATE" ? target : (
        /** @type {HTMLTemplateElement} */
        target.content
      );
      this.c(html);
    }
    this.i(anchor);
  }
  /**
   * @param {string} html
   * @returns {void}
   */
  h(html) {
    this.e.innerHTML = html;
    this.n = Array.from(
      this.e.nodeName === "TEMPLATE" ? this.e.content.childNodes : this.e.childNodes
    );
  }
  /**
   * @returns {void} */
  i(anchor) {
    for (let i = 0; i < this.n.length; i += 1) {
      insert(this.t, this.n[i], anchor);
    }
  }
  /**
   * @param {string} html
   * @returns {void}
   */
  p(html) {
    this.d();
    this.h(html);
    this.i(this.a);
  }
  /**
   * @returns {void} */
  d() {
    this.n.forEach(detach);
  }
};
function get_custom_elements_slots(element2) {
  const result = {};
  element2.childNodes.forEach(
    /** @param {Element} node */
    (node) => {
      result[node.slot || "default"] = true;
    }
  );
  return result;
}

// node_modules/svelte/src/runtime/internal/lifecycle.js
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 {string} */
        type,
        detail,
        { cancelable }
      );
      callbacks.slice().forEach((fn) => {
        fn.call(component, event);
      });
      return !event.defaultPrevented;
    }
    return true;
  };
}
function setContext(key2, context2) {
  get_current_component().$$.context.set(key2, context2);
  return context2;
}
function getContext(key2) {
  return get_current_component().$$.context.get(key2);
}

// node_modules/svelte/src/runtime/internal/scheduler.js
var dirty_components = [];
var binding_callbacks = [];
var render_callbacks = [];
var flush_callbacks = [];
var resolved_promise = /* @__PURE__ */ 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() {
  if (flushidx !== 0) {
    return;
  }
  const saved_component = current_component;
  do {
    try {
      while (flushidx < dirty_components.length) {
        const component = dirty_components[flushidx];
        flushidx++;
        set_current_component(component);
        update(component.$$);
      }
    } catch (e3) {
      dirty_components.length = 0;
      flushidx = 0;
      throw e3;
    }
    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);
  }
}
function flush_render_callbacks(fns) {
  const filtered = [];
  const targets = [];
  render_callbacks.forEach((c) => fns.indexOf(c) === -1 ? filtered.push(c) : targets.push(c));
  targets.forEach((c) => c());
  render_callbacks = filtered;
}

// node_modules/svelte/src/runtime/internal/transitions.js
var outroing = /* @__PURE__ */ new Set();
var outros;
function group_outros() {
  outros = {
    r: 0,
    c: [],
    p: outros
    // parent group
  };
}
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();
  }
}

// node_modules/svelte/src/runtime/internal/await_block.js
function handle_promise(promise, info2) {
  const token = info2.token = {};
  function update2(type, index2, key2, value) {
    if (info2.token !== token)
      return;
    info2.resolved = value;
    let child_ctx = info2.ctx;
    if (key2 !== void 0) {
      child_ctx = child_ctx.slice();
      child_ctx[key2] = value;
    }
    const block = type && (info2.current = type)(child_ctx);
    let needs_flush = false;
    if (info2.block) {
      if (info2.blocks) {
        info2.blocks.forEach((block2, i) => {
          if (i !== index2 && block2) {
            group_outros();
            transition_out(block2, 1, 1, () => {
              if (info2.blocks[i] === block2) {
                info2.blocks[i] = null;
              }
            });
            check_outros();
          }
        });
      } else {
        info2.block.d(1);
      }
      block.c();
      transition_in(block, 1);
      block.m(info2.mount(), info2.anchor);
      needs_flush = true;
    }
    info2.block = block;
    if (info2.blocks)
      info2.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(info2.then, 1, info2.value, value);
        set_current_component(null);
      },
      (error2) => {
        set_current_component(current_component2);
        update2(info2.catch, 2, info2.error, error2);
        set_current_component(null);
        if (!info2.hasCatch) {
          throw error2;
        }
      }
    );
    if (info2.current !== info2.pending) {
      update2(info2.pending, 0);
      return true;
    }
  } else {
    if (info2.current !== info2.then) {
      update2(info2.then, 1, info2.value, promise);
      return true;
    }
    info2.resolved = /** @type {T} */
    promise;
  }
}
function update_await_block_branch(info2, ctx2, dirty) {
  const child_ctx = ctx2.slice();
  const { resolved } = info2;
  if (info2.current === info2.then) {
    child_ctx[info2.value] = resolved;
  }
  if (info2.current === info2.catch) {
    child_ctx[info2.error] = resolved;
  }
  info2.block.p(child_ctx, dirty);
}

// node_modules/svelte/src/runtime/internal/each.js
function ensure_array_like(array_like_or_iterator) {
  return array_like_or_iterator?.length !== void 0 ? array_like_or_iterator : Array.from(array_like_or_iterator);
}
function destroy_block(block, lookup) {
  block.d(1);
  lookup.delete(block.key);
}
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_block39, 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();
  const updates = [];
  i = n;
  while (i--) {
    const child_ctx = get_context(ctx2, list, i);
    const key2 = get_key(child_ctx);
    let block = lookup.get(key2);
    if (!block) {
      block = create_each_block39(key2, child_ctx);
      block.c();
    } else if (dynamic) {
      updates.push(() => block.p(child_ctx, dirty));
    }
    new_lookup.set(key2, new_blocks[i] = block);
    if (key2 in old_indexes)
      deltas.set(key2, Math.abs(i - old_indexes[key2]));
  }
  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]);
  run_all(updates);
  return new_blocks;
}

// node_modules/svelte/src/shared/boolean_attributes.js
var _boolean_attributes = (
  /** @type {const} */
  [
    "allowfullscreen",
    "allowpaymentrequest",
    "async",
    "autofocus",
    "autoplay",
    "checked",
    "controls",
    "default",
    "defer",
    "disabled",
    "formnovalidate",
    "hidden",
    "inert",
    "ismap",
    "loop",
    "multiple",
    "muted",
    "nomodule",
    "novalidate",
    "open",
    "playsinline",
    "readonly",
    "required",
    "reversed",
    "selected"
  ]
);
var boolean_attributes = /* @__PURE__ */ new Set([..._boolean_attributes]);

// node_modules/svelte/src/runtime/internal/Component.js
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) {
  const { fragment, after_update } = component.$$;
  fragment && fragment.m(target, anchor);
  add_render_callback(() => {
    const new_on_destroy = component.$$.on_mount.map(run2).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) {
    flush_render_callbacks($$.after_update);
    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 init2(component, options3, instance80, create_fragment81, not_equal, props2, append_styles = null, dirty = [-1]) {
  const parent_component = current_component;
  set_current_component(component);
  const $$ = component.$$ = {
    fragment: null,
    ctx: [],
    // state
    props: props2,
    update: noop,
    not_equal,
    bound: blank_object(),
    // lifecycle
    on_mount: [],
    on_destroy: [],
    on_disconnect: [],
    before_update: [],
    after_update: [],
    context: new Map(options3.context || (parent_component ? parent_component.$$.context : [])),
    // everything else
    callbacks: blank_object(),
    dirty,
    skip_bound: false,
    root: options3.target || parent_component.$$.root
  };
  append_styles && append_styles($$.root);
  let ready = false;
  $$.ctx = instance80 ? instance80(component, options3.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_fragment81 ? create_fragment81($$.ctx) : false;
  if (options3.target) {
    if (options3.hydrate) {
      start_hydrating();
      const nodes = children(options3.target);
      $$.fragment && $$.fragment.l(nodes);
      nodes.forEach(detach);
    } else {
      $$.fragment && $$.fragment.c();
    }
    if (options3.intro)
      transition_in(component.$$.fragment);
    mount_component(component, options3.target, options3.anchor);
    end_hydrating();
    flush();
  }
  set_current_component(parent_component);
}
var SvelteElement;
if (typeof HTMLElement === "function") {
  SvelteElement = class extends HTMLElement {
    /** The Svelte component constructor */
    $$ctor;
    /** Slots */
    $$s;
    /** The Svelte component instance */
    $$c;
    /** Whether or not the custom element is connected */
    $$cn = false;
    /** Component props data */
    $$d = {};
    /** `true` if currently in the process of reflecting component props back to attributes */
    $$r = false;
    /** @type {Record<string, CustomElementPropDefinition>} Props definition (name, reflected, type etc) */
    $$p_d = {};
    /** @type {Record<string, Function[]>} Event listeners */
    $$l = {};
    /** @type {Map<Function, Function>} Event listener unsubscribe functions */
    $$l_u = /* @__PURE__ */ new Map();
    constructor($$componentCtor, $$slots, use_shadow_dom) {
      super();
      this.$$ctor = $$componentCtor;
      this.$$s = $$slots;
      if (use_shadow_dom) {
        this.attachShadow({ mode: "open" });
      }
    }
    addEventListener(type, listener, options3) {
      this.$$l[type] = this.$$l[type] || [];
      this.$$l[type].push(listener);
      if (this.$$c) {
        const unsub = this.$$c.$on(type, listener);
        this.$$l_u.set(listener, unsub);
      }
      super.addEventListener(type, listener, options3);
    }
    removeEventListener(type, listener, options3) {
      super.removeEventListener(type, listener, options3);
      if (this.$$c) {
        const unsub = this.$$l_u.get(listener);
        if (unsub) {
          unsub();
          this.$$l_u.delete(listener);
        }
      }
    }
    async connectedCallback() {
      this.$$cn = true;
      if (!this.$$c) {
        let create_slot2 = function(name2) {
          return () => {
            let node;
            const obj = {
              c: function create() {
                node = element("slot");
                if (name2 !== "default") {
                  attr(node, "name", name2);
                }
              },
              /**
               * @param {HTMLElement} target
               * @param {HTMLElement} [anchor]
               */
              m: function mount(target, anchor) {
                insert(target, node, anchor);
              },
              d: function destroy(detaching) {
                if (detaching) {
                  detach(node);
                }
              }
            };
            return obj;
          };
        };
        await Promise.resolve();
        if (!this.$$cn || this.$$c) {
          return;
        }
        const $$slots = {};
        const existing_slots = get_custom_elements_slots(this);
        for (const name2 of this.$$s) {
          if (name2 in existing_slots) {
            $$slots[name2] = [create_slot2(name2)];
          }
        }
        for (const attribute of this.attributes) {
          const name2 = this.$$g_p(attribute.name);
          if (!(name2 in this.$$d)) {
            this.$$d[name2] = get_custom_element_value(name2, attribute.value, this.$$p_d, "toProp");
          }
        }
        for (const key2 in this.$$p_d) {
          if (!(key2 in this.$$d) && this[key2] !== void 0) {
            this.$$d[key2] = this[key2];
            delete this[key2];
          }
        }
        this.$$c = new this.$$ctor({
          target: this.shadowRoot || this,
          props: {
            ...this.$$d,
            $$slots,
            $$scope: {
              ctx: []
            }
          }
        });
        const reflect_attributes = () => {
          this.$$r = true;
          for (const key2 in this.$$p_d) {
            this.$$d[key2] = this.$$c.$$.ctx[this.$$c.$$.props[key2]];
            if (this.$$p_d[key2].reflect) {
              const attribute_value = get_custom_element_value(
                key2,
                this.$$d[key2],
                this.$$p_d,
                "toAttribute"
              );
              if (attribute_value == null) {
                this.removeAttribute(this.$$p_d[key2].attribute || key2);
              } else {
                this.setAttribute(this.$$p_d[key2].attribute || key2, attribute_value);
              }
            }
          }
          this.$$r = false;
        };
        this.$$c.$$.after_update.push(reflect_attributes);
        reflect_attributes();
        for (const type in this.$$l) {
          for (const listener of this.$$l[type]) {
            const unsub = this.$$c.$on(type, listener);
            this.$$l_u.set(listener, unsub);
          }
        }
        this.$$l = {};
      }
    }
    // We don't need this when working within Svelte code, but for compatibility of people using this outside of Svelte
    // and setting attributes through setAttribute etc, this is helpful
    attributeChangedCallback(attr2, _oldValue, newValue) {
      if (this.$$r)
        return;
      attr2 = this.$$g_p(attr2);
      this.$$d[attr2] = get_custom_element_value(attr2, newValue, this.$$p_d, "toProp");
      this.$$c?.$set({ [attr2]: this.$$d[attr2] });
    }
    disconnectedCallback() {
      this.$$cn = false;
      Promise.resolve().then(() => {
        if (!this.$$cn) {
          this.$$c.$destroy();
          this.$$c = void 0;
        }
      });
    }
    $$g_p(attribute_name) {
      return Object.keys(this.$$p_d).find(
        (key2) => this.$$p_d[key2].attribute === attribute_name || !this.$$p_d[key2].attribute && key2.toLowerCase() === attribute_name
      ) || attribute_name;
    }
  };
}
function get_custom_element_value(prop, value, props_definition, transform) {
  const type = props_definition[prop]?.type;
  value = type === "Boolean" && typeof value !== "boolean" ? value != null : value;
  if (!transform || !props_definition[prop]) {
    return value;
  } else if (transform === "toAttribute") {
    switch (type) {
      case "Object":
      case "Array":
        return value == null ? null : JSON.stringify(value);
      case "Boolean":
        return value ? "" : null;
      case "Number":
        return value == null ? null : value;
      default:
        return value;
    }
  } else {
    switch (type) {
      case "Object":
      case "Array":
        return value && JSON.parse(value);
      case "Boolean":
        return value;
      case "Number":
        return value != null ? +value : value;
      default:
        return value;
    }
  }
}
var SvelteComponent = class {
  /**
   * ### PRIVATE API
   *
   * Do not use, may change at any time
   *
   * @type {any}
   */
  $$ = void 0;
  /**
   * ### PRIVATE API
   *
   * Do not use, may change at any time
   *
   * @type {any}
   */
  $$set = void 0;
  /** @returns {void} */
  $destroy() {
    destroy_component(this, 1);
    this.$destroy = noop;
  }
  /**
   * @template {Extract<keyof Events, string>} K
   * @param {K} type
   * @param {((e: Events[K]) => void) | null | undefined} callback
   * @returns {() => void}
   */
  $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);
    };
  }
  /**
   * @param {Partial<Props>} props
   * @returns {void}
   */
  $set(props2) {
    if (this.$$set && !is_empty(props2)) {
      this.$$.skip_bound = true;
      this.$$set(props2);
      this.$$.skip_bound = false;
    }
  }
};

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

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

// src/lib/result.ts
var Ok = class _Ok {
  constructor(value) {
    this.value = value;
  }
  is_ok = true;
  is_err = false;
  and_then(op) {
    return op(this.value);
  }
  map(op) {
    return new _Ok(op(this.value));
  }
  map_err() {
    return this;
  }
  or_else() {
    return this;
  }
  unwrap() {
    return this.value;
  }
  unwrap_or() {
    return this.value;
  }
};
var Err = class _Err {
  constructor(error2) {
    this.error = error2;
  }
  is_ok = false;
  is_err = true;
  and_then() {
    return this;
  }
  map() {
    return this;
  }
  or_else(op) {
    return op(this.error);
  }
  map_err(op) {
    return new _Err(op(this.error));
  }
  unwrap() {
    throw new Error("Unwrap called on error.");
  }
  unwrap_or(val) {
    return val;
  }
};
function ok(value) {
  return new Ok(value);
}
function err2(error2) {
  return new Err(error2);
}
function collect(items) {
  const ok_values = [];
  for (const r of items) {
    if (r.is_ok) {
      ok_values.push(r.value);
    } else {
      return r;
    }
  }
  return ok(ok_values);
}

// src/lib/json.ts
function parseJSON(data) {
  try {
    return ok(JSON.parse(data));
  } catch (error2) {
    if (error2 instanceof SyntaxError) {
      return err2(`JSON syntax error: ${error2.message}`);
    }
    throw error2;
  }
}

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

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

// src/log.ts
function log_error(...args2) {
  console.error(...args2);
}
function assert2(condition, message, ...extraArgs) {
  console.assert(condition, message, ...extraArgs);
}

// src/i18n.ts
var translations;
var validator = record(string);
function _(text2) {
  if (translations === void 0) {
    const res2 = (
      // The DOM is not available in tests
      // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
      globalThis.document !== void 0 ? getScriptTagValue("#translations", validator) : ok({})
    );
    translations = res2.unwrap_or({});
    if (res2.is_err) {
      log_error(`Loading translations failed: ${res2.error}`);
    }
  }
  return translations[text2] ?? text2;
}
function format(text2, values) {
  return text2.replace(
    /%\(\w+\)s/g,
    (match) => values[match.slice(2, -2)] ?? "MISSING"
  );
}

// src/lib/interval.ts
var DEFAULT_INTERVAL = "month";
var INTERVALS = [
  "year",
  "quarter",
  "month",
  "week",
  "day"
];
function getInterval(s) {
  if (s && INTERVALS.includes(s)) {
    return s;
  }
  return DEFAULT_INTERVAL;
}
function intervalLabel(s) {
  return {
    year: _("Yearly"),
    quarter: _("Quarterly"),
    month: _("Monthly"),
    week: _("Weekly"),
    day: _("Daily")
  }[s];
}

// 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/store.ts
function derived_array(store, getter) {
  let val = [];
  return derived(
    store,
    (store_val, set2) => {
      const newVal = getter(store_val);
      if (!shallow_equal(val, newVal)) {
        set2(newVal);
        val = newVal;
      }
    },
    val
  );
}
function localStorageSyncedStore(key2, validator2, init4, values = () => []) {
  const fullKey = `fava-${key2}`;
  const store = writable(void 0, (set2) => {
    const stored_val = localStorage.getItem(fullKey);
    let initial = null;
    if (stored_val) {
      const val = parseJSON(stored_val).and_then(validator2).unwrap_or(null);
      if (val !== null) {
        initial = val;
      }
    }
    set2(initial ?? init4());
    store.subscribe((val) => {
      localStorage.setItem(fullKey, JSON.stringify(val));
    });
  });
  return { ...store, values };
}

// src/stores/index.ts
var conversion = writable("");
var interval = writable(DEFAULT_INTERVAL);
var errors = writable([]);
var ledgerData = writable();
var fava_options = derived(ledgerData, (v) => v.fava_options);
var conversion_currencies = derived_array(
  fava_options,
  ($fava_options) => $fava_options.conversion_currencies
);
var locale = derived(
  fava_options,
  ($fava_options) => $fava_options.locale
);
var options = derived(ledgerData, (v) => v.options);
var ledger_title = derived(options, ($options) => $options.title);
var operating_currency = derived_array(
  options,
  ($options) => [...$options.operating_currency].sort()
);
var precisions = derived(ledgerData, (v) => v.precisions);
var HAVE_EXCEL = derived(ledgerData, (v) => v.have_excel);
var incognito = derived(ledgerData, (v) => v.incognito);
var base_url = derived(ledgerData, (v) => v.base_url);
var extensions = derived(ledgerData, (v) => v.extensions);
var accounts = derived_array(ledgerData, (v) => v.accounts);
var currency_name = derived(
  ledgerData,
  ({ currency_names }) => (c) => currency_names[c] ?? c
);
var account_details = derived(ledgerData, (v) => v.account_details);
var currencies = derived_array(ledgerData, (v) => v.currencies);
var links = derived_array(ledgerData, (v) => v.links);
var payees = derived_array(ledgerData, (v) => v.payees);
var tags = derived_array(ledgerData, (v) => v.tags);
var years = derived_array(ledgerData, (v) => v.years);
var currencies_sorted = derived_array(
  currencies,
  ($currencies) => [...$currencies].sort()
);

// src/stores/url.ts
var urlHash = writable("");
var urlSyncedParams = [
  "account",
  "charts",
  "conversion",
  "filter",
  "interval",
  "time"
];
var pathname = writable();
var search = writable();
var searchParams = derived(
  search,
  ($search) => new URLSearchParams($search)
);
var synced_query_string = derived([searchParams], ([s]) => {
  const params = new URLSearchParams();
  for (const name2 of urlSyncedParams) {
    const value = s.get(name2);
    if (value) {
      params.set(name2, value);
    } else {
      params.delete(name2);
    }
  }
  const str = params.toString();
  return str ? `?${str}` : str;
});
function closeOverlay() {
  if (window.location.hash) {
    window.history.pushState({}, "", "#");
  }
  urlHash.set("");
}

// src/helpers.ts
function getUrlPath(url) {
  const $base_url = get_store_value(base_url);
  return $base_url && url.pathname.startsWith($base_url) ? decodeURI(url.pathname.slice($base_url.length)) : null;
}
function urlFor(report, params, update2 = true) {
  const url = `${get_store_value(base_url)}${report}`;
  const urlParams = new URLSearchParams();
  if (update2) {
    const oldParams = get_store_value(searchParams);
    for (const name2 of urlSyncedParams) {
      const value = oldParams.get(name2);
      if (value) {
        urlParams.set(name2, value);
      }
    }
  }
  if (params) {
    Object.entries(params).forEach(([key2, value]) => {
      if (value !== void 0) {
        urlParams.set(key2, `${value}`);
      }
    });
  }
  const urlParamString = urlParams.toString();
  return urlParamString ? `${url}?${urlParams.toString()}` : url;
}
function urlForSource(file_path, line) {
  return get_store_value(fava_options).use_external_editor ? `beancount://${file_path}?lineno=${line}` : urlFor("editor/", { file_path, line });
}
var urlForAccount = derived(
  [searchParams],
  () => (account2, params) => urlFor(`account/${account2}/`, params)
);

// src/stores/mtime.ts
var ledger_mtime_writable = writable(BigInt("0"));
var ledger_mtime = ledger_mtime_writable;
function set_mtime(text2) {
  const new_value = text2.startsWith("X") ? (
    // the timestamp is replaced by a sequence of `X` in incognito mode.
    BigInt(Date.now())
  ) : BigInt(text2);
  ledger_mtime_writable.update((v) => new_value > v ? new_value : v);
}
function read_mtime() {
  const el = document.getElementById("ledger-mtime");
  const text2 = el?.textContent;
  if (text2) {
    el.remove();
    set_mtime(text2);
  }
}

// src/lib/fetch.ts
var FetchError = class extends Error {
};
function fetch2(input, init4 = {}) {
  return window.fetch(input, { credentials: "same-origin", ...init4 });
}
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,
  mtime: defaultValue(string, () => null)
});
async function fetchJSON(input, init4) {
  const res2 = await fetch2(input, init4).then(handleJSON);
  const validated = response_validator(res2).unwrap_or(null);
  if (validated) {
    if (typeof validated.mtime === "string") {
      set_mtime(validated.mtime);
    }
    return validated.data;
  }
  log_error(res2);
  throw new FetchError("Invalid response: missing data or mtime key.");
}
async function handleText(response) {
  if (!response.ok) {
    const msg = await response.text();
    throw new Error(msg || response.statusText);
  }
  return response.text();
}

// src/notifications.ts
var notificationList = /* @__PURE__ */ (() => {
  let value = null;
  return () => {
    if (value === null) {
      value = document.createElement("div");
      value.className = "notifications";
      value.style.right = "10px";
      document.body.appendChild(value);
    }
    const headerHeight = document.querySelector("header")?.getBoundingClientRect().height ?? 50;
    value.style.top = `${headerHeight + 10}px`;
    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?.();
  });
  setTimeout(() => {
    notification.remove();
  }, 5e3);
}
function notify_warn(msg) {
  notify(msg, "warning");
  console.warn(msg);
}
function notify_err(error2, msg) {
  if (error2 instanceof Error) {
    notify(msg(error2), "error");
  }
  log_error(error2);
}

// src/lib/events.ts
var Events = class {
  events;
  constructor() {
    this.events = /* @__PURE__ */ new Map();
  }
  /**
   * Register an event listener.
   *
   * @returns A function to remove the event listener.
   */
  on(event, callback) {
    const events2 = this.events.get(event) ?? [];
    this.events.set(event, [...events2, callback]);
    return () => {
      this.remove(event, callback);
    };
  }
  /**
   * Register an event listener that will only be executed once.
   */
  once(event, callback) {
    const runOnce = () => {
      this.remove(event, runOnce);
      callback();
    };
    this.on(event, runOnce);
  }
  /**
   * Remove an event listener.
   */
  remove(event, callback) {
    const events2 = this.events.get(event);
    if (events2) {
      this.events.set(
        event,
        events2.filter((c) => c !== callback)
      );
    }
  }
  /**
   * Trigger all listeners for an event.
   */
  trigger(event) {
    const events2 = this.events.get(event);
    events2?.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/sidebar/page-title.ts
var raw_page_title = writable("");
var has_changes = writable(false);
var page_title = derived(
  raw_page_title,
  ($raw_page_title) => {
    if ($raw_page_title.startsWith("account:")) {
      return {
        title: $raw_page_title.slice("account:".length),
        type: "account"
      };
    }
    return { title: $raw_page_title, type: "plain" };
  }
);
function updatePageTitle() {
  const v = getScriptTagValue("#page-title", string);
  if (v.is_ok) {
    raw_page_title.set(v.value);
  }
}

// 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(null);
var hierarchyChartMode = localStorageSyncedStore(
  "hierarchy-chart-mode",
  union(constant("treemap"), constant("sunburst")),
  () => "treemap",
  () => [
    ["treemap", _("Treemap")],
    ["sunburst", _("Sunburst")]
  ]
);
var lineChartMode = localStorageSyncedStore(
  "line-chart-mode",
  union(constant("line"), constant("area")),
  () => "line",
  () => [
    ["line", _("Line chart")],
    ["area", _("Area chart")]
  ]
);
var barChartMode = localStorageSyncedStore(
  "bar-chart-mode",
  union(constant("stacked"), constant("single")),
  () => "stacked",
  () => [
    ["stacked", _("Stacked Bars")],
    ["single", _("Single Bars")]
  ]
);
var chartToggledCurrencies = localStorageSyncedStore(
  "chart-toggled-currencies",
  array(string),
  () => []
);
var treemapCurrency = writable(null);
var currency_suggestions = derived(
  [operating_currency, currencies_sorted, conversion_currencies],
  ([$operating_currency, $currencies_sorted, $conversion_currencies]) => $conversion_currencies.length > 0 ? $conversion_currencies : [
    ...$operating_currency,
    ...$currencies_sorted.filter(
      (c) => !$operating_currency.includes(c) && iso4217_default.has(c)
    )
  ]
);
var conversions = derived(
  currency_suggestions,
  ($currency_suggestions) => [
    "at_cost",
    "at_value",
    "units",
    ...$currency_suggestions
  ]
);

// src/stores/filters.ts
var time_filter = writable("");
var account_filter = writable("");
var fql_filter = writable("");
var filter_params = derived(
  [time_filter, account_filter, fql_filter],
  ([$time_filter, $account_filter, $fql_filter]) => ({
    time: $time_filter,
    account: $account_filter,
    filter: $fql_filter
  })
);
function getURLFilters(url) {
  return {
    account: url.searchParams.get("account") ?? "",
    filter: url.searchParams.get("filter") ?? "",
    time: url.searchParams.get("time") ?? "",
    conversion: url.searchParams.get("conversion") ?? "",
    interval: url.searchParams.get("interval") ?? ""
  };
}

// src/router.ts
function setStoreValuesFromURL() {
  const params = new URL(window.location.href).searchParams;
  account_filter.set(params.get("account") ?? "");
  fql_filter.set(params.get("filter") ?? "");
  time_filter.set(params.get("time") ?? "");
  interval.set(getInterval(params.get("interval")));
  conversion.set(params.get("conversion") ?? "at_cost");
  showCharts.set(params.get("charts") !== "false");
}
var is_loading_internal = writable(false);
var is_loading = is_loading_internal;
var Router = class extends Events {
  /** The URL hash. */
  hash;
  /** The URL pathname. */
  pathname;
  /** The URL search string. */
  search;
  /** The <article> element. */
  article;
  /** The frontend rendered routes. */
  frontend_routes;
  /** A possibly frontend rendered component. */
  frontend_route;
  /**
   * Function to intercept navigation, e.g., when there are unsaved changes.
   *
   * If they return a string, that is displayed to the user in an alert to
   * confirm navigation.
   */
  interruptHandlers;
  constructor() {
    super();
    const article = document.querySelector("article");
    if (!article) {
      throw new Error("<article> element is missing from markup");
    }
    this.article = article;
    this.hash = window.location.hash;
    this.pathname = window.location.pathname;
    this.search = window.location.search;
    this.interruptHandlers = /* @__PURE__ */ new Set();
  }
  /**
   * Add an interrupt handler. Returns a function that removes it.
   * This can be used directly in a svelte onMount hook.
   */
  addInteruptHandler(handler) {
    this.interruptHandlers.add(handler);
    return () => {
      this.interruptHandlers.delete(handler);
    };
  }
  /**
   * Check whether any of the registered interruptHandlers wants to stop
   * navigation.
   */
  shouldInterrupt() {
    for (const handler of this.interruptHandlers) {
      const ret = handler();
      if (ret) {
        return ret;
      }
    }
    return null;
  }
  async frontendRender(url) {
    const report = getUrlPath(url);
    const route = this.frontend_routes?.find(
      (r) => report?.startsWith(`${r.report}/`)
    );
    if (route) {
      is_loading_internal.set(true);
      try {
        await route.render(this.article, url, this.frontend_route);
      } finally {
        is_loading_internal.set(false);
      }
      raw_page_title.set(route.title);
    } else {
      this.frontend_route?.destroy();
    }
    this.frontend_route = route;
  }
  /**
   * This should be called once when the page has been loaded. Initializes the
   * router and takes over clicking on links.
   */
  init(frontend_routes2) {
    this.frontend_routes = frontend_routes2;
    urlHash.set(window.location.hash.slice(1));
    this.updateState();
    this.frontendRender(new URL(window.location.href)).catch(log_error);
    window.addEventListener("beforeunload", (event) => {
      const leaveMessage = this.shouldInterrupt();
      if (leaveMessage) {
        event.preventDefault();
      }
    });
    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();
  }
  /**
   * Go to URL. If load is `true`, load the page at URL, otherwise only update
   * the current state.
   */
  navigate(url, load = true) {
    if (load) {
      this.loadURL(url).catch(log_error);
    } else {
      window.history.pushState(null, "", url);
      this.updateState();
    }
  }
  /*
   * Replace <article> contents with the page at `url`.
   *
   * If `historyState` is false, do not create a history state and do not
   * scroll to top.
   */
  async loadURL(url, historyState = true) {
    const leaveMessage = this.shouldInterrupt();
    if (leaveMessage) {
      if (!window.confirm(leaveMessage)) {
        return;
      }
    }
    const getUrl = new URL(url, window.location.href);
    await this.frontendRender(getUrl);
    try {
      if (!this.frontend_route) {
        getUrl.searchParams.set("partial", "true");
        is_loading_internal.set(true);
        const content2 = await fetch2(getUrl.toString()).then(handleText);
        if (historyState) {
          window.history.pushState(null, "", url);
          window.scroll(0, 0);
        }
        this.updateState();
        this.article.innerHTML = content2;
      } else {
        if (historyState) {
          window.history.pushState(null, "", url);
          window.scroll(0, 0);
        }
        this.updateState();
      }
      this.trigger("page-loaded");
      setStoreValuesFromURL();
      const hash2 = window.location.hash.slice(1);
      urlHash.set(hash2);
      if (hash2) {
        document.getElementById(hash2)?.scrollIntoView();
      }
    } catch (error2) {
      notify_err(error2, (e3) => `Loading ${url} failed: ${e3.message}`);
    } finally {
      is_loading_internal.set(false);
    }
  }
  /*
   * Update the routers state.
   *
   * The routers state is used to distinguish between the user navigating the
   * browser history or the hash changing.
   */
  updateState() {
    this.hash = window.location.hash;
    this.pathname = window.location.pathname;
    this.search = window.location.search;
    pathname.set(this.pathname);
    search.set(this.search);
  }
  /*
   * Intercept all clicks on links (<a>) and .navigate() to the link instead.
   *
   * Doesn't intercept if
   *  - a button different from the main button is used,
   *  - a modifier key is pressed,
   *  - the link starts with a hash '#', or
   *  - the link has a `data-remote` attribute.
   */
  takeOverLinks() {
    const is_normal_click = (event) => event.button === 0 && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey;
    const is_external_link = (link) => link.hasAttribute("data-remote") || link instanceof HTMLAnchorElement && (link.host !== window.location.host || !link.protocol.startsWith("http"));
    delegate(
      document,
      "click",
      "a",
      (event, link) => {
        if (!is_normal_click(event)) {
          return;
        }
        if (event.defaultPrevented) {
          return;
        }
        if (link.getAttribute("href")?.charAt(0) === "#") {
          return;
        }
        if (is_external_link(link)) {
          return;
        }
        event.preventDefault();
        const href = link instanceof HTMLAnchorElement ? link.href : link.href.baseVal;
        this.navigate(href);
      }
    );
  }
  /*
   * Reload the page.
   */
  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);
}

// 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 number2(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(number2).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, key2 = keyof) {
    super();
    Object.defineProperties(this, { _intern: { value: /* @__PURE__ */ new Map() }, _key: { value: key2 } });
    if (entries != null)
      for (const [key3, value] of entries)
        this.set(key3, value);
  }
  get(key2) {
    return super.get(intern_get(this, key2));
  }
  has(key2) {
    return super.has(intern_get(this, key2));
  }
  set(key2, value) {
    return super.set(intern_set(this, key2), value);
  }
  delete(key2) {
    return super.delete(intern_delete(this, key2));
  }
};
var InternSet = class extends Set {
  constructor(values, key2 = keyof) {
    super();
    Object.defineProperties(this, { _intern: { value: /* @__PURE__ */ new Map() }, _key: { value: key2 } });
    if (values != null)
      for (const value of values)
        this.add(value);
  }
  has(value) {
    return super.has(intern_get(this, value));
  }
  add(value) {
    return super.add(intern_set(this, value));
  }
  delete(value) {
    return super.delete(intern_delete(this, value));
  }
};
function intern_get({ _intern, _key }, value) {
  const key2 = _key(value);
  return _intern.has(key2) ? _intern.get(key2) : value;
}
function intern_set({ _intern, _key }, value) {
  const key2 = _key(value);
  if (_intern.has(key2))
    return _intern.get(key2);
  _intern.set(key2, value);
  return value;
}
function intern_delete({ _intern, _key }, value) {
  const key2 = _key(value);
  if (_intern.has(key2)) {
    value = _intern.get(key2);
    _intern.delete(key2);
  }
  return value;
}
function keyof(value) {
  return value !== null && typeof value === "object" ? value.valueOf() : value;
}

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

// node_modules/d3-array/src/group.js
function group(values, ...keys) {
  return nest(values, identity2, identity2, keys);
}
function rollup(values, reduce, ...keys) {
  return nest(values, identity2, reduce, 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 key2 = keyof2(value, ++index2, values2);
      const group2 = groups2.get(key2);
      if (group2)
        group2.push(value);
      else
        groups2.set(key2, [value]);
    }
    for (const [key2, values3] of groups2) {
      groups2.set(key2, regroup(values3, i));
    }
    return map2(groups2);
  }(values, 0);
}

// node_modules/d3-array/src/permute.js
function permute(source2, keys) {
  return Array.from(keys, (key2) => source2[key2]);
}

// node_modules/d3-array/src/sort.js
function sort(values, ...F) {
  if (typeof values[Symbol.iterator] !== "function")
    throw new TypeError("values is not iterable");
  values = Array.from(values);
  let [f] = F;
  if (f && f.length !== 2 || F.length > 1) {
    const index2 = Uint32Array.from(values, (d, i) => i);
    if (F.length > 1) {
      F = F.map((f2) => values.map(f2));
      index2.sort((i, j) => {
        for (const f2 of F) {
          const c = ascendingDefined(f2[i], f2[j]);
          if (c)
            return c;
        }
      });
    } else {
      f = values.map(f);
      index2.sort((i, j) => ascendingDefined(f[i], f[j]));
    }
    return permute(values, index2);
  }
  return values.sort(compareDefined(f));
}
function compareDefined(compare2 = ascending) {
  if (compare2 === ascending)
    return ascendingDefined;
  if (typeof compare2 !== "function")
    throw new TypeError("compare is not a function");
  return (a, b) => {
    const x2 = compare2(a, b);
    if (x2 || x2 === 0)
      return x2;
    return (compare2(b, b) === 0) - (compare2(a, a) === 0);
  };
}
function ascendingDefined(a, b) {
  return (a == null || !(a >= a)) - (b == null || !(b >= b)) || (a < b ? -1 : a > b ? 1 : 0);
}

// node_modules/d3-array/src/ticks.js
var e10 = Math.sqrt(50);
var e5 = Math.sqrt(10);
var e2 = Math.sqrt(2);
function tickSpec(start2, stop2, count2) {
  const step = (stop2 - start2) / Math.max(0, count2), power = Math.floor(Math.log10(step)), error2 = step / Math.pow(10, power), factor = error2 >= e10 ? 10 : error2 >= e5 ? 5 : error2 >= e2 ? 2 : 1;
  let i1, i2, inc;
  if (power < 0) {
    inc = Math.pow(10, -power) / factor;
    i1 = Math.round(start2 * inc);
    i2 = Math.round(stop2 * inc);
    if (i1 / inc < start2)
      ++i1;
    if (i2 / inc > stop2)
      --i2;
    inc = -inc;
  } else {
    inc = Math.pow(10, power) * factor;
    i1 = Math.round(start2 / inc);
    i2 = Math.round(stop2 / inc);
    if (i1 * inc < start2)
      ++i1;
    if (i2 * inc > stop2)
      --i2;
  }
  if (i2 < i1 && 0.5 <= count2 && count2 < 2)
    return tickSpec(start2, stop2, count2 * 2);
  return [i1, i2, inc];
}
function ticks(start2, stop2, count2) {
  stop2 = +stop2, start2 = +start2, count2 = +count2;
  if (!(count2 > 0))
    return [];
  if (start2 === stop2)
    return [start2];
  const reverse = stop2 < start2, [i1, i2, inc] = reverse ? tickSpec(stop2, start2, count2) : tickSpec(start2, stop2, count2);
  if (!(i2 >= i1))
    return [];
  const n = i2 - i1 + 1, ticks2 = new Array(n);
  if (reverse) {
    if (inc < 0)
      for (let i = 0; i < n; ++i)
        ticks2[i] = (i2 - i) / -inc;
    else
      for (let i = 0; i < n; ++i)
        ticks2[i] = (i2 - i) * inc;
  } else {
    if (inc < 0)
      for (let i = 0; i < n; ++i)
        ticks2[i] = (i1 + i) / -inc;
    else
      for (let i = 0; i < n; ++i)
        ticks2[i] = (i1 + i) * inc;
  }
  return ticks2;
}
function tickIncrement(start2, stop2, count2) {
  stop2 = +stop2, start2 = +start2, count2 = +count2;
  return tickSpec(start2, stop2, count2)[2];
}
function tickStep(start2, stop2, count2) {
  stop2 = +stop2, start2 = +start2, count2 = +count2;
  const reverse = stop2 < start2, inc = reverse ? tickIncrement(stop2, start2, count2) : tickIncrement(start2, stop2, count2);
  return (reverse ? -1 : 1) * (inc < 0 ? 1 / -inc : inc);
}

// 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/range.js
function range(start2, stop2, step) {
  start2 = +start2, stop2 = +stop2, step = (n = arguments.length) < 2 ? (stop2 = start2, start2 = 0, 1) : n < 3 ? 1 : +step;
  var i = -1, n = Math.max(0, Math.ceil((stop2 - start2) / step)) | 0, range2 = new Array(n);
  while (++i < n) {
    range2[i] = start2 + i * step;
  }
  return range2;
}

// node_modules/d3-array/src/sum.js
function sum(values, valueof) {
  let sum2 = 0;
  if (valueof === void 0) {
    for (let value of values) {
      if (value = +value) {
        sum2 += value;
      }
    }
  } else {
    let index2 = -1;
    for (let value of values) {
      if (value = +valueof(value, ++index2, values)) {
        sum2 += value;
      }
    }
  }
  return sum2;
}

// node_modules/d3-array/src/intersection.js
function intersection(values, ...others) {
  values = new InternSet(values);
  others = others.map(set);
  out:
    for (const value of values) {
      for (const other of others) {
        if (!other.has(value)) {
          values.delete(value);
          continue out;
        }
      }
    }
  return values;
}
function set(values) {
  return values instanceof InternSet ? values : new InternSet(values);
}

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

// node_modules/d3-hierarchy/src/hierarchy/each.js
function each_default(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 sum2 = +value(node.data) || 0, children3 = node.children, i = children3 && children3.length;
    while (--i >= 0)
      sum2 += children3[i].value;
    node.value = sum2;
  });
}

// node_modules/d3-hierarchy/src/hierarchy/sort.js
function sort_default(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 start2 = this, ancestor = leastCommonAncestor(start2, end), nodes = [start2];
  while (start2 !== ancestor) {
    start2 = start2.parent;
    nodes.push(start2);
  }
  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_default() {
  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_default,
  eachAfter: eachAfter_default,
  eachBefore: eachBefore_default,
  find: find_default,
  sum: sum_default,
  sort: sort_default,
  path: path_default,
  ancestors: ancestors_default,
  descendants: descendants_default,
  leaves: leaves_default,
  links: links_default,
  copy: node_copy,
  [Symbol.iterator]: iterator_default
};

// 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_default(x2) {
  return function() {
    return x2;
  };
}

// node_modules/d3-hierarchy/src/treemap/round.js
function round_default(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_default);
    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_default);
    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_default(+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_default(+x2), treemap) : paddingTop;
  };
  treemap.paddingRight = function(x2) {
    return arguments.length ? (paddingRight = typeof x2 === "function" ? x2 : constant_default(+x2), treemap) : paddingRight;
  };
  treemap.paddingBottom = function(x2) {
    return arguments.length ? (paddingBottom = typeof x2 === "function" ? x2 : constant_default(+x2), treemap) : paddingBottom;
  };
  treemap.paddingLeft = function(x2) {
    return arguments.length ? (paddingLeft = typeof x2 === "function" ? x2 : constant_default(+x2), treemap) : paddingLeft;
  };
  return treemap;
}

// src/charts/hierarchy.ts
function addInternalNodesAsLeaves({
  account: account2,
  balance,
  children: children3
}) {
  if (children3.length) {
    const c = children3.map(addInternalNodesAsLeaves);
    c.push({ account: account2, balance, children: [], dummy: true });
    return { account: account2, balance: {}, children: c, dummy: false };
  }
  return { account: account2, balance, children: [], dummy: false };
}
var HierarchyChart = class {
  constructor(name2, data) {
    this.name = name2;
    this.data = data;
  }
  type = "hierarchy";
};
var account_hierarchy_validator = object({
  account: string,
  balance: record(number),
  balance_children: record(number),
  children: lazy(() => array(account_hierarchy_validator)),
  cost: optional(record(number)),
  cost_children: optional(record(number)),
  has_txns: defaultValue(boolean, () => false)
});
function hierarchy_from_parsed_data(label, data, { currencies: currencies2 }) {
  const root2 = addInternalNodesAsLeaves(data);
  return new HierarchyChart(
    label,
    new Map(
      currencies2.map((currency) => {
        const r = hierarchy(root2);
        const root_balance = sum(
          r.descendants(),
          (n) => n.data.balance[currency] ?? 0
        );
        const sign = root_balance ? Math.sign(root_balance) : 1;
        r.sum(
          (d) => sign * Math.max(sign * (d.balance[currency] ?? 0), 0)
        ).sort((a, b) => sign * ((b.value ?? 0) - (a.value ?? 0)));
        return [currency, r];
      }).filter(([, h]) => h.value)
    )
  );
}
var hierarchy_data_with_modifier = object({
  modifier: number,
  root: unknown
});
function hierarchy2(label, json, $chartContext) {
  const with_modifier = hierarchy_data_with_modifier(json);
  if (with_modifier.is_ok) {
    notify_warn(
      "Tree for the hierarchy chart should now be specified at the top-level directly.\n{ modifier: 1, root: { ...children } } -> { ...children }"
    );
  }
  const root2 = with_modifier.is_ok ? with_modifier.value.root : json;
  return account_hierarchy_validator(root2).map(
    (r) => hierarchy_from_parsed_data(label, r, $chartContext)
  );
}

// src/lib/objects.ts
function is_empty2(obj) {
  return Object.keys(obj).length === 0;
}

// src/entries.ts
var entry_meta_validator = record(
  defaultValue(
    union(boolean, number, string),
    () => "Unsupported metadata value"
  )
);
var Posting = class _Posting {
  account;
  amount;
  meta;
  constructor() {
    this.account = "";
    this.amount = "";
    this.meta = {};
  }
  is_empty() {
    return !this.account && !this.amount && is_empty2(this.meta);
  }
  static raw_validator = object({
    account: string,
    amount: string,
    meta: defaultValue(entry_meta_validator, () => ({}))
  });
  static validator = (json) => _Posting.raw_validator(json).map(
    (value) => Object.assign(new _Posting(), value)
  );
};
var validatorBase = {
  t: string,
  date: string,
  meta: entry_meta_validator
};
var entryBaseValidator = object(
  validatorBase
);
var EntryBase = class {
  t;
  date;
  meta;
  constructor(type, date4) {
    this.t = type;
    this.meta = {};
    this.date = date4;
  }
};
var Balance = class _Balance extends EntryBase {
  account;
  amount;
  constructor(date4) {
    super("Balance", date4);
    this.account = "";
    this.amount = { number: "", currency: "" };
  }
  static raw_validator = object({
    ...validatorBase,
    t: constant("Balance"),
    account: string,
    amount: object({ number: string, currency: string })
  });
  static validator = (json) => _Balance.raw_validator(json).map(
    (value) => Object.assign(new _Balance(value.date), value)
  );
};
var Document = class _Document extends EntryBase {
  account;
  filename;
  constructor(date4) {
    super("Document", date4);
    this.account = "";
    this.filename = "";
  }
  static raw_validator = object({
    ...validatorBase,
    t: constant("Document"),
    account: string,
    filename: string
  });
  static validator = (json) => _Document.raw_validator(json).map(
    (value) => Object.assign(new _Document(value.date), value)
  );
};
var Event = class _Event extends EntryBase {
  type;
  description;
  constructor(date4) {
    super("Event", date4);
    this.type = "";
    this.description = "";
  }
  static raw_validator = object({
    ...validatorBase,
    t: constant("Event"),
    type: string,
    description: string
  });
  static validator = (json) => _Event.raw_validator(json).map(
    (value) => Object.assign(new _Event(value.date), value)
  );
};
var Note = class _Note extends EntryBase {
  account;
  comment;
  constructor(date4) {
    super("Note", date4);
    this.account = "";
    this.comment = "";
  }
  static raw_validator = object({
    ...validatorBase,
    t: constant("Note"),
    account: string,
    comment: string
  });
  static validator = (json) => _Note.raw_validator(json).map(
    (value) => Object.assign(new _Note(value.date), value)
  );
};
var Transaction = class _Transaction extends EntryBase {
  flag;
  payee;
  narration;
  tags;
  links;
  postings;
  constructor(date4) {
    super("Transaction", date4);
    this.flag = "*";
    this.payee = "";
    this.narration = "";
    this.tags = [];
    this.links = [];
    this.postings = [];
  }
  toString() {
    const postings = this.postings.map((p) => `  ${p.account}  ${p.amount}`);
    return `${this.date} ${this.flag} "${this.payee}" "${this.narration}"
${postings.join("\n")}`;
  }
  toJSON() {
    return {
      ...this,
      postings: this.postings.filter((p) => !p.is_empty())
    };
  }
  static raw_validator = object({
    ...validatorBase,
    t: constant("Transaction"),
    flag: string,
    payee: optional_string,
    narration: optional_string,
    tags: array(string),
    links: array(string),
    postings: array(Posting.validator)
  });
  static validator = (json) => _Transaction.raw_validator(json).map(
    (value) => Object.assign(new _Transaction(value.date), value)
  );
};
var entryValidator = union(
  Balance.validator,
  Document.validator,
  Event.validator,
  Note.validator,
  Transaction.validator
);
function isDuplicate(e3) {
  return !!e3.meta.__duplicate__;
}

// src/api/validators.ts
var error_validator = object({
  type: string,
  message: string,
  source: optional(object({ filename: string, lineno: number }))
});
var account_details2 = record(
  object({
    balance_string: optional(string),
    close_date: optional(date),
    last_entry: optional(object({ date, entry_hash: string })),
    uptodate_status: optional(string)
  })
);
var fava_options2 = object({
  auto_reload: boolean,
  currency_column: number,
  conversion_currencies: array(string),
  collapse_pattern: array(string),
  import_config: optional(string),
  indent: number,
  invert_income_liabilities_equity: boolean,
  show_closed_accounts: boolean,
  show_accounts_with_zero_balance: boolean,
  show_accounts_with_zero_transactions: boolean,
  locale: optional(string),
  uptodate_indicator_grey_lookback_days: number,
  insert_entry: array(
    object({ date: string, filename: string, lineno: number, re: string })
  ),
  use_external_editor: boolean
});
var options2 = object({
  documents: array(string),
  filename: string,
  include: array(string),
  name_assets: string,
  name_equity: string,
  name_expenses: string,
  name_income: string,
  name_liabilities: string,
  operating_currency: array(string),
  title: string
});
var extensions2 = array(
  object({
    name: string,
    report_title: optional(string),
    has_js_module: boolean
  })
);
var ledgerDataValidator = object({
  account_details: account_details2,
  accounts: array(string),
  base_url: string,
  currencies: array(string),
  currency_names: record(string),
  errors: array(error_validator),
  extensions: extensions2,
  fava_options: fava_options2,
  have_excel: boolean,
  incognito: boolean,
  links: array(string),
  options: options2,
  other_ledgers: array(tuple([string, string])),
  payees: array(string),
  precisions: record(number),
  sidebar_links: array(tuple([string, string])),
  tags: array(string),
  upcoming_events_count: number,
  user_queries: array(object({ name: string, query_string: string })),
  years: array(string)
});
var importable_files_validator = array(
  object({
    name: string,
    basename: string,
    importers: array(
      object({
        account: string,
        importer_name: string,
        date: optional(string),
        name: optional(string)
      })
    )
  })
);
var date_range = object({ begin: date, end: date });
var commodities = array(
  object({ base: string, quote: string, prices: array(tuple([date, number])) })
);
var context = object({
  entry: entryBaseValidator,
  balances_before: optional(record(array(string))),
  balances_after: optional(record(array(string))),
  sha256sum: string,
  slice: string
});
var account_budget = object({
  budget: record(number),
  budget_children: record(number)
});
var source = object({
  file_path: string,
  sha256sum: string,
  source: string
});
var tree_report = object({
  charts: unknown,
  trees: array(account_hierarchy_validator),
  date_range: optional(date_range)
});
var getAPIValidators = {
  balance_sheet: tree_report,
  account_report: object({
    charts: unknown,
    journal: optional(string),
    dates: optional(array(date_range)),
    interval_balances: optional(array(account_hierarchy_validator)),
    budgets: optional(record(array(account_budget)))
  }),
  changed: boolean,
  commodities,
  context,
  documents: array(Document.validator),
  errors: array(error_validator),
  events: array(Event.validator),
  extract: array(entryValidator),
  imports: importable_files_validator,
  income_statement: tree_report,
  ledger_data: ledgerDataValidator,
  move: string,
  payee_accounts: array(string),
  payee_transaction: Transaction.validator,
  query_result: object({ chart: unknown, table: string }),
  source,
  trial_balance: tree_report
};

// src/api/index.ts
async function put(endpoint, body2) {
  const opts2 = body2 instanceof FormData ? { body: body2 } : {
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body2)
  };
  const url = urlFor(`api/${endpoint}`);
  const json = await fetchJSON(url, { method: "PUT", ...opts2 });
  const res2 = string(json);
  if (res2.is_ok) {
    return res2.value;
  }
  notify(`Invalid data returned in API request: ${res2.error}`, "error");
  throw new Error(res2.error);
}
async function get(endpoint, ...[params]) {
  const url = urlFor(`api/${endpoint}`, params, false);
  const json = await fetchJSON(url);
  const res2 = getAPIValidators[endpoint](json);
  if (res2.is_ok) {
    return res2.value;
  }
  notify(`Invalid data returned in API request: ${res2.error}`, "error");
  throw new Error(res2.error);
}
async function doDelete(endpoint, params) {
  const url = urlFor(`api/${endpoint}`, params, false);
  const json = await fetchJSON(url, { method: "DELETE" });
  const res2 = string(json);
  if (res2.is_ok) {
    return res2.value;
  }
  notify(`Invalid data returned in API request: ${res2.error}`, "error");
  throw new Error(res2.error);
}
async function moveDocument(filename, account2, new_name) {
  try {
    const msg = await get("move", { filename, account: account2, new_name });
    notify(msg);
    return true;
  } catch (error2) {
    notify_err(error2, (e3) => e3.message);
    return false;
  }
}
async function deleteDocument(filename) {
  try {
    const msg = await doDelete("document", { filename });
    notify(msg);
    return true;
  } catch (error2) {
    notify_err(error2, (e3) => e3.message);
    return false;
  }
}
async function saveEntries(entries) {
  if (!entries.length) {
    return;
  }
  try {
    const data = await put("add_entries", { entries });
    router_default.reload();
    notify(data);
  } catch (error2) {
    notify_err(error2, (e3) => `Saving failed: ${e3.message}`);
    throw error2;
  }
}

// src/clipboard.ts
var CopyableText = class extends HTMLElement {
  constructor() {
    super();
    this.addEventListener("click", (event) => {
      const text2 = this.getAttribute("data-clipboard-text");
      if (text2) {
        navigator.clipboard.writeText(text2).catch(log_error);
      }
      event.stopPropagation();
    });
  }
};

// node_modules/@codemirror/state/dist/index.js
var Text = class _Text {
  /**
  Get the line description around the given position.
  */
  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);
  }
  /**
  Get the description for the given (1-based) line number.
  */
  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 a range of the text with the given content.
  */
  replace(from, to, text2) {
    [from, to] = clip(this, from, to);
    let parts = [];
    this.decompose(
      0,
      from,
      parts,
      2
      /* Open.To */
    );
    if (text2.length)
      text2.decompose(
        0,
        text2.length,
        parts,
        1 | 2
        /* Open.To */
      );
    this.decompose(
      to,
      this.length,
      parts,
      1
      /* Open.From */
    );
    return TextNode.from(parts, this.length - (to - from) + text2.length);
  }
  /**
  Append another document to this one.
  */
  append(other) {
    return this.replace(this.length, this.length, other);
  }
  /**
  Retrieve the text between the given points.
  */
  slice(from, to = this.length) {
    [from, to] = clip(this, from, to);
    let parts = [];
    this.decompose(from, to, parts, 0);
    return TextNode.from(parts, to - from);
  }
  /**
  Test whether this text is equal to another instance.
  */
  eq(other) {
    if (other == this)
      return true;
    if (other.length != this.length || other.lines != this.lines)
      return false;
    let start2 = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1);
    let a = new RawTextCursor(this), b = new RawTextCursor(other);
    for (let skip = start2, pos = start2; ; ) {
      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;
    }
  }
  /**
  Iterate over the text. When `dir` is `-1`, iteration happens
  from end to start. This will return lines and the breaks between
  them as separate strings.
  */
  iter(dir = 1) {
    return new RawTextCursor(this, dir);
  }
  /**
  Iterate over a range of the text. When `from` > `to`, the
  iterator will run in reverse.
  */
  iterRange(from, to = this.length) {
    return new PartialTextCursor(this, from, to);
  }
  /**
  Return a cursor that iterates over the given range of lines,
  _without_ returning the line breaks between, and yielding empty
  strings for empty lines.
  
  When `from` and `to` are given, they should be 1-based line numbers.
  */
  iterLines(from, to) {
    let inner;
    if (from == null) {
      inner = this.iter();
    } else {
      if (to == null)
        to = this.lines + 1;
      let start2 = this.line(from).from;
      inner = this.iterRange(start2, Math.max(start2, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to));
    }
    return new LineCursor(inner);
  }
  /**
  Return the document as a string, using newline characters to
  separate lines.
  */
  toString() {
    return this.sliceString(0);
  }
  /**
  Convert the document to an array of lines (which can be
  deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)).
  */
  toJSON() {
    let lines = [];
    this.flatten(lines);
    return lines;
  }
  /**
  @internal
  */
  constructor() {
  }
  /**
  Create a `Text` instance for the given array of 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 _TextLeaf 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 string4 = this.text[i], end = offset + string4.length;
      if ((isLine ? line : end) >= target)
        return new Line(offset, end, line, string4);
      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);
    [from, to] = clip(this, from, to);
    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") {
    [from, to] = clip(this, from, to);
    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 _TextNode 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) {
    [from, to] = clip(this, from, to);
    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") {
    [from, to] = clip(this, from, to);
    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
      /* Tree.BranchShift */
    ), 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, start2, end) {
    this.value = "";
    this.done = false;
    this.cursor = new RawTextCursor(text2, start2 > end ? -1 : 1);
    this.pos = start2 > end ? text2.length : 0;
    this.from = Math.min(start2, end);
    this.to = Math.max(start2, 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.afterBreak) {
      this.value = "";
      this.afterBreak = false;
    } else 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 {
  /**
  @internal
  */
  constructor(from, to, number7, text2) {
    this.from = from;
    this.to = to;
    this.number = number7;
    this.text = text2;
  }
  /**
  The length of the line (not including any line break after it).
  */
  get length() {
    return this.to - this.from;
  }
};
function clip(text2, from, to) {
  from = Math.max(0, Math.min(text2.length, from));
  return [from, Math.max(from, Math.min(text2.length, to))];
}
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 _ChangeDesc {
  // Sections are encoded as pairs of integers. The first is the
  // length in the current document, and the second is -1 for
  // unaffected sections, and the length of the replacement content
  // otherwise. So an insertion would be (0, n>0), a deletion (n>0,
  // 0), and a replacement two positive numbers.
  /**
  @internal
  */
  constructor(sections) {
    this.sections = sections;
  }
  /**
  The length of the document before the change.
  */
  get length() {
    let result = 0;
    for (let i = 0; i < this.sections.length; i += 2)
      result += this.sections[i];
    return result;
  }
  /**
  The length of the document after the change.
  */
  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;
  }
  /**
  False when there are actual changes in this set.
  */
  get empty() {
    return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0;
  }
  /**
  Iterate over the unchanged parts left by these changes. `posA`
  provides the position of the range in the old document, `posB`
  the new position in the changed document.
  */
  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;
    }
  }
  /**
  Iterate over the ranges changed by these changes. (See
  [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a
  variant that also provides you with the inserted text.)
  `fromA`/`toA` provides the extent of the change in the starting
  document, `fromB`/`toB` the extent of the replacement in the
  changed document.
  
  When `individual` is true, adjacent changes (which are kept
  separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are
  reported separately.
  */
  iterChangedRanges(f, individual = false) {
    iterChanges(this, f, individual);
  }
  /**
  Get a description of the inverted form of these changes.
  */
  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);
  }
  /**
  Compute the combined effect of applying another set of changes
  after this one. The length of the document after this set should
  match the length before `other`.
  */
  composeDesc(other) {
    return this.empty ? other : other.empty ? this : composeSets(this, other);
  }
  /**
  Map this description, which should start with the same document
  as `other`, over another set of changes, so that it can be
  applied after it. When `before` is true, map as if the changes
  in `other` happened before the ones in `this`.
  */
  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;
  }
  /**
  Check whether these changes touch a given range. When one of the
  changes entirely covers the range, the string `"cover"` is
  returned.
  */
  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;
  }
  /**
  @internal
  */
  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;
  }
  /**
  Serialize this change desc to a JSON-representable value.
  */
  toJSON() {
    return this.sections;
  }
  /**
  Create a change desc from its JSON representation (as produced
  by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).
  */
  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);
  }
  /**
  @internal
  */
  static create(sections) {
    return new _ChangeDesc(sections);
  }
};
var ChangeSet = class _ChangeSet extends ChangeDesc {
  constructor(sections, inserted) {
    super(sections);
    this.inserted = inserted;
  }
  /**
  Apply the changes to a document, returning the modified
  document.
  */
  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);
  }
  /**
  Given the document as it existed _before_ the changes, return a
  change set that represents the inverse of this set, which could
  be used to go from the document created by the changes back to
  the document as it existed before the changes.
  */
  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);
  }
  /**
  Combine two subsequent change sets into a single set. `other`
  must start in the document produced by `this`. If `this` goes
  `docA` → `docB` and `other` represents `docB` → `docC`, the
  returned value will represent the change `docA` → `docC`.
  */
  compose(other) {
    return this.empty ? other : other.empty ? this : composeSets(this, other, true);
  }
  /**
  Given another change set starting in the same document, maps this
  change set over the other, producing a new change set that can be
  applied to the document produced by applying `other`. When
  `before` is `true`, order changes as if `this` comes before
  `other`, otherwise (the default) treat `other` as coming first.
  
  Given two changes `A` and `B`, `A.compose(B.map(A))` and
  `B.compose(A.map(B, true))` will produce the same document. This
  provides a basic form of [operational
  transformation](https://en.wikipedia.org/wiki/Operational_transformation),
  and can be used for collaborative editing.
  */
  map(other, before = false) {
    return other.empty ? this : mapSet(this, other, before, true);
  }
  /**
  Iterate over the changed ranges in the document, calling `f` for
  each, with the range in the original document (`fromA`-`toA`)
  and the range that replaces it in the new document
  (`fromB`-`toB`).
  
  When `individual` is true, adjacent changes are reported
  separately.
  */
  iterChanges(f, individual = false) {
    iterChanges(this, f, individual);
  }
  /**
  Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change
  set.
  */
  get desc() {
    return ChangeDesc.create(this.sections);
  }
  /**
  @internal
  */
  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)
    };
  }
  /**
  Serialize this change set to a JSON-representable value.
  */
  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;
  }
  /**
  Create a change set for the given changes, for a document of the
  given length, using `lineSep` as line separator.
  */
  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 set2 = new _ChangeSet(sections, inserted);
      total = total ? total.compose(set2.map(total)) : set2;
      sections = [];
      inserted = [];
      pos = 0;
    }
    function process2(spec) {
      if (Array.isArray(spec)) {
        for (let sub of spec)
          process2(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;
      }
    }
    process2(changes);
    flush2(!total);
    return total;
  }
  /**
  Create an empty changeset of the given length.
  */
  static empty(length) {
    return new _ChangeSet(length ? [length, -1] : [], []);
  }
  /**
  Create a changeset from its JSON representation (as produced by
  [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON).
  */
  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);
  }
  /**
  @internal
  */
  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(set2) {
    this.set = set2;
    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 _SelectionRange {
  constructor(from, to, flags2) {
    this.from = from;
    this.to = to;
    this.flags = flags2;
  }
  /**
  The anchor of the range—the side that doesn't move when you
  extend it.
  */
  get anchor() {
    return this.flags & 32 ? this.to : this.from;
  }
  /**
  The head of the range, which is moved when the range is
  [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).
  */
  get head() {
    return this.flags & 32 ? this.from : this.to;
  }
  /**
  True when `anchor` and `head` are at the same position.
  */
  get empty() {
    return this.from == this.to;
  }
  /**
  If this is a cursor that is explicitly associated with the
  character on one of its sides, this returns the side. -1 means
  the character before its position, 1 the character after, and 0
  means no association.
  */
  get assoc() {
    return this.flags & 8 ? -1 : this.flags & 16 ? 1 : 0;
  }
  /**
  The bidirectional text level associated with this cursor, if
  any.
  */
  get bidiLevel() {
    let level = this.flags & 7;
    return level == 7 ? null : level;
  }
  /**
  The goal column (stored vertical offset) associated with a
  cursor. This is used to preserve the vertical position when
  [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across
  lines of different length.
  */
  get goalColumn() {
    let value = this.flags >> 6;
    return value == 16777215 ? void 0 : value;
  }
  /**
  Map this range through a change, producing a valid range in the
  updated document.
  */
  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 this range to cover at least `from` to `to`.
  */
  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);
  }
  /**
  Compare this range to another range.
  */
  eq(other, includeAssoc = false) {
    return this.anchor == other.anchor && this.head == other.head && (!includeAssoc || !this.empty || this.assoc == other.assoc);
  }
  /**
  Return a JSON-serializable object representing the range.
  */
  toJSON() {
    return { anchor: this.anchor, head: this.head };
  }
  /**
  Convert a JSON representation of a range to a `SelectionRange`
  instance.
  */
  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);
  }
  /**
  @internal
  */
  static create(from, to, flags2) {
    return new _SelectionRange(from, to, flags2);
  }
};
var EditorSelection = class _EditorSelection {
  constructor(ranges, mainIndex) {
    this.ranges = ranges;
    this.mainIndex = mainIndex;
  }
  /**
  Map a selection through a change. Used to adjust the selection
  position for changes.
  */
  map(change, assoc = -1) {
    if (change.empty)
      return this;
    return _EditorSelection.create(this.ranges.map((r) => r.map(change, assoc)), this.mainIndex);
  }
  /**
  Compare this selection to another selection. By default, ranges
  are compared only by position. When `includeAssoc` is true,
  cursor ranges must also have the same
  [`assoc`](https://codemirror.net/6/docs/ref/#state.SelectionRange.assoc) value.
  */
  eq(other, includeAssoc = false) {
    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], includeAssoc))
        return false;
    return true;
  }
  /**
  Get the primary selection range. Usually, you should make sure
  your code applies to _all_ ranges, by using methods like
  [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange).
  */
  get main() {
    return this.ranges[this.mainIndex];
  }
  /**
  Make sure the selection only has one range. Returns a selection
  holding only the main range from this selection.
  */
  asSingle() {
    return this.ranges.length == 1 ? this : new _EditorSelection([this.main], 0);
  }
  /**
  Extend this selection with an extra range.
  */
  addRange(range2, main = true) {
    return _EditorSelection.create([range2].concat(this.ranges), main ? 0 : this.mainIndex + 1);
  }
  /**
  Replace a given range with another range, and then normalize the
  selection to merge and sort ranges if necessary.
  */
  replaceRange(range2, which = this.mainIndex) {
    let ranges = this.ranges.slice();
    ranges[which] = range2;
    return _EditorSelection.create(ranges, this.mainIndex);
  }
  /**
  Convert this selection to an object that can be serialized to
  JSON.
  */
  toJSON() {
    return { ranges: this.ranges.map((r) => r.toJSON()), main: this.mainIndex };
  }
  /**
  Create a selection from a JSON representation.
  */
  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);
  }
  /**
  Create a selection holding a single range.
  */
  static single(anchor, head = anchor) {
    return new _EditorSelection([_EditorSelection.range(anchor, head)], 0);
  }
  /**
  Sort and merge the given set of ranges, creating a valid
  selection.
  */
  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);
  }
  /**
  Create a cursor selection range at the given position. You can
  safely ignore the optional arguments in most situations.
  */
  static cursor(pos, assoc = 0, bidiLevel, goalColumn) {
    return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 8 : 16) | (bidiLevel == null ? 7 : Math.min(6, bidiLevel)) | (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215) << 6);
  }
  /**
  Create a selection range.
  */
  static range(anchor, head, goalColumn, bidiLevel) {
    let flags2 = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215) << 6 | (bidiLevel == null ? 7 : Math.min(6, bidiLevel));
    return head < anchor ? SelectionRange.create(head, anchor, 32 | 16 | flags2) : SelectionRange.create(anchor, head, (head > anchor ? 8 : 0) | flags2);
  }
  /**
  @internal
  */
  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 _Facet {
  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;
  }
  /**
  Returns a facet reader for this facet, which can be used to
  [read](https://codemirror.net/6/docs/ref/#state.EditorState.facet) it but not to define values for it.
  */
  get reader() {
    return this;
  }
  /**
  Define a new facet.
  */
  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);
  }
  /**
  Returns an extension that adds the given value to this facet.
  */
  of(value) {
    return new FacetProvider([], this, 0, value);
  }
  /**
  Create an extension that computes a value for the facet from a
  state. You must take care to declare the parts of the state that
  this value depends on, since your function is only called again
  for a new state when one of those parts changed.
  
  In cases where your value depends only on a single field, you'll
  want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.
  */
  compute(deps, get2) {
    if (this.isStatic)
      throw new Error("Can't compute a static facet");
    return new FacetProvider(deps, this, 1, get2);
  }
  /**
  Create an extension that computes zero or more values for this
  facet from a state.
  */
  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 id2 = this.id, idx = addresses[id2] >> 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, oldAddr = oldState.config.address[id2];
        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 = getter(state), oldVal, compare2) : compare2(newVal = getter(state), oldVal))) {
            state.values[idx] = oldVal;
            return 0;
          }
        } else {
          newVal = getter(state);
        }
        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 addr2 of addrs)
    if (ensureAddr(state, addr2) & 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 addr2 of providerAddrs)
        ensureAddr(state, addr2);
      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 _StateField {
  constructor(id2, createF, updateF, compareF, spec) {
    this.id = id2;
    this.createF = createF;
    this.updateF = updateF;
    this.compareF = compareF;
    this.spec = spec;
    this.provides = void 0;
  }
  /**
  Define a state field.
  */
  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 init4 = state.facet(initField).find((i) => i.field == this);
    return ((init4 === null || init4 === void 0 ? void 0 : init4.create) || this.createF)(state);
  }
  /**
  @internal
  */
  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;
      }
    };
  }
  /**
  Returns an extension that enables this field and overrides the
  way it is initialized. Can be useful when you need to provide a
  non-default starting value for the field.
  */
  init(create) {
    return [this, initField.of({ field: this, create })];
  }
  /**
  State field instances can be used as
  [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a
  given state.
  */
  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 = {
  /**
  The highest precedence level, for extensions that should end up
  near the start of the precedence ordering.
  */
  highest: /* @__PURE__ */ prec(Prec_.highest),
  /**
  A higher-than-default precedence, for extensions that should
  come before those with default precedence.
  */
  high: /* @__PURE__ */ prec(Prec_.high),
  /**
  The default precedence, which is also used for extensions
  without an explicit precedence.
  */
  default: /* @__PURE__ */ prec(Prec_.default),
  /**
  A lower-than-default precedence.
  */
  low: /* @__PURE__ */ prec(Prec_.low),
  /**
  The lowest precedence level. Meant for things that should end up
  near the end of the extension order.
  */
  lowest: /* @__PURE__ */ prec(Prec_.lowest)
};
var PrecExtension = class {
  constructor(inner, prec2) {
    this.inner = inner;
    this.prec = prec2;
  }
};
var Compartment = class _Compartment {
  /**
  Create an instance of this compartment to add to your [state
  configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).
  */
  of(ext2) {
    return new CompartmentInstance(this, ext2);
  }
  /**
  Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that
  reconfigures this compartment.
  */
  reconfigure(content2) {
    return _Compartment.reconfigure.of({ compartment: this, extension: content2 });
  }
  /**
  Get the current content of the compartment in the state, or
  `undefined` if it isn't present.
  */
  get(state) {
    return state.config.compartments.get(this);
  }
};
var CompartmentInstance = class {
  constructor(compartment, inner) {
    this.compartment = compartment;
    this.inner = inner;
  }
};
var Configuration = class _Configuration {
  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
        /* SlotStatus.Unresolved */
      );
  }
  staticFacet(facet) {
    let addr2 = this.address[facet.id];
    return addr2 == null ? facet.default : this.staticValues[addr2 >> 1];
  }
  static resolve(base2, compartments, oldState) {
    let fields = [];
    let facets = /* @__PURE__ */ Object.create(null);
    let newCompartments = /* @__PURE__ */ new Map();
    for (let ext2 of flatten(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 id2 in facets) {
      let providers = facets[id2], facet = providers[0].facet;
      let oldProviders = oldFacets && oldFacets[id2] || [];
      if (providers.every(
        (p) => p.type == 0
        /* Provider.Static */
      )) {
        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 flatten(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, addr2) {
  if (addr2 & 1)
    return 2;
  let idx = addr2 >> 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, addr2) {
  return addr2 & 1 ? state.config.staticValues[addr2 >> 1] : state.values[addr2 >> 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 {
  /**
  @internal
  */
  constructor(type, value) {
    this.type = type;
    this.value = value;
  }
  /**
  Define a new type of annotation.
  */
  static define() {
    return new AnnotationType();
  }
};
var AnnotationType = class {
  /**
  Create an instance of this annotation.
  */
  of(value) {
    return new Annotation(this, value);
  }
};
var StateEffectType = class {
  /**
  @internal
  */
  constructor(map2) {
    this.map = map2;
  }
  /**
  Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this
  type.
  */
  of(value) {
    return new StateEffect(this, value);
  }
};
var StateEffect = class _StateEffect {
  /**
  @internal
  */
  constructor(type, value) {
    this.type = type;
    this.value = value;
  }
  /**
  Map this effect through a position mapping. Will return
  `undefined` when that ends up deleting the effect.
  */
  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);
  }
  /**
  Tells you whether this effect object is of a given
  [type](https://codemirror.net/6/docs/ref/#state.StateEffectType).
  */
  is(type) {
    return this.type == type;
  }
  /**
  Define a new effect type. The type parameter indicates the type
  of values that his effect holds. It should be a type that
  doesn't include `undefined`, since that is used in
  [mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is
  removed.
  */
  static define(spec = {}) {
    return new StateEffectType(spec.map || ((v) => v));
  }
  /**
  Map an array of effects through a change set.
  */
  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 _Transaction {
  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 == _Transaction.time))
      this.annotations = annotations.concat(_Transaction.time.of(Date.now()));
  }
  /**
  @internal
  */
  static create(startState, changes, selection2, effects, annotations, scrollIntoView3) {
    return new _Transaction(startState, changes, selection2, effects, annotations, scrollIntoView3);
  }
  /**
  The new document produced by the transaction. Contrary to
  [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't
  force the entire new state to be computed right away, so it is
  recommended that [transaction
  filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter
  when they need to look at the new document.
  */
  get newDoc() {
    return this._doc || (this._doc = this.changes.apply(this.startState.doc));
  }
  /**
  The new selection produced by the transaction. If
  [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,
  this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's
  current selection through the changes made by the transaction.
  */
  get newSelection() {
    return this.selection || this.startState.selection.map(this.changes);
  }
  /**
  The new state created by the transaction. Computed on demand
  (but retained for subsequent access), so it is recommended not to
  access it in [transaction
  filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.
  */
  get state() {
    if (!this._state)
      this.startState.applyTransaction(this);
    return this._state;
  }
  /**
  Get the value of the given annotation type, if any.
  */
  annotation(type) {
    for (let ann of this.annotations)
      if (ann.type == type)
        return ann.value;
    return void 0;
  }
  /**
  Indicates whether the transaction changed the document.
  */
  get docChanged() {
    return !this.changes.empty;
  }
  /**
  Indicates whether this transaction reconfigures the state
  (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or
  with a top-level configuration
  [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).
  */
  get reconfigured() {
    return this.startState.config != this.state.config;
  }
  /**
  Returns true if the transaction has a [user
  event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to
  or more specific than `event`. For example, if the transaction
  has `"select.pointer"` as user event, `"select"` and
  `"select.pointer"` will match it.
  */
  isUserEvent(event) {
    let e3 = this.annotation(_Transaction.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 _EditorState {
  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 addr2 = this.config.address[field.id];
    if (addr2 == null) {
      if (require2)
        throw new RangeError("Field is not present in this state");
      return void 0;
    }
    ensureAddr(this, addr2);
    return getAddr(this, addr2);
  }
  /**
  Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this
  state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)
  can be passed. Unless
  [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the
  [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec
  are assumed to start in the _current_ document (not the document
  produced by previous specs), and its
  [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and
  [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer
  to the document created by its _own_ changes. The resulting
  transaction contains the combined effect of all the different
  specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later
  specs take precedence over earlier ones.
  */
  update(...specs) {
    return resolveTransaction(this, specs, true);
  }
  /**
  @internal
  */
  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, key2) => compartments.set(key2, 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();
    }
    let selection2 = tr.startState.facet(allowMultipleSelections) ? tr.newSelection : tr.newSelection.asSingle();
    new _EditorState(conf, tr.newDoc, selection2, startValues, (state, slot) => slot.update(state, tr), tr);
  }
  /**
  Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that
  replaces every selection range with the given content.
  */
  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)
    }));
  }
  /**
  Create a set of changes and a new selection by running the given
  function for each range in the active selection. The function
  can return an optional set of changes (in the coordinate space
  of the start document), plus an updated range (in the coordinate
  space of the document produced by the call's own changes). This
  method will merge all the changes and ranges into a single
  changeset and selection, and return it as a [transaction
  spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to
  [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).
  */
  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
    };
  }
  /**
  Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change
  description, taking the state's document length and line
  separator into account.
  */
  changes(spec = []) {
    if (spec instanceof ChangeSet)
      return spec;
    return ChangeSet.of(spec, this.doc.length, this.facet(_EditorState.lineSeparator));
  }
  /**
  Using the state's [line
  separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a
  [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.
  */
  toText(string4) {
    return Text.of(string4.split(this.facet(_EditorState.lineSeparator) || DefaultSplit));
  }
  /**
  Return the given range of the document as a string.
  */
  sliceDoc(from = 0, to = this.doc.length) {
    return this.doc.sliceString(from, to, this.lineBreak);
  }
  /**
  Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).
  */
  facet(facet) {
    let addr2 = this.config.address[facet.id];
    if (addr2 == null)
      return facet.default;
    ensureAddr(this, addr2);
    return getAddr(this, addr2);
  }
  /**
  Convert this state to a JSON-serializable object. When custom
  fields should be serialized, you can pass them in as an object
  mapping property names (in the resulting object, which should
  not use `doc` or `selection`) to fields.
  */
  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;
  }
  /**
  Deserialize a state from its JSON representation. When custom
  fields should be deserialized, pass the same object you passed
  to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as
  third argument.
  */
  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
    });
  }
  /**
  Create a new state. You'll usually only need this when
  initializing an editor—updated states are created by applying
  transactions.
  */
  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);
  }
  /**
  The size (in columns) of a tab in the document, determined by
  the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.
  */
  get tabSize() {
    return this.facet(_EditorState.tabSize);
  }
  /**
  Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)
  string for this state.
  */
  get lineBreak() {
    return this.facet(_EditorState.lineSeparator) || "\n";
  }
  /**
  Returns true when the editor is
  [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.
  */
  get readOnly() {
    return this.facet(readOnly);
  }
  /**
  Look up a translation for the given phrase (via the
  [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the
  original string if no translation is found.
  
  If additional arguments are passed, they will be inserted in
  place of markers like `$1` (for the first value) and `$2`, etc.
  A single `$` is equivalent to `$1`, and `$$` will produce a
  literal dollar sign.
  */
  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;
  }
  /**
  Find the values for a given language data field, provided by the
  the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.
  
  Examples of language data fields are...
  
  - [`"commentTokens"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying
    comment syntax.
  - [`"autocomplete"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override)
    for providing language-specific completion sources.
  - [`"wordChars"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding
    characters that should be considered part of words in this
    language.
  - [`"closeBrackets"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls
    bracket closing behavior.
  */
  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;
  }
  /**
  Return a function that can categorize strings (expected to
  represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))
  into one of:
  
   - Word (contains an alphanumeric character or a character
     explicitly listed in the local language's `"wordChars"`
     language data, which should be a string)
   - Space (contains only whitespace)
   - Other (anything else)
  */
  charCategorizer(at) {
    return makeCategorizer(this.languageDataAt("wordChars", at).join(""));
  }
  /**
  Find the word at the given position, meaning the range
  containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters
  around it. If no word characters are adjacent to the position,
  this returns null.
  */
  wordAt(pos) {
    let { text: text2, from, length } = this.doc.lineAt(pos);
    let cat = this.charCategorizer(pos);
    let start2 = pos - from, end = pos - from;
    while (start2 > 0) {
      let prev = findClusterBreak(text2, start2, false);
      if (cat(text2.slice(prev, start2)) != CharCategory.Word)
        break;
      start2 = prev;
    }
    while (end < length) {
      let next = findClusterBreak(text2, end);
      if (cat(text2.slice(end, next)) != CharCategory.Word)
        break;
      end = next;
    }
    return start2 == end ? null : EditorSelection.range(start2 + 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 key2 of Object.keys(config2)) {
      let value = config2[key2], current = result[key2];
      if (current === void 0)
        result[key2] = value;
      else if (current === value || value === void 0)
        ;
      else if (Object.hasOwnProperty.call(combine, key2))
        result[key2] = combine[key2](current, value);
      else
        throw new Error("Config merge conflict for field " + key2);
    }
  for (let key2 in defaults3)
    if (result[key2] === void 0)
      result[key2] = defaults3[key2];
  return result;
}
var RangeValue = class {
  /**
  Compare this value with another value. Used when comparing
  rangesets. The default implementation compares by identity.
  Unless you are only creating a fixed number of unique instances
  of your value type, it is a good idea to implement this
  properly.
  */
  eq(other) {
    return this == other;
  }
  /**
  Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.
  */
  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 _Range {
  constructor(from, to, value) {
    this.from = from;
    this.to = to;
    this.value = value;
  }
  /**
  @internal
  */
  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 _Chunk {
  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];
  }
  // Find the index of the given position and side. Use the ranges'
  // `from` pos when `end == false`, `to` when `end == true`.
  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 _RangeSet {
  constructor(chunkPos, chunk, nextLayer, maxPoint) {
    this.chunkPos = chunkPos;
    this.chunk = chunk;
    this.nextLayer = nextLayer;
    this.maxPoint = maxPoint;
  }
  /**
  @internal
  */
  static create(chunkPos, chunk, nextLayer, maxPoint) {
    return new _RangeSet(chunkPos, chunk, nextLayer, maxPoint);
  }
  /**
  @internal
  */
  get length() {
    let last = this.chunk.length - 1;
    return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);
  }
  /**
  The number of ranges in the set.
  */
  get size() {
    if (this.isEmpty)
      return 0;
    let size = this.nextLayer.size;
    for (let chunk of this.chunk)
      size += chunk.value.length;
    return size;
  }
  /**
  @internal
  */
  chunkEnd(index2) {
    return this.chunkPos[index2] + this.chunk[index2].length;
  }
  /**
  Update the range set, optionally adding new ranges or filtering
  out existing ones.
  
  (Note: The type parameter is just there as a kludge to work
  around TypeScript variance issues that prevented `RangeSet<X>`
  from being a subtype of `RangeSet<Y>` when `X` is a subtype of
  `Y`.)
  */
  update(updateSpec) {
    let { add: add3 = [], sort: sort2 = false, filterFrom = 0, filterTo = this.length } = updateSpec;
    let filter2 = updateSpec.filter;
    if (add3.length == 0 && !filter2)
      return this;
    if (sort2)
      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 this range set through a set of changes, return the new set.
  */
  map(changes) {
    if (changes.empty || this.isEmpty)
      return this;
    let chunks = [], chunkPos = [], maxPoint = -1;
    for (let i = 0; i < this.chunk.length; i++) {
      let start2 = this.chunkPos[i], chunk = this.chunk[i];
      let touch = changes.touchesRange(start2, start2 + chunk.length);
      if (touch === false) {
        maxPoint = Math.max(maxPoint, chunk.maxPoint);
        chunks.push(chunk);
        chunkPos.push(changes.mapPos(start2));
      } else if (touch === true) {
        let { mapped, pos } = chunk.map(start2, 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);
  }
  /**
  Iterate over the ranges that touch the region `from` to `to`,
  calling `f` for each. There is no guarantee that the ranges will
  be reported in any specific order. When the callback returns
  `false`, iteration stops.
  */
  between(from, to, f) {
    if (this.isEmpty)
      return;
    for (let i = 0; i < this.chunk.length; i++) {
      let start2 = this.chunkPos[i], chunk = this.chunk[i];
      if (to >= start2 && from <= start2 + chunk.length && chunk.between(start2, from - start2, to - start2, f) === false)
        return;
    }
    this.nextLayer.between(from, to, f);
  }
  /**
  Iterate over the ranges in this set, in order, including all
  ranges that end at or after `from`.
  */
  iter(from = 0) {
    return HeapCursor.from([this]).goto(from);
  }
  /**
  @internal
  */
  get isEmpty() {
    return this.nextLayer == this;
  }
  /**
  Iterate over the ranges in a collection of sets, in order,
  starting from `from`.
  */
  static iter(sets, from = 0) {
    return HeapCursor.from(sets).goto(from);
  }
  /**
  Iterate over two groups of sets, calling methods on `comparator`
  to notify it of possible differences.
  */
  static compare(oldSets, newSets, textDiff, comparator, minPointSize = -1) {
    let a = oldSets.filter((set2) => set2.maxPoint > 0 || !set2.isEmpty && set2.maxPoint >= minPointSize);
    let b = newSets.filter((set2) => set2.maxPoint > 0 || !set2.isEmpty && set2.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);
  }
  /**
  Compare the contents of two groups of range sets, returning true
  if they are equivalent in the given range.
  */
  static eq(oldSets, newSets, from = 0, to) {
    if (to == null)
      to = 1e9 - 1;
    let a = oldSets.filter((set2) => !set2.isEmpty && newSets.indexOf(set2) < 0);
    let b = newSets.filter((set2) => !set2.isEmpty && oldSets.indexOf(set2) < 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();
    }
  }
  /**
  Iterate over a group of range sets at the same time, notifying
  the iterator about the ranges covering every given piece of
  content. Returns the open count (see
  [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end
  of the iteration.
  */
  static spans(sets, from, to, iterator, minPointSize = -1) {
    let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from;
    let openRanges = cursor.openStart;
    for (; ; ) {
      let curTo = Math.min(cursor.to, to);
      if (cursor.point) {
        let active = cursor.activeForPoint(cursor.to);
        let openCount = cursor.pointFrom < from ? active.length + 1 : cursor.point.startSide < 0 ? active.length : Math.min(active.length, openRanges);
        iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank);
        openRanges = Math.min(cursor.openEnd(curTo), active.length);
      } else if (curTo > pos) {
        iterator.span(pos, curTo, cursor.active, openRanges);
        openRanges = cursor.openEnd(curTo);
      }
      if (cursor.to > to)
        return openRanges + (cursor.point && cursor.to > to ? 1 : 0);
      pos = cursor.to;
      cursor.next();
    }
  }
  /**
  Create a range set for the given range or array of ranges. By
  default, this expects the ranges to be _sorted_ (by start
  position and, if two start at the same position,
  `value.startSide`). You can pass `true` as second argument to
  cause the method to sort them.
  */
  static of(ranges, sort2 = false) {
    let build = new RangeSetBuilder();
    for (let range2 of ranges instanceof Range ? [ranges] : sort2 ? lazySort(ranges) : ranges)
      build.add(range2.from, range2.to, range2.value);
    return build.finish();
  }
  /**
  Join an array of range sets into a single set.
  */
  static join(sets) {
    if (!sets.length)
      return _RangeSet.empty;
    let result = sets[sets.length - 1];
    for (let i = sets.length - 2; i >= 0; i--) {
      for (let layer2 = sets[i]; layer2 != _RangeSet.empty; layer2 = layer2.nextLayer)
        result = new _RangeSet(layer2.chunkPos, layer2.chunk, result, Math.max(layer2.maxPoint, result.maxPoint));
    }
    return result;
  }
};
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 _RangeSetBuilder {
  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 = [];
    }
  }
  /**
  Create an empty builder.
  */
  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;
  }
  /**
  Add a range. Ranges should be added in sorted (by `from` and
  `value.startSide`) order.
  */
  add(from, to, value) {
    if (!this.addInner(from, to, value))
      (this.nextLayer || (this.nextLayer = new _RangeSetBuilder())).add(from, to, value);
  }
  /**
  @internal
  */
  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;
  }
  /**
  @internal
  */
  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 the range set. Returns the new set. The builder can't be
  used anymore after this has been called.
  */
  finish() {
    return this.finishInner(RangeSet.empty);
  }
  /**
  @internal
  */
  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 set2 of a)
    for (let i = 0; i < set2.chunk.length; i++)
      if (set2.chunk[i].maxPoint <= 0)
        inA.set(set2.chunk[i], set2.chunkPos[i]);
  let shared = /* @__PURE__ */ new Set();
  for (let set2 of b)
    for (let i = 0; i < set2.chunk.length; i++) {
      let known = inA.get(set2.chunk[i]);
      if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set2.chunkPos[i] && !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set2.chunk[i].length)))
        shared.add(set2.chunk[i]);
    }
  return shared;
}
var LayerCursor = class {
  constructor(layer2, skip, minPoint, rank = 0) {
    this.layer = layer2;
    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 _HeapCursor {
  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 && (rank - this.activeRank[i] || to - this.activeTo[i]) > 0)
      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);
  }
  // After calling this, if `this.point` != null, the next range is a
  // point. Otherwise, it's a regular range, covered by `this.active`.
  next() {
    let from = this.to, wasPoint = this.point;
    this.point = null;
    let trackOpen = this.openStart < 0 ? [] : null;
    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);
          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;
          this.cursor.next();
          this.forward(this.to, this.endSide);
          break;
        }
      }
    }
    if (trackOpen) {
      this.openStart = 0;
      for (let i = trackOpen.length - 1; i >= 0 && trackOpen[i] < from; i--)
        this.openStart++;
    }
  }
  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), 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(string4, tabSize, to = string4.length) {
  let n = 0;
  for (let i = 0; i < to; ) {
    if (string4.charCodeAt(i) == 9) {
      n += tabSize - n % tabSize;
      i++;
    } else {
      n++;
      i = findClusterBreak(string4, i);
    }
  }
  return n;
}
function findColumn(string4, col, tabSize, strict) {
  for (let i = 0, n = 0; ; ) {
    if (n >= col)
      return i;
    if (i == string4.length)
      break;
    n += string4.charCodeAt(i) == 9 ? tabSize - n % tabSize : 1;
    i = findClusterBreak(string4, i);
  }
  return strict === true ? -1 : string4.length;
}

// node_modules/style-mod/src/style-mod.js
var C2 = "\u037C";
var COUNT = typeof Symbol == "undefined" ? "__" + C2 : Symbol.for(C2);
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 {
  // :: (Object<Style>, ?{finish: ?(string) → string})
  // Create a style module from the given spec.
  //
  // When `finish` is given, it is called on regular (non-`@`)
  // selectors (after `&` expansion) to compute the final selector.
  constructor(spec, options3) {
    this.rules = [];
    let { finish } = options3 || {};
    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);
  }
  // :: () → string
  // Returns a string containing the module's CSS rules.
  getRules() {
    return this.rules.join("\n");
  }
  // :: () → string
  // Generate a new unique CSS class name.
  static newName() {
    let id2 = top[COUNT] || 1;
    top[COUNT] = id2 + 1;
    return C2 + id2.toString(36);
  }
  // :: (union<Document, ShadowRoot>, union<[StyleModule], StyleModule>, ?{nonce: ?string})
  //
  // Mount the given set of modules in the given DOM root, which ensures
  // that the CSS rules defined by the module are available in that
  // context.
  //
  // Rules are only added to the document once per root.
  //
  // Rule order will follow the order of the modules, so that rules from
  // modules later in the array take precedence of those from earlier
  // modules. If you call this function multiple times for the same root
  // in a way that changes the order of already mounted modules, the old
  // order will be changed.
  //
  // If a Content Security Policy nonce is provided, it is added to
  // the `<style>` tag generated by the library.
  static mount(root2, modules, options3) {
    let set2 = root2[SET], nonce = options3 && options3.nonce;
    if (!set2)
      set2 = new StyleSet(root2, nonce);
    else if (nonce)
      set2.setNonce(nonce);
    set2.mount(Array.isArray(modules) ? modules : [modules], root2);
  }
};
var adoptedSet = /* @__PURE__ */ new Map();
var StyleSet = class {
  constructor(root2, nonce) {
    let doc2 = root2.ownerDocument || root2, win = doc2.defaultView;
    if (!root2.head && root2.adoptedStyleSheets && win.CSSStyleSheet) {
      let adopted = adoptedSet.get(doc2);
      if (adopted)
        return root2[SET] = adopted;
      this.sheet = new win.CSSStyleSheet();
      adoptedSet.set(doc2, this);
    } else {
      this.styleTag = doc2.createElement("style");
      if (nonce)
        this.styleTag.setAttribute("nonce", nonce);
    }
    this.modules = [];
    root2[SET] = this;
  }
  mount(modules, root2) {
    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) {
      if (root2.adoptedStyleSheets.indexOf(this.sheet) < 0)
        root2.adoptedStyleSheets = [this.sheet, ...root2.adoptedStyleSheets];
    } else {
      let text2 = "";
      for (let i = 0; i < this.modules.length; i++)
        text2 += this.modules[i].getRules() + "\n";
      this.styleTag.textContent = text2;
      let target = root2.head || root2;
      if (this.styleTag.parentNode != target)
        target.insertBefore(this.styleTag, target.firstChild);
    }
  }
  setNonce(nonce) {
    if (this.styleTag && this.styleTag.getAttribute("nonce") != nonce)
      this.styleTag.setAttribute("nonce", nonce);
  }
};

// node_modules/w3c-keyname/index.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 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);
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 = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || 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;
}
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 getScale(elt, rect) {
  let scaleX = rect.width / elt.offsetWidth;
  let scaleY = rect.height / elt.offsetHeight;
  if (scaleX > 0.995 && scaleX < 1.005 || !isFinite(scaleX) || Math.abs(rect.width - elt.offsetWidth) < 1)
    scaleX = 1;
  if (scaleY > 0.995 && scaleY < 1.005 || !isFinite(scaleY) || Math.abs(rect.height - elt.offsetHeight) < 1)
    scaleY = 1;
  return { scaleX, scaleY };
}
function scrollRectIntoView(dom, rect, side, x2, y2, xMargin, yMargin, ltr) {
  let doc2 = dom.ownerDocument, win = doc2.defaultView || window;
  for (let cur2 = dom, stop2 = false; cur2 && !stop2; ) {
    if (cur2.nodeType == 1) {
      let bounding, top3 = cur2 == doc2.body;
      let scaleX = 1, scaleY = 1;
      if (top3) {
        bounding = windowRect(win);
      } else {
        if (/^(fixed|sticky)$/.test(getComputedStyle(cur2).position))
          stop2 = true;
        if (cur2.scrollHeight <= cur2.clientHeight && cur2.scrollWidth <= cur2.clientWidth) {
          cur2 = cur2.assignedSlot || cur2.parentNode;
          continue;
        }
        let rect2 = cur2.getBoundingClientRect();
        ({ scaleX, scaleY } = getScale(cur2, rect2));
        bounding = {
          left: rect2.left,
          right: rect2.left + cur2.clientWidth * scaleX,
          top: rect2.top,
          bottom: rect2.top + cur2.clientHeight * scaleY
        };
      }
      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 start2 = cur2.scrollTop;
            cur2.scrollTop += moveY / scaleY;
            movedY = (cur2.scrollTop - start2) * scaleY;
          }
          if (moveX) {
            let start2 = cur2.scrollLeft;
            cur2.scrollLeft += moveX / scaleX;
            movedX = (cur2.scrollLeft - start2) * scaleX;
          }
          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;
    }
  }
}
function scrollableParent(dom) {
  let doc2 = dom.ownerDocument;
  for (let cur2 = dom.parentNode; cur2; ) {
    if (cur2 == doc2.body) {
      break;
    } else if (cur2.nodeType == 1) {
      if (cur2.scrollHeight > cur2.clientHeight || cur2.scrollWidth > cur2.clientWidth)
        return cur2;
      cur2 = cur2.assignedSlot || cur2.parentNode;
    } else if (cur2.nodeType == 11) {
      cur2 = cur2.host;
    } else {
      break;
    }
  }
  return null;
}
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) {
    let { anchorNode, focusNode } = range2;
    this.set(anchorNode, Math.min(range2.anchorOffset, anchorNode ? maxOffset(anchorNode) : 0), focusNode, Math.min(range2.focusOffset, focusNode ? maxOffset(focusNode) : 0));
  }
  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 options3 = { key: name2, code: name2, keyCode: code, which: code, cancelable: true };
  let down = new KeyboardEvent("keydown", options3);
  down.synthetic = true;
  elt.dispatchEvent(down);
  let up = new KeyboardEvent("keyup", options3);
  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;
  offset = Math.min(offset, maxOffset(node));
  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;
    }
  }
}
function isScrolledToBottom(elt) {
  return elt.scrollTop > Math.max(1, elt.scrollHeight - elt.clientHeight - 4);
}
var DOMPos = class _DOMPos {
  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 _ContentView {
  constructor() {
    this.parent = null;
    this.dom = null;
    this.flags = 2;
  }
  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;
  }
  sync(view, track) {
    if (this.flags & 2) {
      let parent2 = this.dom;
      let prev = null, next;
      for (let child of this.children) {
        if (child.flags & 7) {
          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(view, track);
          child.flags &= ~7;
        }
        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.flags & 1) {
      for (let child of this.children)
        if (child.flags & 7) {
          child.sync(view, track);
          child.flags &= ~7;
        }
    }
  }
  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.flags |= 2;
    this.markParentsDirty(andParent);
  }
  markParentsDirty(childList) {
    for (let parent2 = this.parent; parent2; parent2 = parent2.parent) {
      if (childList)
        parent2.flags |= 2;
      if (parent2.flags & 1)
        return;
      parent2.flags |= 1;
      childList = false;
    }
  }
  setParent(parent2) {
    if (this.parent != parent2) {
      this.parent = parent2;
      if (this.flags & 7)
        this.markParentsDirty(true);
    }
  }
  setDOM(dom) {
    if (this.dom == dom)
      return;
    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 && children3.indexOf(child) < 0)
        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;
  }
  get isWidget() {
    return false;
  }
  get isHidden() {
    return false;
  }
  merge(from, to, source2, hasStart, openStart, openEnd) {
    return false;
  }
  become(other) {
    return false;
  }
  canReuseDOM(other) {
    return other.constructor == this.constructor && !((this.flags | other.flags) & 8);
  }
  // When this is a zero-length view with a side, this should return a
  // number <= 0 to indicate it is before its position, or a
  // number > 0 when after its position.
  getSide() {
    return 0;
  }
  destroy() {
    for (let child of this.children)
      if (child.parent == this)
        child.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 || after.breakAfter && (last === null || last === void 0 ? void 0 : last.breakAfter))) {
      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.children.length && !after.children[0].length)
          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 gecko = !ie2 && /* @__PURE__ */ /gecko\/(\d+)/i.test(nav.userAgent);
var chrome = !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,
  gecko_version: gecko ? +(/* @__PURE__ */ /Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
  chrome: !!chrome,
  chrome_version: chrome ? +chrome[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 _TextView extends ContentView {
  constructor(text2) {
    super();
    this.text = text2;
  }
  get length() {
    return this.text.length;
  }
  createDOM(textDOM) {
    this.setDOM(textDOM || document.createTextNode(this.text));
  }
  sync(view, 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, source2) {
    if (this.flags & 8 || source2 && (!(source2 instanceof _TextView) || this.length - (to - from) + source2.length > MaxJoinLen || source2.flags & 8))
      return false;
    this.text = this.text.slice(0, from) + (source2 ? source2.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();
    result.flags |= this.flags & 8;
    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 _MarkView 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;
  }
  canReuseDOM(other) {
    return super.canReuseDOM(other) && !((this.flags | other.flags) & 8);
  }
  reuseDOM(node) {
    if (node.nodeName == this.mark.tagName.toUpperCase()) {
      this.setDOM(node);
      this.flags |= 4 | 2;
    }
  }
  sync(view, track) {
    if (!this.dom)
      this.setDOM(this.setAttrs(document.createElement(this.mark.tagName)));
    else if (this.flags & 4)
      this.setAttrs(this.dom);
    super.sync(view, track);
  }
  merge(from, to, source2, _hasStart, openStart, openEnd) {
    if (source2 && (!(source2 instanceof _MarkView && source2.mark.eq(this.mark)) || from && openStart <= 0 || to < this.length && openEnd <= 0))
      return false;
    mergeChildrenInto(this, from, to, source2 ? source2.children.slice() : [], 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, flatten2 = 0;
  if (pos == 0 && side < 0 || pos == length && side >= 0) {
    if (!(browser.chrome || browser.gecko)) {
      if (pos) {
        from--;
        flatten2 = 1;
      } else if (to < length) {
        to++;
        flatten2 = -1;
      }
    }
  } else {
    if (side < 0)
      from--;
    else if (to < length)
      to++;
  }
  let rects = textRange(text2, from, to).getClientRects();
  if (!rects.length)
    return null;
  let rect = rects[(flatten2 ? flatten2 < 0 : side >= 0) ? 0 : rects.length - 1];
  if (browser.safari && !flatten2 && rect.width == 0)
    rect = Array.prototype.find.call(rects, (r) => r.width) || rect;
  return flatten2 ? flattenRect(rect, flatten2 < 0) : rect || null;
}
var WidgetView = class _WidgetView extends ContentView {
  static create(widget, length, side) {
    return new _WidgetView(widget, length, side);
  }
  constructor(widget, length, side) {
    super();
    this.widget = widget;
    this.length = length;
    this.side = side;
    this.prevWidget = null;
  }
  split(from) {
    let result = _WidgetView.create(this.widget, this.length - from, this.side);
    this.length -= from;
    return result;
  }
  sync(view) {
    if (!this.dom || !this.widget.updateDOM(this.dom, view)) {
      if (this.dom && this.prevWidget)
        this.prevWidget.destroy(this.dom);
      this.prevWidget = null;
      this.setDOM(this.widget.toDOM(view));
      if (!this.widget.editable)
        this.dom.contentEditable = "false";
    }
  }
  getSide() {
    return this.side;
  }
  merge(from, to, source2, hasStart, openStart, openEnd) {
    if (source2 && (!(source2 instanceof _WidgetView) || !this.widget.compare(source2.widget) || from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))
      return false;
    this.length = from + (source2 ? source2.length : 0) + (this.length - to);
    return true;
  }
  become(other) {
    if (other instanceof _WidgetView && other.side == this.side && this.widget.constructor == other.widget.constructor) {
      if (!this.widget.compare(other.widget))
        this.markDirty(true);
      if (this.dom && !this.prevWidget)
        this.prevWidget = this.widget;
      this.widget = other.widget;
      this.length = other.length;
      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, text2 = view && view.state.doc, start2 = this.posAtStart;
    return text2 ? text2.slice(start2, start2 + this.length) : Text.empty;
  }
  domAtPos(pos) {
    return (this.length ? pos == 0 : this.side > 0) ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length);
  }
  domBoundsAround() {
    return null;
  }
  coordsAt(pos, side) {
    let custom2 = this.widget.coordsAt(this.dom, pos, side);
    if (custom2)
      return custom2;
    let rects = this.dom.getClientRects(), rect = null;
    if (!rects.length)
      return null;
    let fromBack = this.side ? this.side < 0 : pos > 0;
    for (let i = fromBack ? rects.length - 1 : 0; ; i += fromBack ? -1 : 1) {
      rect = rects[i];
      if (pos > 0 ? i == 0 : i == rects.length - 1 || rect.top < rect.bottom)
        break;
    }
    return flattenRect(rect, !fromBack);
  }
  get isEditable() {
    return false;
  }
  get isWidget() {
    return true;
  }
  get isHidden() {
    return this.widget.isHidden;
  }
  destroy() {
    super.destroy();
    if (this.dom)
      this.widget.destroy(this.dom);
  }
};
var WidgetBufferView = class _WidgetBufferView 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 this.side > 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom);
  }
  localPosFromDOM() {
    return 0;
  }
  domBoundsAround() {
    return null;
  }
  coordsAt(pos) {
    return this.dom.getBoundingClientRect();
  }
  get overrideDOMText() {
    return Text.empty;
  }
  get isHidden() {
    return true;
  }
};
TextView.prototype.children = WidgetView.prototype.children = WidgetBufferView.prototype.children = noChildren;
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 || after.isHidden && side > 0) && (end > pos2 || off == end && child.getSide() > 0)) {
          after = child;
          afterPos = pos2 - off;
        } else if (off < pos2 || off == end && child.getSide() < 0 && !child.isHidden) {
          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(source2, target) {
  for (let name2 in source2) {
    if (name2 == "class" && target.class)
      target.class += " " + source2.class;
    else if (name2 == "style" && target.style)
      target.style += ";" + source2.style;
    else
      target[name2] = source2[name2];
  }
  return target;
}
var noAttrs = /* @__PURE__ */ Object.create(null);
function attrsEq(a, b, ignore) {
  if (a == b)
    return true;
  if (!a)
    a = noAttrs;
  if (!b)
    b = noAttrs;
  let keysA = Object.keys(a), keysB = Object.keys(b);
  if (keysA.length - (ignore && keysA.indexOf(ignore) > -1 ? 1 : 0) != keysB.length - (ignore && keysB.indexOf(ignore) > -1 ? 1 : 0))
    return false;
  for (let key2 of keysA) {
    if (key2 != ignore && (keysB.indexOf(key2) == -1 || a[key2] !== b[key2]))
      return false;
  }
  return true;
}
function updateAttrs(dom, prev, attrs) {
  let changed = false;
  if (prev) {
    for (let name2 in prev)
      if (!(attrs && name2 in attrs)) {
        changed = true;
        if (name2 == "style")
          dom.style.cssText = "";
        else
          dom.removeAttribute(name2);
      }
  }
  if (attrs) {
    for (let name2 in attrs)
      if (!(prev && prev[name2] == attrs[name2])) {
        changed = true;
        if (name2 == "style")
          dom.style.cssText = attrs[name2];
        else
          dom.setAttribute(name2, attrs[name2]);
      }
  }
  return changed;
}
function getAttrs(dom) {
  let attrs = /* @__PURE__ */ Object.create(null);
  for (let i = 0; i < dom.attributes.length; i++) {
    let attr2 = dom.attributes[i];
    attrs[attr2.name] = attr2.value;
  }
  return attrs;
}
var LineView = class _LineView extends ContentView {
  constructor() {
    super(...arguments);
    this.children = [];
    this.length = 0;
    this.prevAttrs = void 0;
    this.attrs = null;
    this.breakAfter = 0;
  }
  // Consumes source
  merge(from, to, source2, hasStart, openStart, openEnd) {
    if (source2) {
      if (!(source2 instanceof _LineView))
        return false;
      if (!this.dom)
        source2.transferDOM(this);
    }
    if (hasStart)
      this.setDeco(source2 ? source2.attrs : null);
    mergeChildrenInto(this, from, to, source2 ? source2.children.slice() : [], 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);
  }
  // Only called when building a line view in ContentBuilder
  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.flags |= 4 | 2;
    }
  }
  sync(view, 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.flags & 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(view, 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, textHeight;
    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;
      textHeight = rects[0].height;
    }
    return !totalWidth ? null : {
      lineHeight: this.dom.getBoundingClientRect().height,
      charWidth: totalWidth / this.length,
      textHeight
    };
  }
  coordsAt(pos, side) {
    let rect = coordsInChildren(this, pos, side);
    if (!this.children.length && rect && this.parent) {
      let { heightOracle } = this.parent.view.viewState, height4 = rect.bottom - rect.top;
      if (Math.abs(height4 - heightOracle.lineHeight) < 2 && heightOracle.textHeight < height4) {
        let dist2 = (height4 - heightOracle.textHeight) / 2;
        return { top: rect.top + dist2, bottom: rect.bottom - dist2, left: rect.left, right: rect.left };
      }
    }
    return rect;
  }
  become(_other) {
    return false;
  }
  covers() {
    return true;
  }
  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 _BlockWidgetView extends ContentView {
  constructor(widget, length, deco) {
    super();
    this.widget = widget;
    this.length = length;
    this.deco = deco;
    this.breakAfter = 0;
    this.prevWidget = null;
  }
  merge(from, to, source2, _takeDeco, openStart, openEnd) {
    if (source2 && (!(source2 instanceof _BlockWidgetView) || !this.widget.compare(source2.widget) || from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))
      return false;
    this.length = from + (source2 ? source2.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.deco);
    end.breakAfter = this.breakAfter;
    return end;
  }
  get children() {
    return noChildren;
  }
  sync(view) {
    if (!this.dom || !this.widget.updateDOM(this.dom, view)) {
      if (this.dom && this.prevWidget)
        this.prevWidget.destroy(this.dom);
      this.prevWidget = null;
      this.setDOM(this.widget.toDOM(view));
      if (!this.widget.editable)
        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.widget.constructor == this.widget.constructor) {
      if (!other.widget.compare(this.widget))
        this.markDirty(true);
      if (this.dom && !this.prevWidget)
        this.prevWidget = this.widget;
      this.widget = other.widget;
      this.length = other.length;
      this.deco = other.deco;
      this.breakAfter = other.breakAfter;
      return true;
    }
    return false;
  }
  ignoreMutation() {
    return true;
  }
  ignoreEvent(event) {
    return this.widget.ignoreEvent(event);
  }
  get isEditable() {
    return false;
  }
  get isWidget() {
    return true;
  }
  coordsAt(pos, side) {
    return this.widget.coordsAt(this.dom, pos, side);
  }
  destroy() {
    super.destroy();
    if (this.dom)
      this.widget.destroy(this.dom);
  }
  covers(side) {
    let { startSide, endSide } = this.deco;
    return startSide == endSide ? false : side < 0 ? startSide < 0 : endSide > 0;
  }
};
var WidgetType = class {
  /**
  Compare this instance to another instance of the same type.
  (TypeScript can't express this, but only instances of the same
  specific class will be passed to this method.) This is used to
  avoid redrawing widgets when they are replaced by a new
  decoration of the same type. The default implementation just
  returns `false`, which will cause new instances of the widget to
  always be redrawn.
  */
  eq(widget) {
    return false;
  }
  /**
  Update a DOM element created by a widget of the same type (but
  different, non-`eq` content) to reflect this widget. May return
  true to indicate that it could update, false to indicate it
  couldn't (in which case the widget will be redrawn). The default
  implementation just returns false.
  */
  updateDOM(dom, view) {
    return false;
  }
  /**
  @internal
  */
  compare(other) {
    return this == other || this.constructor == other.constructor && this.eq(other);
  }
  /**
  The estimated height this widget will have, to be used when
  estimating the height of content that hasn't been drawn. May
  return -1 to indicate you don't know. The default implementation
  returns -1.
  */
  get estimatedHeight() {
    return -1;
  }
  /**
  For inline widgets that are displayed inline (as opposed to
  `inline-block`) and introduce line breaks (through `<br>` tags
  or textual newlines), this must indicate the amount of line
  breaks they introduce. Defaults to 0.
  */
  get lineBreaks() {
    return 0;
  }
  /**
  Can be used to configure which kinds of events inside the widget
  should be ignored by the editor. The default is to ignore all
  events.
  */
  ignoreEvent(event) {
    return true;
  }
  /**
  Override the way screen coordinates for positions at/in the
  widget are found. `pos` will be the offset into the widget, and
  `side` the side of the position that is being queried—less than
  zero for before, greater than zero for after, and zero for
  directly at that position.
  */
  coordsAt(dom, pos, side) {
    return null;
  }
  /**
  @internal
  */
  get isHidden() {
    return false;
  }
  /**
  @internal
  */
  get editable() {
    return false;
  }
  /**
  This is called when the an instance of the widget is removed
  from the editor view.
  */
  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;
  }
  /**
  @internal
  */
  get heightRelevant() {
    return false;
  }
  /**
  Create a mark decoration, which influences the styling of the
  content in its range. Nested mark decorations will cause nested
  DOM elements to be created. Nesting order is determined by
  precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), with
  the higher-precedence decorations creating the inner DOM nodes.
  Such elements are split on line boundaries and on the boundaries
  of lower-precedence decorations.
  */
  static mark(spec) {
    return new MarkDecoration(spec);
  }
  /**
  Create a widget decoration, which displays a DOM element at the
  given position.
  */
  static widget(spec) {
    let side = Math.max(-1e4, Math.min(1e4, spec.side || 0)), block = !!spec.block;
    side += block && !spec.inlineOrder ? side > 0 ? 3e8 : -4e8 : side > 0 ? 1e8 : -1e8;
    return new PointDecoration(spec, side, side, block, spec.widget || null, false);
  }
  /**
  Create a replace decoration which replaces the given range with
  a widget, or simply hides it.
  */
  static replace(spec) {
    let block = !!spec.block, startSide, endSide;
    if (spec.isBlockGap) {
      startSide = -5e8;
      endSide = 4e8;
    } else {
      let { start: start2, end } = getInclusive(spec, block);
      startSide = (start2 ? block ? -3e8 : -1 : 5e8) - 1;
      endSide = (end ? block ? 2e8 : 1 : -6e8) + 1;
    }
    return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true);
  }
  /**
  Create a line decoration, which can add DOM attributes to the
  line starting at the given position.
  */
  static line(spec) {
    return new LineDecoration(spec);
  }
  /**
  Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given
  decorated range or ranges. If the ranges aren't already sorted,
  pass `true` for `sort` to make the library sort them for you.
  */
  static set(of, sort2 = false) {
    return RangeSet.of(of, sort2);
  }
  /**
  @internal
  */
  hasHeight() {
    return this.widget ? this.widget.estimatedHeight > -1 : false;
  }
};
Decoration.none = RangeSet.empty;
var MarkDecoration = class _MarkDecoration extends Decoration {
  constructor(spec) {
    let { start: start2, end } = getInclusive(spec);
    super(start2 ? -1 : 5e8, end ? 1 : -6e8, null, spec);
    this.tagName = spec.tagName || "span";
    this.class = spec.class || "";
    this.attrs = spec.attributes || null;
  }
  eq(other) {
    var _a2, _b;
    return this == other || other instanceof _MarkDecoration && this.tagName == other.tagName && (this.class || ((_a2 = this.attrs) === null || _a2 === void 0 ? void 0 : _a2.class)) == (other.class || ((_b = other.attrs) === null || _b === void 0 ? void 0 : _b.class)) && attrsEq(this.attrs, other.attrs, "class");
  }
  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 _LineDecoration extends Decoration {
  constructor(spec) {
    super(-2e8, -2e8, null, spec);
  }
  eq(other) {
    return other instanceof _LineDecoration && this.spec.class == other.spec.class && 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 _PointDecoration 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;
  }
  // Only relevant when this.block == true
  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 || this.widget.lineBreaks > 0);
  }
  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: start2, inclusiveEnd: end } = spec;
  if (start2 == null)
    start2 = spec.inclusive;
  if (end == null)
    end = spec.inclusive;
  return { start: start2 !== null && start2 !== void 0 ? start2 : 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 ContentBuilder = class _ContentBuilder {
  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.bufferMarks = [];
    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.deco.endSide < 0);
  }
  getLine() {
    if (!this.curLine) {
      this.content.push(this.curLine = new LineView());
      this.atCursorPos = true;
    }
    return this.curLine;
  }
  flushBuffer(active = this.bufferMarks) {
    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 (this.pendingBuffer && openEnd <= this.bufferMarks.length)
      this.flushBuffer();
    else
      this.pendingBuffer = 0;
    if (!this.posCovered() && !(openEnd && this.content.length && this.content[this.content.length - 1] instanceof BlockWidgetView))
      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;
          this.atCursorPos = true;
          length--;
          continue;
        } else {
          this.text = value;
          this.textOff = 0;
        }
      }
      let take = Math.min(
        this.text.length - this.textOff,
        length,
        512
        /* T.Chunk */
      );
      this.flushBuffer(active.slice(active.length - 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) {
        if (deco.startSide > 0 && !this.posCovered())
          this.getLine();
        this.addBlockWidget(new BlockWidgetView(deco.widget || NullWidget.block, len, deco));
      } else {
        let view = WidgetView.create(deco.widget || NullWidget.inline, 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 || openStart > active.length || deco.startSide <= 0);
        let line = this.getLine();
        if (this.pendingBuffer == 2 && !cursorBefore && !view.isEditable)
          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 || openStart > active.length ? 1 : 2;
        if (this.pendingBuffer)
          this.bufferMarks = active.slice();
      }
    } 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(tag) {
    super();
    this.tag = tag;
  }
  eq(other) {
    return other.tag == this.tag;
  }
  toDOM() {
    return document.createElement(this.tag);
  }
  updateDOM(elt) {
    return elt.nodeName.toLowerCase() == this.tag;
  }
  get isHidden() {
    return true;
  }
};
NullWidget.inline = /* @__PURE__ */ new NullWidget("span");
NullWidget.block = /* @__PURE__ */ new NullWidget("div");
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 <= 8204 ? 256 : 64336 <= ch && ch <= 65023 ? 4 : 1;
}
var BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/;
var BidiSpan = class {
  /**
  The direction of this span.
  */
  get dir() {
    return this.level % 2 ? RTL : LTR;
  }
  /**
  @internal
  */
  constructor(from, to, level) {
    this.from = from;
    this.to = to;
    this.level = level;
  }
  /**
  @internal
  */
  side(end, dir) {
    return this.dir == dir == end ? this.to : this.from;
  }
  /**
  @internal
  */
  forward(forward, dir) {
    return forward == (this.dir == dir);
  }
  /**
  @internal
  */
  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;
  }
};
function isolatesEq(a, b) {
  if (a.length != b.length)
    return false;
  for (let i = 0; i < a.length; i++) {
    let iA = a[i], iB = b[i];
    if (iA.from != iB.from || iA.to != iB.to || iA.direction != iB.direction || !isolatesEq(iA.inner, iB.inner))
      return false;
  }
  return true;
}
var types = [];
function computeCharTypes(line, rFrom, rTo, isolates, outerType) {
  for (let iI = 0; iI <= isolates.length; iI++) {
    let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
    let prevType = iI ? 256 : outerType;
    for (let i = from, prev = prevType, prevStrong = prevType; i < to; 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 = from, prev = prevType, prevStrong = prevType; i < to; i++) {
      let type = types[i];
      if (type == 128) {
        if (i < to - 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 < to && types[end] == 64)
          end++;
        let replace = i && prev == 8 || end < rTo && 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;
    }
  }
}
function processBracketPairs(line, rFrom, rTo, isolates, outerType) {
  let oppositeType = outerType == 1 ? 2 : 1;
  for (let iI = 0, sI = 0, context2 = 0; iI <= isolates.length; iI++) {
    let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
    for (let i = from, ch, br, type; i < to; 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 flags2 = BracketStack[sJ + 2];
              let type2 = flags2 & 2 ? outerType : !(flags2 & 4) ? 0 : flags2 & 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++] = context2;
        }
      } else if ((type = types[i]) == 2 || type == 1) {
        let embed = type == outerType;
        context2 = 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;
          }
        }
      }
    }
  }
}
function processNeutrals(rFrom, rTo, isolates, outerType) {
  for (let iI = 0, prev = outerType; iI <= isolates.length; iI++) {
    let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
    for (let i = from; i < to; ) {
      let type = types[i];
      if (type == 256) {
        let end = i + 1;
        for (; ; ) {
          if (end == to) {
            if (iI == isolates.length)
              break;
            end = isolates[iI++].to;
            to = iI < isolates.length ? isolates[iI].from : rTo;
          } else if (types[end] == 256) {
            end++;
          } else {
            break;
          }
        }
        let beforeL = prev == 1;
        let afterL = (end < rTo ? types[end] : outerType) == 1;
        let replace = beforeL == afterL ? beforeL ? 1 : 2 : outerType;
        for (let j = end, jI = iI, fromJ = jI ? isolates[jI - 1].to : rFrom; j > i; ) {
          if (j == fromJ) {
            j = isolates[--jI].from;
            fromJ = jI ? isolates[jI - 1].to : rFrom;
          }
          types[--j] = replace;
        }
        i = end;
      } else {
        prev = type;
        i++;
      }
    }
  }
}
function emitSpans(line, from, to, level, baseLevel, isolates, order) {
  let ourType = level % 2 ? 2 : 1;
  if (level % 2 == baseLevel % 2) {
    for (let iCh = from, iI = 0; iCh < to; ) {
      let sameDir = true, isNum = false;
      if (iI == isolates.length || iCh < isolates[iI].from) {
        let next = types[iCh];
        if (next != ourType) {
          sameDir = false;
          isNum = next == 16;
        }
      }
      let recurse = !sameDir && ourType == 1 ? [] : null;
      let localLevel = sameDir ? level : level + 1;
      let iScan = iCh;
      run:
        for (; ; ) {
          if (iI < isolates.length && iScan == isolates[iI].from) {
            if (isNum)
              break run;
            let iso = isolates[iI];
            if (!sameDir)
              for (let upto = iso.to, jI = iI + 1; ; ) {
                if (upto == to)
                  break run;
                if (jI < isolates.length && isolates[jI].from == upto)
                  upto = isolates[jI++].to;
                else if (types[upto] == ourType)
                  break run;
                else
                  break;
              }
            iI++;
            if (recurse) {
              recurse.push(iso);
            } else {
              if (iso.from > iCh)
                order.push(new BidiSpan(iCh, iso.from, localLevel));
              let dirSwap = iso.direction == LTR != !(localLevel % 2);
              computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
              iCh = iso.to;
            }
            iScan = iso.to;
          } else if (iScan == to || (sameDir ? types[iScan] != ourType : types[iScan] == ourType)) {
            break;
          } else {
            iScan++;
          }
        }
      if (recurse)
        emitSpans(line, iCh, iScan, level + 1, baseLevel, recurse, order);
      else if (iCh < iScan)
        order.push(new BidiSpan(iCh, iScan, localLevel));
      iCh = iScan;
    }
  } else {
    for (let iCh = to, iI = isolates.length; iCh > from; ) {
      let sameDir = true, isNum = false;
      if (!iI || iCh > isolates[iI - 1].to) {
        let next = types[iCh - 1];
        if (next != ourType) {
          sameDir = false;
          isNum = next == 16;
        }
      }
      let recurse = !sameDir && ourType == 1 ? [] : null;
      let localLevel = sameDir ? level : level + 1;
      let iScan = iCh;
      run:
        for (; ; ) {
          if (iI && iScan == isolates[iI - 1].to) {
            if (isNum)
              break run;
            let iso = isolates[--iI];
            if (!sameDir)
              for (let upto = iso.from, jI = iI; ; ) {
                if (upto == from)
                  break run;
                if (jI && isolates[jI - 1].to == upto)
                  upto = isolates[--jI].from;
                else if (types[upto - 1] == ourType)
                  break run;
                else
                  break;
              }
            if (recurse) {
              recurse.push(iso);
            } else {
              if (iso.to < iCh)
                order.push(new BidiSpan(iso.to, iCh, localLevel));
              let dirSwap = iso.direction == LTR != !(localLevel % 2);
              computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
              iCh = iso.from;
            }
            iScan = iso.from;
          } else if (iScan == from || (sameDir ? types[iScan - 1] != ourType : types[iScan - 1] == ourType)) {
            break;
          } else {
            iScan--;
          }
        }
      if (recurse)
        emitSpans(line, iScan, iCh, level + 1, baseLevel, recurse, order);
      else if (iScan < iCh)
        order.push(new BidiSpan(iScan, iCh, localLevel));
      iCh = iScan;
    }
  }
}
function computeSectionOrder(line, level, baseLevel, isolates, from, to, order) {
  let outerType = level % 2 ? 2 : 1;
  computeCharTypes(line, from, to, isolates, outerType);
  processBracketPairs(line, from, to, isolates, outerType);
  processNeutrals(from, to, isolates, outerType);
  emitSpans(line, from, to, level, baseLevel, isolates, order);
}
function computeOrder(line, direction, isolates) {
  if (!line)
    return [new BidiSpan(0, 0, direction == RTL ? 1 : 0)];
  if (direction == LTR && !isolates.length && !BidiRE.test(line))
    return trivialOrder(line.length);
  if (isolates.length)
    while (line.length > types.length)
      types[types.length] = 256;
  let order = [], level = direction == LTR ? 0 : 1;
  computeSectionOrder(line, level, level, isolates, 0, line.length, order);
  return order;
}
function trivialOrder(length) {
  return [new BidiSpan(0, length, 0)];
}
var movedOver = "";
function moveVisually(line, order, dir, start2, forward) {
  var _a2;
  let startIndex = start2.head - line.from;
  let spanI = BidiSpan.find(order, startIndex, (_a2 = start2.bidiLevel) !== null && _a2 !== void 0 ? _a2 : -1, start2.assoc);
  let span = order[spanI], spanEnd = span.side(forward, dir);
  if (startIndex == spanEnd) {
    let nextI = spanI += forward ? 1 : -1;
    if (nextI < 0 || nextI >= order.length)
      return null;
    span = order[spanI = nextI];
    startIndex = span.side(!forward, dir);
    spanEnd = span.side(forward, dir);
  }
  let nextIndex = findClusterBreak(line.text, startIndex, span.forward(forward, dir));
  if (nextIndex < span.from || nextIndex > span.to)
    nextIndex = spanEnd;
  movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex));
  let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)];
  if (nextSpan && nextIndex == spanEnd && nextSpan.level + (forward ? 0 : 1) < span.level)
    return EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, nextSpan.forward(forward, dir) ? 1 : -1, nextSpan.level);
  return EditorSelection.cursor(nextIndex + line.from, span.forward(forward, dir) ? -1 : 1, span.level);
}
function autoDirection(text2, from, to) {
  for (let i = from; i < to; i++) {
    let type = charType(text2.charCodeAt(i));
    if (type == 1)
      return LTR;
    if (type == 2 || type == 4)
      return RTL;
  }
  return LTR;
}
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 focusChangeEffect = /* @__PURE__ */ Facet.define();
var perLineTextDirection = /* @__PURE__ */ Facet.define({
  combine: (values) => values.some((x2) => x2)
});
var nativeSelectionHidden = /* @__PURE__ */ Facet.define({
  combine: (values) => values.some((x2) => x2)
});
var ScrollTarget = class _ScrollTarget {
  constructor(range2, y2 = "nearest", x2 = "nearest", yMargin = 5, xMargin = 5, isSnapshot = false) {
    this.range = range2;
    this.y = y2;
    this.x = x2;
    this.yMargin = yMargin;
    this.xMargin = xMargin;
    this.isSnapshot = isSnapshot;
  }
  map(changes) {
    return changes.empty ? this : new _ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
  }
  clip(state) {
    return this.range.to <= state.doc.length ? this : new _ScrollTarget(EditorSelection.cursor(state.doc.length), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
  }
};
var scrollIntoView = /* @__PURE__ */ StateEffect.define({ map: (t4, ch) => t4.map(ch) });
function logException(state, exception, context2) {
  let handler = state.facet(exceptionSink);
  if (handler.length)
    handler[0](exception);
  else if (window.onerror)
    window.onerror(String(exception), context2, void 0, void 0, exception);
  else if (context2)
    console.error(context2 + ":", 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 _ViewPlugin {
  constructor(id2, create, domEventHandlers, domEventObservers, buildExtensions) {
    this.id = id2;
    this.create = create;
    this.domEventHandlers = domEventHandlers;
    this.domEventObservers = domEventObservers;
    this.extension = buildExtensions(this);
  }
  /**
  Define a plugin from a constructor function that creates the
  plugin's value, given an editor view.
  */
  static define(create, spec) {
    const { eventHandlers, eventObservers, provide, decorations: deco } = spec || {};
    return new _ViewPlugin(nextPluginID++, create, eventHandlers, eventObservers, (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;
    });
  }
  /**
  Create a plugin for a class whose constructor takes a single
  editor view as argument.
  */
  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 outerDecorations = /* @__PURE__ */ Facet.define();
var atomicRanges = /* @__PURE__ */ Facet.define();
var bidiIsolatedRanges = /* @__PURE__ */ Facet.define();
function getIsolatedRanges(view, line) {
  let isolates = view.state.facet(bidiIsolatedRanges);
  if (!isolates.length)
    return isolates;
  let sets = isolates.map((i) => i instanceof Function ? i(view) : i);
  let result = [];
  RangeSet.spans(sets, line.from, line.to, {
    point() {
    },
    span(fromDoc, toDoc, active, open) {
      let from = fromDoc - line.from, to = toDoc - line.from;
      let level = result;
      for (let i = active.length - 1; i >= 0; i--, open--) {
        let direction = active[i].spec.bidiIsolate, update2;
        if (direction == null)
          direction = autoDirection(line.text, from, to);
        if (open > 0 && level.length && (update2 = level[level.length - 1]).to == from && update2.direction == direction) {
          update2.to = to;
          level = update2.inner;
        } else {
          let add3 = { from, to, direction, inner: [] };
          level.push(add3);
          level = add3.inner;
        }
      }
    }
  });
  return result;
}
var scrollMargins = /* @__PURE__ */ Facet.define();
function getScrollMargins(view) {
  let left2 = 0, right2 = 0, top3 = 0, bottom2 = 0;
  for (let source2 of view.state.facet(scrollMargins)) {
    let m = source2(view);
    if (m) {
      if (m.left != null)
        left2 = Math.max(left2, m.left);
      if (m.right != null)
        right2 = Math.max(right2, m.right);
      if (m.top != null)
        top3 = Math.max(top3, m.top);
      if (m.bottom != null)
        bottom2 = Math.max(bottom2, m.bottom);
    }
  }
  return { left: left2, right: right2, top: top3, bottom: bottom2 };
}
var styleModule = /* @__PURE__ */ Facet.define();
var ChangedRange = class _ChangedRange {
  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(set2) {
    let i = set2.length, me = this;
    for (; i > 0; i--) {
      let range2 = set2[i - 1];
      if (range2.fromA > me.toA)
        continue;
      if (range2.toA < me.fromA)
        break;
      me = me.join(range2);
      set2.splice(i - 1, 1);
    }
    set2.splice(i, 0, me);
    return set2;
  }
  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 _ViewUpdate {
  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;
  }
  /**
  @internal
  */
  static create(view, state, transactions) {
    return new _ViewUpdate(view, state, transactions);
  }
  /**
  Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or
  [visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this
  update.
  */
  get viewportChanged() {
    return (this.flags & 4) > 0;
  }
  /**
  Indicates whether the height of a block element in the editor
  changed in this update.
  */
  get heightChanged() {
    return (this.flags & 2) > 0;
  }
  /**
  Returns true when the document was modified or the size of the
  editor, or elements within the editor, changed.
  */
  get geometryChanged() {
    return this.docChanged || (this.flags & (8 | 2)) > 0;
  }
  /**
  True when this update indicates a focus change.
  */
  get focusChanged() {
    return (this.flags & 1) > 0;
  }
  /**
  Whether the document changed in this update.
  */
  get docChanged() {
    return !this.changes.empty;
  }
  /**
  Whether the selection was explicitly set in this update.
  */
  get selectionSet() {
    return this.transactions.some((tr) => tr.selection);
  }
  /**
  @internal
  */
  get empty() {
    return this.flags == 0 && this.transactions.length == 0;
  }
};
var DocView = class extends ContentView {
  get length() {
    return this.view.state.doc.length;
  }
  constructor(view) {
    super();
    this.view = view;
    this.decorations = [];
    this.dynamicDecorationMap = [false];
    this.domChanged = null;
    this.hasComposition = null;
    this.markedForComposition = /* @__PURE__ */ new Set();
    this.compositionBarrier = Decoration.none;
    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, null);
  }
  // Update the document view to a given state.
  update(update2) {
    var _a2;
    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);
      }
    }
    let readCompositionAt = -1;
    if (this.view.inputState.composing >= 0) {
      if ((_a2 = this.domChanged) === null || _a2 === void 0 ? void 0 : _a2.newSel)
        readCompositionAt = this.domChanged.newSel.head;
      else if (!touchesComposition(update2.changes, this.hasComposition) && !update2.selectionSet)
        readCompositionAt = update2.state.selection.main.head;
    }
    let composition = readCompositionAt > -1 ? findCompositionRange(this.view, update2.changes, readCompositionAt) : null;
    this.domChanged = null;
    if (this.hasComposition) {
      this.markedForComposition.clear();
      let { from, to } = this.hasComposition;
      changedRanges = new ChangedRange(from, to, update2.changes.mapPos(from, -1), update2.changes.mapPos(to, 1)).addToSet(changedRanges.slice());
    }
    this.hasComposition = composition ? { from: composition.range.fromB, to: composition.range.toB } : null;
    if ((browser.ie || browser.chrome) && !composition && 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.flags & 7) && changedRanges.length == 0) {
      return false;
    } else {
      this.updateInner(changedRanges, update2.startState.doc.length, composition);
      if (update2.transactions.length)
        this.lastUpdate = Date.now();
      return true;
    }
  }
  // Used by update and the constructor do perform the actual DOM
  // update
  updateInner(changes, oldLength, composition) {
    this.view.viewState.mustMeasureContent = true;
    this.updateChildren(changes, oldLength, composition);
    let { observer } = this.view;
    observer.ignore(() => {
      this.dom.style.height = this.view.viewState.contentHeight / this.view.scaleY + "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(this.view, track);
      this.flags &= ~7;
      if (track && (track.written || observer.selectionRange.focusNode != track.node))
        this.forceSelection = true;
      this.dom.style.height = "";
    });
    this.markedForComposition.forEach(
      (cView) => cView.flags &= ~8
      /* ViewFlag.Composition */
    );
    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, composition) {
    let ranges = composition ? composition.range.addToSet(changes.slice()) : changes;
    let cursor = this.childCursor(oldLength);
    for (let i = ranges.length - 1; ; i--) {
      let next = i >= 0 ? ranges[i] : null;
      if (!next)
        break;
      let { fromA, toA, fromB, toB } = next, content2, breakAtStart, openStart, openEnd;
      if (composition && composition.range.fromB < toB && composition.range.toB > fromB) {
        let before = ContentBuilder.build(this.view.state.doc, fromB, composition.range.fromB, this.decorations, this.dynamicDecorationMap);
        let after = ContentBuilder.build(this.view.state.doc, composition.range.toB, toB, this.decorations, this.dynamicDecorationMap);
        breakAtStart = before.breakAtStart;
        openStart = before.openStart;
        openEnd = after.openEnd;
        let compLine = this.compositionView(composition);
        if (after.breakAtStart) {
          compLine.breakAfter = 1;
        } else if (after.content.length && compLine.merge(compLine.length, compLine.length, after.content[0], false, after.openStart, 0)) {
          compLine.breakAfter = after.content[0].breakAfter;
          after.content.shift();
        }
        if (before.content.length && compLine.merge(0, 0, before.content[before.content.length - 1], true, 0, before.openEnd)) {
          before.content.pop();
        }
        content2 = before.content.concat(compLine).concat(after.content);
      } else {
        ({ 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);
    }
    if (composition)
      this.fixCompositionDOM(composition);
  }
  compositionView(composition) {
    let cur2 = new TextView(composition.text.nodeValue);
    cur2.flags |= 8;
    for (let { deco } of composition.marks)
      cur2 = new MarkView(deco, [cur2], cur2.length);
    let line = new LineView();
    line.append(cur2, 0);
    return line;
  }
  fixCompositionDOM(composition) {
    let fix = (dom, cView2) => {
      cView2.flags |= 8 | (cView2.children.some(
        (c) => c.flags & 7
        /* ViewFlag.Dirty */
      ) ? 1 : 0);
      this.markedForComposition.add(cView2);
      let prev = ContentView.get(dom);
      if (prev && prev != cView2)
        prev.dom = null;
      cView2.setDOM(dom);
    };
    let pos = this.childPos(composition.range.fromB, 1);
    let cView = this.children[pos.i];
    fix(composition.line, cView);
    for (let i = composition.marks.length - 1; i >= -1; i--) {
      pos = cView.childPos(pos.off, 1);
      cView = cView.children[pos.i];
      fix(i >= 0 ? composition.marks[i].node : composition.text, cView);
    }
  }
  // Sync the DOM selection to this.state.selection
  updateSelection(mustRead = false, fromPointer = false) {
    if (mustRead || !this.view.observer.selectionRange.focusNode)
      this.view.observer.readSelectionRange();
    let activeElt = this.view.root.activeElement, focused = activeElt == this.dom;
    let selectionNotFocus = !focused && hasSelection(this.dom, this.view.observer.selectionRange) && !(activeElt && this.dom.contains(activeElt));
    if (!(focused || fromPointer || selectionNotFocus))
      return;
    let force = this.forceSelection;
    this.forceSelection = false;
    let main = this.view.state.selection.main;
    let anchor = this.moveToLine(this.domAtPos(main.anchor));
    let head = main.empty ? anchor : this.moveToLine(this.domAtPos(main.head));
    if (browser.gecko && main.empty && !this.hasComposition && 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.suppressWidgetCursorChange(domSel, main)) {
      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.node, text2.offset);
            }
          }
          rawSel.collapse(anchor.node, anchor.offset);
          if (main.bidiLevel != null && rawSel.caretBidiLevel !== void 0)
            rawSel.caretBidiLevel = 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);
        }
        if (selectionNotFocus && this.view.root.activeElement == this.dom) {
          this.dom.blur();
          if (activeElt)
            activeElt.focus();
        }
      });
      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);
  }
  // If a zero-length widget is inserted next to the cursor during
  // composition, avoid moving it across it and disrupting the
  // composition.
  suppressWidgetCursorChange(sel, cursor) {
    return this.hasComposition && cursor.empty && !this.compositionBarrier.size && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset) && this.posFromDOM(sel.focusNode, sel.focusOffset) == cursor.head;
  }
  enforceCursorAssoc() {
    if (this.hasComposition)
      return;
    let { view } = this, cursor = view.state.selection.main;
    let sel = getSelection(view.root);
    let { anchorNode, anchorOffset } = view.observer.selectionRange;
    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");
    view.observer.readSelectionRange();
    let newRange = view.observer.selectionRange;
    if (view.docView.posFromDOM(newRange.anchorNode, newRange.anchorOffset) != cursor.from)
      sel.collapse(anchorNode, anchorOffset);
  }
  // If a position is in/near a block widget, move it to a nearby text
  // line, since we don't want the cursor inside a block widget.
  moveToLine(pos) {
    let dom = this.dom, newPos;
    if (pos.node != dom)
      return pos;
    for (let i = pos.offset; !newPos && i < dom.childNodes.length; i++) {
      let view = ContentView.get(dom.childNodes[i]);
      if (view instanceof LineView)
        newPos = view.domAtPos(0);
    }
    for (let i = pos.offset - 1; !newPos && i >= 0; i--) {
      let view = ContentView.get(dom.childNodes[i]);
      if (view instanceof LineView)
        newPos = view.domAtPos(view.length);
    }
    return newPos ? new DOMPos(newPos.node, newPos.offset, true) : pos;
  }
  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) {
    let best = null, bestPos = 0;
    for (let off = this.length, i = this.children.length - 1; i >= 0; i--) {
      let child = this.children[i], end = off - child.breakAfter, start2 = end - child.length;
      if (end < pos)
        break;
      if (start2 <= pos && (start2 < pos || child.covers(-1)) && (end > pos || child.covers(1)) && (!best || child instanceof LineView && !(best instanceof LineView && side >= 0))) {
        best = child;
        bestPos = start2;
      }
      off = start2;
    }
    return best ? best.coordsAt(pos - bestPos, side) : null;
  }
  coordsForChar(pos) {
    let { i, off } = this.childPos(pos, 1), child = this.children[i];
    if (!(child instanceof LineView))
      return null;
    while (child.children.length) {
      let { i: i2, off: childOff } = child.childPos(off, 1);
      for (; ; i2++) {
        if (i2 == child.children.length)
          return null;
        if ((child = child.children[i2]).length)
          break;
      }
      off = childOff;
    }
    if (!(child instanceof TextView))
      return null;
    let end = findClusterBreak(child.text, off);
    if (end == off)
      return null;
    let rects = textRange(child.dom, off, end).getClientRects();
    for (let i2 = 0; i2 < rects.length; i2++) {
      let rect = rects[i2];
      if (i2 == rects.length - 1 || rect.top < rect.bottom && rect.left < rect.right)
        return rect;
    }
    return null;
  }
  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, textHeight;
    dummy.className = "cm-line";
    dummy.style.width = "99999px";
    dummy.style.position = "absolute";
    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;
      textHeight = rect ? rect.height : lineHeight;
      dummy.remove();
    });
    return { lineHeight, charWidth, textHeight };
  }
  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) / this.view.scaleY;
        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 i = 1;
    let allDeco = this.view.state.facet(decorations).map((d) => {
      let dynamic = this.dynamicDecorationMap[i++] = typeof d == "function";
      return dynamic ? d(this.view) : d;
    });
    let dynamicOuter = false, outerDeco = this.view.state.facet(outerDecorations).map((d, i2) => {
      let dynamic = typeof d == "function";
      if (dynamic)
        dynamicOuter = true;
      return dynamic ? d(this.view) : d;
    });
    if (outerDeco.length) {
      this.dynamicDecorationMap[i++] = dynamicOuter;
      allDeco.push(RangeSet.join(outerDeco));
    }
    this.decorations = [
      this.compositionBarrier,
      ...allDeco,
      this.computeBlockGapDeco(),
      this.view.viewState.lineGapDeco
    ];
    while (i < this.decorations.length)
      this.dynamicDecorationMap[i++] = false;
    return this.decorations;
  }
  // Starting a composition will style the inserted text with the
  // style of the text before it, and this is only cleared when the
  // composition ends, because touching it before that will abort it.
  // This (called from compositionstart handler) tries to notice when
  // the cursor is after a non-inclusive mark, where the styling could
  // be jarring, and insert an ad-hoc widget before the cursor to
  // isolate it from the style before it.
  maybeCreateCompositionBarrier() {
    let { main: { head, empty: empty4 } } = this.view.state.selection;
    if (!empty4)
      return false;
    let found = null;
    for (let set2 of this.decorations) {
      set2.between(head, head, (from, to, value) => {
        if (value.point)
          found = false;
        else if (value.endSide < 0 && from < head && to == head)
          found = true;
      });
      if (found === false)
        break;
    }
    this.compositionBarrier = found ? Decoration.set(compositionBarrierWidget.range(head)) : Decoration.none;
    return !!found;
  }
  clearCompositionBarrier() {
    this.compositionBarrier = Decoration.none;
  }
  scrollIntoView(target) {
    if (target.isSnapshot) {
      let ref = this.view.viewState.lineBlockAt(target.range.head);
      this.view.scrollDOM.scrollTop = ref.top - target.yMargin;
      this.view.scrollDOM.scrollLeft = target.xMargin;
      return;
    }
    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 margins = getScrollMargins(this.view);
    let targetRect = {
      left: rect.left - margins.left,
      top: rect.top - margins.top,
      right: rect.right + margins.right,
      bottom: rect.bottom + margins.bottom
    };
    let { offsetWidth, offsetHeight } = this.view.scrollDOM;
    scrollRectIntoView(this.view.scrollDOM, targetRect, range2.head < range2.anchor ? -1 : 1, target.x, target.y, Math.max(Math.min(target.xMargin, offsetWidth), -offsetWidth), Math.max(Math.min(target.yMargin, offsetHeight), -offsetHeight), this.view.textDirection == Direction.LTR);
  }
};
var compositionBarrierWidget = /* @__PURE__ */ Decoration.widget({ side: -1, widget: NullWidget.inline });
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");
    elt.className = "cm-gap";
    this.updateDOM(elt);
    return elt;
  }
  eq(other) {
    return other.height == this.height;
  }
  updateDOM(elt) {
    elt.style.height = this.height + "px";
    return true;
  }
  get editable() {
    return true;
  }
  get estimatedHeight() {
    return this.height;
  }
  ignoreEvent() {
    return false;
  }
};
function findCompositionNode(view, headPos) {
  let sel = view.observer.selectionRange;
  let textNode = sel.focusNode && nearbyTextNode(sel.focusNode, sel.focusOffset, 0);
  if (!textNode)
    return null;
  let from = headPos - textNode.offset;
  return { from, to: from + textNode.node.nodeValue.length, node: textNode.node };
}
function findCompositionRange(view, changes, headPos) {
  let found = findCompositionNode(view, headPos);
  if (!found)
    return null;
  let { node: textNode, from, to } = found, text2 = textNode.nodeValue;
  if (/[\n\r]/.test(text2))
    return null;
  if (view.state.doc.sliceString(found.from, found.to) != text2)
    return null;
  let inv = changes.invertedDesc;
  let range2 = new ChangedRange(inv.mapPos(from), inv.mapPos(to), from, to);
  let marks2 = [];
  for (let parent2 = textNode.parentNode; ; parent2 = parent2.parentNode) {
    let parentView = ContentView.get(parent2);
    if (parentView instanceof MarkView)
      marks2.push({ node: parent2, deco: parentView.mark });
    else if (parentView instanceof LineView || parent2.nodeName == "DIV" && parent2.parentNode == view.contentDOM)
      return { range: range2, text: textNode, marks: marks2, line: parent2 };
    else if (parent2 != view.contentDOM)
      marks2.push({ node: parent2, deco: new MarkDecoration({
        inclusive: true,
        attributes: getAttrs(parent2),
        tagName: parent2.tagName.toLowerCase()
      }) });
    else
      return null;
  }
}
function nearbyTextNode(startNode, startOffset, side) {
  if (side <= 0)
    for (let node = startNode, offset = startOffset; ; ) {
      if (node.nodeType == 3)
        return { node, offset };
      if (node.nodeType == 1 && offset > 0) {
        node = node.childNodes[offset - 1];
        offset = maxOffset(node);
      } else {
        break;
      }
    }
  if (side >= 0)
    for (let node = startNode, offset = startOffset; ; ) {
      if (node.nodeType == 3)
        return { node, offset };
      if (node.nodeType == 1 && offset < node.childNodes.length && side >= 0) {
        node = node.childNodes[offset];
        offset = 0;
      } else {
        break;
      }
    }
  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 DecorationComparator {
  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 touchesComposition(changes, composition) {
  let touched = false;
  if (composition)
    changes.iterChangedRanges((from, to) => {
      if (from < composition.to && to > composition.from)
        touched = true;
    });
  return touched;
}
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;
        let side = dy ? y2 < rect.top ? -1 : 1 : dx ? x2 < rect.left ? -1 : 1 : 0;
        closestOverlap = !side || (side > 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, coords, precise, bias = -1) {
  var _a2, _b;
  let content2 = view.contentDOM.getBoundingClientRect(), docTop = content2.top + view.viewState.paddingTop;
  let block, { docHeight } = view.viewState;
  let { x: x2, y: y2 } = coords, yOffset = y2 - docTop;
  if (yOffset < 0)
    return 0;
  if (yOffset > docHeight)
    return view.state.doc.length;
  for (let halfLine = view.viewState.heightOracle.textHeight / 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));
  }
  let nearest = view.docView.nearest(node);
  if (!nearest)
    return null;
  if (nearest.isWidget && ((_b = nearest.dom) === null || _b === void 0 ? void 0 : _b.nodeType) == 1) {
    let rect = nearest.dom.getBoundingClientRect();
    return coords.y < rect.top || coords.y <= rect.bottom && coords.x <= (rect.left + rect.right) / 2 ? nearest.posAtStart : nearest.posAtEnd;
  } else {
    return nearest.localPosFromDOM(node, offset) + nearest.posAtStart;
  }
}
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 textHeight = view.viewState.heightOracle.textHeight;
    let line = Math.floor((y2 - block.top - (view.defaultLineHeight - textHeight) * 0.5) / textHeight);
    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 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 moveToLineBoundary(view, start2, forward, includeWrap) {
  let line = blockAt(view, start2.head);
  let coords = !includeWrap || line.type != BlockType.Text || !(view.lineWrapping || line.widgetLineBreaks) ? null : view.coordsAtPos(start2.assoc < 0 && start2.head > line.from ? start2.head - 1 : start2.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);
  }
  return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1);
}
function moveByChar(view, start2, forward, by) {
  let line = view.state.doc.lineAt(start2.head), spans = view.bidiSpans(line);
  let direction = view.textDirectionAt(line.from);
  for (let cur2 = start2, 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 = view.visualLineSide(line, !forward);
    }
    if (!check) {
      if (!by)
        return next;
      check = by(char);
    } else if (!check(char)) {
      return cur2;
    }
    cur2 = next;
  }
}
function byGroup(view, pos, start2) {
  let categorize = view.state.charCategorizer(pos);
  let cat = categorize(start2);
  return (next) => {
    let nextCat = categorize(next);
    if (cat == CharCategory.Space)
      cat = nextCat;
    return cat == nextCat;
  };
}
function moveVertically(view, start2, forward, distance) {
  let startPos = start2.head, dir = forward ? 1 : -1;
  if (startPos == (forward ? view.state.doc.length : 0))
    return EditorSelection.cursor(startPos, start2.assoc);
  let goal = start2.goalColumn, startY;
  let rect = view.contentDOM.getBoundingClientRect();
  let startCoords = view.coordsAtPos(startPos, start2.assoc || -1), 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 dist2 = distance !== null && distance !== void 0 ? distance : view.viewState.heightOracle.textHeight >> 1;
  for (let extra = 0; ; extra += 10) {
    let curY = startY + (dist2 + 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)) {
      let charRect = view.docView.coordsForChar(pos);
      let assoc = !charRect || curY < charRect.top ? -1 : 1;
      return EditorSelection.cursor(pos, assoc, void 0, goal);
    }
  }
}
function skipAtomicRanges(atoms, pos, bias) {
  for (; ; ) {
    let moved = 0;
    for (let set2 of atoms) {
      set2.between(pos - 1, pos + 1, (from, to, value) => {
        if (pos > from && pos < to) {
          let side = moved || bias || (pos - from < to - pos ? -1 : 1);
          pos = side < 0 ? from : to;
          moved = side;
        }
      });
    }
    if (!moved)
      return pos;
  }
}
function skipAtoms(view, oldPos, pos) {
  let newPos = skipAtomicRanges(view.state.facet(atomicRanges).map((f) => f(view)), pos.from, oldPos.head > pos.from ? -1 : 1);
  return newPos == pos.from ? pos : EditorSelection.cursor(newPos, newPos < pos.from ? 1 : -1);
}
var InputState = class {
  setSelectionOrigin(origin) {
    this.lastSelectionOrigin = origin;
    this.lastSelectionTime = Date.now();
  }
  constructor(view) {
    this.view = view;
    this.lastKeyCode = 0;
    this.lastKeyTime = 0;
    this.lastTouchTime = 0;
    this.lastFocusTime = 0;
    this.lastScrollTop = 0;
    this.lastScrollLeft = 0;
    this.pendingIOSKey = void 0;
    this.lastSelectionOrigin = null;
    this.lastSelectionTime = 0;
    this.lastEscPress = 0;
    this.lastContextMenu = 0;
    this.scrollHandlers = [];
    this.handlers = /* @__PURE__ */ Object.create(null);
    this.composing = -1;
    this.compositionFirstChange = null;
    this.compositionEndedAt = 0;
    this.compositionPendingKey = false;
    this.compositionPendingChange = false;
    this.mouseSelection = null;
    this.draggedContent = null;
    this.handleEvent = this.handleEvent.bind(this);
    this.notifiedFocused = view.hasFocus;
    if (browser.safari)
      view.contentDOM.addEventListener("input", () => null);
    if (browser.gecko)
      firefoxCopyCutHack(view.contentDOM.ownerDocument);
  }
  handleEvent(event) {
    if (!eventBelongsToEditor(this.view, event) || this.ignoreDuringComposition(event))
      return;
    if (event.type == "keydown" && this.keydown(event))
      return;
    this.runHandlers(event.type, event);
  }
  runHandlers(type, event) {
    let handlers2 = this.handlers[type];
    if (handlers2) {
      for (let observer of handlers2.observers)
        observer(this.view, event);
      for (let handler of handlers2.handlers) {
        if (event.defaultPrevented)
          break;
        if (handler(this.view, event)) {
          event.preventDefault();
          break;
        }
      }
    }
  }
  ensureHandlers(plugins) {
    let handlers2 = computeHandlers(plugins), prev = this.handlers, dom = this.view.contentDOM;
    for (let type in handlers2)
      if (type != "scroll") {
        let passive = !handlers2[type].handlers.length;
        let exists = prev[type];
        if (exists && passive != !exists.handlers.length) {
          dom.removeEventListener(type, this.handleEvent);
          exists = null;
        }
        if (!exists)
          dom.addEventListener(type, this.handleEvent, { passive });
      }
    for (let type in prev)
      if (type != "scroll" && !handlers2[type])
        dom.removeEventListener(type, this.handleEvent);
    this.handlers = handlers2;
  }
  keydown(event) {
    this.lastKeyCode = event.keyCode;
    this.lastKeyTime = Date.now();
    if (event.keyCode == 9 && Date.now() < this.lastEscPress + 2e3)
      return true;
    if (event.keyCode != 27 && modifierCodes.indexOf(event.keyCode) < 0)
      this.view.inputState.lastEscPress = 0;
    if (browser.android && browser.chrome && !event.synthetic && (event.keyCode == 13 || event.keyCode == 8)) {
      this.view.observer.delayAndroidKey(event.key, event.keyCode);
      return true;
    }
    let pending;
    if (browser.ios && !event.synthetic && !event.altKey && !event.metaKey && ((pending = PendingKeys.find((key2) => key2.keyCode == event.keyCode)) && !event.ctrlKey || EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey && !event.shiftKey)) {
      this.pendingIOSKey = pending || event;
      setTimeout(() => this.flushIOSKey(), 250);
      return true;
    }
    if (event.keyCode != 229)
      this.view.observer.forceFlush();
    return false;
  }
  flushIOSKey() {
    let key2 = this.pendingIOSKey;
    if (!key2)
      return false;
    this.pendingIOSKey = void 0;
    return dispatchKey(this.view.contentDOM, key2.key, key2.keyCode);
  }
  ignoreDuringComposition(event) {
    if (!/^key/.test(event.type))
      return false;
    if (this.composing > 0)
      return true;
    if (browser.safari && !browser.ios && this.compositionPendingKey && Date.now() - this.compositionEndedAt < 100) {
      this.compositionPendingKey = false;
      return true;
    }
    return false;
  }
  startMouseSelection(mouseSelection) {
    if (this.mouseSelection)
      this.mouseSelection.destroy();
    this.mouseSelection = mouseSelection;
  }
  update(update2) {
    if (this.mouseSelection)
      this.mouseSelection.update(update2);
    if (this.draggedContent && update2.docChanged)
      this.draggedContent = this.draggedContent.map(update2.changes);
    if (update2.transactions.length)
      this.lastKeyCode = this.lastSelectionTime = 0;
  }
  destroy() {
    if (this.mouseSelection)
      this.mouseSelection.destroy();
  }
};
function bindHandler(plugin, handler) {
  return (view, event) => {
    try {
      return handler.call(plugin, event, view);
    } catch (e3) {
      logException(view.state, e3);
    }
  };
}
function computeHandlers(plugins) {
  let result = /* @__PURE__ */ Object.create(null);
  function record2(type) {
    return result[type] || (result[type] = { observers: [], handlers: [] });
  }
  for (let plugin of plugins) {
    let spec = plugin.spec;
    if (spec && spec.domEventHandlers)
      for (let type in spec.domEventHandlers) {
        let f = spec.domEventHandlers[type];
        if (f)
          record2(type).handlers.push(bindHandler(plugin.value, f));
      }
    if (spec && spec.domEventObservers)
      for (let type in spec.domEventObservers) {
        let f = spec.domEventObservers[type];
        if (f)
          record2(type).observers.push(bindHandler(plugin.value, f));
      }
  }
  for (let type in handlers)
    record2(type).handlers.push(handlers[type]);
  for (let type in observers)
    record2(type).observers.push(observers[type]);
  return result;
}
var PendingKeys = [
  { key: "Backspace", keyCode: 8, inputType: "deleteContentBackward" },
  { key: "Enter", keyCode: 13, inputType: "insertParagraph" },
  { key: "Enter", keyCode: 13, inputType: "insertLineBreak" },
  { key: "Delete", keyCode: 46, inputType: "deleteContentForward" }
];
var EmacsyPendingKeys = "dthko";
var modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225];
var dragScrollMargin = 6;
function dragScrollSpeed(dist2) {
  return Math.max(0, dist2) * 0.7 + 8;
}
function dist(a, b) {
  return Math.max(Math.abs(a.clientX - b.clientX), Math.abs(a.clientY - b.clientY));
}
var MouseSelection = class {
  constructor(view, startEvent, style, mustSelect) {
    this.view = view;
    this.startEvent = startEvent;
    this.style = style;
    this.mustSelect = mustSelect;
    this.scrollSpeed = { x: 0, y: 0 };
    this.scrolling = -1;
    this.lastEvent = startEvent;
    this.scrollParent = scrollableParent(view.contentDOM);
    this.atoms = view.state.facet(atomicRanges).map((f) => f(view));
    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.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false;
  }
  start(event) {
    if (this.dragging === false)
      this.select(event);
  }
  move(event) {
    var _a2;
    if (event.buttons == 0)
      return this.destroy();
    if (this.dragging || this.dragging == null && dist(this.startEvent, event) < 10)
      return;
    this.select(this.lastEvent = event);
    let sx = 0, sy = 0;
    let rect = ((_a2 = this.scrollParent) === null || _a2 === void 0 ? void 0 : _a2.getBoundingClientRect()) || { left: 0, top: 0, right: this.view.win.innerWidth, bottom: this.view.win.innerHeight };
    let margins = getScrollMargins(this.view);
    if (event.clientX - margins.left <= rect.left + dragScrollMargin)
      sx = -dragScrollSpeed(rect.left - event.clientX);
    else if (event.clientX + margins.right >= rect.right - dragScrollMargin)
      sx = dragScrollSpeed(event.clientX - rect.right);
    if (event.clientY - margins.top <= rect.top + dragScrollMargin)
      sy = -dragScrollSpeed(rect.top - event.clientY);
    else if (event.clientY + margins.bottom >= rect.bottom - dragScrollMargin)
      sy = dragScrollSpeed(event.clientY - rect.bottom);
    this.setScrollSpeed(sx, sy);
  }
  up(event) {
    if (this.dragging == null)
      this.select(this.lastEvent);
    if (!this.dragging)
      event.preventDefault();
    this.destroy();
  }
  destroy() {
    this.setScrollSpeed(0, 0);
    let doc2 = this.view.contentDOM.ownerDocument;
    doc2.removeEventListener("mousemove", this.move);
    doc2.removeEventListener("mouseup", this.up);
    this.view.inputState.mouseSelection = this.view.inputState.draggedContent = null;
  }
  setScrollSpeed(sx, sy) {
    this.scrollSpeed = { x: sx, y: sy };
    if (sx || sy) {
      if (this.scrolling < 0)
        this.scrolling = setInterval(() => this.scroll(), 50);
    } else if (this.scrolling > -1) {
      clearInterval(this.scrolling);
      this.scrolling = -1;
    }
  }
  scroll() {
    if (this.scrollParent) {
      this.scrollParent.scrollLeft += this.scrollSpeed.x;
      this.scrollParent.scrollTop += this.scrollSpeed.y;
    } else {
      this.view.win.scrollBy(this.scrollSpeed.x, this.scrollSpeed.y);
    }
    if (this.dragging === false)
      this.select(this.lastEvent);
  }
  skipAtoms(sel) {
    let ranges = null;
    for (let i = 0; i < sel.ranges.length; i++) {
      let range2 = sel.ranges[i], updated = null;
      if (range2.empty) {
        let pos = skipAtomicRanges(this.atoms, range2.from, 0);
        if (pos != range2.from)
          updated = EditorSelection.cursor(pos, -1);
      } else {
        let from = skipAtomicRanges(this.atoms, range2.from, -1);
        let to = skipAtomicRanges(this.atoms, range2.to, 1);
        if (from != range2.from || to != range2.to)
          updated = EditorSelection.range(range2.from == range2.anchor ? from : to, range2.from == range2.head ? from : to);
      }
      if (updated) {
        if (!ranges)
          ranges = sel.ranges.slice();
        ranges[i] = updated;
      }
    }
    return ranges ? EditorSelection.create(ranges, sel.mainIndex) : sel;
  }
  select(event) {
    let { view } = this, selection2 = this.skipAtoms(this.style.get(event, this.extend, this.multiple));
    if (this.mustSelect || !selection2.eq(view.state.selection, this.dragging === false))
      this.view.dispatch({
        selection: selection2,
        userEvent: "select.pointer"
      });
    this.mustSelect = false;
  }
  update(update2) {
    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 observers = /* @__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
  });
}
observers.scroll = (view) => {
  view.inputState.lastScrollTop = view.scrollDOM.scrollTop;
  view.inputState.lastScrollLeft = view.scrollDOM.scrollLeft;
};
handlers.keydown = (view, event) => {
  view.inputState.setSelectionOrigin("select");
  if (event.keyCode == 27)
    view.inputState.lastEscPress = Date.now();
  return false;
};
observers.touchstart = (view, e3) => {
  view.inputState.lastTouchTime = Date.now();
  view.inputState.setSelectionOrigin("select.pointer");
};
observers.touchmove = (view) => {
  view.inputState.setSelectionOrigin("select.pointer");
};
handlers.mousedown = (view, event) => {
  view.observer.flush();
  if (view.inputState.lastTouchTime > Date.now() - 2e3)
    return false;
  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.hasFocus;
    view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus));
    if (mustFocus)
      view.observer.ignore(() => focusPreventScroll(view.contentDOM));
    let mouseSel = view.inputState.mouseSelection;
    if (mouseSel) {
      mouseSel.start(event);
      return mouseSel.dragging === false;
    }
  }
  return false;
};
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 start2 = queryPos(view, event), type = getClickType(event);
  let startSel = view.state.selection;
  return {
    update(update2) {
      if (update2.docChanged) {
        start2.pos = update2.changes.mapPos(start2.pos);
        startSel = startSel.map(update2.changes);
      }
    },
    get(event2, extend3, multiple) {
      let cur2 = queryPos(view, event2), removed;
      let range2 = rangeForClick(view, cur2.pos, cur2.bias, type);
      if (start2.pos != cur2.pos && !extend3) {
        let startRange = rangeForClick(view, start2.pos, start2.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 && type == 1 && startSel.ranges.length > 1 && (removed = removeRangeAround(startSel, cur2.pos)))
        return removed;
      else if (multiple)
        return startSel.addRange(range2);
      else
        return EditorSelection.create([range2]);
    }
  };
}
function removeRangeAround(sel, pos) {
  for (let i = 0; i < sel.ranges.length; i++) {
    let { from, to } = sel.ranges[i];
    if (from <= pos && to >= pos)
      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));
  }
  return null;
}
handlers.dragstart = (view, event) => {
  let { selection: { main: range2 } } = view.state;
  if (event.target.draggable) {
    let cView = view.docView.nearest(event.target);
    if (cView && cView.isWidget) {
      let from = cView.posAtStart, to = from + cView.length;
      if (from >= range2.to || to <= range2.from)
        range2 = EditorSelection.range(from, to);
    }
  }
  let { inputState } = view;
  if (inputState.mouseSelection)
    inputState.mouseSelection.dragging = true;
  inputState.draggedContent = range2;
  if (event.dataTransfer) {
    event.dataTransfer.setData("Text", view.state.sliceDoc(range2.from, range2.to));
    event.dataTransfer.effectAllowed = "copyMove";
  }
  return false;
};
handlers.dragend = (view) => {
  view.inputState.draggedContent = null;
  return false;
};
function dropText(view, event, text2, direct) {
  if (!text2)
    return;
  let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
  let { draggedContent } = view.inputState;
  let del = direct && draggedContent && dragMovesSelection(view, event) ? { from: draggedContent.from, to: draggedContent.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"
  });
  view.inputState.draggedContent = null;
}
handlers.drop = (view, event) => {
  if (!event.dataTransfer)
    return false;
  if (view.state.readOnly)
    return true;
  let files2 = event.dataTransfer.files;
  if (files2 && files2.length) {
    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]);
    }
    return true;
  } else {
    let text2 = event.dataTransfer.getData("Text");
    if (text2) {
      dropText(view, event, text2, true);
      return true;
    }
  }
  return false;
};
handlers.paste = (view, event) => {
  if (view.state.readOnly)
    return true;
  view.observer.flush();
  let data = brokenClipboardAPI ? null : event.clipboardData;
  if (data) {
    doPaste(view, data.getData("text/plain") || data.getData("text/uri-text"));
    return true;
  } else {
    capturePaste(view);
    return false;
  }
};
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 false;
  lastLinewiseCopy = linewise ? text2 : null;
  if (event.type == "cut" && !view.state.readOnly)
    view.dispatch({
      changes: ranges,
      scrollIntoView: true,
      userEvent: "delete.cut"
    });
  let data = brokenClipboardAPI ? null : event.clipboardData;
  if (data) {
    data.clearData();
    data.setData("text/plain", text2);
    return true;
  } else {
    captureCopy(view, text2);
    return false;
  }
};
var isFocusChange = /* @__PURE__ */ Annotation.define();
function focusChangeTransaction(state, focus) {
  let effects = [];
  for (let getEffect of state.facet(focusChangeEffect)) {
    let effect = getEffect(state, focus);
    if (effect)
      effects.push(effect);
  }
  return effects ? state.update({ effects, annotations: isFocusChange.of(true) }) : null;
}
function updateForFocusChange(view) {
  setTimeout(() => {
    let focus = view.hasFocus;
    if (focus != view.inputState.notifiedFocused) {
      let tr = focusChangeTransaction(view.state, focus);
      if (tr)
        view.dispatch(tr);
      else
        view.update([]);
    }
  }, 10);
}
observers.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);
};
observers.blur = (view) => {
  view.observer.clearSelectionRange();
  updateForFocusChange(view);
};
observers.compositionstart = observers.compositionupdate = (view) => {
  if (view.inputState.compositionFirstChange == null)
    view.inputState.compositionFirstChange = true;
  if (view.inputState.composing < 0) {
    view.inputState.composing = 0;
    if (view.docView.maybeCreateCompositionBarrier()) {
      view.update([]);
      view.docView.clearCompositionBarrier();
    }
  }
};
observers.compositionend = (view) => {
  view.inputState.composing = -1;
  view.inputState.compositionEndedAt = Date.now();
  view.inputState.compositionPendingKey = true;
  view.inputState.compositionPendingChange = view.observer.pendingRecords().length > 0;
  view.inputState.compositionFirstChange = null;
  if (browser.chrome && browser.android) {
    view.observer.flushSoon();
  } else if (view.inputState.compositionPendingChange) {
    Promise.resolve().then(() => view.observer.flush());
  } else {
    setTimeout(() => {
      if (view.inputState.composing < 0 && view.docView.hasComposition)
        view.update([]);
    }, 50);
  }
};
observers.contextmenu = (view) => {
  view.inputState.lastContextMenu = Date.now();
};
handlers.beforeinput = (view, event) => {
  var _a2;
  let pending;
  if (browser.chrome && browser.android && (pending = PendingKeys.find((key2) => key2.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);
    }
  }
  return false;
};
var appliedFirefoxHack = /* @__PURE__ */ new Set();
function firefoxCopyCutHack(doc2) {
  if (!appliedFirefoxHack.has(doc2)) {
    appliedFirefoxHack.add(doc2);
    doc2.addEventListener("copy", () => {
    });
    doc2.addEventListener("cut", () => {
    });
  }
}
var wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"];
var HeightOracle = class {
  constructor(lineWrapping) {
    this.lineWrapping = lineWrapping;
    this.doc = Text.empty;
    this.heightSamples = {};
    this.lineHeight = 14;
    this.charWidth = 7;
    this.textHeight = 14;
    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.max(0, 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, textHeight, 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.textHeight = textHeight;
    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 _BlockInfo {
  /**
  @internal
  */
  constructor(from, length, top3, height4, _content) {
    this.from = from;
    this.length = length;
    this.top = top3;
    this.height = height4;
    this._content = _content;
  }
  /**
  The type of element this is. When querying lines, this may be
  an array of all the blocks that make up the line.
  */
  get type() {
    return typeof this._content == "number" ? BlockType.Text : Array.isArray(this._content) ? this._content : this._content.type;
  }
  /**
  The end of the element as a document position.
  */
  get to() {
    return this.from + this.length;
  }
  /**
  The bottom position of the element.
  */
  get bottom() {
    return this.top + this.height;
  }
  /**
  If this is a widget block, this will return the widget
  associated with it.
  */
  get widget() {
    return this._content instanceof PointDecoration ? this._content.widget : null;
  }
  /**
  If this is a textblock, this holds the number of line breaks
  that appear in widgets inside the block.
  */
  get widgetLineBreaks() {
    return typeof this._content == "number" ? this._content : 0;
  }
  /**
  @internal
  */
  join(other) {
    let content2 = (Array.isArray(this._content) ? this._content : [this]).concat(Array.isArray(other._content) ? other._content : [other]);
    return new _BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, content2);
  }
};
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 _HeightMap {
  constructor(length, height4, flags2 = 2) {
    this.length = length;
    this.height = height4;
    this.flags = flags2;
  }
  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;
    }
  }
  // Base case is to replace a leaf node, which simply builds a tree
  // from the new nodes and returns that (HeightMapBranch and
  // HeightMapGap override this to actually use from/to)
  replace(_from, _to, nodes) {
    return _HeightMap.of(nodes);
  }
  // Again, these are base cases, and are overridden for branch and gap nodes.
  decomposeLeft(_to, result) {
    result.push(this);
  }
  decomposeRight(_from, result) {
    result.push(this);
  }
  applyChanges(decorations2, oldDoc, oracle, changes) {
    let me = this, doc2 = oracle.doc;
    for (let i = changes.length - 1; i >= 0; i--) {
      let { fromA, toA, fromB, toB } = changes[i];
      let start2 = me.lineAt(fromA, QueryType.ByPosNoHeight, oracle.setDoc(oldDoc), 0, 0);
      let end = start2.to >= toA ? start2 : me.lineAt(toA, QueryType.ByPosNoHeight, oracle, 0, 0);
      toB += end.to - toA;
      toA = end.to;
      while (i > 0 && start2.from <= changes[i - 1].toA) {
        fromA = changes[i - 1].fromA;
        fromB = changes[i - 1].fromB;
        i--;
        if (fromA < start2.from)
          start2 = me.lineAt(fromA, QueryType.ByPosNoHeight, oracle, 0, 0);
      }
      fromB += start2.from - fromA;
      fromA = start2.from;
      let nodes = NodeBuilder.build(oracle.setDoc(doc2), decorations2, fromB, toB);
      me = me.replace(fromA, toA, nodes);
    }
    return me.updateHeight(oracle, 0);
  }
  static empty() {
    return new HeightMapText(0, 0);
  }
  // nodes uses null values to indicate the position of line breaks.
  // There are never line breaks at the start or end of the array, or
  // two line breaks next to each other, and the array isn't allowed
  // to be empty (same restrictions as return value from the builder).
  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, deco) {
    super(length, height4);
    this.deco = deco;
  }
  blockAt(_height, _oracle, top3, offset) {
    return new BlockInfo(offset, this.length, top3, this.height, this.deco || 0);
  }
  lineAt(_value, _type, oracle, top3, offset) {
    return this.blockAt(0, oracle, top3, offset);
  }
  forEachLine(from, to, oracle, top3, offset, f) {
    if (from <= offset + this.length && to >= offset)
      f(this.blockAt(0, oracle, 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 _HeightMapText extends HeightMapBlock {
  constructor(length, height4) {
    super(length, height4, null);
    this.collapsed = 0;
    this.widgetHeight = 0;
    this.breaks = 0;
  }
  blockAt(_height, _oracle, top3, offset) {
    return new BlockInfo(offset, this.length, top3, this.height, this.breaks);
  }
  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.breaks * oracle.lineHeight);
    this.outdated = false;
    return this;
  }
  toString() {
    return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`;
  }
};
var HeightMapGap = class _HeightMapGap extends HeightMap {
  constructor(length) {
    super(length, 0);
  }
  heightMetrics(oracle, offset) {
    let firstLine = oracle.doc.lineAt(offset).number, lastLine = oracle.doc.lineAt(offset + this.length).number;
    let lines = lastLine - firstLine + 1;
    let perLine, perChar = 0;
    if (oracle.lineWrapping) {
      let totalPerLine = Math.min(this.height, oracle.lineHeight * lines);
      perLine = totalPerLine / lines;
      if (this.length > lines + 1)
        perChar = (this.height - totalPerLine) / (this.length - lines - 1);
    } else {
      perLine = this.height / lines;
    }
    return { firstLine, lastLine, perLine, perChar };
  }
  blockAt(height4, oracle, top3, offset) {
    let { firstLine, lastLine, perLine, perChar } = this.heightMetrics(oracle, offset);
    if (oracle.lineWrapping) {
      let guess = offset + Math.round(Math.max(0, Math.min(1, (height4 - top3) / this.height)) * this.length);
      let line = oracle.doc.lineAt(guess), lineHeight = perLine + line.length * perChar;
      let lineTop = Math.max(top3, height4 - lineHeight / 2);
      return new BlockInfo(line.from, line.length, lineTop, lineHeight, 0);
    } else {
      let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height4 - top3) / perLine)));
      let { from, length } = oracle.doc.line(firstLine + line);
      return new BlockInfo(from, length, top3 + perLine * line, perLine, 0);
    }
  }
  lineAt(value, type, oracle, top3, offset) {
    if (type == QueryType.ByHeight)
      return this.blockAt(value, oracle, top3, offset);
    if (type == QueryType.ByPosNoHeight) {
      let { from, to } = oracle.doc.lineAt(value);
      return new BlockInfo(from, to - from, 0, 0, 0);
    }
    let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
    let line = oracle.doc.lineAt(value), lineHeight = perLine + line.length * perChar;
    let linesAbove = line.number - firstLine;
    let lineTop = top3 + perLine * linesAbove + perChar * (line.from - offset - linesAbove);
    return new BlockInfo(line.from, line.length, Math.max(top3, Math.min(lineTop, top3 + this.height - lineHeight)), lineHeight, 0);
  }
  forEachLine(from, to, oracle, top3, offset, f) {
    from = Math.max(from, offset);
    to = Math.min(to, offset + this.length);
    let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
    for (let pos = from, lineTop = top3; pos <= to; ) {
      let line = oracle.doc.lineAt(pos);
      if (pos == from) {
        let linesAbove = line.number - firstLine;
        lineTop += perLine * linesAbove + perChar * (from - offset - linesAbove);
      }
      let lineHeight = perLine + perChar * line.length;
      f(new BlockInfo(line.from, line.length, lineTop, lineHeight, 0));
      lineTop += 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;
      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);
      if (singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon || Math.abs(singleHeight - this.heightMetrics(oracle, offset).perLine) >= Epsilon)
        oracle.heightChanged = true;
      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, oracle, top3, offset) {
    let mid = top3 + this.left.height;
    return height4 < mid ? this.left.blockAt(height4, oracle, top3, offset) : this.right.blockAt(height4, oracle, mid, offset + this.left.length + this.break);
  }
  lineAt(value, type, oracle, 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, oracle, top3, offset) : this.right.lineAt(value, type, oracle, 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, oracle, rightTop, rightOffset));
    else
      return this.left.lineAt(rightOffset, subQuery, oracle, top3, offset).join(base2);
  }
  forEachLine(from, to, oracle, 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, oracle, top3, offset, f);
      if (to >= rightOffset)
        this.right.forEachLine(from, to, oracle, rightTop, rightOffset, f);
    } else {
      let mid = this.lineAt(rightOffset, QueryType.ByPos, oracle, top3, offset);
      if (from < mid.from)
        this.left.forEachLine(from, mid.from - 1, oracle, top3, offset, f);
      if (mid.to >= from && mid.from <= to)
        f(mid);
      if (to > mid.to)
        this.right.forEachLine(mid.to + 1, to, oracle, 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 _NodeBuilder {
  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;
      let breaks = deco.widget ? deco.widget.lineBreaks : 0;
      if (height4 < 0)
        height4 = this.oracle.lineHeight;
      let len = to - from;
      if (deco.block) {
        this.addBlock(new HeightMapBlock(len, height4, deco));
      } else if (len || breaks || height4 >= relevantWidgetHeight) {
        this.addLineDeco(height4, breaks, 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();
    let deco = block.deco;
    if (deco && deco.startSide > 0 && !this.isCovered)
      this.ensureLine();
    this.nodes.push(block);
    this.writtenTo = this.pos = this.pos + block.length;
    if (deco && deco.endSide > 0)
      this.covering = block;
  }
  addLineDeco(height4, breaks, length) {
    let line = this.ensureLine();
    line.length += length;
    line.collapsed += length;
    line.widgetHeight = Math.max(line.widgetHeight, height4);
    line.breaks += breaks;
    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;
  }
  // Always called with a region that on both sides either stretches
  // to a line break or the end of the document.
  // The returned array uses null to indicate line breaks, but never
  // starts or ends in a line break, or has multiple line breaks next
  // to each other.
  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 DecorationComparator2();
  RangeSet.compare(a, b, diff, comp, 0);
  return comp.changes;
}
var DecorationComparator2 = 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(viewState, wrapping) {
    return Decoration.replace({
      widget: new LineGapWidget(this.size * (wrapping ? viewState.scaleY : viewState.scaleX), 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.scrollTop = 0;
    this.scrolledToBottom = true;
    this.scaleX = 1;
    this.scaleY = 1;
    this.scrollAnchorPos = 0;
    this.scrollAnchorHeight = -1;
    this.scaler = IdScaler;
    this.scrollTarget = null;
    this.printing = false;
    this.mustMeasureContent = true;
    this.defaultTextDirection = Direction.LTR;
    this.visibleRanges = [];
    this.mustEnforceCursorAssoc = false;
    let guessWrapping = state.facet(contentAttributes).some((v) => typeof v != "function" && v.class == "cm-lineWrapping");
    this.heightOracle = new HeightOracle(guessWrapping);
    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(this, 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, this.heightMap, this.viewports);
  }
  updateViewportLines() {
    this.viewportLines = [];
    this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.heightOracle.setDoc(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;
    let scrollAnchor = this.scrolledToBottom ? null : this.scrollAnchorAt(this.scrollTop);
    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;
    if (scrollAnchor) {
      this.scrollAnchorPos = update2.changes.mapPos(scrollAnchor.from, -1);
      this.scrollAnchorHeight = scrollAnchor.top;
    } else {
      this.scrollAnchorPos = -1;
      this.scrollAnchorHeight = this.heightMap.height;
    }
    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 && !update2.state.facet(nativeSelectionHidden))
      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 domRect = dom.getBoundingClientRect();
    let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != domRect.height;
    this.contentDOMHeight = domRect.height;
    this.mustMeasureContent = false;
    let result = 0, bias = 0;
    if (domRect.width && domRect.height) {
      let { scaleX, scaleY } = getScale(dom, domRect);
      if (this.scaleX != scaleX || this.scaleY != scaleY) {
        this.scaleX = scaleX;
        this.scaleY = scaleY;
        result |= 8;
        refresh = measureContent = true;
      }
    }
    let paddingTop = (parseInt(style.paddingTop) || 0) * this.scaleY;
    let paddingBottom = (parseInt(style.paddingBottom) || 0) * this.scaleY;
    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 scrollTop = view.scrollDOM.scrollTop * this.scaleY;
    if (this.scrollTop != scrollTop) {
      this.scrollAnchorHeight = -1;
      this.scrollTop = scrollTop;
    }
    this.scrolledToBottom = isScrolledToBottom(view.scrollDOM);
    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 = domRect.width;
    if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) {
      this.contentDOMWidth = domRect.width;
      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, textHeight } = view.docView.measureTextSize();
        refresh = lineHeight > 0 && oracle.refresh(whiteSpace, lineHeight, charWidth, textHeight, 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 = (refresh ? HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle, [new ChangedRange(0, 0, 0, view.state.doc.length)]) : 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, oracle = this.heightOracle;
    let { visibleTop, visibleBottom } = this;
    let viewport = new Viewport(map2.lineAt(visibleTop - marginTop * 1e3, QueryType.ByHeight, oracle, 0, 0).from, map2.lineAt(visibleBottom + (1 - marginTop) * 1e3, QueryType.ByHeight, oracle, 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, oracle, 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, oracle, 0, 0).from, map2.lineAt(topPos + viewHeight + 1e3 / 2, QueryType.ByHeight, oracle, 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.heightOracle, 0, 0).from, this.heightMap.lineAt(to, QueryType.ByPos, this.heightOracle, 0, 0).to);
  }
  // Checks if a given viewport covers the visible part of the
  // document and not too much beyond that.
  viewportIsAppropriate({ from, to }, bias = 0) {
    if (!this.inView)
      return true;
    let { top: top3 } = this.heightMap.lineAt(from, QueryType.ByPos, this.heightOracle, 0, 0);
    let { bottom: bottom2 } = this.heightMap.lineAt(to, QueryType.ByPos, this.heightOracle, 0, 0);
    let { visibleTop, visibleBottom } = this;
    return (from == 0 || top3 <= visibleTop - Math.max(10, Math.min(
      -bias,
      250
      /* VP.MaxCoverMargin */
    ))) && (to == this.state.doc.length || bottom2 >= visibleBottom + Math.max(10, Math.min(
      bias,
      250
      /* VP.MaxCoverMargin */
    ))) && (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;
  }
  // Computes positions in the viewport where the start or end of a
  // line should be hidden, trying to reuse existing line gaps when
  // appropriate to avoid unneccesary redraws.
  // Uses crude character-counting for the positioning and sizing,
  // since actual DOM coordinates aren't always available and
  // predictable. Relies on generous margins (see LG.Margin) to hide
  // the artifacts this might produce from the user.
  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, 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.heightOracle, 0, 0), this.scaler);
  }
  lineBlockAtHeight(height4) {
    return scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height4), QueryType.ByHeight, this.heightOracle, 0, 0), this.scaler);
  }
  scrollAnchorAt(scrollTop) {
    let block = this.lineBlockAtHeight(scrollTop + 8);
    return block.from >= this.viewport.from || this.viewportLines[0].top - scrollTop > 200 ? block : this.viewportLines[0];
  }
  elementAtHeight(height4) {
    return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height4), this.heightOracle, 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 dist2 = Math.floor(total * ratio);
  for (let i = 0; ; i++) {
    let { from, to } = ranges[i], size = to - from;
    if (dist2 <= size)
      return from + dist2;
    dist2 -= 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(oracle, heightMap, viewports) {
    let vpHeight = 0, base2 = 0, domBase = 0;
    this.viewports = viewports.map(({ from, to }) => {
      let top3 = heightMap.lineAt(from, QueryType.ByPos, oracle, 0, 0).top;
      let bottom2 = heightMap.lineAt(to, QueryType.ByPos, oracle, 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._content) ? block._content.map((b) => scaleBlock(b, scaler)) : block._content);
}
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, {
  "&": {
    position: "relative !important",
    boxSizing: "border-box",
    "&.cm-focused": {
      // Provide a simple default outline to make sure a focused
      // editor is visually distinct. Can't leave the default behavior
      // because that will apply to the content element, which is
      // inside the scrollable container and doesn't include the
      // gutters. We also can't use an 'auto' outline, since those
      // are, for some reason, drawn behind the element content, which
      // will cause things like the active line background to cover
      // the outline (#297).
      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,
    display: "block",
    whiteSpace: "pre",
    wordWrap: "normal",
    // https://github.com/codemirror/dev/issues/456
    boxSizing: "border-box",
    minHeight: "100%",
    padding: "4px 0",
    outline: "none",
    "&[contenteditable=true]": {
      WebkitUserModify: "read-write-plaintext-only"
    }
  },
  ".cm-lineWrapping": {
    whiteSpace_fallback: "pre-wrap",
    // For IE
    whiteSpace: "break-spaces",
    wordBreak: "break-word",
    // For Safari, which doesn't support overflow-wrap: anywhere
    overflowWrap: "anywhere",
    flexShrink: 1
  },
  "&light .cm-content": { caretColor: "black" },
  "&dark .cm-content": { caretColor: "white" },
  ".cm-line": {
    display: "block",
    padding: "0 2px 0 6px"
  },
  ".cm-layer": {
    position: "absolute",
    left: 0,
    top: 0,
    contain: "size style",
    "& > *": {
      position: "absolute"
    }
  },
  "&light .cm-selectionBackground": {
    background: "#d9d9d9"
  },
  "&dark .cm-selectionBackground": {
    background: "#222"
  },
  "&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
    background: "#d7d4f0"
  },
  "&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
    background: "#233"
  },
  ".cm-cursorLayer": {
    pointerEvents: "none"
  },
  "&.cm-focused > .cm-scroller > .cm-cursorLayer": {
    animation: "steps(1) cm-blink 1.2s infinite"
  },
  // Two animations defined so that we can switch between them to
  // restart the animation without forcing another style
  // recomputation.
  "@keyframes cm-blink": { "0%": {}, "50%": { opacity: 0 }, "100%": {} },
  "@keyframes cm-blink2": { "0%": {}, "50%": { opacity: 0 }, "100%": {} },
  ".cm-cursor, .cm-dropCursor": {
    borderLeft: "1.2px solid black",
    marginLeft: "-0.6px",
    pointerEvents: "none"
  },
  ".cm-cursor": {
    display: "none"
  },
  "&dark .cm-cursor": {
    borderLeftColor: "#444"
  },
  ".cm-dropCursor": {
    position: "absolute"
  },
  "&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor": {
    display: "block"
  },
  ".cm-iso": {
    unicodeBidi: "isolate"
  },
  ".cm-announced": {
    position: "fixed",
    top: "-10000px"
  },
  "@media print": {
    ".cm-announced": { display: "none" }
  },
  "&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",
    insetInlineStart: 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",
    // Necessary -- prevents margin collapsing
    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-highlightSpace:before": {
    content: "attr(data-display)",
    position: "absolute",
    pointerEvents: "none",
    color: "#888"
  },
  ".cm-highlightTab": {
    backgroundImage: `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="20"><path stroke="%23888" stroke-width="1" fill="none" d="M1 10H196L190 5M190 15L196 10M197 4L197 16"/></svg>')`,
    backgroundSize: "auto 100%",
    backgroundPosition: "right 90%",
    backgroundRepeat: "no-repeat"
  },
  ".cm-trailingSpace": {
    backgroundColor: "#ff332255"
  },
  ".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 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(start2, end) {
    if (!start2)
      return this;
    let parent2 = start2.parentNode;
    for (let cur2 = start2; ; ) {
      this.findPointBefore(parent2, cur2);
      let oldLen = this.text.length;
      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.text.length > oldLen)
        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, length) {
    for (let point2 of this.points)
      if (node.nodeType == 3 ? point2.node == node : node.contains(point2.node))
        point2.pos = this.text.length + (isAtEnd(node, point2.node, point2.offset) ? length : 0);
  }
};
function isAtEnd(parent2, node, offset) {
  for (; ; ) {
    if (!node || offset < maxOffset(node))
      return false;
    if (node == parent2)
      return true;
    offset = domIndex(node) + 1;
    node = node.parentNode;
  }
}
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 DOMChange = class {
  constructor(view, start2, end, typeOver) {
    this.typeOver = typeOver;
    this.bounds = null;
    this.text = "";
    let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView;
    if (view.state.readOnly && start2 > -1) {
      this.newSel = null;
    } else if (start2 > -1 && (this.bounds = view.docView.domBoundsAround(start2, 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);
      let vp = view.viewport;
      if ((browser.ios || browser.chrome) && view.state.selection.main.empty && head != anchor && (vp.from > 0 || vp.to < view.state.doc.length)) {
        let from = Math.min(head, anchor), to = Math.max(head, anchor);
        let offFrom = vp.from - from, offTo = vp.to - to;
        if ((offFrom == 0 || offFrom == 1 || from == 0) && (offTo == 0 || offTo == -1 || to == view.state.doc.length)) {
          head = 0;
          anchor = view.state.doc.length;
        }
      }
      this.newSel = EditorSelection.single(anchor, head);
    }
  }
};
function applyDOMChange(view, domChange) {
  let change;
  let { newSel } = domChange, sel = view.state.selection.main;
  let lastKey = view.inputState.lastKeyTime > Date.now() - 100 ? view.inputState.lastKeyCode : -1;
  if (domChange.bounds) {
    let { from, to } = domChange.bounds;
    let preferredPos = sel.from, preferredSide = null;
    if (lastKey === 8 || 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 && lastKey == 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()) && view.contentDOM.getAttribute("autocorrect") == "off") {
    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) {
    if (browser.ios && view.inputState.flushIOSKey())
      return true;
    if (browser.android && (change.to == sel.to && // GBoard will sometimes remove a space it just inserted
    // after a completion when you press enter
    (change.from == sel.from || change.from == sel.from - 1 && view.state.sliceDoc(change.from, sel.from) == " ") && 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 || lastKey == 8 && change.insert.length < change.to - change.from && change.to > sel.head) && 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.inputState.composing >= 0)
      view.inputState.composing++;
    let defaultTr;
    let defaultInsert = () => defaultTr || (defaultTr = applyDefaultInsert(view, change, newSel));
    if (!view.state.facet(inputHandler).some((h) => h(view, change.from, change.to, text2, defaultInsert)))
      view.dispatch(defaultInsert());
    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 applyDefaultInsert(view, change, newSel) {
  let tr, startState = view.state, sel = startState.selection.main;
  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 && 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, composition = newSel && findCompositionNode(view, newSel.main.head);
      if (composition) {
        let dLen = change.insert.length - (change.to - change.from);
        compositionRange = { from: composition.from, to: composition.to - dLen };
      } else {
        compositionRange = 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 || // Unfortunately, there's no way to make multiple
        // changes in the same node work without aborting
        // composition, so cursors in the composition range are
        // ignored.
        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 || view.inputState.compositionPendingChange && view.inputState.compositionEndedAt > Date.now() - 50) {
    view.inputState.compositionPendingChange = false;
    userEvent += ".compose";
    if (view.inputState.compositionFirstChange) {
      userEvent += ".start";
      view.inputState.compositionFirstChange = false;
    }
  }
  return startState.update(tr, { userEvent, scrollIntoView: true });
}
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.resizeScroll = 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.resizeScroll = new ResizeObserver(() => {
        var _a2;
        if (((_a2 = this.view.docView) === null || _a2 === void 0 ? void 0 : _a2.lastUpdate) < Date.now() - 75)
          this.onResize();
      });
      this.resizeScroll.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"));
        }
      }, { threshold: [0, 1e-3] });
      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.runHandlers("scroll", 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 context2 = sel.anchorNode && view.docView.nearest(sel.anchorNode);
    if (context2 && context2.ignoreEvent(event)) {
      if (!wasChanged)
        this.selectionChanged = false;
      return;
    }
    if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty && // (Selection.isCollapsed isn't reliable on IE)
    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);
  }
  // Throw away any pending changes
  clear() {
    this.processRecords();
    this.queue.length = 0;
    this.selectionChanged = false;
  }
  // Chrome Android, especially in combination with GBoard, not only
  // doesn't reliably fire regular key events, but also often
  // surrounds the effect of enter or backspace with a bunch of
  // composition events that, when interrupted, cause text duplication
  // or other kinds of corruption. This hack makes the editor back off
  // from handling DOM changes for a moment when such a key is
  // detected (via beforeinput or keydown), and then tries to flush
  // them or, if that has no effect, dispatches the given key.
  delayAndroidKey(key2, keyCode) {
    var _a2;
    if (!this.delayedAndroidKey) {
      let flush2 = () => {
        let key3 = this.delayedAndroidKey;
        if (key3) {
          this.clearDelayedAndroidKey();
          this.view.inputState.lastKeyCode = key3.keyCode;
          this.view.inputState.lastKeyTime = Date.now();
          let flushed = this.flush();
          if (!flushed && key3.force)
            dispatchKey(this.dom, key3.key, key3.keyCode);
        }
      };
      this.flushingAndroidKey = this.view.win.requestAnimationFrame(flush2);
    }
    if (!this.delayedAndroidKey || key2 == "Enter")
      this.delayedAndroidKey = {
        key: key2,
        keyCode,
        // Only run the key handler when no changes are detected if
        // this isn't coming right after another change, in which case
        // it is probably part of a weird chain of updates, and should
        // be ignored if it returns the DOM to its previous state.
        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();
  }
  pendingRecords() {
    for (let mut of this.observer.takeRecords())
      this.queue.push(mut);
    return this.queue;
  }
  processRecords() {
    let records = this.pendingRecords();
    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;
    let change = new DOMChange(this.view, from, to, typeOver);
    this.view.docView.domChanged = { newSel: change.newSel ? change.newSel.main : null };
    return change;
  }
  // Apply pending changes, if any
  flush(readSelection = true) {
    if (this.delayedFlush >= 0 || this.delayedAndroidKey)
      return false;
    if (readSelection)
      this.readSelectionRange();
    let domChange = this.readChange();
    if (!domChange) {
      this.view.requestMeasure();
      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.flags |= 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.resizeScroll) === 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 _EditorView {
  /**
  The current editor state.
  */
  get state() {
    return this.viewState.state;
  }
  /**
  To be able to display large documents without consuming too much
  memory or overloading the browser, CodeMirror only draws the
  code that is visible (plus a margin around it) to the DOM. This
  property tells you the extent of the current drawn viewport, in
  document positions.
  */
  get viewport() {
    return this.viewState.viewport;
  }
  /**
  When there are, for example, large collapsed ranges in the
  viewport, its size can be a lot bigger than the actual visible
  content. Thus, if you are doing something like styling the
  content in the viewport, it is preferable to only do so for
  these ranges, which are the subset of the viewport that is
  actually drawn.
  */
  get visibleRanges() {
    return this.viewState.visibleRanges;
  }
  /**
  Returns false when the editor is entirely scrolled out of view
  or otherwise hidden.
  */
  get inView() {
    return this.viewState.inView;
  }
  /**
  Indicates whether the user is currently composing text via
  [IME](https://en.wikipedia.org/wiki/Input_method), and at least
  one change has been made in the current composition.
  */
  get composing() {
    return this.inputState.composing > 0;
  }
  /**
  Indicates whether the user is currently in composing state. Note
  that on some platforms, like Android, this will be the case a
  lot, since just putting the cursor on a word starts a
  composition there.
  */
  get compositionStarted() {
    return this.inputState.composing >= 0;
  }
  /**
  The document or shadow root that the view lives in.
  */
  get root() {
    return this._root;
  }
  /**
  @internal
  */
  get win() {
    return this.dom.ownerDocument.defaultView || window;
  }
  /**
  Construct a new view. You'll want to either provide a `parent`
  option, or put `view.dom` into your document after creating a
  view, so that the user can see the editor.
  */
  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.className = "cm-announced";
    this.announceDOM.setAttribute("aria-live", "polite");
    this.dom = document.createElement("div");
    this.dom.appendChild(this.announceDOM);
    this.dom.appendChild(this.scrollDOM);
    if (config2.parent)
      config2.parent.appendChild(this.dom);
    let { dispatch } = config2;
    this.dispatchTransactions = config2.dispatchTransactions || dispatch && ((trs) => trs.forEach((tr) => dispatch(tr, this))) || ((trs) => this.update(trs));
    this.dispatch = this.dispatch.bind(this);
    this._root = config2.root || getRoot(config2.parent) || document;
    this.viewState = new ViewState(config2.state || EditorState.create(config2));
    if (config2.scrollTo && config2.scrollTo.is(scrollIntoView))
      this.viewState.scrollTarget = config2.scrollTo.value.clip(this.viewState.state);
    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.plugins);
    this.docView = new DocView(this);
    this.mountStyles();
    this.updateAttrs();
    this.updateState = 0;
    this.requestMeasure();
  }
  dispatch(...input) {
    let trs = input.length == 1 && input[0] instanceof Transaction2 ? input : input.length == 1 && Array.isArray(input[0]) ? input[0] : [this.state.update(...input)];
    this.dispatchTransactions(trs, this);
  }
  /**
  Update the view for the given array of transactions. This will
  update the visible document and selection to match the state
  produced by the transactions, and notify view plugins of the
  change. You should usually call
  [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this
  as a primitive.
  */
  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 focus = this.hasFocus, focusFlag = 0, dispatchFocus = null;
    if (transactions.some((tr) => tr.annotation(isFocusChange))) {
      this.inputState.notifiedFocused = focus;
      focusFlag = 1;
    } else if (focus != this.inputState.notifiedFocused) {
      this.inputState.notifiedFocused = focus;
      dispatchFocus = focusChangeTransaction(state, focus);
      if (!dispatchFocus)
        focusFlag = 1;
    }
    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);
    update2.flags |= focusFlag;
    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.clip(this.state);
      }
      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 (redrawn)
      this.docViewUpdate();
    if (!update2.empty)
      for (let listener of this.state.facet(updateListener)) {
        try {
          listener(update2);
        } catch (e3) {
          logException(this.state, e3, "update listener");
        }
      }
    if (dispatchFocus || domChange)
      Promise.resolve().then(() => {
        if (dispatchFocus && this.state == dispatchFocus.startState)
          this.dispatch(dispatchFocus);
        if (domChange) {
          if (!applyDOMChange(this, domChange) && pendingKey.force)
            dispatchKey(this.contentDOM, pendingKey.key, pendingKey.keyCode);
        }
      });
  }
  /**
  Reset the view to the given state. (This will cause the entire
  document to be redrawn and all view plugins to be reinitialized,
  so you should probably only use it when the new state isn't
  derived from the old state. Otherwise, use
  [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.)
  */
  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.destroy();
      this.docView = new DocView(this);
      this.inputState.ensureHandlers(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();
    } else {
      for (let p of this.plugins)
        p.mustUpdate = update2;
    }
    for (let i = 0; i < this.plugins.length; i++)
      this.plugins[i].update(this);
    if (prevSpecs != specs)
      this.inputState.ensureHandlers(this.plugins);
  }
  docViewUpdate() {
    for (let plugin of this.plugins) {
      let val = plugin.value;
      if (val && val.docViewUpdate) {
        try {
          val.docViewUpdate(this);
        } catch (e3) {
          logException(this.state, e3, "doc view update listener");
        }
      }
    }
  }
  /**
  @internal
  */
  measure(flush2 = true) {
    if (this.destroyed)
      return;
    if (this.measureScheduled > -1)
      this.win.cancelAnimationFrame(this.measureScheduled);
    if (this.observer.delayedAndroidKey) {
      this.measureScheduled = -1;
      this.requestMeasure();
      return;
    }
    this.measureScheduled = 0;
    if (flush2)
      this.observer.forceFlush();
    let updated = null;
    let sDOM = this.scrollDOM, scrollTop = sDOM.scrollTop * this.scaleY;
    let { scrollAnchorPos, scrollAnchorHeight } = this.viewState;
    if (Math.abs(scrollTop - this.viewState.scrollTop) > 1)
      scrollAnchorHeight = -1;
    this.viewState.scrollAnchorHeight = -1;
    try {
      for (let i = 0; ; i++) {
        if (scrollAnchorHeight < 0) {
          if (isScrolledToBottom(sDOM)) {
            scrollAnchorPos = -1;
            scrollAnchorHeight = this.viewState.heightMap.height;
          } else {
            let block = this.viewState.scrollAnchorAt(scrollTop);
            scrollAnchorPos = block.from;
            scrollAnchorHeight = block.top;
          }
        }
        this.updateState = 1;
        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;
        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);
          if (redrawn)
            this.docViewUpdate();
        }
        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 (redrawn)
          this.docView.updateSelection(true);
        if (!update2.viewportChanged && this.measureRequests.length == 0) {
          if (this.viewState.editorHeight) {
            if (this.viewState.scrollTarget) {
              this.docView.scrollIntoView(this.viewState.scrollTarget);
              this.viewState.scrollTarget = null;
              scrollAnchorHeight = -1;
              continue;
            } else {
              let newAnchorHeight = scrollAnchorPos < 0 ? this.viewState.heightMap.height : this.viewState.lineBlockAt(scrollAnchorPos).top;
              let diff = newAnchorHeight - scrollAnchorHeight;
              if (diff > 1 || diff < -1) {
                scrollTop = scrollTop + diff;
                sDOM.scrollTop = scrollTop / this.scaleY;
                scrollAnchorHeight = -1;
                continue;
              }
            }
          }
          break;
        }
      }
    } finally {
      this.updateState = 0;
      this.measureScheduled = -1;
    }
    if (updated && !updated.empty)
      for (let listener of this.state.facet(updateListener))
        listener(updated);
  }
  /**
  Get the CSS classes for the currently active editor themes.
  */
  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);
    let nonce = this.state.facet(_EditorView.cspNonce);
    StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1).reverse(), nonce ? { nonce } : void 0);
  }
  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);
  }
  /**
  Schedule a layout measurement, optionally providing callbacks to
  do custom DOM measuring followed by a DOM write phase. Using
  this is preferable reading DOM layout directly from, for
  example, an event handler, because it'll make sure measuring and
  drawing done by other components is synchronized, avoiding
  unnecessary DOM layout computations.
  */
  requestMeasure(request) {
    if (this.measureScheduled < 0)
      this.measureScheduled = this.win.requestAnimationFrame(() => this.measure());
    if (request) {
      if (this.measureRequests.indexOf(request) > -1)
        return;
      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);
    }
  }
  /**
  Get the value of a specific plugin, if present. Note that
  plugins that crash can be dropped from a view, so even when you
  know you registered a given plugin, it is recommended to check
  the return value of this method.
  */
  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;
  }
  /**
  The top position of the document, in screen coordinates. This
  may be negative when the editor is scrolled down. Points
  directly to the top of the first line, not above the padding.
  */
  get documentTop() {
    return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop;
  }
  /**
  Reports the padding above and below the document.
  */
  get documentPadding() {
    return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom };
  }
  /**
  If the editor is transformed with CSS, this provides the scale
  along the X axis. Otherwise, it will just be 1. Note that
  transforms other than translation and scaling are not supported.
  */
  get scaleX() {
    return this.viewState.scaleX;
  }
  /**
  Provide the CSS transformed scale along the Y axis.
  */
  get scaleY() {
    return this.viewState.scaleY;
  }
  /**
  Find the text line or block widget at the given vertical
  position (which is interpreted as relative to the [top of the
  document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop)).
  */
  elementAtHeight(height4) {
    this.readMeasured();
    return this.viewState.elementAtHeight(height4);
  }
  /**
  Find the line block (see
  [`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) at the given
  height, again interpreted relative to the [top of the
  document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop).
  */
  lineBlockAtHeight(height4) {
    this.readMeasured();
    return this.viewState.lineBlockAtHeight(height4);
  }
  /**
  Get the extent and vertical position of all [line
  blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions
  are relative to the [top of the
  document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop);
  */
  get viewportLineBlocks() {
    return this.viewState.viewportLines;
  }
  /**
  Find the line block around the given document position. A line
  block is a range delimited on both sides by either a
  non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^replace) line breaks, or the
  start/end of the document. It will usually just hold a line of
  text, but may be broken into multiple textblocks by block
  widgets.
  */
  lineBlockAt(pos) {
    return this.viewState.lineBlockAt(pos);
  }
  /**
  The editor's total content height.
  */
  get contentHeight() {
    return this.viewState.contentHeight;
  }
  /**
  Move a cursor position by [grapheme
  cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak). `forward` determines whether
  the motion is away from the line start, or towards it. In
  bidirectional text, the line is traversed in visual order, using
  the editor's [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).
  When the start position was the last one on the line, the
  returned position will be across the line break. If there is no
  further line, the original position is returned.
  
  By default, this method moves over a single cluster. The
  optional `by` argument can be used to move across more. It will
  be called with the first cluster as argument, and should return
  a predicate that determines, for each subsequent cluster,
  whether it should also be moved over.
  */
  moveByChar(start2, forward, by) {
    return skipAtoms(this, start2, moveByChar(this, start2, forward, by));
  }
  /**
  Move a cursor position across the next group of either
  [letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter
  non-whitespace characters.
  */
  moveByGroup(start2, forward) {
    return skipAtoms(this, start2, moveByChar(this, start2, forward, (initial) => byGroup(this, start2.head, initial)));
  }
  /**
  Get the cursor position visually at the start or end of a line.
  Note that this may differ from the _logical_ position at its
  start or end (which is simply at `line.from`/`line.to`) if text
  at the start or end goes against the line's base text direction.
  */
  visualLineSide(line, end) {
    let order = this.bidiSpans(line), dir = this.textDirectionAt(line.from);
    let span = order[end ? order.length - 1 : 0];
    return EditorSelection.cursor(span.side(end, dir) + line.from, span.forward(!end, dir) ? 1 : -1);
  }
  /**
  Move to the next line boundary in the given direction. If
  `includeWrap` is true, line wrapping is on, and there is a
  further wrap point on the current line, the wrap point will be
  returned. Otherwise this function will return the start or end
  of the line.
  */
  moveToLineBoundary(start2, forward, includeWrap = true) {
    return moveToLineBoundary(this, start2, forward, includeWrap);
  }
  /**
  Move a cursor position vertically. When `distance` isn't given,
  it defaults to moving to the next line (including wrapped
  lines). Otherwise, `distance` should provide a positive distance
  in pixels.
  
  When `start` has a
  [`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical
  motion will use that as a target horizontal position. Otherwise,
  the cursor's own horizontal position is used. The returned
  cursor will have its goal column set to whichever column was
  used.
  */
  moveVertically(start2, forward, distance) {
    return skipAtoms(this, start2, moveVertically(this, start2, forward, distance));
  }
  /**
  Find the DOM parent node and offset (child offset if `node` is
  an element, character offset when it is a text node) at the
  given document position.
  
  Note that for positions that aren't currently in
  `visibleRanges`, the resulting DOM position isn't necessarily
  meaningful (it may just point before or after a placeholder
  element).
  */
  domAtPos(pos) {
    return this.docView.domAtPos(pos);
  }
  /**
  Find the document position at the given DOM node. Can be useful
  for associating positions with DOM events. Will raise an error
  when `node` isn't part of the editor content.
  */
  posAtDOM(node, offset = 0) {
    return this.docView.posFromDOM(node, offset);
  }
  posAtCoords(coords, precise = true) {
    this.readMeasured();
    return posAtCoords(this, coords, precise);
  }
  /**
  Get the screen coordinates at the given document position.
  `side` determines whether the coordinates are based on the
  element before (-1) or after (1) the position (if no element is
  available on the given side, the method will transparently use
  another strategy to get reasonable coordinates).
  */
  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);
  }
  /**
  Return the rectangle around a given character. If `pos` does not
  point in front of a character that is in the viewport and
  rendered (i.e. not replaced, not a line break), this will return
  null. For space characters that are a line wrap point, this will
  return the position before the line break.
  */
  coordsForChar(pos) {
    this.readMeasured();
    return this.docView.coordsForChar(pos);
  }
  /**
  The default width of a character in the editor. May not
  accurately reflect the width of all characters (given variable
  width fonts or styling of invididual ranges).
  */
  get defaultCharacterWidth() {
    return this.viewState.heightOracle.charWidth;
  }
  /**
  The default height of a line in the editor. May not be accurate
  for all lines.
  */
  get defaultLineHeight() {
    return this.viewState.heightOracle.lineHeight;
  }
  /**
  The text direction
  ([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction)
  CSS property) of the editor's content element.
  */
  get textDirection() {
    return this.viewState.defaultTextDirection;
  }
  /**
  Find the text direction of the block at the given position, as
  assigned by CSS. If
  [`perLineTextDirection`](https://codemirror.net/6/docs/ref/#view.EditorView^perLineTextDirection)
  isn't enabled, or the given position is outside of the viewport,
  this will always return the same as
  [`textDirection`](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). Note that
  this may trigger a DOM layout.
  */
  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);
  }
  /**
  Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping)
  (as determined by the
  [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space)
  CSS property of its content element).
  */
  get lineWrapping() {
    return this.viewState.heightOracle.lineWrapping;
  }
  /**
  Returns the bidirectional text structure of the given line
  (which should be in the current document) as an array of span
  objects. The order of these spans matches the [text
  direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is
  left-to-right, the leftmost spans come first, otherwise the
  rightmost spans come first.
  */
  bidiSpans(line) {
    if (line.length > MaxBidiLine)
      return trivialOrder(line.length);
    let dir = this.textDirectionAt(line.from), isolates;
    for (let entry of this.bidiCache) {
      if (entry.from == line.from && entry.dir == dir && (entry.fresh || isolatesEq(entry.isolates, isolates = getIsolatedRanges(this, line))))
        return entry.order;
    }
    if (!isolates)
      isolates = getIsolatedRanges(this, line);
    let order = computeOrder(line.text, dir, isolates);
    this.bidiCache.push(new CachedOrder(line.from, line.to, dir, isolates, true, order));
    return order;
  }
  /**
  Check whether the editor has focus.
  */
  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;
  }
  /**
  Put focus on the editor.
  */
  focus() {
    this.observer.ignore(() => {
      focusPreventScroll(this.contentDOM);
      this.docView.updateSelection();
    });
  }
  /**
  Update the [root](https://codemirror.net/6/docs/ref/##view.EditorViewConfig.root) in which the editor lives. This is only
  necessary when moving the editor's existing DOM to a new window or shadow root.
  */
  setRoot(root2) {
    if (this._root != root2) {
      this._root = root2;
      this.observer.setWindow((root2.nodeType == 9 ? root2 : root2.ownerDocument).defaultView || window);
      this.mountStyles();
    }
  }
  /**
  Clean up this editor view, removing its element from the
  document, unregistering event handlers, and notifying
  plugins. The view instance can no longer be used after
  calling this.
  */
  destroy() {
    for (let plugin of this.plugins)
      plugin.destroy(this);
    this.plugins = [];
    this.inputState.destroy();
    this.docView.destroy();
    this.dom.remove();
    this.observer.destroy();
    if (this.measureScheduled > -1)
      this.win.cancelAnimationFrame(this.measureScheduled);
    this.destroyed = true;
  }
  /**
  Returns an effect that can be
  [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to
  cause it to scroll the given position or range into view.
  */
  static scrollIntoView(pos, options3 = {}) {
    return scrollIntoView.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options3.y, options3.x, options3.yMargin, options3.xMargin));
  }
  /**
  Return an effect that resets the editor to its current (at the
  time this method was called) scroll position. Note that this
  only affects the editor's own scrollable element, not parents.
  See also
  [`EditorViewConfig.scrollTo`](https://codemirror.net/6/docs/ref/#view.EditorViewConfig.scrollTo).
  
  The effect should be used with a document identical to the one
  it was created for. Failing to do so is not an error, but may
  not scroll to the expected position. You can
  [map](https://codemirror.net/6/docs/ref/#state.StateEffect.map) the effect to account for changes.
  */
  scrollSnapshot() {
    let { scrollTop, scrollLeft } = this.scrollDOM;
    let ref = this.viewState.scrollAnchorAt(scrollTop);
    return scrollIntoView.of(new ScrollTarget(EditorSelection.cursor(ref.from), "start", "start", ref.top - scrollTop, scrollLeft, true));
  }
  /**
  Returns an extension that can be used to add DOM event handlers.
  The value should be an object mapping event names to handler
  functions. For any given event, such functions are ordered by
  extension precedence, and the first handler to return true will
  be assumed to have handled that event, and no other handlers or
  built-in behavior will be activated for it. These are registered
  on the [content element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except
  for `scroll` handlers, which will be called any time the
  editor's [scroll element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of
  its parent nodes is scrolled.
  */
  static domEventHandlers(handlers2) {
    return ViewPlugin.define(() => ({}), { eventHandlers: handlers2 });
  }
  /**
  Create an extension that registers DOM event observers. Contrary
  to event [handlers](https://codemirror.net/6/docs/ref/#view.EditorView^domEventHandlers),
  observers can't be prevented from running by a higher-precedence
  handler returning true. They also don't prevent other handlers
  and observers from running when they return true, and should not
  call `preventDefault`.
  */
  static domEventObservers(observers2) {
    return ViewPlugin.define(() => ({}), { eventObservers: observers2 });
  }
  /**
  Create a theme extension. The first argument can be a
  [`style-mod`](https://github.com/marijnh/style-mod#documentation)
  style spec providing the styles for the theme. These will be
  prefixed with a generated class for the style.
  
  Because the selectors will be prefixed with a scope class, rule
  that directly match the editor's [wrapper
  element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be
  added—need to be explicitly differentiated by adding an `&` to
  the selector for that element—for example
  `&.cm-focused`.
  
  When `dark` is set to true, the theme will be marked as dark,
  which will cause the `&dark` rules from [base
  themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to
  `&light` when a light theme is active).
  */
  static theme(spec, options3) {
    let prefix = StyleModule.newName();
    let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))];
    if (options3 && options3.dark)
      result.push(darkTheme.of(true));
    return result;
  }
  /**
  Create an extension that adds styles to the base theme. Like
  with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the
  place of the editor wrapper element when directly targeting
  that. You can also use `&dark` or `&light` instead to only
  target editors with a dark or light theme.
  */
  static baseTheme(spec) {
    return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs)));
  }
  /**
  Retrieve an editor view instance from the view's DOM
  representation.
  */
  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.focusChangeEffect = focusChangeEffect;
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.outerDecorations = outerDecorations;
EditorView.atomicRanges = atomicRanges;
EditorView.bidiIsolatedRanges = bidiIsolatedRanges;
EditorView.scrollMargins = scrollMargins;
EditorView.darkTheme = darkTheme;
EditorView.cspNonce = /* @__PURE__ */ Facet.define({ combine: (values) => values.length ? values[0] : "" });
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 _CachedOrder {
  constructor(from, to, dir, isolates, fresh, order) {
    this.from = from;
    this.to = to;
    this.dir = dir;
    this.isolates = isolates;
    this.fresh = fresh;
    this.order = order;
  }
  static update(cache, changes) {
    if (changes.empty && !cache.some((c) => c.fresh))
      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.isolates, false, entry.order));
    }
    return result;
  }
};
function attrsFromFacet(view, facet, base2) {
  for (let sources = view.state.facet(facet), i = sources.length - 1; i >= 0; i--) {
    let source2 = sources[i], value = typeof source2 == "function" ? source2(view) : source2;
    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, meta2;
  for (let i = 0; i < parts.length - 1; ++i) {
    const mod = parts[i];
    if (/^(cmd|meta|m)$/i.test(mod))
      meta2 = 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")
        meta2 = true;
      else
        ctrl = true;
    } else
      throw new Error("Unrecognized modifier name: " + mod);
  }
  if (alt)
    result = "Alt-" + result;
  if (ctrl)
    result = "Ctrl-" + result;
  if (meta2)
    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, key2, command2, preventDefault, stopPropagation) => {
    var _a2, _b;
    let scopeObj = bound[scope] || (bound[scope] = /* @__PURE__ */ Object.create(null));
    let parts = key2.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,
          stopPropagation: false,
          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,
      stopPropagation: 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;
    if (stopPropagation)
      binding.stopPropagation = 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, stopPropagation: false, run: [] };
        for (let key2 in scopeObj)
          scopeObj[key2].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, b.stopPropagation);
      if (b.shift)
        add3(scope, "Shift-" + name2, b.shift, b.preventDefault, b.stopPropagation);
    }
  }
  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 = "", handled = false, prevented = false, stopPropagation = false;
  if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) {
    prefix = storedPrefix.prefix + " ";
    if (modifierCodes.indexOf(event.keyCode) < 0) {
      prevented = true;
      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)) {
            if (binding.stopPropagation)
              stopPropagation = true;
            return true;
          }
        }
      if (binding.preventDefault) {
        if (binding.stopPropagation)
          stopPropagation = true;
        prevented = true;
      }
    }
    return false;
  };
  let scopeObj = map2[scope], baseName, shiftName;
  if (scopeObj) {
    if (runFor(scopeObj[prefix + modifiers(name2, event, !isChar)])) {
      handled = true;
    } else if (isChar && (event.altKey || event.metaKey || event.ctrlKey) && // Ctrl-Alt may be used for AltGr on Windows
    !(browser.windows && event.ctrlKey && event.altKey) && (baseName = base[event.keyCode]) && baseName != name2) {
      if (runFor(scopeObj[prefix + modifiers(baseName, event, true)])) {
        handled = true;
      } else if (event.shiftKey && (shiftName = shift[event.keyCode]) != name2 && shiftName != baseName && runFor(scopeObj[prefix + modifiers(shiftName, event, false)])) {
        handled = true;
      }
    } else if (isChar && event.shiftKey && runFor(scopeObj[prefix + modifiers(name2, event, true)])) {
      handled = true;
    }
    if (!handled && runFor(scopeObj._any))
      handled = true;
  }
  if (prevented)
    handled = true;
  if (handled && stopPropagation)
    event.stopPropagation();
  return handled;
}
var RectangleMarker = class _RectangleMarker {
  /**
  Create a marker with the given class and dimensions. If `width`
  is null, the DOM element will get no width style.
  */
  constructor(className, left2, top3, width, height4) {
    this.className = className;
    this.left = left2;
    this.top = top3;
    this.width = width;
    this.height = height4;
  }
  draw() {
    let elt = document.createElement("div");
    elt.className = this.className;
    this.adjust(elt);
    return elt;
  }
  update(elt, prev) {
    if (prev.className != this.className)
      return false;
    this.adjust(elt);
    return true;
  }
  adjust(elt) {
    elt.style.left = this.left + "px";
    elt.style.top = this.top + "px";
    if (this.width != null)
      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;
  }
  /**
  Create a set of rectangles for the given selection range,
  assigning them theclass`className`. Will create a single
  rectangle for empty ranges, and a set of selection-style
  rectangles covering the range's content (in a bidi-aware
  way) for non-empty ones.
  */
  static forRange(view, className, range2) {
    if (range2.empty) {
      let pos = view.coordsAtPos(range2.head, range2.assoc || 1);
      if (!pos)
        return [];
      let base2 = getBase(view);
      return [new _RectangleMarker(className, pos.left - base2.left, pos.top - base2.top, null, pos.bottom - pos.top)];
    } else {
      return rectanglesForRange(view, className, range2);
    }
  }
};
function getBase(view) {
  let rect = view.scrollDOM.getBoundingClientRect();
  let left2 = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth * view.scaleX;
  return { left: left2 - view.scrollDOM.scrollLeft * view.scaleX, top: rect.top - view.scrollDOM.scrollTop * view.scaleY };
}
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 rectanglesForRange(view, className, 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 lineElt = content2.querySelector(".cm-line"), lineStyle = lineElt && window.getComputedStyle(lineElt);
  let leftSide = contentRect.left + (lineStyle ? parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)) : 0);
  let rightSide = contentRect.right - (lineStyle ? parseInt(lineStyle.paddingRight) : 0);
  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 (visualStart && (view.lineWrapping || startBlock.widgetLineBreaks))
    visualStart = wrappedLine(view, from, visualStart);
  if (visualEnd && (view.lineWrapping || endBlock.widgetLineBreaks))
    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 - (visualStart && visualEnd ? 1 : 0) || startBlock.widgetLineBreaks > 1 && top3.bottom + view.defaultLineHeight / 2 < bottom2.top)
      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 RectangleMarker(
      className,
      left2 - base2.left,
      top3 - base2.top - 0.01,
      right2 - left2,
      bottom2 - top3 + 0.01
      /* C.Epsilon */
    );
  }
  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);
      if (!fromCoords || !toCoords)
        return;
      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 start2 = 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 > start2 && r.from < end) {
        for (let pos = Math.max(r.from, start2), 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 <= start2, Math.min(spanTo, endPos), to2 == null && spanTo >= end, span.dir);
          }
          pos = docLine.to + 1;
          if (pos >= endPos)
            break;
        }
      }
    if (horizontal.length == 0)
      addSpan(start2, 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 sameMarker(a, b) {
  return a.constructor == b.constructor && a.eq(b);
}
var LayerView = class {
  constructor(view, layer2) {
    this.view = view;
    this.layer = layer2;
    this.drawn = [];
    this.scaleX = 1;
    this.scaleY = 1;
    this.measureReq = { read: this.measure.bind(this), write: this.draw.bind(this) };
    this.dom = view.scrollDOM.appendChild(document.createElement("div"));
    this.dom.classList.add("cm-layer");
    if (layer2.above)
      this.dom.classList.add("cm-layer-above");
    if (layer2.class)
      this.dom.classList.add(layer2.class);
    this.scale();
    this.dom.setAttribute("aria-hidden", "true");
    this.setOrder(view.state);
    view.requestMeasure(this.measureReq);
    if (layer2.mount)
      layer2.mount(this.dom, view);
  }
  update(update2) {
    if (update2.startState.facet(layerOrder) != update2.state.facet(layerOrder))
      this.setOrder(update2.state);
    if (this.layer.update(update2, this.dom) || update2.geometryChanged) {
      this.scale();
      update2.view.requestMeasure(this.measureReq);
    }
  }
  docViewUpdate(view) {
    if (this.layer.updateOnDocViewUpdate !== false)
      view.requestMeasure(this.measureReq);
  }
  setOrder(state) {
    let pos = 0, order = state.facet(layerOrder);
    while (pos < order.length && order[pos] != this.layer)
      pos++;
    this.dom.style.zIndex = String((this.layer.above ? 150 : -1) - pos);
  }
  measure() {
    return this.layer.markers(this.view);
  }
  scale() {
    let { scaleX, scaleY } = this.view;
    if (scaleX != this.scaleX || scaleY != this.scaleY) {
      this.scaleX = scaleX;
      this.scaleY = scaleY;
      this.dom.style.transform = `scale(${1 / scaleX}, ${1 / scaleY})`;
    }
  }
  draw(markers) {
    if (markers.length != this.drawn.length || markers.some((p, i) => !sameMarker(p, this.drawn[i]))) {
      let old = this.dom.firstChild, oldI = 0;
      for (let marker of markers) {
        if (marker.update && old && marker.constructor && this.drawn[oldI].constructor && marker.update(old, this.drawn[oldI])) {
          old = old.nextSibling;
          oldI++;
        } else {
          this.dom.insertBefore(marker.draw(), old);
        }
      }
      while (old) {
        let next = old.nextSibling;
        old.remove();
        old = next;
      }
      this.drawn = markers;
    }
  }
  destroy() {
    if (this.layer.destroy)
      this.layer.destroy(this.dom, this.view);
    this.dom.remove();
  }
};
var layerOrder = /* @__PURE__ */ Facet.define();
function layer(config2) {
  return [
    ViewPlugin.define((v) => new LayerView(v, config2)),
    layerOrder.of(config2)
  ];
}
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),
    cursorLayer,
    selectionLayer,
    hideNativeSelection,
    nativeSelectionHidden.of(true)
  ];
}
function configChanged(update2) {
  return update2.startState.facet(selectionConfig) != update2.state.facet(selectionConfig);
}
var cursorLayer = /* @__PURE__ */ layer({
  above: true,
  markers(view) {
    let { state } = view, conf = state.facet(selectionConfig);
    let cursors = [];
    for (let r of state.selection.ranges) {
      let prim = r == state.selection.main;
      if (r.empty ? !prim || CanHidePrimary : conf.drawRangeCursor) {
        let className = prim ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary";
        let cursor = r.empty ? r : EditorSelection.cursor(r.head, r.head > r.anchor ? -1 : 1);
        for (let piece of RectangleMarker.forRange(view, className, cursor))
          cursors.push(piece);
      }
    }
    return cursors;
  },
  update(update2, dom) {
    if (update2.transactions.some((tr) => tr.selection))
      dom.style.animationName = dom.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink";
    let confChange = configChanged(update2);
    if (confChange)
      setBlinkRate(update2.state, dom);
    return update2.docChanged || update2.selectionSet || confChange;
  },
  mount(dom, view) {
    setBlinkRate(view.state, dom);
  },
  class: "cm-cursorLayer"
});
function setBlinkRate(state, dom) {
  dom.style.animationDuration = state.facet(selectionConfig).cursorBlinkRate + "ms";
}
var selectionLayer = /* @__PURE__ */ layer({
  above: false,
  markers(view) {
    return view.state.selection.ranges.map((r) => r.empty ? [] : RectangleMarker.forRange(view, "cm-selectionBackground", r)).reduce((a, b) => a.concat(b));
  },
  update(update2, dom) {
    return update2.docChanged || update2.selectionSet || update2.viewportChanged || configChanged(update2);
  },
  class: "cm-selectionLayer"
});
var themeSpec = {
  ".cm-line": {
    "& ::selection": { backgroundColor: "transparent !important" },
    "&::selection": { backgroundColor: "transparent !important" }
  }
};
if (CanHidePrimary) {
  themeSpec[".cm-line"].caretColor = "transparent !important";
  themeSpec[".cm-content"] = { caretColor: "transparent !important" };
}
var hideNativeSelection = /* @__PURE__ */ Prec.highest(/* @__PURE__ */ EditorView.theme(themeSpec));
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 {
  /**
  Create a decorator.
  */
  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;
  }
  /**
  Compute the full set of decorations for matches in the given
  view's viewport. You'll want to call this when initializing your
  plugin.
  */
  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();
  }
  /**
  Update a set of decorations for a view update. `deco` _must_ be
  the set of decorations produced by _this_ `MatchDecorator` for
  the view state before the update.
  */
  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 start2 = 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])) {
              start2 = 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 = start2 - 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, start2, end, (from2, m2) => this.addMatch(m2, view, from2, add3));
        }
        deco = deco.update({ filterFrom: start2, filterTo: end, filter: (from2, to2) => from2 < start2 || 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 / this.view.scaleX)
            });
          }
          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(options3, code) {
    super();
    this.options = options3;
    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;
  }
  coordsAt(dom) {
    let rects = dom.firstChild ? clientRectsFor(dom.firstChild) : [];
    if (!rects.length)
      return null;
    let style = window.getComputedStyle(dom.parentNode);
    let rect = flattenRect(rects[0], style.direction != "rtl");
    let lineHeight = parseInt(style.lineHeight);
    if (rect.bottom - rect.top > lineHeight * 1.5)
      return { left: rect.left, right: rect.right, top: rect.top, bottom: rect.top + lineHeight };
    return rect;
  }
  ignoreEvent() {
    return false;
  }
};
function placeholder(content2) {
  return ViewPlugin.fromClass(class {
    constructor(view) {
      this.view = view;
      this.placeholder = content2 ? Decoration.set([Decoration.widget({ widget: new Placeholder(content2), side: 1 }).range(0)]) : Decoration.none;
    }
    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 start2 = findColumn(line.text, startCol, state.tabSize, true);
      if (start2 < 0) {
        ranges.push(EditorSelection.cursor(line.to));
      } else {
        let end = findColumn(line.text, endCol, state.tabSize);
        ranges.push(EditorSelection.range(line.from + start2, 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 start2 = getPos(view, event), startSel = view.state.selection;
  if (!start2)
    return null;
  return {
    update(update2) {
      if (update2.docChanged) {
        let newStart = update2.changes.mapPos(update2.startState.doc.line(start2.line).from);
        let newLine = update2.state.doc.lineAt(newStart);
        start2 = { line: newLine.number, col: start2.col, off: Math.min(start2.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, start2, cur2);
      if (!ranges.length)
        return startSel;
      if (multiple)
        return EditorSelection.create(ranges.concat(startSel.ranges));
      else
        return EditorSelection.create(ranges);
    }
  };
}
function rectangularSelection(options3) {
  let filter2 = (options3 === null || options3 === void 0 ? void 0 : options3.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, removeTooltipView) {
    this.facet = facet;
    this.createTooltipView = createTooltipView;
    this.removeTooltipView = removeTooltipView;
    this.input = view.state.facet(facet);
    this.tooltips = this.input.filter((t4) => t4);
    let prev = null;
    this.tooltipViews = this.tooltips.map((t4) => prev = createTooltipView(t4, prev));
  }
  update(update2, above) {
    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 = [], newAbove = above ? [] : null;
    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, i ? tooltipViews[i - 1] : null);
        if (newAbove)
          newAbove[i] = !!tip.above;
      } else {
        let tooltipView = tooltipViews[i] = this.tooltipViews[known];
        if (newAbove)
          newAbove[i] = above[known];
        if (tooltipView.update)
          tooltipView.update(update2);
      }
    }
    for (let t4 of this.tooltipViews)
      if (tooltipViews.indexOf(t4) < 0) {
        this.removeTooltipView(t4);
        (_a2 = t4.destroy) === null || _a2 === void 0 ? void 0 : _a2.call(t4);
      }
    if (above) {
      newAbove.forEach((val, i) => above[i] = val);
      above.length = newAbove.length;
    }
    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 knownHeight = /* @__PURE__ */ new WeakMap();
var tooltipPlugin = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.above = [];
    this.inView = true;
    this.madeAbsolute = false;
    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.resizeObserver = typeof ResizeObserver == "function" ? new ResizeObserver(() => this.measureSoon()) : null;
    this.manager = new TooltipViewManager(view, showTooltip, (t4, p) => this.createTooltip(t4, p), (t4) => {
      if (this.resizeObserver)
        this.resizeObserver.unobserve(t4.dom);
      t4.dom.remove();
    });
    this.above = this.manager.tooltips.map((t4) => !!t4.above);
    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, this.above);
    if (updated)
      this.observeIntersection();
    let shouldMeasure = updated || update2.geometryChanged;
    let newConfig = update2.state.facet(tooltipConfig);
    if (newConfig.position != this.position && !this.madeAbsolute) {
      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, prev) {
    let tooltipView = tooltip2.create(this.view);
    let before = prev ? prev.dom : null;
    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.insertBefore(arrow, before);
    }
    tooltipView.dom.style.position = this.position;
    tooltipView.dom.style.top = Outside;
    tooltipView.dom.style.left = "0px";
    this.container.insertBefore(tooltipView.dom, before);
    if (tooltipView.mount)
      tooltipView.mount(this.view);
    if (this.resizeObserver)
      this.resizeObserver.observe(tooltipView.dom);
    return tooltipView;
  }
  destroy() {
    var _a2, _b, _c;
    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);
    }
    if (this.parent)
      this.container.remove();
    (_b = this.resizeObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
    (_c = this.intersectionObserver) === null || _c === void 0 ? void 0 : _c.disconnect();
    clearTimeout(this.measureTimeout);
  }
  readMeasure() {
    let editor2 = this.view.dom.getBoundingClientRect();
    let scaleX = 1, scaleY = 1, makeAbsolute = false;
    if (this.position == "fixed" && this.manager.tooltipViews.length) {
      let { dom } = this.manager.tooltipViews[0];
      if (browser.gecko) {
        makeAbsolute = dom.offsetParent != this.container.ownerDocument.body;
      } else if (dom.style.top == Outside && dom.style.left == "0px") {
        let rect = dom.getBoundingClientRect();
        makeAbsolute = Math.abs(rect.top + 1e4) > 1 || Math.abs(rect.left) > 1;
      }
    }
    if (makeAbsolute || this.position == "absolute") {
      if (this.parent) {
        let rect = this.parent.getBoundingClientRect();
        if (rect.width && rect.height) {
          scaleX = rect.width / this.parent.offsetWidth;
          scaleY = rect.height / this.parent.offsetHeight;
        }
      } else {
        ({ scaleX, scaleY } = this.view.viewState);
      }
    }
    return {
      editor: editor2,
      parent: this.parent ? this.container.getBoundingClientRect() : editor2,
      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),
      scaleX,
      scaleY,
      makeAbsolute
    };
  }
  writeMeasure(measured) {
    var _a2;
    if (measured.makeAbsolute) {
      this.madeAbsolute = true;
      this.position = "absolute";
      for (let t4 of this.manager.tooltipViews)
        t4.dom.style.position = "absolute";
    }
    let { editor: editor2, space: space2, scaleX, scaleY } = 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(editor2.top, space2.top) || pos.top >= Math.min(editor2.bottom, space2.bottom) || pos.right < Math.max(editor2.left, space2.left) - 0.1 || pos.left > Math.min(editor2.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 = (_a2 = knownHeight.get(tView)) !== null && _a2 !== void 0 ? _a2 : 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 = this.above[i];
      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 = this.above[i] = !above;
      let spaceVert = (above ? pos.top - space2.top : space2.bottom - pos.bottom) - arrowHeight;
      if (spaceVert < height4 && tView.resize !== false) {
        if (spaceVert < this.view.defaultLineHeight) {
          dom.style.top = Outside;
          continue;
        }
        knownHeight.set(tView, height4);
        dom.style.height = (height4 = spaceVert) / scaleY + "px";
      } else if (dom.style.height) {
        dom.style.height = "";
      }
      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) / scaleY + "px";
        dom.style.left = (left2 - measured.parent.left) / scaleX + "px";
      } else {
        dom.style.top = top3 / scaleY + "px";
        dom.style.left = left2 / scaleX + "px";
      }
      if (arrow) {
        let arrowLeft = pos.left + (ltr ? offset.x : -offset.x) - (left2 + 14 - 7);
        arrow.style.left = arrowLeft / scaleX + "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(measured.space);
    }
  }
  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;
      }
    }
  }
}, {
  eventObservers: {
    scroll() {
      this.maybeMeasure();
    }
  }
});
var baseTheme = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-tooltip": {
    zIndex: 100,
    boxSizing: "border-box"
  },
  "&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({
  combine: (inputs) => inputs.reduce((a, i) => a.concat(i), [])
});
var HoverTooltipHost = class _HoverTooltipHost {
  // Needs to be static so that host tooltip instances always match
  static create(view) {
    return new _HoverTooltipHost(view);
  }
  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, p) => this.createHostedView(t4, p), (t4) => t4.dom.remove());
  }
  createHostedView(tooltip2, prev) {
    let hostedView = tooltip2.create(this.view);
    hostedView.dom.classList.add("cm-tooltip-section");
    this.dom.insertBefore(hostedView.dom, prev ? prev.dom.nextSibling : this.dom.firstChild);
    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(space2) {
    for (let hostedView of this.manager.tooltipViews) {
      if (hostedView.positioned)
        hostedView.positioned(space2);
    }
  }
  update(update2) {
    this.manager.update(update2);
  }
  destroy() {
    var _a2;
    for (let t4 of this.manager.tooltipViews)
      (_a2 = t4.destroy) === null || _a2 === void 0 ? void 0 : _a2.call(t4);
  }
  passProp(name2) {
    let value = void 0;
    for (let view of this.manager.tooltipViews) {
      let given = view[name2];
      if (given !== void 0) {
        if (value === void 0)
          value = given;
        else if (value !== given)
          return void 0;
      }
    }
    return value;
  }
  get offset() {
    return this.passProp("offset");
  }
  get getCoords() {
    return this.passProp("getCoords");
  }
  get overlap() {
    return this.passProp("overlap");
  }
  get resize() {
    return this.passProp("resize");
  }
};
var showHoverTooltipHost = /* @__PURE__ */ showTooltip.compute([showHoverTooltip], (state) => {
  let tooltips = state.facet(showHoverTooltip);
  if (tooltips.length === 0)
    return null;
  return {
    pos: Math.min(...tooltips.map((t4) => t4.pos)),
    end: Math.max(...tooltips.map((t4) => {
      var _a2;
      return (_a2 = t4.end) !== null && _a2 !== void 0 ? _a2 : t4.pos;
    })),
    create: HoverTooltipHost.create,
    above: tooltips[0].above,
    arrow: tooltips.some((t4) => t4.arrow)
  };
});
var HoverPlugin = class {
  constructor(view, source2, field, setHover, hoverTime) {
    this.view = view;
    this.source = source2;
    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.length)
      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 { view, lastMove } = this;
    let desc = view.docView.nearest(lastMove.target);
    if (!desc)
      return;
    let pos, side = 1;
    if (desc instanceof WidgetView) {
      pos = desc.posAtStart;
    } else {
      pos = view.posAtCoords(lastMove);
      if (pos == null)
        return;
      let posCoords = view.coordsAtPos(pos);
      if (!posCoords || lastMove.y < posCoords.top || lastMove.y > posCoords.bottom || lastMove.x < posCoords.left - view.defaultCharacterWidth || lastMove.x > posCoords.right + view.defaultCharacterWidth)
        return;
      let bidi = view.bidiSpans(view.state.doc.lineAt(pos)).find((s) => s.from <= pos && s.to >= pos);
      let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1;
      side = lastMove.x < posCoords.left ? -rtl : rtl;
    }
    let open = this.source(view, pos, side);
    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 && !(Array.isArray(result) && !result.length))
            view.dispatch({ effects: this.setHover.of(Array.isArray(result) ? result : [result]) });
        }
      }, (e3) => logException(view.state, e3, "hover tooltip"));
    } else if (open && !(Array.isArray(open) && !open.length)) {
      view.dispatch({ effects: this.setHover.of(Array.isArray(open) ? open : [open]) });
    }
  }
  get tooltip() {
    let plugin = this.view.plugin(tooltipPlugin);
    let index2 = plugin ? plugin.manager.tooltips.findIndex((t4) => t4.create == HoverTooltipHost.create) : -1;
    return index2 > -1 ? plugin.manager.tooltipViews[index2] : null;
  }
  mousemove(event) {
    var _a2, _b;
    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 { active, tooltip: tooltip2 } = this;
    if (active.length && tooltip2 && !isInTooltip(tooltip2.dom, event) || this.pending) {
      let { pos } = active[0] || this.pending, end = (_b = (_a2 = active[0]) === null || _a2 === void 0 ? void 0 : _a2.end) !== null && _b !== void 0 ? _b : pos;
      if (pos == end ? this.view.posAtCoords(this.lastMove) != pos : !isOverRange(this.view, pos, end, event.clientX, event.clientY)) {
        this.view.dispatch({ effects: this.setHover.of([]) });
        this.pending = null;
      }
    }
  }
  mouseleave(event) {
    clearTimeout(this.hoverTimeout);
    this.hoverTimeout = -1;
    let { active } = this;
    if (active.length) {
      let { tooltip: tooltip2 } = this;
      let inTooltip = tooltip2 && tooltip2.dom.contains(event.relatedTarget);
      if (!inTooltip)
        this.view.dispatch({ effects: this.setHover.of([]) });
      else
        this.watchTooltipLeave(tooltip2.dom);
    }
  }
  watchTooltipLeave(tooltip2) {
    let watch = (event) => {
      tooltip2.removeEventListener("mouseleave", watch);
      if (this.active.length && !this.view.dom.contains(event.relatedTarget))
        this.view.dispatch({ effects: this.setHover.of([]) });
    };
    tooltip2.addEventListener("mouseleave", watch);
  }
  destroy() {
    clearTimeout(this.hoverTimeout);
    this.view.dom.removeEventListener("mouseleave", this.mouseleave);
    this.view.dom.removeEventListener("mousemove", this.mousemove);
  }
};
var tooltipMargin = 4;
function isInTooltip(tooltip2, event) {
  let rect = tooltip2.getBoundingClientRect();
  return event.clientX >= rect.left - tooltipMargin && event.clientX <= rect.right + tooltipMargin && event.clientY >= rect.top - tooltipMargin && event.clientY <= rect.bottom + tooltipMargin;
}
function isOverRange(view, from, to, x2, y2, margin) {
  let rect = view.scrollDOM.getBoundingClientRect();
  let docBottom = view.documentTop + view.documentPadding.top + view.contentHeight;
  if (rect.left > x2 || rect.right < x2 || rect.top > y2 || Math.min(rect.bottom, docBottom) < y2)
    return false;
  let pos = view.posAtCoords({ x: x2, y: y2 }, false);
  return pos >= from && pos <= to;
}
function hoverTooltip(source2, options3 = {}) {
  let setHover = StateEffect.define();
  let hoverState = StateField.define({
    create() {
      return [];
    },
    update(value, tr) {
      if (value.length) {
        if (options3.hideOnChange && (tr.docChanged || tr.selection))
          value = [];
        else if (options3.hideOn)
          value = value.filter((v) => !options3.hideOn(tr, v));
        if (tr.docChanged) {
          let mapped = [];
          for (let tooltip2 of value) {
            let newPos = tr.changes.mapPos(tooltip2.pos, -1, MapMode.TrackDel);
            if (newPos != null) {
              let copy2 = Object.assign(/* @__PURE__ */ Object.create(null), tooltip2);
              copy2.pos = newPos;
              if (copy2.end != null)
                copy2.end = tr.changes.mapPos(copy2.end);
              mapped.push(copy2);
            }
          }
          value = mapped;
        }
      }
      for (let effect of tr.effects) {
        if (effect.is(setHover))
          value = effect.value;
        if (effect.is(closeHoverTooltipEffect))
          value = [];
      }
      return value;
    },
    provide: (f) => showHoverTooltip.from(f)
  });
  return [
    hoverState,
    ViewPlugin.define((view) => new HoverPlugin(
      view,
      source2,
      hoverState,
      setHover,
      options3.hoverTime || 300
      /* Hover.Time */
    )),
    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 {
  /**
  @internal
  */
  compare(other) {
    return this == other || this.constructor == other.constructor && this.eq(other);
  }
  /**
  Compare this marker to another marker of the same type.
  */
  eq(other) {
    return false;
  }
  /**
  Called if the marker has a `toDOM` method and its representation
  was removed from a gutter.
  */
  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,
  widgetMarker: () => 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 / this.view.scaleY + "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 / this.view.scaleY + "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) {
      if (classSet.length)
        classSet = [];
      if (Array.isArray(line.type)) {
        let first = true;
        for (let b of line.type) {
          if (b.type == BlockType.Text && first) {
            advanceCursor(lineClasses, classSet, b.from);
            for (let cx of contexts)
              cx.line(this.view, b, classSet);
            first = false;
          } else if (b.widget) {
            for (let cx of contexts)
              cx.widget(this.view, b);
          }
        }
      } else if (line.type == BlockType.Text) {
        advanceCursor(lineClasses, classSet, line.from);
        for (let cx of contexts)
          cx.line(this.view, line, classSet);
      } else if (line.widget) {
        for (let cx of contexts)
          cx.widget(this.view, line);
      }
    }
    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 * view.scaleX } : { right: value.dom.offsetWidth * view.scaleX };
  })
});
function asArray2(val) {
  return Array.isArray(val) ? val : [val];
}
function advanceCursor(cursor, collect2, pos) {
  while (cursor.value && cursor.from <= pos) {
    if (cursor.from == pos)
      collect2.push(cursor.value);
    cursor.next();
  }
}
var UpdateContext = class {
  constructor(gutter2, viewport, height4) {
    this.gutter = gutter2;
    this.height = height4;
    this.i = 0;
    this.cursor = RangeSet.iter(gutter2.markers, viewport.from);
  }
  addElement(view, block, markers) {
    let { gutter: gutter2 } = this, above = (block.top - this.height) / view.scaleY, height4 = block.height / view.scaleY;
    if (this.i == gutter2.elements.length) {
      let newElt = new GutterElement(view, height4, above, markers);
      gutter2.elements.push(newElt);
      gutter2.dom.appendChild(newElt.dom);
    } else {
      gutter2.elements[this.i].update(view, height4, above, markers);
    }
    this.height = block.bottom;
    this.i++;
  }
  line(view, line, extraMarkers) {
    let localMarkers = [];
    advanceCursor(this.cursor, localMarkers, line.from);
    if (extraMarkers.length)
      localMarkers = localMarkers.concat(extraMarkers);
    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;
    this.addElement(view, line, localMarkers);
  }
  widget(view, block) {
    let marker = this.gutter.config.widgetMarker(view, block.widget, block);
    if (marker)
      this.addElement(view, block, [marker]);
  }
  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 target = event.target, y2;
        if (target != this.dom && this.dom.contains(target)) {
          while (target.parentNode != this.dom)
            target = target.parentNode;
          let rect = target.getBoundingClientRect();
          y2 = (rect.top + rect.bottom) / 2;
        } else {
          y2 = event.clientY;
        }
        let line = view.lineBlockAtHeight(y2 - 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.height = height4;
      this.dom.style.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(number7) {
    super();
    this.number = number7;
  }
  eq(other) {
    return this.number == other.number;
  }
  toDOM() {
    return document.createTextNode(this.number);
  }
};
function formatNumber(view, number7) {
  return view.state.facet(lineNumberConfig).formatNumber(number7, 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));
  },
  widgetMarker: () => null,
  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;
}
function matcher(decorator) {
  return ViewPlugin.define((view) => ({
    decorations: decorator.createDeco(view),
    update(u) {
      this.decorations = decorator.updateDeco(u, this.decorations);
    }
  }), {
    decorations: (v) => v.decorations
  });
}
var trailingHighlighter = /* @__PURE__ */ matcher(/* @__PURE__ */ new MatchDecorator({
  regexp: /\s+$/g,
  decoration: /* @__PURE__ */ Decoration.mark({ class: "cm-trailingSpace" }),
  boundary: /\S/
}));
function highlightTrailingWhitespace() {
  return trailingHighlighter;
}

// 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 {
  /**
  Create a new node prop type.
  */
  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");
    });
  }
  /**
  This is meant to be used with
  [`NodeSet.extend`](#common.NodeSet.extend) or
  [`LRParser.configure`](#lr.ParserConfig.props) to compute
  prop values for each node type in the set. Takes a [match
  object](#common.NodeType^match) or function that returns undefined
  if the node type doesn't get this prop, and the prop's value if
  it does.
  */
  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.isolate = new NodeProp({ deserialize: (value) => {
  if (value && value != "rtl" && value != "ltr" && value != "auto")
    throw new RangeError("Invalid value for isolate: " + value);
  return value || "auto";
} });
NodeProp.contextHash = new NodeProp({ perNode: true });
NodeProp.lookAhead = new NodeProp({ perNode: true });
NodeProp.mounted = new NodeProp({ perNode: true });
var MountedTree = class {
  constructor(tree, overlay, parser) {
    this.tree = tree;
    this.overlay = overlay;
    this.parser = parser;
  }
  /**
  @internal
  */
  static get(tree) {
    return tree && tree.props && tree.props[NodeProp.mounted.id];
  }
};
var noProps = /* @__PURE__ */ Object.create(null);
var NodeType = class _NodeType {
  /**
  @internal
  */
  constructor(name2, props2, id2, flags2 = 0) {
    this.name = name2;
    this.props = props2;
    this.id = id2;
    this.flags = flags2;
  }
  /**
  Define a node type.
  */
  static define(spec) {
    let props2 = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps;
    let flags2 = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0);
    let type = new _NodeType(spec.name || "", props2, spec.id, flags2);
    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");
          props2[src[0].id] = src[1];
        }
      }
    return type;
  }
  /**
  Retrieves a node prop for this type. Will return `undefined` if
  the prop isn't present on this node.
  */
  prop(prop) {
    return this.props[prop.id];
  }
  /**
  True when this is the top node of a grammar.
  */
  get isTop() {
    return (this.flags & 1) > 0;
  }
  /**
  True when this node is produced by a skip rule.
  */
  get isSkipped() {
    return (this.flags & 2) > 0;
  }
  /**
  Indicates whether this is an error node.
  */
  get isError() {
    return (this.flags & 4) > 0;
  }
  /**
  When true, this node type doesn't correspond to a user-declared
  named node, for example because it is used to cache repetition.
  */
  get isAnonymous() {
    return (this.flags & 8) > 0;
  }
  /**
  Returns true when this node's name or one of its
  [groups](#common.NodeProp^group) matches the given string.
  */
  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;
  }
  /**
  Create a function from node types to arbitrary values by
  specifying an object whose property names are node or
  [group](#common.NodeProp^group) names. Often useful with
  [`NodeProp.add`](#common.NodeProp.add). You can put multiple
  names, separated by spaces, in a single property name to map
  multiple node names to a single value.
  */
  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
  /* NodeFlag.Anonymous */
);
var NodeSet = class _NodeSet {
  /**
  Create a set with the given types. The `id` property of each
  type should correspond to its position within the array.
  */
  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");
  }
  /**
  Create a copy of this set with some node properties added. The
  arguments to this method can be created with
  [`NodeProp.add`](#common.NodeProp.add).
  */
  extend(...props2) {
    let newTypes = [];
    for (let type of this.types) {
      let newProps = null;
      for (let source2 of props2) {
        let add3 = source2(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 Tree2 = class _Tree {
  /**
  Construct a new tree. See also [`Tree.build`](#common.Tree^build).
  */
  constructor(type, children3, positions, length, props2) {
    this.type = type;
    this.children = children3;
    this.positions = positions;
    this.length = length;
    this.props = null;
    if (props2 && props2.length) {
      this.props = /* @__PURE__ */ Object.create(null);
      for (let [prop, value] of props2)
        this.props[typeof prop == "number" ? prop : prop.id] = value;
    }
  }
  /**
  @internal
  */
  toString() {
    let mounted = MountedTree.get(this);
    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 + ")" : "");
  }
  /**
  Get a [tree cursor](#common.TreeCursor) positioned at the top of
  the tree. Mode can be used to [control](#common.IterMode) which
  nodes the cursor visits.
  */
  cursor(mode = 0) {
    return new TreeCursor2(this.topNode, mode);
  }
  /**
  Get a [tree cursor](#common.TreeCursor) pointing into this tree
  at the given position and side (see
  [`moveTo`](#common.TreeCursor.moveTo).
  */
  cursorAt(pos, side = 0, mode = 0) {
    let scope = CachedNode.get(this) || this.topNode;
    let cursor = new TreeCursor2(scope);
    cursor.moveTo(pos, side);
    CachedNode.set(this, cursor._tree);
    return cursor;
  }
  /**
  Get a [syntax node](#common.SyntaxNode) object for the top of the
  tree.
  */
  get topNode() {
    return new TreeNode(this, 0, 0, null);
  }
  /**
  Get the [syntax node](#common.SyntaxNode) at the given position.
  If `side` is -1, this will move into nodes that end at the
  position. If 1, it'll move into nodes that start at the
  position. With 0, it'll only enter nodes that cover the position
  from both sides.
  
  Note that this will not enter
  [overlays](#common.MountedTree.overlay), and you often want
  [`resolveInner`](#common.Tree.resolveInner) instead.
  */
  resolve(pos, side = 0) {
    let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
    CachedNode.set(this, node);
    return node;
  }
  /**
  Like [`resolve`](#common.Tree.resolve), but will enter
  [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
  pointing into the innermost overlaid tree at the given position
  (with parent links going through all parent structure, including
  the host trees).
  */
  resolveInner(pos, side = 0) {
    let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
    CachedInnerNode.set(this, node);
    return node;
  }
  /**
  In some situations, it can be useful to iterate through all
  nodes around a position, including those in overlays that don't
  directly cover the position. This method gives you an iterator
  that will produce all nodes, from small to big, around the given
  position.
  */
  resolveStack(pos, side = 0) {
    return stackIterator(this, pos, side);
  }
  /**
  Iterate over the tree and its children, calling `enter` for any
  node that touches the `from`/`to` region (if given) before
  running over such a node's children, and `leave` (if given) when
  leaving the node. When `enter` returns `false`, that node will
  not have its children iterated over (or `leave` called).
  */
  iterate(spec) {
    let { enter, leave, from = 0, to = this.length } = spec;
    let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;
    for (let c = this.cursor(mode | IterMode.IncludeAnonymous); ; ) {
      let entered = false;
      if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {
        if (c.firstChild())
          continue;
        entered = true;
      }
      for (; ; ) {
        if (entered && leave && (anon || !c.type.isAnonymous))
          leave(c);
        if (c.nextSibling())
          break;
        if (!c.parent())
          return;
        entered = true;
      }
    }
  }
  /**
  Get the value of the given [node prop](#common.NodeProp) for this
  node. Works with both per-node and per-type props.
  */
  prop(prop) {
    return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : void 0;
  }
  /**
  Returns the node's [per-node props](#common.NodeProp.perNode) in a
  format that can be passed to the [`Tree`](#common.Tree)
  constructor.
  */
  get propValues() {
    let result = [];
    if (this.props)
      for (let id2 in this.props)
        result.push([+id2, this.props[id2]]);
    return result;
  }
  /**
  Balance the direct children of this tree, producing a copy of
  which may have children grouped into subtrees with type
  [`NodeType.none`](#common.NodeType^none).
  */
  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)));
  }
  /**
  Build a tree from a postfix-ordered buffer of node information,
  or a cursor over such a buffer.
  */
  static build(data) {
    return buildTree(data);
  }
};
Tree2.empty = new Tree2(NodeType.none, [], [], 0);
var FlatBufferCursor = class _FlatBufferCursor {
  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 _TreeBuffer {
  /**
  Create a tree buffer.
  */
  constructor(buffer, length, set2) {
    this.buffer = buffer;
    this.length = length;
    this.set = set2;
  }
  /**
  @internal
  */
  get type() {
    return NodeType.none;
  }
  /**
  @internal
  */
  toString() {
    let result = [];
    for (let index2 = 0; index2 < this.buffer.length; ) {
      result.push(this.childString(index2));
      index2 = this.buffer[index2 + 3];
    }
    return result.join(",");
  }
  /**
  @internal
  */
  childString(index2) {
    let id2 = this.buffer[index2], endIndex = this.buffer[index2 + 3];
    let type = this.set.types[id2], 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(",") + ")";
  }
  /**
  @internal
  */
  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;
  }
  /**
  @internal
  */
  slice(startI, endI, from) {
    let b = this.buffer;
    let copy2 = new Uint16Array(endI - startI), len = 0;
    for (let i = startI, j = 0; i < endI; ) {
      copy2[j++] = b[i++];
      copy2[j++] = b[i++] - from;
      let to = copy2[j++] = b[i++] - from;
      copy2[j++] = b[i++] - startI;
      len = Math.max(len, to);
    }
    return new _TreeBuffer(copy2, len, 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 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 BaseNode = class {
  cursor(mode = 0) {
    return new TreeCursor2(this, mode);
  }
  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);
  }
  resolve(pos, side = 0) {
    return resolveNode(this, pos, side, false);
  }
  resolveInner(pos, side = 0) {
    return resolveNode(this, pos, side, true);
  }
  matchContext(context2) {
    return matchNodeContext(this, context2);
  }
  enterUnfinishedNodesBefore(pos) {
    let scan = this.childBefore(pos), node = this;
    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;
  }
  get node() {
    return this;
  }
  get next() {
    return this.parent;
  }
};
var TreeNode = class _TreeNode extends BaseNode {
  constructor(_tree, from, index2, _parent) {
    super();
    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], start2 = positions[i] + parent2.from;
        if (!checkSide(side, pos, start2, start2 + next.length))
          continue;
        if (next instanceof TreeBuffer) {
          if (mode & IterMode.ExcludeBuffers)
            continue;
          let index2 = next.findChild(0, next.buffer.length, dir, pos - start2, side);
          if (index2 > -1)
            return new BufferNode(new BufferContext(parent2, next, i, start2), null, index2);
        } else if (mode & IterMode.IncludeAnonymous || (!next.type.isAnonymous || hasChild(next))) {
          let mounted;
          if (!(mode & IterMode.IgnoreMounts) && (mounted = MountedTree.get(next)) && !mounted.overlay)
            return new _TreeNode(mounted.tree, start2, i, parent2);
          let inner = new _TreeNode(next, start2, 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
      /* Side.DontCare */
    );
  }
  get lastChild() {
    return this.nextChild(
      this._tree.children.length - 1,
      -1,
      0,
      4
      /* Side.DontCare */
    );
  }
  childAfter(pos) {
    return this.nextChild(
      0,
      1,
      pos,
      2
      /* Side.After */
    );
  }
  childBefore(pos) {
    return this.nextChild(
      this._tree.children.length - 1,
      -1,
      pos,
      -2
      /* Side.Before */
    );
  }
  enter(pos, side, mode = 0) {
    let mounted;
    if (!(mode & IterMode.IgnoreOverlays) && (mounted = MountedTree.get(this._tree)) && 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
      /* Side.DontCare */
    ) : null;
  }
  get prevSibling() {
    return this._parent && this.index >= 0 ? this._parent.nextChild(
      this.index - 1,
      -1,
      0,
      4
      /* Side.DontCare */
    ) : null;
  }
  get tree() {
    return this._tree;
  }
  toTree() {
    return this._tree;
  }
  /**
  @internal
  */
  toString() {
    return this._tree.toString();
  }
};
function getChildren(node, type, before, after) {
  let cur2 = node.cursor(), result = [];
  if (!cur2.firstChild())
    return result;
  if (before != null)
    for (let found = false; !found; ) {
      found = 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, context2, i = context2.length - 1) {
  for (let p = node.parent; i >= 0; p = p.parent) {
    if (!p)
      return false;
    if (!p.type.isAnonymous) {
      if (context2[i] && context2[i] != p.name)
        return false;
      i--;
    }
  }
  return true;
}
var BufferContext = class {
  constructor(parent2, buffer, index2, start2) {
    this.parent = parent2;
    this.buffer = buffer;
    this.index = index2;
    this.start = start2;
  }
};
var BufferNode = class _BufferNode extends BaseNode {
  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];
  }
  constructor(context2, _parent, index2) {
    super();
    this.context = context2;
    this._parent = _parent;
    this.index = index2;
    this.type = context2.buffer.set.types[context2.buffer.buffer[index2]];
  }
  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
      /* Side.DontCare */
    );
  }
  get lastChild() {
    return this.child(
      -1,
      0,
      4
      /* Side.DontCare */
    );
  }
  childAfter(pos) {
    return this.child(
      1,
      pos,
      2
      /* Side.After */
    );
  }
  childBefore(pos) {
    return this.child(
      -1,
      pos,
      -2
      /* Side.Before */
    );
  }
  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
      /* Side.DontCare */
    );
  }
  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
      /* Side.DontCare */
    ));
  }
  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];
      children3.push(buffer.slice(startI, endI, from));
      positions.push(0);
    }
    return new Tree2(this.type, children3, positions, this.to - this.from);
  }
  /**
  @internal
  */
  toString() {
    return this.context.buffer.childString(this.index);
  }
};
function iterStack(heads) {
  if (!heads.length)
    return null;
  let pick = 0, picked = heads[0];
  for (let i = 1; i < heads.length; i++) {
    let node = heads[i];
    if (node.from > picked.from || node.to < picked.to) {
      picked = node;
      pick = i;
    }
  }
  let next = picked instanceof TreeNode && picked.index < 0 ? null : picked.parent;
  let newHeads = heads.slice();
  if (next)
    newHeads[pick] = next;
  else
    newHeads.splice(pick, 1);
  return new StackIterator(newHeads, picked);
}
var StackIterator = class {
  constructor(heads, node) {
    this.heads = heads;
    this.node = node;
  }
  get next() {
    return iterStack(this.heads);
  }
};
function stackIterator(tree, pos, side) {
  let inner = tree.resolveInner(pos, side), layers = null;
  for (let scan = inner instanceof TreeNode ? inner : inner.context.parent; scan; scan = scan.parent) {
    if (scan.index < 0) {
      let parent2 = scan.parent;
      (layers || (layers = [inner])).push(parent2.resolve(pos, side));
      scan = parent2;
    } else {
      let mount = MountedTree.get(scan.tree);
      if (mount && mount.overlay && mount.overlay[0].from <= pos && mount.overlay[mount.overlay.length - 1].to >= pos) {
        let root2 = new TreeNode(mount.tree, mount.overlay[0].from + scan.from, -1, scan);
        (layers || (layers = [inner])).push(resolveNode(root2, pos, side, false));
      }
    }
  }
  return layers ? iterStack(layers) : inner;
}
var TreeCursor2 = class {
  /**
  Shorthand for `.type.name`.
  */
  get name() {
    return this.type.name;
  }
  /**
  @internal
  */
  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);
    }
  }
  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: start2, buffer } = this.buffer;
    this.type = type || buffer.set.types[buffer.buffer[index2]];
    this.from = start2 + buffer.buffer[index2 + 1];
    this.to = start2 + buffer.buffer[index2 + 2];
    return true;
  }
  /**
  @internal
  */
  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);
  }
  /**
  @internal
  */
  toString() {
    return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
  }
  /**
  @internal
  */
  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);
  }
  /**
  Move the cursor to this node's first child. When this returns
  false, the node has no child, and the cursor has not been moved.
  */
  firstChild() {
    return this.enterChild(
      1,
      0,
      4
      /* Side.DontCare */
    );
  }
  /**
  Move the cursor to this node's last child.
  */
  lastChild() {
    return this.enterChild(
      -1,
      0,
      4
      /* Side.DontCare */
    );
  }
  /**
  Move the cursor to the first child that ends after `pos`.
  */
  childAfter(pos) {
    return this.enterChild(
      1,
      pos,
      2
      /* Side.After */
    );
  }
  /**
  Move to the last child that starts before `pos`.
  */
  childBefore(pos) {
    return this.enterChild(
      -1,
      pos,
      -2
      /* Side.Before */
    );
  }
  /**
  Move the cursor to the child around `pos`. If side is -1 the
  child may end at that position, when 1 it may start there. This
  will also enter [overlaid](#common.MountedTree.overlay)
  [mounted](#common.NodeProp^mounted) trees unless `overlays` is
  set to false.
  */
  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);
  }
  /**
  Move to the node's parent node, if this isn't the top node.
  */
  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);
  }
  /**
  @internal
  */
  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
          /* Side.DontCare */
        ));
    } 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;
  }
  /**
  Move to this node's next sibling, if any.
  */
  nextSibling() {
    return this.sibling(1);
  }
  /**
  Move to this node's previous sibling, if any.
  */
  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
      /* Side.DontCare */
    ))
      return true;
    for (; ; ) {
      if (this.sibling(dir))
        return true;
      if (this.atLastNode(dir) || !this.parent())
        return false;
    }
  }
  /**
  Move to the next node in a
  [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)
  traversal, going from a node to its first child or, if the
  current node is empty or `enter` is false, its next sibling or
  the next sibling of the first parent node that has one.
  */
  next(enter = true) {
    return this.move(1, enter);
  }
  /**
  Move to the next node in a last-to-first pre-order traveral. A
  node is followed by its last child or, if it has none, its
  previous sibling or the previous sibling of the first parent
  node that has one.
  */
  prev(enter = true) {
    return this.move(-1, enter);
  }
  /**
  Move the cursor to the innermost node that covers `pos`. If
  `side` is -1, it will enter nodes that end at `pos`. If it is 1,
  it will enter nodes that start at `pos`.
  */
  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 a [syntax node](#common.SyntaxNode) at the cursor's current
  position.
  */
  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 the [tree](#common.Tree) that represents the current node, if
  any. Will return null when the node is in a [tree
  buffer](#common.TreeBuffer).
  */
  get tree() {
    return this.buffer ? null : this._tree._tree;
  }
  /**
  Iterate over the current node and all its descendants, calling
  `enter` when entering a node and `leave`, if given, when leaving
  one. When `enter` returns `false`, any children of that node are
  skipped, and `leave` isn't called for it.
  */
  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;
      }
    }
  }
  /**
  Test whether the current node matches a given context—a sequence
  of direct parent node names. Empty strings in the context array
  are treated as wildcards.
  */
  matchContext(context2) {
    if (!this.buffer)
      return matchNodeContext(this.node, context2);
    let { buffer } = this.buffer, { types: types2 } = buffer.set;
    for (let i = context2.length - 1, d = this.stack.length - 1; i >= 0; d--) {
      if (d < 0)
        return matchNodeContext(this.node, context2, i);
      let type = types2[buffer.buffer[this.stack[d]]];
      if (!type.isAnonymous) {
        if (context2[i] && context2[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, depth) {
    let { id: id2, start: start2, end, size } = cursor;
    let lookAheadAtStart = lookAhead;
    while (size < 0) {
      cursor.next();
      if (size == -1) {
        let node2 = reused[id2];
        children4.push(node2);
        positions2.push(start2 - parentStart);
        return;
      } else if (size == -3) {
        contextHash = id2;
        return;
      } else if (size == -4) {
        lookAhead = id2;
        return;
      } else {
        throw new RangeError(`Unrecognized record size: ${size}`);
      }
    }
    let type = types2[id2], node, buffer2;
    let startPos = start2 - parentStart;
    if (end - start2 <= 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 = id2 >= minRepeatType ? id2 : -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, start2, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);
            lastGroup = localChildren.length;
            lastEnd = cursor.end;
          }
          cursor.next();
        } else if (depth > 2500) {
          takeFlatNode(start2, endPos, localChildren, localPositions);
        } else {
          takeNode(start2, endPos, localChildren, localPositions, localInRepeat, depth + 1);
        }
      }
      if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
        makeRepeatLeaf(localChildren, localPositions, start2, lastGroup, start2, 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 - start2, make, make);
      } else {
        node = makeTree(type, localChildren, localPositions, end - start2, lookAheadAtStart - end);
      }
    }
    children4.push(node);
    positions2.push(startPos);
  }
  function takeFlatNode(parentStart, minPos, children4, positions2) {
    let nodes = [];
    let nodeCount = 0, stopAt = -1;
    while (cursor.pos > minPos) {
      let { id: id2, start: start2, end, size } = cursor;
      if (size > 4) {
        cursor.next();
      } else if (stopAt > -1 && start2 < stopAt) {
        break;
      } else {
        if (stopAt < 0)
          stopAt = end - maxBufferLength;
        nodes.push(id2, start2, end);
        nodeCount++;
        cursor.next();
      }
    }
    if (nodeCount) {
      let buffer2 = new Uint16Array(nodeCount * 4);
      let start2 = nodes[nodes.length - 2];
      for (let i = nodes.length - 3, j = 0; i >= 0; i -= 3) {
        buffer2[j++] = nodes[i];
        buffer2[j++] = nodes[i + 1] - start2;
        buffer2[j++] = nodes[i + 2] - start2;
        buffer2[j++] = j;
      }
      children4.push(new TreeBuffer(buffer2, nodes[2] - start2, nodeSet2));
      positions2.push(start2 - parentStart);
    }
  }
  function makeBalanced(type) {
    return (children4, positions2, length2) => {
      let lookAhead2 = 0, lastI = children4.length - 1, last, lookAheadProp;
      if (lastI >= 0 && (last = children4[lastI]) instanceof Tree2) {
        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, props2) {
    if (contextHash) {
      let pair = [NodeProp.contextHash, contextHash];
      props2 = props2 ? [pair].concat(props2) : [pair];
    }
    if (lookAhead2 > 25) {
      let pair = [NodeProp.lookAhead, lookAhead2];
      props2 = props2 ? [pair].concat(props2) : [pair];
    }
    return new Tree2(type, children4, positions2, length2, props2);
  }
  function findBufferSize(maxSize, inRepeat) {
    let fork = cursor.fork();
    let size = 0, start2 = 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 = start2;
          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();
        }
        start2 = nodeStart2;
        size += nodeSize2;
        skip += localSkipped;
      }
    if (inRepeat < 0 || size == maxSize) {
      result.size = size;
      result.start = start2;
      result.skip = skip;
    }
    return result.size > 4 ? result : void 0;
  }
  function copyToBuffer(bufferStart, buffer2, index2) {
    let { id: id2, start: start2, end, size } = cursor;
    cursor.next();
    if (size >= 0 && id2 < 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] = start2 - bufferStart;
      buffer2[--index2] = id2;
    } else if (size == -3) {
      contextHash = id2;
    } else if (size == -4) {
      lookAhead = id2;
    }
    return index2;
  }
  let children3 = [], positions = [];
  while (cursor.pos > 0)
    takeNode(data.start || 0, data.bufferStart || 0, children3, positions, -1, 0);
  let length = (_a2 = data.length) !== null && _a2 !== void 0 ? _a2 : children3.length ? positions[0] + children3[0].length : 0;
  return new Tree2(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 Tree2)) {
        size = 1;
        break;
      }
      size += nodeSize(balanceType, child);
    }
    nodeSizeCache.set(node, size);
  }
  return size;
}
function balanceRange(balanceType, children3, positions, from, to, start2, 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
    /* Balance.BranchFactor */
  );
  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 - start2);
    }
  }
  divide(children3, positions, from, to, 0);
  return (mkTop || mkTree)(localChildren, localPositions, length);
}
var TreeFragment = class _TreeFragment {
  /**
  Construct a tree fragment. You'll usually want to use
  [`addTree`](#common.TreeFragment^addTree) and
  [`applyChanges`](#common.TreeFragment^applyChanges) instead of
  calling this directly.
  */
  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);
  }
  /**
  Whether the start of the fragment represents the start of a
  parse, or the end of a change. (In the second case, it may not
  be safe to reuse some nodes at the start, depending on the
  parsing algorithm.)
  */
  get openStart() {
    return (this.open & 1) > 0;
  }
  /**
  Whether the end of the fragment represents the end of a
  full-document parse, or the start of a change.
  */
  get openEnd() {
    return (this.open & 2) > 0;
  }
  /**
  Create a set of fragments from a freshly parsed tree, or update
  an existing set of fragments by replacing the ones that overlap
  with a tree with content from the new tree. When `partial` is
  true, the parse is treated as incomplete, and the resulting
  fragment has [`openEnd`](#common.TreeFragment.openEnd) set to
  true.
  */
  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;
  }
  /**
  Apply a set of edits to an array of fragments, removing or
  splitting fragments as necessary to remove edited ranges, and
  adjusting offsets for fragments that moved.
  */
  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 Parser2 = class {
  /**
  Start a parse, returning a [partial parse](#common.PartialParse)
  object. [`fragments`](#common.TreeFragment) can be passed in to
  make the parse incremental.
  
  By default, the entire input is parsed. You can pass `ranges`,
  which should be a sorted array of non-empty, non-overlapping
  ranges, to parse only those ranges. The tree returned in that
  case will start at `ranges[0].from`.
  */
  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);
  }
  /**
  Run a full parse, returning the resulting tree.
  */
  parse(input, fragments, ranges) {
    let parse = this.startParse(input, fragments, ranges);
    for (; ; ) {
      let done = parse.advance();
      if (done)
        return done;
    }
  }
};
var StringInput = class {
  constructor(string4) {
    this.string = string4;
  }
  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 _Tag {
  /**
  @internal
  */
  constructor(set2, base2, modified) {
    this.set = set2;
    this.base = base2;
    this.modified = modified;
    this.id = nextTagID++;
  }
  /**
  Define a new tag. If `parent` is given, the tag is treated as a
  sub-tag of that parent, and
  [highlighters](#highlight.tagHighlighter) that don't mention
  this tag will try to fall back to the parent tag (or grandparent
  tag, etc).
  */
  static define(parent2) {
    if (parent2 === null || parent2 === void 0 ? void 0 : parent2.base)
      throw new Error("Can not derive from a modified tag");
    let tag = new _Tag([], null, []);
    tag.set.push(tag);
    if (parent2)
      for (let t4 of parent2.set)
        tag.set.push(t4);
    return tag;
  }
  /**
  Define a tag _modifier_, which is a function that, given a tag,
  will return a tag that is a subtag of the original. Applying the
  same modifier to a twice tag will return the same value (`m1(t1)
  == m1(t1)`) and applying multiple modifiers will, regardless or
  order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`).
  
  When multiple modifiers are applied to a given base tag, each
  smaller set of modifiers is registered as a parent, so that for
  example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`,
  `m1(m3(t1)`, and so on.
  */
  static defineModifier() {
    let mod = new Modifier();
    return (tag) => {
      if (tag.modified.indexOf(mod) > -1)
        return tag;
      return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id));
    };
  }
};
var nextModifierID = 0;
var Modifier = class _Modifier {
  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 set2 = [], tag = new Tag(set2, base2, mods);
    for (let m of mods)
      m.instances.push(tag);
    let configs = powerSet(mods);
    for (let parent2 of base2.set)
      if (!parent2.modified.length)
        for (let config2 of configs)
          set2.push(_Modifier.get(parent2, config2));
    return tag;
  }
};
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, context2, next) {
    this.tags = tags3;
    this.mode = mode;
    this.context = context2;
    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, options3) {
  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 tag of style.tag)
        map2[tag.id] = style.class;
  }
  let { scope, all = null } = options3 || {};
  return {
    style: (tags4) => {
      let cls = all;
      for (let tag of tags4) {
        for (let sub of tag.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: start2, to: end } = cursor;
    if (start2 >= 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(Math.max(from, start2), 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 + start2, 1);
      let innerHighlighters = this.highlighters.filter((h) => !h.scope || h.scope(mounted.tree.type));
      let hasChild2 = cursor.firstChild();
      for (let i = 0, pos = start2; ; i++) {
        let next = i < mounted.overlay.length ? mounted.overlay[i] : null;
        let nextPos = next ? next.from + start2 : 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(rangeTo, cursor.to), cls);
            if (cursor.to >= nextPos || !cursor.nextSibling())
              break;
          }
        }
        if (!next || nextPos > to)
          break;
        pos = next.to + start2;
        if (pos > from) {
          this.highlightRange(inner.cursor(), Math.max(from, next.from + start2), Math.min(to, pos), "", innerHighlighters);
          this.startSpan(Math.min(to, pos), cls);
        }
      }
      if (hasChild2)
        cursor.parent();
    } else if (cursor.firstChild()) {
      if (mounted)
        inheritedClass = "";
      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 = {
  /**
  A comment.
  */
  comment,
  /**
  A line [comment](#highlight.tags.comment).
  */
  lineComment: t(comment),
  /**
  A block [comment](#highlight.tags.comment).
  */
  blockComment: t(comment),
  /**
  A documentation [comment](#highlight.tags.comment).
  */
  docComment: t(comment),
  /**
  Any kind of identifier.
  */
  name,
  /**
  The [name](#highlight.tags.name) of a variable.
  */
  variableName: t(name),
  /**
  A type [name](#highlight.tags.name).
  */
  typeName,
  /**
  A tag name (subtag of [`typeName`](#highlight.tags.typeName)).
  */
  tagName: t(typeName),
  /**
  A property or field [name](#highlight.tags.name).
  */
  propertyName,
  /**
  An attribute name (subtag of [`propertyName`](#highlight.tags.propertyName)).
  */
  attributeName: t(propertyName),
  /**
  The [name](#highlight.tags.name) of a class.
  */
  className: t(name),
  /**
  A label [name](#highlight.tags.name).
  */
  labelName: t(name),
  /**
  A namespace [name](#highlight.tags.name).
  */
  namespace: t(name),
  /**
  The [name](#highlight.tags.name) of a macro.
  */
  macroName: t(name),
  /**
  A literal value.
  */
  literal,
  /**
  A string [literal](#highlight.tags.literal).
  */
  string: string2,
  /**
  A documentation [string](#highlight.tags.string).
  */
  docString: t(string2),
  /**
  A character literal (subtag of [string](#highlight.tags.string)).
  */
  character: t(string2),
  /**
  An attribute value (subtag of [string](#highlight.tags.string)).
  */
  attributeValue: t(string2),
  /**
  A number [literal](#highlight.tags.literal).
  */
  number: number3,
  /**
  An integer [number](#highlight.tags.number) literal.
  */
  integer: t(number3),
  /**
  A floating-point [number](#highlight.tags.number) literal.
  */
  float: t(number3),
  /**
  A boolean [literal](#highlight.tags.literal).
  */
  bool: t(literal),
  /**
  Regular expression [literal](#highlight.tags.literal).
  */
  regexp: t(literal),
  /**
  An escape [literal](#highlight.tags.literal), for example a
  backslash escape in a string.
  */
  escape: t(literal),
  /**
  A color [literal](#highlight.tags.literal).
  */
  color: t(literal),
  /**
  A URL [literal](#highlight.tags.literal).
  */
  url: t(literal),
  /**
  A language keyword.
  */
  keyword,
  /**
  The [keyword](#highlight.tags.keyword) for the self or this
  object.
  */
  self: t(keyword),
  /**
  The [keyword](#highlight.tags.keyword) for null.
  */
  null: t(keyword),
  /**
  A [keyword](#highlight.tags.keyword) denoting some atomic value.
  */
  atom: t(keyword),
  /**
  A [keyword](#highlight.tags.keyword) that represents a unit.
  */
  unit: t(keyword),
  /**
  A modifier [keyword](#highlight.tags.keyword).
  */
  modifier: t(keyword),
  /**
  A [keyword](#highlight.tags.keyword) that acts as an operator.
  */
  operatorKeyword: t(keyword),
  /**
  A control-flow related [keyword](#highlight.tags.keyword).
  */
  controlKeyword: t(keyword),
  /**
  A [keyword](#highlight.tags.keyword) that defines something.
  */
  definitionKeyword: t(keyword),
  /**
  A [keyword](#highlight.tags.keyword) related to defining or
  interfacing with modules.
  */
  moduleKeyword: t(keyword),
  /**
  An operator.
  */
  operator,
  /**
  An [operator](#highlight.tags.operator) that dereferences something.
  */
  derefOperator: t(operator),
  /**
  Arithmetic-related [operator](#highlight.tags.operator).
  */
  arithmeticOperator: t(operator),
  /**
  Logical [operator](#highlight.tags.operator).
  */
  logicOperator: t(operator),
  /**
  Bit [operator](#highlight.tags.operator).
  */
  bitwiseOperator: t(operator),
  /**
  Comparison [operator](#highlight.tags.operator).
  */
  compareOperator: t(operator),
  /**
  [Operator](#highlight.tags.operator) that updates its operand.
  */
  updateOperator: t(operator),
  /**
  [Operator](#highlight.tags.operator) that defines something.
  */
  definitionOperator: t(operator),
  /**
  Type-related [operator](#highlight.tags.operator).
  */
  typeOperator: t(operator),
  /**
  Control-flow [operator](#highlight.tags.operator).
  */
  controlOperator: t(operator),
  /**
  Program or markup punctuation.
  */
  punctuation,
  /**
  [Punctuation](#highlight.tags.punctuation) that separates
  things.
  */
  separator: t(punctuation),
  /**
  Bracket-style [punctuation](#highlight.tags.punctuation).
  */
  bracket,
  /**
  Angle [brackets](#highlight.tags.bracket) (usually `<` and `>`
  tokens).
  */
  angleBracket: t(bracket),
  /**
  Square [brackets](#highlight.tags.bracket) (usually `[` and `]`
  tokens).
  */
  squareBracket: t(bracket),
  /**
  Parentheses (usually `(` and `)` tokens). Subtag of
  [bracket](#highlight.tags.bracket).
  */
  paren: t(bracket),
  /**
  Braces (usually `{` and `}` tokens). Subtag of
  [bracket](#highlight.tags.bracket).
  */
  brace: t(bracket),
  /**
  Content, for example plain text in XML or markup documents.
  */
  content,
  /**
  [Content](#highlight.tags.content) that represents a heading.
  */
  heading,
  /**
  A level 1 [heading](#highlight.tags.heading).
  */
  heading1: t(heading),
  /**
  A level 2 [heading](#highlight.tags.heading).
  */
  heading2: t(heading),
  /**
  A level 3 [heading](#highlight.tags.heading).
  */
  heading3: t(heading),
  /**
  A level 4 [heading](#highlight.tags.heading).
  */
  heading4: t(heading),
  /**
  A level 5 [heading](#highlight.tags.heading).
  */
  heading5: t(heading),
  /**
  A level 6 [heading](#highlight.tags.heading).
  */
  heading6: t(heading),
  /**
  A prose separator (such as a horizontal rule).
  */
  contentSeparator: t(content),
  /**
  [Content](#highlight.tags.content) that represents a list.
  */
  list: t(content),
  /**
  [Content](#highlight.tags.content) that represents a quote.
  */
  quote: t(content),
  /**
  [Content](#highlight.tags.content) that is emphasized.
  */
  emphasis: t(content),
  /**
  [Content](#highlight.tags.content) that is styled strong.
  */
  strong: t(content),
  /**
  [Content](#highlight.tags.content) that is part of a link.
  */
  link: t(content),
  /**
  [Content](#highlight.tags.content) that is styled as code or
  monospace.
  */
  monospace: t(content),
  /**
  [Content](#highlight.tags.content) that has a strike-through
  style.
  */
  strikethrough: t(content),
  /**
  Inserted text in a change-tracking format.
  */
  inserted: t(),
  /**
  Deleted text.
  */
  deleted: t(),
  /**
  Changed text.
  */
  changed: t(),
  /**
  An invalid or unsyntactic element.
  */
  invalid: t(),
  /**
  Metadata or meta-instruction.
  */
  meta,
  /**
  [Metadata](#highlight.tags.meta) that applies to the entire
  document.
  */
  documentMeta: t(meta),
  /**
  [Metadata](#highlight.tags.meta) that annotates or adds
  attributes to a given syntactic element.
  */
  annotation: t(meta),
  /**
  Processing instruction or preprocessor directive. Subtag of
  [meta](#highlight.tags.meta).
  */
  processingInstruction: t(meta),
  /**
  [Modifier](#highlight.Tag^defineModifier) that indicates that a
  given element is being defined. Expected to be used with the
  various [name](#highlight.tags.name) tags.
  */
  definition: Tag.defineModifier(),
  /**
  [Modifier](#highlight.Tag^defineModifier) that indicates that
  something is constant. Mostly expected to be used with
  [variable names](#highlight.tags.variableName).
  */
  constant: Tag.defineModifier(),
  /**
  [Modifier](#highlight.Tag^defineModifier) used to indicate that
  a [variable](#highlight.tags.variableName) or [property
  name](#highlight.tags.propertyName) is being called or defined
  as a function.
  */
  function: Tag.defineModifier(),
  /**
  [Modifier](#highlight.Tag^defineModifier) that can be applied to
  [names](#highlight.tags.name) to indicate that they belong to
  the language's standard environment.
  */
  standard: Tag.defineModifier(),
  /**
  [Modifier](#highlight.Tag^defineModifier) that indicates a given
  [names](#highlight.tags.name) is local to some scope.
  */
  local: Tag.defineModifier(),
  /**
  A generic variant [modifier](#highlight.Tag^defineModifier) that
  can be used to tag language-specific alternative variants of
  some common tag. It is recommended for themes to define special
  forms of at least the [string](#highlight.tags.string) and
  [variable name](#highlight.tags.variableName) tags, since those
  come up a lot.
  */
  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 sublanguageProp = /* @__PURE__ */ new NodeProp();
var Language2 = class {
  /**
  Construct a language object. If you need to invoke this
  directly, first define a data facet with
  [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then
  configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it
  to the language's outer syntax node.
  */
  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) => {
        let top3 = topNodeAt(state, pos, side), data2 = top3.type.prop(languageDataProp);
        if (!data2)
          return [];
        let base2 = state.facet(data2), sub = top3.type.prop(sublanguageProp);
        if (sub) {
          let innerNode = top3.resolve(pos - top3.from, side);
          for (let sublang of sub)
            if (sublang.test(innerNode, state)) {
              let data3 = state.facet(sublang.facet);
              return sublang.type == "replace" ? data3 : data3.concat(base2);
            }
        }
        return base2;
      })
    ].concat(extraExtensions);
  }
  /**
  Query whether this language is active at the given position.
  */
  isActiveAt(state, pos, side = -1) {
    return topNodeAt(state, pos, side).type.prop(languageDataProp) == this.data;
  }
  /**
  Find the document regions that were parsed using this language.
  The returned regions will _include_ any nested languages rooted
  in this language, when those exist.
  */
  findRegions(state) {
    let lang = state.facet(language);
    if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data)
      return [{ from: 0, to: state.doc.length }];
    if (!lang || !lang.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 Tree2)
          explore(ch, tree.positions[i] + from);
      }
    };
    explore(syntaxTree(state), 0);
    return result;
  }
  /**
  Indicates whether this language allows nested languages. The
  default implementation returns true.
  */
  get allowsNesting() {
    return true;
  }
};
Language2.setState = /* @__PURE__ */ StateEffect.define();
function topNodeAt(state, pos, side) {
  let topLang = state.facet(language), tree = syntaxTree(state).topNode;
  if (!topLang || topLang.allowsNesting) {
    for (let node = tree; node; node = node.enter(pos, side, IterMode.ExcludeBuffers))
      if (node.type.isTop)
        tree = node;
  }
  return tree;
}
function syntaxTree(state) {
  let field = state.field(Language2.state, false);
  return field ? field.tree : Tree2.empty;
}
var DocInput = class {
  /**
  Create an input object for the given document.
  */
  constructor(doc2) {
    this.doc = doc2;
    this.cursorPos = 0;
    this.string = "";
    this.cursor = doc2.iter();
  }
  get length() {
    return this.doc.length;
  }
  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 _ParseContext {
  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 = [];
  }
  /**
  @internal
  */
  static create(parser, state, viewport) {
    return new _ParseContext(parser, state, [], Tree2.empty, 0, viewport, [], null);
  }
  startParse() {
    return this.parser.startParse(new DocInput(this.state.doc), this.fragments);
  }
  /**
  @internal
  */
  work(until, upto) {
    if (upto != null && upto >= this.state.doc.length)
      upto = void 0;
    if (this.tree != Tree2.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;
      }
    });
  }
  /**
  @internal
  */
  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;
  }
  /**
  @internal
  */
  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 = Tree2.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);
  }
  /**
  @internal
  */
  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;
  }
  /**
  @internal
  */
  reset() {
    if (this.parse) {
      this.takeTree();
      this.parse = null;
    }
  }
  /**
  Notify the parse scheduler that the given region was skipped
  because it wasn't in view, and the parse should be restarted
  when it comes into view.
  */
  skipUntilInView(from, to) {
    this.skipped.push({ from, to });
  }
  /**
  Returns a parser intended to be used as placeholder when
  asynchronously loading a nested parser. It'll skip its input and
  mark it as not-really-parsed, so that the next update will parse
  it again.
  
  When `until` is given, a reparse will be scheduled when that
  promise resolves.
  */
  static getSkippingParser(until) {
    return new class extends Parser2 {
      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 Tree2(NodeType.none, [], [], to - from);
          },
          stoppedAt: null,
          stopAt() {
          }
        };
        return parser;
      }
    }();
  }
  /**
  @internal
  */
  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;
  }
  /**
  Get the context for the current parse, or `null` if no editor
  parse is in progress.
  */
  static get() {
    return currentContext;
  }
};
function cutFragments(fragments, from, to) {
  return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]);
}
var LanguageState = class _LanguageState {
  constructor(context2) {
    this.context = context2;
    this.tree = context2.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);
  }
};
Language2.state = /* @__PURE__ */ StateField.define({
  create: LanguageState.init,
  update(value, tr) {
    for (let e3 of tr.effects)
      if (e3.is(Language2.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
    /* Work.MaxPause */
  );
  return () => clearTimeout(timeout);
};
if (typeof requestIdleCallback != "undefined")
  requestIdle = (callback) => {
    let idle = -1, timeout = setTimeout(
      () => {
        idle = requestIdleCallback(callback, {
          timeout: 500 - 100
          /* Work.MinPause */
        });
      },
      100
      /* Work.MinPause */
    );
    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(Language2.state).context;
    if (cx.updateViewport(update2.view.viewport) || this.view.viewport.to > cx.treeLen)
      this.scheduleWork();
    if (update2.docChanged || update2.selectionSet) {
      if (this.view.hasFocus)
        this.chunkBudget += 50;
      this.scheduleWork();
    }
    this.checkAsyncSchedule(cx);
  }
  scheduleWork() {
    if (this.working)
      return;
    let { state } = this.view, field = state.field(Language2.state);
    if (field.tree != field.context.tree || !field.context.isDone(state.doc.length))
      this.working = requestIdle(this.work);
  }
  work(deadline) {
    this.working = null;
    let now2 = Date.now();
    if (this.chunkEnd < now2 && (this.chunkEnd < 0 || this.view.hasFocus)) {
      this.chunkEnd = now2 + 3e4;
      this.chunkBudget = 3e3;
    }
    if (this.chunkBudget <= 0)
      return;
    let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language2.state);
    if (field.tree == field.context.tree && field.context.isDone(
      vpTo + 1e5
      /* Work.MaxParseAhead */
    ))
      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() - now2;
    if (done || this.chunkBudget <= 0) {
      field.context.takeTree();
      this.view.dispatch({ effects: Language2.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((err3) => logException(this.view.state, err3)).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) => [
    Language2.state,
    parseWorker,
    EditorView.contentAttributes.compute([language2], (state) => {
      let lang = state.facet(language2);
      return lang && lang.name ? { "data-language": lang.name } : {};
    })
  ]
});
var LanguageSupport = class {
  /**
  Create a language support object.
  */
  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 "  ";
    let unit2 = values[0];
    if (!unit2 || /\S/.test(unit2) || Array.from(unit2).some((e3) => e3 != unit2[0]))
      throw new Error("Invalid indent unit: " + JSON.stringify(values[0]));
    return unit2;
  }
});
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, ch = state.facet(indentUnit)[0];
  if (ch == "	") {
    while (cols >= ts) {
      result += "	";
      cols -= ts;
    }
    ch = " ";
  }
  for (let i = 0; i < cols; i++)
    result += ch;
  return result;
}
function getIndentation(context2, pos) {
  if (context2 instanceof EditorState)
    context2 = new IndentContext(context2);
  for (let service of context2.state.facet(indentService)) {
    let result = service(context2, pos);
    if (result !== void 0)
      return result;
  }
  let tree = syntaxTree(context2.state);
  return tree.length >= pos ? syntaxIndentation(context2, tree, pos) : null;
}
var IndentContext = class {
  /**
  Create an indent context.
  */
  constructor(state, options3 = {}) {
    this.state = state;
    this.options = options3;
    this.unit = getIndentUnit(state);
  }
  /**
  Get a description of the line at the given position, taking
  [simulated line
  breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
  into account. If there is such a break at `pos`, the `bias`
  argument determines whether the part of the line line before or
  after the break is used.
  */
  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;
  }
  /**
  Get the text directly after `pos`, either the entire line
  or the next 100 characters, whichever is shorter.
  */
  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));
  }
  /**
  Find the column for the given position.
  */
  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;
  }
  /**
  Find the column position (taking tabs into account) of the given
  position in the given string.
  */
  countColumn(line, pos = line.length) {
    return countColumn(line, this.state.tabSize, pos);
  }
  /**
  Find the indentation column of the line at the given point.
  */
  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|$/));
  }
  /**
  Returns the [simulated line
  break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
  for this context, if any.
  */
  get simulatedBreak() {
    return this.options.simulateBreak || null;
  }
};
var indentNodeProp = /* @__PURE__ */ new NodeProp();
function syntaxIndentation(cx, ast, pos) {
  let stack = ast.resolveStack(pos);
  let inner = stack.node.enterUnfinishedNodesBefore(pos);
  if (inner != stack.node) {
    let add3 = [];
    for (let cur2 = inner; cur2 != stack.node; cur2 = cur2.parent)
      add3.push(cur2);
    for (let i = add3.length - 1; i >= 0; i--)
      stack = { node: add3[i], next: stack };
  }
  return indentFor(stack, cx, pos);
}
function indentFor(stack, cx, pos) {
  for (let cur2 = stack; cur2; cur2 = cur2.next) {
    let strategy = indentStrategy(cur2.node);
    if (strategy)
      return strategy(TreeIndentContext.create(cx, pos, cur2));
  }
  return 0;
}
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 topIndent() {
  return 0;
}
var TreeIndentContext = class _TreeIndentContext extends IndentContext {
  constructor(base2, pos, context2) {
    super(base2.state, base2.options);
    this.base = base2;
    this.pos = pos;
    this.context = context2;
  }
  /**
  The syntax tree node to which the indentation strategy
  applies.
  */
  get node() {
    return this.context.node;
  }
  /**
  @internal
  */
  static create(base2, pos, context2) {
    return new _TreeIndentContext(base2, pos, context2);
  }
  /**
  Get the text directly after `this.pos`, either the entire line
  or the next 100 characters, whichever is shorter.
  */
  get textAfter() {
    return this.textAfterPos(this.pos);
  }
  /**
  Get the indentation at the reference line for `this.node`, which
  is the line on which it starts, unless there is a node that is
  _not_ a parent of this node covering the start of that line. If
  so, the line at the start of that node is tried, again skipping
  on if it is covered by another such node.
  */
  get baseIndent() {
    return this.baseIndentFor(this.node);
  }
  /**
  Get the indentation for the reference line of the given node
  (see [`baseIndent`](https://codemirror.net/6/docs/ref/#language.TreeIndentContext.baseIndent)).
  */
  baseIndentFor(node) {
    let line = this.state.doc.lineAt(node.from);
    for (; ; ) {
      let atBreak = node.resolve(line.from);
      while (atBreak.parent && atBreak.parent.from == atBreak.from)
        atBreak = atBreak.parent;
      if (isParent(atBreak, node))
        break;
      line = this.state.doc.lineAt(atBreak.from);
    }
    return this.lineIndent(line.from);
  }
  /**
  Continue looking for indentations in the node's parent nodes,
  and return the result of that.
  */
  continue() {
    return indentFor(this.context.next, this.base, this.pos);
  }
};
function isParent(parent2, of) {
  for (let cur2 = of; cur2; cur2 = cur2.parent)
    if (parent2 == cur2)
      return true;
  return false;
}
function bracketedAligned(context2) {
  let tree = context2.node;
  let openToken = tree.childAfter(tree.from), last = tree.lastChild;
  if (!openToken)
    return null;
  let sim = context2.options.simulateBreak;
  let openLine = context2.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(context2, align, units, closing2, closedAt) {
  let after = context2.textAfter, space2 = after.match(/^\s*/)[0].length;
  let closed = closing2 && after.slice(space2, space2 + closing2.length) == closing2 || closedAt == context2.pos + space2;
  let aligned = align ? bracketedAligned(context2) : null;
  if (aligned)
    return closed ? context2.column(aligned.from) : context2.column(aligned.to);
  return context2.baseIndent + (closed ? 0 : context2.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, start2, end) {
  let tree = syntaxTree(state);
  if (tree.length < end)
    return null;
  let stack = tree.resolveStack(end, 1);
  let found = null;
  for (let iter = stack; iter; iter = iter.next) {
    let cur2 = iter.node;
    if (cur2.to <= end || cur2.from > end)
      continue;
    if (found && cur2.from < start2)
      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 >= start2 && 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)) {
        let { preparePlaceholder } = tr.state.facet(foldConfig);
        let widget = !preparePlaceholder ? foldWidget : Decoration.replace({ widget: new PreparedFoldWidget(preparePlaceholder(tr.state, e3.value)) });
        folded = folded.update({ add: [widget.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,
  preparePlaceholder: 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;
}
function widgetToDOM(view, prepared) {
  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, prepared);
  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 foldWidget = /* @__PURE__ */ Decoration.replace({ widget: /* @__PURE__ */ new class extends WidgetType {
  toDOM(view) {
    return widgetToDOM(view, null);
  }
}() });
var PreparedFoldWidget = class extends WidgetType {
  constructor(value) {
    super();
    this.value = value;
  }
  eq(other) {
    return this.value == other.value;
  }
  toDOM(view) {
    return widgetToDOM(view, this.value);
  }
};
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 _HighlightStyle {
  constructor(specs, options3) {
    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 options3.all == "string" ? options3.all : options3.all ? def(options3.all) : void 0;
    const scopeOpt = options3.scope;
    this.scope = scopeOpt instanceof Language2 ? (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 = options3.themeType;
  }
  /**
  Create a highlighter style that associates the given styles to
  the given tags. The specs must be objects that hold a style tag
  or array of tags in their `tag` property, and either a single
  `class` property providing a static CSS class (for highlighter
  that rely on external styling), or a
  [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style
  set of CSS properties (which define the styling for those tags).
  
  The CSS rules created for a highlighter will be emitted in the
  order of the spec's properties. That means that for elements that
  have multiple tags associated with them, styles defined further
  down in the list will have a higher CSS precedence than styles
  defined earlier.
  */
  static define(specs, options3) {
    return new _HighlightStyle(specs, options3 || {});
  }
};
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, options3) {
  let ext2 = [treeHighlighter], themeType;
  if (highlighter instanceof HighlightStyle) {
    if (highlighter.module)
      ext2.push(EditorView.styleModule.of(highlighter.module));
    themeType = highlighter.themeType;
  }
  if (options3 === null || options3 === void 0 ? void 0 : options3.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));
    this.decoratedTo = view.viewport.to;
  }
  update(update2) {
    let tree = syntaxTree(update2.state), highlighters = getHighlighters(update2.state);
    let styleChange = highlighters != getHighlighters(update2.startState);
    let { viewport } = update2.view, decoratedToMapped = update2.changes.mapPos(this.decoratedTo, 1);
    if (tree.length < viewport.to && !styleChange && tree.type == this.tree.type && decoratedToMapped >= viewport.to) {
      this.decorations = this.decorations.map(update2.changes);
      this.decoratedTo = decoratedToMapped;
    } else if (tree != this.tree || update2.viewportChanged || styleChange) {
      this.tree = tree;
      this.decorations = this.buildDeco(update2.view, highlighters);
      this.decoratedTo = viewport.to;
    }
  }
  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: "#404740"
  },
  {
    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];
}
var bracketMatchingHandle = /* @__PURE__ */ new NodeProp();
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 findHandle(node) {
  let hasHandle = node.type.prop(bracketMatchingHandle);
  return hasHandle ? hasHandle(node.node) : node;
}
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) {
      let handle2 = findHandle(cur2);
      if (handle2 && (dir > 0 ? pos >= handle2.from && pos < handle2.to : pos > handle2.from && pos <= handle2.to))
        return matchMarkedBrackets(state, pos, dir, cur2, handle2, matches, brackets);
    }
  }
  return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets);
}
function matchMarkedBrackets(_state, _pos, dir, token, handle2, matching, brackets) {
  let parent2 = token.parent, firstToken = { from: handle2.from, to: handle2.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) {
          let endHandle = findHandle(cursor);
          return { start: firstToken, end: endHandle ? { from: endHandle.from, to: endHandle.to } : void 0, matched: true };
        } else if (matchingNodes(cursor.type, dir, brackets)) {
          depth++;
        } else if (matchingNodes(cursor.type, -dir, brackets)) {
          if (depth == 0) {
            let endHandle = findHandle(cursor);
            return {
              start: firstToken,
              end: endHandle && endHandle.from < endHandle.to ? { from: endHandle.from, to: endHandle.to } : void 0,
              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(string4, end, tabSize, startIndex = 0, startValue = 0) {
  if (end == null) {
    end = string4.search(/[^\s\u00a0]/);
    if (end == -1)
      end = string4.length;
  }
  let n = startValue;
  for (let i = startIndex; i < end; i++) {
    if (string4.charCodeAt(i) == 9)
      n += tabSize - n % tabSize;
    else
      n++;
  }
  return n;
}
var StringStream = class {
  /**
  Create a stream.
  */
  constructor(string4, tabSize, indentUnit2, overrideIndent) {
    this.string = string4;
    this.tabSize = tabSize;
    this.indentUnit = indentUnit2;
    this.overrideIndent = overrideIndent;
    this.pos = 0;
    this.start = 0;
    this.lastColumnPos = 0;
    this.lastColumnValue = 0;
  }
  /**
  True if we are at the end of the line.
  */
  eol() {
    return this.pos >= this.string.length;
  }
  /**
  True if we are at the start of the line.
  */
  sol() {
    return this.pos == 0;
  }
  /**
  Get the next code unit after the current position, or undefined
  if we're at the end of the line.
  */
  peek() {
    return this.string.charAt(this.pos) || void 0;
  }
  /**
  Read the next code unit and advance `this.pos`.
  */
  next() {
    if (this.pos < this.string.length)
      return this.string.charAt(this.pos++);
  }
  /**
  Match the next character against the given string, regular
  expression, or predicate. Consume and return it if it matches.
  */
  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;
    }
  }
  /**
  Continue matching characters that match the given string,
  regular expression, or predicate function. Return true if any
  characters were consumed.
  */
  eatWhile(match) {
    let start2 = this.pos;
    while (this.eat(match)) {
    }
    return this.pos > start2;
  }
  /**
  Consume whitespace ahead of `this.pos`. Return true if any was
  found.
  */
  eatSpace() {
    let start2 = this.pos;
    while (/[\s\u00a0]/.test(this.string.charAt(this.pos)))
      ++this.pos;
    return this.pos > start2;
  }
  /**
  Move to the end of the line.
  */
  skipToEnd() {
    this.pos = this.string.length;
  }
  /**
  Move to directly before the given character, if found on the
  current line.
  */
  skipTo(ch) {
    let found = this.string.indexOf(ch, this.pos);
    if (found > -1) {
      this.pos = found;
      return true;
    }
  }
  /**
  Move back `n` characters.
  */
  backUp(n) {
    this.pos -= n;
  }
  /**
  Get the column position at `this.pos`.
  */
  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;
  }
  /**
  Get the indentation column of the current line.
  */
  indentation() {
    var _a2;
    return (_a2 = this.overrideIndent) !== null && _a2 !== void 0 ? _a2 : countCol(this.string, null, this.tabSize);
  }
  /**
  Match the input against the given string or regular expression
  (which should start with a `^`). Return true or the regexp match
  if it matches.
  
  Unless `consume` is set to `false`, this will move `this.pos`
  past the matched text.
  
  When matching a string `caseInsensitive` can be set to true to
  make the match case-insensitive.
  */
  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;
    }
  }
  /**
  Get the current token.
  */
  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 IndentedFrom = /* @__PURE__ */ new WeakMap();
var StreamLanguage = class _StreamLanguage extends Language2 {
  constructor(parser) {
    let data = defineLanguageFacet(parser.languageData);
    let p = fullParser(parser), self2;
    let impl = new class extends Parser2 {
      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;
  }
  /**
  Define a stream language.
  */
  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 from = void 0;
    let { overrideIndentation } = cx.options;
    if (overrideIndentation) {
      from = IndentedFrom.get(cx.state);
      if (from != null && from < pos - 1e4)
        from = void 0;
    }
    let start2 = findState(this, tree, 0, at.from, from !== null && from !== void 0 ? from : pos), statePos, state;
    if (start2) {
      state = start2.state;
      statePos = start2.pos + 1;
    } else {
      state = this.streamParser.startState(cx.unit);
      statePos = 0;
    }
    if (pos - statePos > 1e4)
      return null;
    while (statePos < pos) {
      let line2 = cx.state.doc.lineAt(statePos), end = Math.min(pos, line2.to);
      if (line2.length) {
        let indentation = overrideIndentation ? overrideIndentation(line2.from) : -1;
        let stream = new StringStream(line2.text, cx.state.tabSize, cx.unit, indentation < 0 ? void 0 : indentation);
        while (stream.pos < end - line2.from)
          readToken(this.streamParser.token, stream, state);
      } else {
        this.streamParser.blankLine(state, cx.unit);
      }
      if (end == pos)
        break;
      statePos = line2.to + 1;
    }
    let line = cx.lineAt(pos);
    if (overrideIndentation && from == null)
      IndentedFrom.set(cx.state, line.from);
    return this.streamParser.indent(state, /^\s*(.*)/.exec(line.text)[1], cx);
  }
  get allowsNesting() {
    return false;
  }
};
function findState(lang, tree, off, startPos, before) {
  let state = off >= startPos && off + tree.length <= before && tree.prop(lang.stateAfter);
  if (state)
    return { state: lang.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 Tree2 && pos < before && findState(lang, child, pos, startPos, before);
    if (found)
      return found;
  }
  return null;
}
function cutTree(lang, tree, from, to, inside2) {
  if (inside2 && from <= 0 && to >= tree.length)
    return tree;
  if (!inside2 && tree.type == lang.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 Tree2) {
      if (!(inner = cutTree(lang, child, from - pos, to - pos, inside2)))
        break;
      return !inside2 ? inner : new Tree2(tree.type, tree.children.slice(0, i).concat(inner), tree.positions.slice(0, i + 1), pos + inner.length);
    }
  }
  return null;
}
function findStartInFragments(lang, 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(lang, f.tree, 0 - f.offset, startPos, to), tree;
    if (found && (tree = cutTree(lang, f.tree, startPos + f.offset, found.pos + f.offset, false)))
      return { state: found.state, tree };
  }
  return { state: lang.streamParser.startState(editorState ? getIndentUnit(editorState) : 4), tree: Tree2.empty };
}
var Parse = class {
  constructor(lang, input, fragments, ranges) {
    this.lang = lang;
    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 context2 = ParseContext.get(), from = ranges[0].from;
    let { state, tree } = findStartInFragments(lang, fragments, from, context2 === null || context2 === void 0 ? void 0 : context2.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 (context2 && this.parsedPos < context2.viewport.from - 1e5) {
      this.state = this.lang.streamParser.startState(getIndentUnit(context2.state));
      context2.skipUntilInView(this.parsedPos, context2.viewport.from);
      this.parsedPos = context2.viewport.from;
    }
    this.moveRangeIndex();
  }
  advance() {
    let context2 = ParseContext.get();
    let parseEnd = this.stoppedAt == null ? this.to : Math.min(this.to, this.stoppedAt);
    let end = Math.min(
      parseEnd,
      this.chunkStart + 2048
      /* C.ChunkSize */
    );
    if (context2)
      end = Math.min(end, context2.viewport.to);
    while (this.parsedPos < end)
      this.parseLine(context2);
    if (this.chunkStart < this.parsedPos)
      this.finishChunk();
    if (this.parsedPos >= parseEnd)
      return this.finish();
    if (context2 && this.parsedPos >= context2.viewport.to) {
      context2.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 start2 = this.ranges[++this.rangeIndex].from;
      offset += start2 - end;
    }
    return offset;
  }
  moveRangeIndex() {
    while (this.ranges[this.rangeIndex].to < this.parsedPos)
      this.rangeIndex++;
  }
  emitToken(id2, 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(id2, from, to, size);
    return offset;
  }
  parseLine(context2) {
    let { line, end } = this.nextLine(), offset = 0, { streamParser } = this.lang;
    let stream = new StringStream(line, context2 ? context2.state.tabSize : 4, context2 ? getIndentUnit(context2.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 = Tree2.build({
      buffer: this.chunk,
      start: this.chunkStart,
      length: this.parsedPos - this.chunkStart,
      nodeSet,
      topID: 0,
      maxBufferLength: 2048,
      reused: this.chunkReused
    });
    tree = new Tree2(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 Tree2(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 byTag = /* @__PURE__ */ Object.create(null);
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(tag) {
    return !tag ? 0 : this.table[tag] || (this.table[tag] = createTokenType(this.extra, tag));
  }
};
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 tags$1 = [];
  for (let name3 of tagStr.split(" ")) {
    let found = [];
    for (let part of name3.split(".")) {
      let value = extra[part] || tags2[part];
      if (!value) {
        warnForPart(part, `Unknown highlighting tag ${part}`);
      } else if (typeof value == "function") {
        if (!found.length)
          warnForPart(part, `Modifier ${part} used at start of tag`);
        else
          found = found.map(value);
      } else {
        if (found.length)
          warnForPart(part, `Tag ${part} used as modifier`);
        else
          found = Array.isArray(value) ? value : [value];
      }
    }
    for (let tag of found)
      tags$1.push(tag);
  }
  if (!tags$1.length)
    return 0;
  let name2 = tagStr.replace(/ /g, "_"), key2 = name2 + " " + tags$1.map((t4) => t4.id);
  let known = byTag[key2];
  if (known)
    return known.id;
  let type = byTag[key2] = NodeType.define({
    id: typeArray.length,
    name: name2,
    props: [styleTags({ [name2]: tags$1 })]
  });
  typeArray.push(type);
  return type.id;
}
function docID(data) {
  let type = NodeType.define({ id: typeArray.length, name: "Document", props: [languageDataProp.add(() => data)], top: true });
  typeArray.push(type);
  return type;
}
var marks = {
  rtl: /* @__PURE__ */ Decoration.mark({ class: "cm-iso", inclusive: true, attributes: { dir: "rtl" }, bidiIsolate: Direction.RTL }),
  ltr: /* @__PURE__ */ Decoration.mark({ class: "cm-iso", inclusive: true, attributes: { dir: "ltr" }, bidiIsolate: Direction.LTR }),
  auto: /* @__PURE__ */ Decoration.mark({ class: "cm-iso", inclusive: true, attributes: { dir: "auto" }, bidiIsolate: null })
};

// node_modules/@codemirror/autocomplete/dist/index.js
var CompletionContext = class {
  /**
  Create a new completion context. (Mostly useful for testing
  completion sources—in the editor, the extension will create
  these for you.)
  */
  constructor(state, pos, explicit) {
    this.state = state;
    this.pos = pos;
    this.explicit = explicit;
    this.abortListeners = [];
  }
  /**
  Get the extent, content, and (if there is a token) type of the
  token before `this.pos`.
  */
  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;
  }
  /**
  Get the match of the given expression directly before the
  cursor.
  */
  matchBefore(expr) {
    let line = this.state.doc.lineAt(this.pos);
    let start2 = Math.max(line.from, this.pos - 250);
    let str = line.text.slice(start2 - line.from, this.pos - line.from);
    let found = str.search(ensureAnchor(expr, false));
    return found < 0 ? null : { from: start2 + found, to: this.pos, text: str.slice(found) };
  }
  /**
  Yields true when the query has been aborted. Can be useful in
  asynchronous queries to avoid doing work that will be ignored.
  */
  get aborted() {
    return this.abortListeners == null;
  }
  /**
  Allows you to register abort handlers, which will be called when
  the query is
  [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
  */
  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(options3) {
  let first = /* @__PURE__ */ Object.create(null), rest = /* @__PURE__ */ Object.create(null);
  for (let { label } of options3) {
    first[label[0]] = true;
    for (let i = 1; i < label.length; i++)
      rest[label[i]] = true;
  }
  let source2 = toSet(first) + toSet(rest) + "*$";
  return [new RegExp("^" + source2), new RegExp(source2)];
}
function completeFromList(list) {
  let options3 = list.map((o) => typeof o == "string" ? { label: o } : o);
  let [validFor, match] = options3.every((o) => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options3);
  return (context2) => {
    let token = context2.matchBefore(match);
    return token || context2.explicit ? { from: token ? token.from : context2.pos, options: options3, validFor } : null;
  };
}
var Option = class {
  constructor(completion, source2, match, score2) {
    this.completion = completion;
    this.source = source2;
    this.match = match;
    this.score = score2;
  }
};
function cur(state) {
  return state.selection.main.from;
}
function ensureAnchor(expr, start2) {
  var _a2;
  let { source: source2 } = expr;
  let addStart = start2 && source2[0] != "^", addEnd = source2[source2.length - 1] != "$";
  if (!addStart && !addEnd)
    return expr;
  return new RegExp(`${addStart ? "^" : ""}(?:${source2})${addEnd ? "$" : ""}`, (_a2 = expr.flags) !== null && _a2 !== void 0 ? _a2 : expr.ignoreCase ? "i" : "");
}
var pickedCompletion = /* @__PURE__ */ Annotation.define();
function insertCompletionText(state, text2, from, to) {
  let { main } = state.selection, fromOff = from - main.from, toOff = to - main.from;
  return Object.assign(Object.assign({}, state.changeByRange((range2) => {
    if (range2 != main && from != to && state.sliceDoc(range2.from + fromOff, range2.from + toOff) != state.sliceDoc(from, to))
      return { range: range2 };
    return {
      changes: { from: range2.from + fromOff, to: to == main.from ? range2.to : range2.from + toOff, insert: text2 },
      range: EditorSelection.cursor(range2.from + fromOff + text2.length)
    };
  })), { scrollIntoView: true, userEvent: "input.complete" });
}
var SourceCache = /* @__PURE__ */ new WeakMap();
function asSource(source2) {
  if (!Array.isArray(source2))
    return source2;
  let known = SourceCache.get(source2);
  if (!known)
    SourceCache.set(source2, known = completeFromList(source2));
  return known;
}
var startCompletionEffect = /* @__PURE__ */ StateEffect.define();
var closeCompletionEffect = /* @__PURE__ */ StateEffect.define();
var FuzzyMatcher = class {
  constructor(pattern) {
    this.pattern = pattern;
    this.chars = [];
    this.folded = [];
    this.any = [];
    this.precise = [];
    this.byWord = [];
    this.score = 0;
    this.matched = [];
    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;
  }
  ret(score2, matched) {
    this.score = score2;
    this.matched = matched;
    return true;
  }
  // Matches a given word (completion) against the pattern (input).
  // Will return a boolean indicating whether there was a match and,
  // on success, set `this.score` to the score, `this.matched` to an
  // array of `from, to` pairs indicating the matched parts of `word`.
  //
  // The score is a number that is more negative the worse the match
  // is. See `Penalty` above.
  match(word) {
    if (this.pattern.length == 0)
      return this.ret(-100, []);
    if (word.length < this.pattern.length)
      return false;
    let { chars, folded, any, precise, byWord } = this;
    if (chars.length == 1) {
      let first = codePointAt(word, 0), firstSize = codePointSize(first);
      let score2 = firstSize == word.length ? 0 : -100;
      if (first == chars[0])
        ;
      else if (first == folded[0])
        score2 += -200;
      else
        return false;
      return this.ret(score2, [0, firstSize]);
    }
    let direct = word.indexOf(this.pattern);
    if (direct == 0)
      return this.ret(word.length == this.pattern.length ? 0 : -100, [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 false;
    }
    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 this.ret(-200 - word.length + (adjacentEnd == word.length ? 0 : -100), [0, adjacentEnd]);
    if (direct > -1)
      return this.ret(-700 - word.length, [direct, direct + this.pattern.length]);
    if (adjacentTo == len)
      return this.ret(-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 ? false : this.result((any[0] ? -700 : 0) + -200 + -1100, any, word);
  }
  result(score2, positions, word) {
    let result = [], i = 0;
    for (let pos of positions) {
      let to = pos + (this.astral ? codePointSize(codePointAt(word, pos)) : 1);
      if (i && result[i - 1] == pos)
        result[i - 1] = to;
      else {
        result[i++] = pos;
        result[i++] = to;
      }
    }
    return this.ret(score2 - word.length, result);
  }
};
var completionConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      activateOnTyping: true,
      activateOnTypingDelay: 100,
      selectOnOpen: true,
      override: null,
      closeOnBlur: true,
      maxRenderedOptions: 100,
      defaultKeymap: true,
      tooltipClass: () => "",
      optionClass: () => "",
      aboveCursor: false,
      icons: true,
      addToOptions: [],
      positionInfo: defaultPositionInfo,
      compareCompletions: (a, b) => a.label.localeCompare(b.label),
      interactionDelay: 75,
      updateSyncTime: 100
    }, {
      defaultKeymap: (a, b) => a && b,
      closeOnBlur: (a, b) => a && b,
      icons: (a, b) => a && b,
      tooltipClass: (a, b) => (c) => joinClass(a(c), b(c)),
      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 defaultPositionInfo(view, list, option, info2, space2, tooltip2) {
  let rtl = view.textDirection == Direction.RTL, left2 = rtl, narrow = false;
  let side = "top", offset, maxWidth;
  let spaceLeft = list.left - space2.left, spaceRight = space2.right - list.right;
  let infoWidth = info2.right - info2.left, infoHeight = info2.bottom - info2.top;
  if (left2 && spaceLeft < Math.min(infoWidth, spaceRight))
    left2 = false;
  else if (!left2 && spaceRight < Math.min(infoWidth, spaceLeft))
    left2 = true;
  if (infoWidth <= (left2 ? spaceLeft : spaceRight)) {
    offset = Math.max(space2.top, Math.min(option.top, space2.bottom - infoHeight)) - list.top;
    maxWidth = Math.min(400, left2 ? spaceLeft : spaceRight);
  } else {
    narrow = true;
    maxWidth = Math.min(
      400,
      (rtl ? list.right : space2.right - list.left) - 30
      /* Info.Margin */
    );
    let spaceBelow = space2.bottom - list.bottom;
    if (spaceBelow >= infoHeight || spaceBelow > list.top) {
      offset = option.bottom - list.top;
    } else {
      side = "bottom";
      offset = list.bottom - option.top;
    }
  }
  let scaleY = (list.bottom - list.top) / tooltip2.offsetHeight;
  let scaleX = (list.right - list.left) / tooltip2.offsetWidth;
  return {
    style: `${side}: ${offset / scaleY}px; max-width: ${maxWidth / scaleX}px`,
    class: "cm-completionInfo-" + (narrow ? rtl ? "left-narrow" : "right-narrow" : left2 ? "left" : "right")
  };
}
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, _v, match) {
      let labelElt = document.createElement("span");
      labelElt.className = "cm-completionLabel";
      let label = completion.displayLabel || completion.label, off = 0;
      for (let j = 0; 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, applyCompletion2) {
    this.view = view;
    this.stateField = stateField;
    this.applyCompletion = applyCompletion2;
    this.info = null;
    this.infoDestroy = null;
    this.placeInfoReq = {
      read: () => this.measureInfo(),
      write: (pos) => this.placeInfo(pos),
      key: this
    };
    this.space = null;
    this.currentClass = "";
    let cState = view.state.field(stateField);
    let { options: options3, selected } = cState.open;
    let config2 = view.state.facet(completionConfig);
    this.optionContent = optionContent(config2);
    this.optionClass = config2.optionClass;
    this.tooltipClass = config2.tooltipClass;
    this.range = rangeAroundSelected(options3.length, selected, config2.maxRenderedOptions);
    this.dom = document.createElement("div");
    this.dom.className = "cm-tooltip-autocomplete";
    this.updateTooltipClass(view.state);
    this.dom.addEventListener("mousedown", (e3) => {
      let { options: options4 } = view.state.field(stateField).open;
      for (let dom = e3.target, match; dom && dom != this.dom; dom = dom.parentNode) {
        if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options4.length) {
          this.applyCompletion(view, options4[+match[1]]);
          e3.preventDefault();
          return;
        }
      }
    });
    this.dom.addEventListener("focusout", (e3) => {
      let state = view.state.field(this.stateField, false);
      if (state && state.tooltip && view.state.facet(completionConfig).closeOnBlur && e3.relatedTarget != view.contentDOM)
        view.dispatch({ effects: closeCompletionEffect.of(null) });
    });
    this.showOptions(options3, cState.id);
  }
  mount() {
    this.updateSel();
  }
  showOptions(options3, id2) {
    if (this.list)
      this.list.remove();
    this.list = this.dom.appendChild(this.createListBox(options3, id2, this.range));
    this.list.addEventListener("scroll", () => {
      if (this.info)
        this.view.requestMeasure(this.placeInfoReq);
    });
  }
  update(update2) {
    var _a2;
    let cState = update2.state.field(this.stateField);
    let prevState = update2.startState.field(this.stateField);
    this.updateTooltipClass(update2.state);
    if (cState != prevState) {
      let { options: options3, selected, disabled } = cState.open;
      if (!prevState.open || prevState.open.options != options3) {
        this.range = rangeAroundSelected(options3.length, selected, update2.state.facet(completionConfig).maxRenderedOptions);
        this.showOptions(options3, cState.id);
      }
      this.updateSel();
      if (disabled != ((_a2 = prevState.open) === null || _a2 === void 0 ? void 0 : _a2.disabled))
        this.dom.classList.toggle("cm-tooltip-autocomplete-disabled", !!disabled);
    }
  }
  updateTooltipClass(state) {
    let cls = this.tooltipClass(state);
    if (cls != this.currentClass) {
      for (let c of this.currentClass.split(" "))
        if (c)
          this.dom.classList.remove(c);
      for (let c of cls.split(" "))
        if (c)
          this.dom.classList.add(c);
      this.currentClass = cls;
    }
  }
  positioned(space2) {
    this.space = space2;
    if (this.info)
      this.view.requestMeasure(this.placeInfoReq);
  }
  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.showOptions(open.options, cState.id);
    }
    if (this.updateSelectedOption(open.selected)) {
      this.destroyInfo();
      let { completion } = open.options[open.selected];
      let { info: info2 } = completion;
      if (!info2)
        return;
      let infoResult = typeof info2 === "string" ? document.createTextNode(info2) : info2(completion);
      if (!infoResult)
        return;
      if ("then" in infoResult) {
        infoResult.then((obj) => {
          if (obj && this.view.state.field(this.stateField, false) == cState)
            this.addInfoPane(obj, completion);
        }).catch((e3) => logException(this.view.state, e3, "completion info"));
      } else {
        this.addInfoPane(infoResult, completion);
      }
    }
  }
  addInfoPane(content2, completion) {
    this.destroyInfo();
    let wrap = this.info = document.createElement("div");
    wrap.className = "cm-tooltip cm-completionInfo";
    if (content2.nodeType != null) {
      wrap.appendChild(content2);
      this.infoDestroy = null;
    } else {
      let { dom, destroy } = content2;
      wrap.appendChild(dom);
      this.infoDestroy = destroy || null;
    }
    this.dom.appendChild(wrap);
    this.view.requestMeasure(this.placeInfoReq);
  }
  updateSelectedOption(selected) {
    let set2 = null;
    for (let opt = this.list.firstChild, i = this.range.from; opt; opt = opt.nextSibling, i++) {
      if (opt.nodeName != "LI" || !opt.id) {
        i--;
      } else if (i == selected) {
        if (!opt.hasAttribute("aria-selected")) {
          opt.setAttribute("aria-selected", "true");
          set2 = opt;
        }
      } else {
        if (opt.hasAttribute("aria-selected"))
          opt.removeAttribute("aria-selected");
      }
    }
    if (set2)
      scrollIntoView2(this.list, set2);
    return set2;
  }
  measureInfo() {
    let sel = this.dom.querySelector("[aria-selected]");
    if (!sel || !this.info)
      return null;
    let listRect = this.dom.getBoundingClientRect();
    let infoRect = this.info.getBoundingClientRect();
    let selRect = sel.getBoundingClientRect();
    let space2 = this.space;
    if (!space2) {
      let win = this.dom.ownerDocument.defaultView || window;
      space2 = { left: 0, top: 0, right: win.innerWidth, bottom: win.innerHeight };
    }
    if (selRect.top > Math.min(space2.bottom, listRect.bottom) - 10 || selRect.bottom < Math.max(space2.top, listRect.top) + 10)
      return null;
    return this.view.state.facet(completionConfig).positionInfo(this.view, listRect, selRect, infoRect, space2, this.dom);
  }
  placeInfo(pos) {
    if (this.info) {
      if (pos) {
        if (pos.style)
          this.info.style.cssText = pos.style;
        this.info.className = "cm-tooltip cm-completionInfo " + (pos.class || "");
      } else {
        this.info.style.cssText = "top: -1e6px";
      }
    }
  }
  createListBox(options3, id2, range2) {
    const ul = document.createElement("ul");
    ul.id = id2;
    ul.setAttribute("role", "listbox");
    ul.setAttribute("aria-expanded", "true");
    ul.setAttribute("aria-label", this.view.state.phrase("Completions"));
    let curSection = null;
    for (let i = range2.from; i < range2.to; i++) {
      let { completion, match } = options3[i], { section } = completion;
      if (section) {
        let name2 = typeof section == "string" ? section : section.name;
        if (name2 != curSection && (i > range2.from || range2.from == 0)) {
          curSection = name2;
          if (typeof section != "string" && section.header) {
            ul.appendChild(section.header(section));
          } else {
            let header = ul.appendChild(document.createElement("completion-section"));
            header.textContent = name2;
          }
        }
      }
      const li = ul.appendChild(document.createElement("li"));
      li.id = id2 + "-" + i;
      li.setAttribute("role", "option");
      let cls = this.optionClass(completion);
      if (cls)
        li.className = cls;
      for (let source2 of this.optionContent) {
        let node = source2(completion, this.view.state, this.view, match);
        if (node)
          li.appendChild(node);
      }
    }
    if (range2.from)
      ul.classList.add("cm-completionListIncompleteTop");
    if (range2.to < options3.length)
      ul.classList.add("cm-completionListIncompleteBottom");
    return ul;
  }
  destroyInfo() {
    if (this.info) {
      if (this.infoDestroy)
        this.infoDestroy();
      this.info.remove();
      this.info = null;
    }
  }
  destroy() {
    this.destroyInfo();
  }
};
function completionTooltip(stateField, applyCompletion2) {
  return (view) => new CompletionTooltip(view, stateField, applyCompletion2);
}
function scrollIntoView2(container, element2) {
  let parent2 = container.getBoundingClientRect();
  let self2 = element2.getBoundingClientRect();
  let scaleY = parent2.height / container.offsetHeight;
  if (self2.top < parent2.top)
    container.scrollTop -= (parent2.top - self2.top) / scaleY;
  else if (self2.bottom > parent2.bottom)
    container.scrollTop += (self2.bottom - parent2.bottom) / scaleY;
}
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 options3 = [];
  let sections = null;
  let addOption = (option) => {
    options3.push(option);
    let { section } = option.completion;
    if (section) {
      if (!sections)
        sections = [];
      let name2 = typeof section == "string" ? section : section.name;
      if (!sections.some((s) => s.name == name2))
        sections.push(typeof section == "string" ? { name: name2 } : section);
    }
  };
  for (let a of active)
    if (a.hasResult()) {
      let getMatch = a.result.getMatch;
      if (a.result.filter === false) {
        for (let option of a.result.options) {
          addOption(new Option(option, a.source, getMatch ? getMatch(option) : [], 1e9 - options3.length));
        }
      } else {
        let matcher2 = new FuzzyMatcher(state.sliceDoc(a.from, a.to));
        for (let option of a.result.options)
          if (matcher2.match(option.label)) {
            let matched = !option.displayLabel ? matcher2.matched : getMatch ? getMatch(option, matcher2.matched) : [];
            addOption(new Option(option, a.source, matched, matcher2.score + (option.boost || 0)));
          }
      }
    }
  if (sections) {
    let sectionOrder = /* @__PURE__ */ Object.create(null), pos = 0;
    let cmp = (a, b) => {
      var _a2, _b;
      return ((_a2 = a.rank) !== null && _a2 !== void 0 ? _a2 : 1e9) - ((_b = b.rank) !== null && _b !== void 0 ? _b : 1e9) || (a.name < b.name ? -1 : 1);
    };
    for (let s of sections.sort(cmp)) {
      pos -= 1e5;
      sectionOrder[s.name] = pos;
    }
    for (let option of options3) {
      let { section } = option.completion;
      if (section)
        option.score += sectionOrder[typeof section == "string" ? section : section.name];
    }
  }
  let result = [], prev = null;
  let compare2 = state.facet(completionConfig).compareCompletions;
  for (let opt of options3.sort((a, b) => b.score - a.score || compare2(a.completion, b.completion))) {
    let cur2 = opt.completion;
    if (!prev || prev.label != cur2.label || prev.detail != cur2.detail || prev.type != null && cur2.type != null && prev.type != cur2.type || prev.apply != cur2.apply || prev.boost != cur2.boost)
      result.push(opt);
    else if (score(opt.completion) > score(prev))
      result[result.length - 1] = opt;
    prev = opt.completion;
  }
  return result;
}
var CompletionDialog = class _CompletionDialog {
  constructor(options3, attrs, tooltip2, timestamp, selected, disabled) {
    this.options = options3;
    this.attrs = attrs;
    this.tooltip = tooltip2;
    this.timestamp = timestamp;
    this.selected = selected;
    this.disabled = disabled;
  }
  setSelected(selected, id2) {
    return selected == this.selected || selected >= this.options.length ? this : new _CompletionDialog(this.options, makeAttrs(id2, selected), this.tooltip, this.timestamp, selected, this.disabled);
  }
  static build(active, state, id2, prev, conf) {
    let options3 = sortOptions(active, state);
    if (!options3.length) {
      return prev && active.some(
        (a) => a.state == 1
        /* State.Pending */
      ) ? new _CompletionDialog(prev.options, prev.attrs, prev.tooltip, prev.timestamp, prev.selected, true) : 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 < options3.length; i++)
        if (options3[i].completion == selectedValue) {
          selected = i;
          break;
        }
    }
    return new _CompletionDialog(options3, makeAttrs(id2, selected), {
      pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8),
      create: createTooltip,
      above: conf.aboveCursor
    }, prev ? prev.timestamp : Date.now(), selected, false);
  }
  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, this.disabled);
  }
};
var CompletionState = class _CompletionState {
  constructor(active, id2, open) {
    this.active = active;
    this.id = id2;
    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((source2) => {
      let value = this.active.find((s) => s.source == source2) || new ActiveSource(
        source2,
        this.active.some(
          (a) => a.state != 0
          /* State.Inactive */
        ) ? 1 : 0
        /* State.Inactive */
      );
      return value.update(tr, conf);
    });
    if (active.length == this.active.length && active.every((a, i) => a == this.active[i]))
      active = this.active;
    let open = this.open;
    if (open && tr.docChanged)
      open = open.map(tr.changes);
    if (tr.selection || active.some((a) => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) || !sameResults(active, this.active))
      open = CompletionDialog.build(active, state, this.id, open, conf);
    else if (open && open.disabled && !active.some(
      (a) => a.state == 1
      /* State.Pending */
    ))
      open = null;
    if (!open && active.every(
      (a) => a.state != 1
      /* State.Pending */
    ) && active.some((a) => a.hasResult()))
      active = active.map((a) => a.hasResult() ? new ActiveSource(
        a.source,
        0
        /* State.Inactive */
      ) : 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(id2, selected) {
  let result = {
    "aria-autocomplete": "list",
    "aria-haspopup": "listbox",
    "aria-controls": id2
  };
  if (selected > -1)
    result["aria-activedescendant"] = id2 + "-" + selected;
  return result;
}
var none2 = [];
function getUserEvent(tr) {
  return tr.isUserEvent("input.type") ? "input" : tr.isUserEvent("delete.backward") ? "delete" : null;
}
var ActiveSource = class _ActiveSource {
  constructor(source2, state, explicitPos = -1) {
    this.source = source2;
    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
        /* State.Inactive */
      );
    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
          /* State.Inactive */
        );
      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
      /* State.Pending */
    );
  }
  handleChange(tr) {
    return tr.changes.touchesRange(cur(tr.startState)) ? new _ActiveSource(
      this.source,
      0
      /* State.Inactive */
    ) : 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 _ActiveResult extends ActiveSource {
  constructor(source2, explicitPos, result, from, to) {
    super(source2, 2, explicitPos);
    this.result = result;
    this.from = from;
    this.to = to;
  }
  hasResult() {
    return true;
  }
  handleUserEvent(tr, type, conf) {
    var _a2;
    let result = this.result;
    if (result.map && !tr.changes.empty)
      result = result.map(result, tr.changes);
    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 || !result || type == "delete" && cur(tr.startState) == this.from)
      return new ActiveSource(
        this.source,
        type == "input" && conf.activateOnTyping ? 1 : 0
        /* State.Inactive */
      );
    let explicitPos = this.explicitPos < 0 ? -1 : tr.changes.mapPos(this.explicitPos);
    if (checkValid(result.validFor, tr.state, from, to))
      return new _ActiveResult(this.source, explicitPos, result, from, to);
    if (result.update && (result = result.update(result, from, to, new CompletionContext(tr.state, pos, explicitPos >= 0))))
      return new _ActiveResult(this.source, explicitPos, result, result.from, (_a2 = result.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
      /* State.Inactive */
    ) : this.map(tr.changes);
  }
  map(mapping) {
    if (mapping.empty)
      return this;
    let result = this.result.map ? this.result.map(this.result, mapping) : this.result;
    if (!result)
      return new ActiveSource(
        this.source,
        0
        /* State.Inactive */
      );
    return 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 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 applyCompletion(view, option) {
  const apply = option.completion.apply || option.completion.label;
  let result = view.state.field(completionState).active.find((a) => a.source == option.source);
  if (!(result instanceof ActiveResult))
    return false;
  if (typeof apply == "string")
    view.dispatch(Object.assign(Object.assign({}, insertCompletionText(view.state, apply, result.from, result.to)), { annotations: pickedCompletion.of(option.completion) }));
  else
    apply(view, option.completion, result.from, result.to);
  return true;
}
var createTooltip = /* @__PURE__ */ completionTooltip(completionState, applyCompletion);
function moveCompletionSelection(forward, by = "option") {
  return (view) => {
    let cState = view.state.field(completionState, false);
    if (!cState || !cState.open || cState.open.disabled || 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 || cState.open.disabled || Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay)
    return false;
  return applyCompletion(view, cState.open.options[cState.open.selected]);
};
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
    /* State.Inactive */
  ))
    return false;
  view.dispatch({ effects: closeCompletionEffect.of(null) });
  return true;
};
var RunningQuery = class {
  constructor(active, context2) {
    this.active = active;
    this.context = context2;
    this.time = Date.now();
    this.updates = [];
    this.done = void 0;
  }
};
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.pendingStart = false;
    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);
    if (update2.transactions.some((tr) => tr.effects.some((e3) => e3.is(startCompletionEffect))))
      this.pendingStart = true;
    let delay = this.pendingStart ? 50 : update2.state.facet(completionConfig).activateOnTypingDelay;
    this.debounceUpdate = cState.active.some((a) => a.state == 1 && !this.running.some((q) => q.active.source == a.source)) ? setTimeout(() => this.startUpdate(), delay) : -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;
    this.pendingStart = false;
    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 context2 = new CompletionContext(state, pos, active.explicitPos == pos);
    let pending = new RunningQuery(active, context2);
    this.running.push(pending);
    Promise.resolve(active.source(context2)).then((result) => {
      if (!pending.context.aborted) {
        pending.done = result || null;
        this.scheduleAccept();
      }
    }, (err3) => {
      this.view.dispatch({ effects: closeCompletionEffect.of(null) });
      logException(this.view.state, err3);
    });
  }
  scheduleAccept() {
    if (this.running.every((q) => q.done !== void 0))
      this.accept();
    else if (this.debounceAccept < 0)
      this.debounceAccept = setTimeout(() => this.accept(), this.view.state.facet(completionConfig).updateSyncTime);
  }
  // For each finished query in this.running, try to create a result
  // or, if appropriate, restart the query.
  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
            /* State.Inactive */
          );
          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(event) {
      let state = this.view.state.field(completionState, false);
      if (state && state.tooltip && this.view.state.facet(completionConfig).closeOnBlur) {
        let dialog = state.open && getTooltip(this.view, state.open.tooltip);
        if (!dialog || !dialog.dom.contains(event.relatedTarget))
          setTimeout(() => this.view.dispatch({ effects: closeCompletionEffect.of(null) }), 10);
      }
    },
    compositionstart() {
      this.composing = 1;
    },
    compositionend() {
      if (this.composing == 3) {
        setTimeout(() => this.view.dispatch({ effects: startCompletionEffect.of(false) }), 20);
      }
      this.composing = 0;
    }
  }
});
var windows = typeof navigator == "object" && /* @__PURE__ */ /Win/.test(navigator.platform);
var commitCharacters = /* @__PURE__ */ Prec.highest(/* @__PURE__ */ EditorView.domEventHandlers({
  keydown(event, view) {
    let field = view.state.field(completionState, false);
    if (!field || !field.open || field.open.disabled || field.open.selected < 0 || event.key.length > 1 || event.ctrlKey && !(windows && event.altKey) || event.metaKey)
      return false;
    let option = field.open.options[field.open.selected];
    let result = field.active.find((a) => a.source == option.source);
    let commitChars = option.completion.commitCharacters || result.result.commitCharacters;
    if (commitChars && commitChars.indexOf(event.key) > -1)
      applyCompletion(view, option);
    return false;
  }
}));
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",
      height: "100%",
      listStyle: "none",
      margin: 0,
      padding: 0,
      "& > li, & > completion-section": {
        padding: "1px 3px",
        lineHeight: 1.2
      },
      "& > li": {
        overflowX: "hidden",
        textOverflow: "ellipsis",
        cursor: "pointer"
      },
      "& > completion-section": {
        display: "list-item",
        borderBottom: "1px solid silver",
        paddingLeft: "0.5em",
        opacity: 0.7
      }
    }
  },
  "&light .cm-tooltip-autocomplete ul li[aria-selected]": {
    background: "#17c",
    color: "white"
  },
  "&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]": {
    background: "#777"
  },
  "&dark .cm-tooltip-autocomplete ul li[aria-selected]": {
    background: "#347",
    color: "white"
  },
  "&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]": {
    background: "#444"
  },
  ".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",
    boxSizing: "content-box"
  },
  ".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'" }
    // Disable emoji rendering
  },
  ".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 _FieldRange {
  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 _Snippet {
  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 _ActiveSnippet {
  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 (editor2, completion, from, to) => {
    let { text: text2, ranges } = snippet2.instantiate(editor2.state, from);
    let spec = {
      changes: { from, to, insert: Text.of(text2) },
      scrollIntoView: true,
      annotations: completion ? [pickedCompletion.of(completion), Transaction2.userEvent.of("input.complete")] : void 0
    };
    if (ranges.length)
      spec.selection = fieldSelection(ranges, 0);
    if (ranges.some((r) => r.field > 0)) {
      let active = new ActiveSnippet(ranges, 0);
      let effects = spec.effects = [setActive.of(active)];
      if (editor2.state.field(snippetState, false) === void 0)
        effects.push(StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme3]));
    }
    editor2.dispatch(editor2.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)),
      scrollIntoView: true
    }));
    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),
      scrollIntoView: true
    });
    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 closedBracket = /* @__PURE__ */ new class extends RangeValue {
}();
closedBracket.startSide = 1;
closedBracket.endSide = -1;
var bracketState = /* @__PURE__ */ StateField.define({
  create() {
    return RangeSet.empty;
  },
  update(value, tr) {
    value = value.map(tr.changes);
    if (tr.selection) {
      let line = tr.state.doc.lineAt(tr.selection.main.head);
      value = value.update({ filter: (from) => from >= line.from && from <= line.to });
    }
    for (let effect of tr.effects)
      if (effect.is(closeBracketEffect))
        value = value.update({ add: [closedBracket.range(effect.value, effect.value + 1)] });
    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, changes = state.changeByRange((range2) => {
    if (range2.empty && nextChar(state.doc, range2.head) == close)
      return {
        changes: { from: range2.head, to: range2.head + close.length, insert: close },
        range: EditorSelection.cursor(range2.head + close.length)
      };
    return dont = { range: range2 };
  });
  return dont ? null : state.update(changes, {
    scrollIntoView: true,
    userEvent: "input.type"
  });
}
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), start2;
    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;
        let content2 = isTriple ? token + token + token : token;
        return {
          changes: { from: pos, to: pos + content2.length, insert: content2 },
          range: EditorSelection.cursor(pos + content2.length)
        };
      }
    } else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token && (start2 = canStartStringAt(state, pos - 2 * token.length, stringPrefixes)) > -1 && nodeStart(state, start2)) {
      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 start2 = state.sliceDoc(node.from, Math.min(node.to, node.from + quoteToken.length + maxPrefix));
    let quotePos = start2.indexOf(quoteToken);
    if (!quotePos || quotePos > -1 && prefixes2.indexOf(start2.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 start2 = pos - prefix.length;
    if (state.sliceDoc(start2, pos) == prefix && charCat(state.sliceDoc(start2 - 1, start2)) != CharCategory.Word)
      return start2;
  }
  return -1;
}
function autocompletion(config2 = {}) {
  return [
    commitCharacters,
    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 { state } = target, line = state.doc.lineAt(state.selection.main.from), config2 = getConfig(target.state, line.from);
  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
  /* CommentOption.Toggle */
);
var toggleBlockComment = /* @__PURE__ */ command(
  changeBlockComment,
  0
  /* CommentOption.Toggle */
);
var toggleBlockCommentByLine = /* @__PURE__ */ command(
  (o, s) => changeBlockComment(o, s, selectedLineRanges(s)),
  0
  /* CommentOption.Toggle */
);
function getConfig(state, pos) {
  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 + /^\s*/.exec(fromLine.text)[0].length, 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, comment2; i < comments.length; i++)
      if (comment2 = comments[i]) {
        let token = tokens[i], { open, close } = comment2;
        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;
    let token = getConfig(state, from).line;
    if (!token)
      continue;
    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 indent = /^\s*/.exec(line.text)[0].length;
        let empty4 = indent == line.length;
        let comment2 = line.text.slice(indent, indent + token.length) == token ? indent : -1;
        if (indent < line.text.length && indent < minIndent)
          minIndent = indent;
        lines.push({ line, comment: comment2, 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: comment2, token } of lines)
      if (comment2 >= 0) {
        let from = line.from + comment2, 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,
      joinToEvent: (_t, isAdjacent2) => isAdjacent2
    }, {
      minDepth: Math.max,
      newGroupDelay: Math.min,
      joinToEvent: (a, b) => (tr, adj) => a(tr, adj) || b(tr, adj)
    });
  }
});
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 item = HistEvent.fromTransaction(tr, fromHist.selection), 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, tr);
    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 _HistEvent {
  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));
  }
  // This does not check `addToHistory` and such, it assumes the
  // transaction needs to be converted to an item. Returns null when
  // there are no changes or effects in the transaction.
  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 start2 = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0;
  let newBranch = branch.slice(start2, 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 _HistoryState {
  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, config2, tr) {
    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 < config2.newGroupDelay && config2.joinToEvent(tr, isAdjacent(lastEvent.changes, event.changes)) || // For compose (but not compose.start) events, always join with previous event
    userEvent == "input.type.compose")) {
      done = updateBranch(done, done.length - 1, config2.minDepth, new HistEvent(event.changes.compose(lastEvent.changes), conc(event.effects, lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none3));
    } else {
      done = updateBranch(done, done.length, config2.minDepth, 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, onlySelection) {
    let branch = side == 0 ? this.done : this.undone;
    if (branch.length == 0)
      return null;
    let event = branch[branch.length - 1], selection2 = event.selectionsAfter[0] || state.selection;
    if (onlySelection && event.selectionsAfter.length) {
      return state.update({
        selection: event.selectionsAfter[event.selectionsAfter.length - 1],
        annotations: fromHistory.of({ side, rest: popSelection(branch), selection: selection2 }),
        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, selection: selection2 }),
        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, true))
    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));
var segmenter = typeof Intl != "undefined" && Intl.Segmenter ? /* @__PURE__ */ new Intl.Segmenter(void 0, { granularity: "word" }) : null;
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, start2, forward) {
  let pos = syntaxTree(state).resolveInner(start2.head);
  let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy;
  for (let at = start2.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 pageInfo(view) {
  let selfScroll = view.scrollDOM.clientHeight < view.scrollDOM.scrollHeight - 2;
  let marginTop = 0, marginBottom = 0, height4;
  if (selfScroll) {
    for (let source2 of view.state.facet(EditorView.scrollMargins)) {
      let margins = source2(view);
      if (margins === null || margins === void 0 ? void 0 : margins.top)
        marginTop = Math.max(margins === null || margins === void 0 ? void 0 : margins.top, marginTop);
      if (margins === null || margins === void 0 ? void 0 : margins.bottom)
        marginBottom = Math.max(margins === null || margins === void 0 ? void 0 : margins.bottom, marginBottom);
    }
    height4 = view.scrollDOM.clientHeight - marginTop - marginBottom;
  } else {
    height4 = (view.dom.ownerDocument.defaultView || window).innerHeight;
  }
  return {
    marginTop,
    marginBottom,
    selfScroll,
    height: Math.max(view.defaultLineHeight, height4 - 5)
  };
}
function cursorByPage(view, forward) {
  let page = pageInfo(view);
  let { state } = view, selection2 = updateSel(state.selection, (range2) => {
    return range2.empty ? view.moveVertically(range2, forward, page.height) : rangeEnd(range2, forward);
  });
  if (selection2.eq(state.selection))
    return false;
  let effect;
  if (page.selfScroll) {
    let startPos = view.coordsAtPos(state.selection.main.head);
    let scrollRect = view.scrollDOM.getBoundingClientRect();
    let scrollTop = scrollRect.top + page.marginTop, scrollBottom = scrollRect.bottom - page.marginBottom;
    if (startPos && startPos.top > scrollTop && startPos.bottom < scrollBottom)
      effect = EditorView.scrollIntoView(selection2.main.head, { y: "start", yMargin: startPos.top - scrollTop });
  }
  view.dispatch(setSel(state, selection2), { effects: effect });
  return true;
}
var cursorPageUp = (view) => cursorByPage(view, false);
var cursorPageDown = (view) => cursorByPage(view, true);
function moveByLineBoundary(view, start2, forward) {
  let line = view.lineBlockAt(start2.head), moved = view.moveToLineBoundary(start2, forward);
  if (moved.head == start2.head && moved.head != (forward ? line.to : line.from))
    moved = view.moveToLineBoundary(start2, 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 && start2.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, head.bidiLevel || void 0);
  });
  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, pageInfo(view).height));
}
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 stack = syntaxTree(state).resolveStack(range2.from, 1);
    for (let cur2 = stack; cur2; cur2 = cur2.next) {
      let { node } = cur2;
      if ((node.from < range2.from && node.to >= range2.to || node.to > range2.to && node.from <= range2.from) && ((_a2 = node.parent) === null || _a2 === void 0 ? void 0 : _a2.parent))
        return EditorSelection.range(node.to, node.from);
    }
    return range2;
  });
  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(range2);
      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, from < range2.head ? -1 : 1) };
  });
  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, (range2) => {
  let pos = range2.from, { 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;
    else if (!forward && /[\ufe00-\ufe0f]/.test(line.text.slice(targetPos - line.from, pos - line.from)))
      targetPos = findClusterBreak(line.text, targetPos - line.from, false, false) + line.from;
  }
  return targetPos;
});
var deleteCharBackward = (view) => deleteByChar(view, false);
var deleteCharForward = (view) => deleteByChar(view, true);
var deleteByGroup = (target, forward) => deleteBy(target, (range2) => {
  let pos = range2.head, { 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 == range2.head && 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 != range2.head)
      cat = nextCat;
    pos = next;
  }
  return pos;
});
var deleteGroupBackward = (target) => deleteByGroup(target, false);
var deleteGroupForward = (target) => deleteByGroup(target, true);
var deleteToLineEnd = (view) => deleteBy(view, (range2) => {
  let lineEnd = view.lineBlockAt(range2.head).to;
  return range2.head < lineEnd ? lineEnd : Math.min(view.state.doc.length, range2.head + 1);
});
var deleteLineBoundaryBackward = (view) => deleteBy(view, (range2) => {
  let lineStart = view.moveToLineBoundary(range2, false).head;
  return range2.head > lineStart ? lineStart : Math.max(0, range2.head - 1);
});
var deleteLineBoundaryForward = (view) => deleteBy(view, (range2) => {
  let lineStart = view.moveToLineBoundary(range2, true).head;
  return range2.head < lineStart ? lineStart : Math.min(view.state.doc.length, range2.head + 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 context2 = syntaxTree(state).resolveInner(pos);
  let before = context2.childBefore(pos), after = context2.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 && !/\S/.test(state.sliceDoc(before.to, after.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 = countColumn(/^\s*/.exec(state.doc.lineAt(from).text)[0], state.tabSize);
      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 context2 = new IndentContext(state, { overrideIndentation: (start2) => {
    let found = updated[start2];
    return found == null ? -1 : found;
  } });
  let changes = changeBySelectedLine(state, (line, changes2, range2) => {
    let indent = getIndentation(context2, 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: deleteLineBoundaryBackward },
  { mac: "Mod-Delete", run: deleteLineBoundaryForward }
].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.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 _LintState {
  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, state);
    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 + (d.markClass ? " " + d.markClass : "") },
        diagnostic: d,
        inclusive: true
      }).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) {
  let line = tr.startState.doc.lineAt(tooltip2.pos);
  return !!(tr.effects.some((e3) => e3.is(setDiagnosticsEffect)) || tr.changes.touchesRange(line.from, line.to));
}
function maybeEnableLint(state, effects) {
  return state.field(lintState, false) ? effects : effects.concat(StateEffect.appendConfig.of(lintExtensions));
}
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", inclusive: true });
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, view.state);
  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, preventDefault: true },
  { key: "F8", run: nextDiagnostic }
];
var lintConfig = /* @__PURE__ */ Facet.define({
  combine(input) {
    return Object.assign({ sources: input.map((i) => i.source).filter((x2) => x2 != null) }, combineConfig(input.map((i) => i.config), {
      delay: 750,
      markerFilter: null,
      tooltipFilter: null,
      needsRefresh: null
    }, {
      needsRefresh: (a, b) => !a ? b : !b ? a : (u) => a(u) || b(u)
    }));
  }
});
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 fired = false, click = (e3) => {
      e3.preventDefault();
      if (fired)
        return;
      fired = true;
      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 _LintPanel {
  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 }) => {
          let scaleY = panel.height / this.list.offsetHeight;
          if (sel.top < panel.top)
            this.list.scrollTop -= (panel.top - sel.top) / scaleY;
          else if (sel.bottom > panel.bottom)
            this.list.scrollTop += (sel.bottom - panel.bottom) / scaleY;
        }
      });
    } 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-diagnostic-hint": { borderLeft: "5px solid #66d" },
  ".cm-diagnosticAction": {
    font: "inherit",
    border: "none",
    padding: "2px 4px",
    backgroundColor: "#444",
    color: "white",
    borderRadius: "3px",
    marginLeft: "8px",
    cursor: "pointer"
  },
  ".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-hint": { backgroundImage: /* @__PURE__ */ underline("#66d") },
  ".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-lintPoint-hint": {
    "&:after": { borderBottomColor: "#66d" }
  },
  ".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
    }
  }
});
function severityWeight(sev) {
  return sev == "error" ? 4 : sev == "warning" ? 3 : sev == "info" ? 2 : 1;
}
var LintGutterMarker = class extends GutterMarker {
  constructor(diagnostics) {
    super();
    this.diagnostics = diagnostics;
    this.severity = diagnostics.reduce((max3, d) => severityWeight(max3) < severityWeight(d.severity) ? d.severity : max3, "hint");
  }
  toDOM(view) {
    let elt = document.createElement("div");
    elt.className = "cm-lint-marker cm-lint-marker-" + this.severity;
    let diagnostics = this.diagnostics;
    let diagnosticsFilter = view.state.facet(lintGutterConfig).tooltipFilter;
    if (diagnosticsFilter)
      diagnostics = diagnosticsFilter(diagnostics, view.state);
    if (diagnostics.length)
      elt.onmouseover = () => gutterMarkerMouseOver(view, elt, diagnostics);
    return elt;
  }
};
function trackHoverOn(view, marker) {
  let mousemove = (event) => {
    let rect = marker.getBoundingClientRect();
    if (event.clientX > rect.left - 10 && event.clientX < rect.right + 10 && event.clientY > rect.top - 10 && event.clientY < rect.bottom + 10)
      return;
    for (let target = event.target; target; target = target.parentNode) {
      if (target.nodeType == 1 && target.classList.contains("cm-tooltip-lint"))
        return;
    }
    window.removeEventListener("mousemove", mousemove);
    if (view.state.field(lintGutterTooltip))
      view.dispatch({ effects: setLintGutterTooltip.of(null) });
  };
  window.addEventListener("mousemove", mousemove);
}
function gutterMarkerMouseOver(view, marker, diagnostics) {
  function hovered() {
    let line = view.elementAtHeight(marker.getBoundingClientRect().top + 5 - view.documentTop);
    const linePos = view.coordsAtPos(line.from);
    if (linePos) {
      view.dispatch({ effects: setLintGutterTooltip.of({
        pos: line.from,
        above: false,
        create() {
          return {
            dom: diagnosticsTooltip(view, diagnostics),
            getCoords: () => marker.getBoundingClientRect()
          };
        }
      }) });
    }
    marker.onmouseout = marker.onmousemove = null;
    trackHoverOn(view, marker);
  }
  let { hoverTime } = view.state.facet(lintGutterConfig);
  let hoverTimeout = setTimeout(hovered, hoverTime);
  marker.onmouseout = () => {
    clearTimeout(hoverTimeout);
    marker.onmouseout = marker.onmousemove = null;
  };
  marker.onmousemove = () => {
    clearTimeout(hoverTimeout);
    hoverTimeout = setTimeout(hovered, hoverTime);
  };
}
function markersForDiagnostics(doc2, diagnostics) {
  let byLine = /* @__PURE__ */ Object.create(null);
  for (let diagnostic of diagnostics) {
    let line = doc2.lineAt(diagnostic.from);
    (byLine[line.from] || (byLine[line.from] = [])).push(diagnostic);
  }
  let markers = [];
  for (let line in byLine) {
    markers.push(new LintGutterMarker(byLine[line]).range(+line));
  }
  return RangeSet.of(markers, true);
}
var lintGutterExtension = /* @__PURE__ */ gutter({
  class: "cm-gutter-lint",
  markers: (view) => view.state.field(lintGutterMarkers)
});
var lintGutterMarkers = /* @__PURE__ */ StateField.define({
  create() {
    return RangeSet.empty;
  },
  update(markers, tr) {
    markers = markers.map(tr.changes);
    let diagnosticFilter = tr.state.facet(lintGutterConfig).markerFilter;
    for (let effect of tr.effects) {
      if (effect.is(setDiagnosticsEffect)) {
        let diagnostics = effect.value;
        if (diagnosticFilter)
          diagnostics = diagnosticFilter(diagnostics || [], tr.state);
        markers = markersForDiagnostics(tr.state.doc, diagnostics.slice(0));
      }
    }
    return markers;
  }
});
var setLintGutterTooltip = /* @__PURE__ */ StateEffect.define();
var lintGutterTooltip = /* @__PURE__ */ StateField.define({
  create() {
    return null;
  },
  update(tooltip2, tr) {
    if (tooltip2 && tr.docChanged)
      tooltip2 = hideTooltip(tr, tooltip2) ? null : Object.assign(Object.assign({}, tooltip2), { pos: tr.changes.mapPos(tooltip2.pos) });
    return tr.effects.reduce((t4, e3) => e3.is(setLintGutterTooltip) ? e3.value : t4, tooltip2);
  },
  provide: (field) => showTooltip.from(field)
});
var lintGutterTheme = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-gutter-lint": {
    width: "1.4em",
    "& .cm-gutterElement": {
      padding: ".2em"
    }
  },
  ".cm-lint-marker": {
    width: "1em",
    height: "1em"
  },
  ".cm-lint-marker-info": {
    content: /* @__PURE__ */ svg(`<path fill="#aaf" stroke="#77e" stroke-width="6" stroke-linejoin="round" d="M5 5L35 5L35 35L5 35Z"/>`)
  },
  ".cm-lint-marker-warning": {
    content: /* @__PURE__ */ svg(`<path fill="#fe8" stroke="#fd7" stroke-width="6" stroke-linejoin="round" d="M20 6L37 35L3 35Z"/>`)
  },
  ".cm-lint-marker-error": {
    content: /* @__PURE__ */ svg(`<circle cx="20" cy="20" r="15" fill="#f87" stroke="#f43" stroke-width="6"/>`)
  }
});
var lintExtensions = [
  lintState,
  /* @__PURE__ */ EditorView.decorations.compute([lintState], (state) => {
    let { selected, panel } = state.field(lintState);
    return !selected || !panel || selected.from == selected.to ? Decoration.none : Decoration.set([
      activeMark.range(selected.from, selected.to)
    ]);
  }),
  /* @__PURE__ */ hoverTooltip(lintTooltip, { hideOn: hideTooltip }),
  baseTheme4
];
var lintGutterConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      hoverTime: 300,
      markerFilter: null,
      tooltipFilter: null
    });
  }
});
function lintGutter(config2 = {}) {
  return [lintGutterConfig.of(config2), lintGutterMarkers, lintGutterExtension, lintGutterTheme, lintGutterTooltip];
}

// node_modules/@codemirror/search/dist/index.js
var basicNormalize = typeof String.prototype.normalize == "function" ? (x2) => x2.normalize("NFKD") : (x2) => x2;
var SearchCursor = class {
  /**
  Create a text cursor. The query is the search string, `from` to
  `to` provides the region to search.
  
  When `normalize` is given, it will be called, on both the query
  string and the content it is matched against, before comparing.
  You can, for example, create a case-insensitive search by
  passing `s => s.toLowerCase()`.
  
  Text is always normalized with
  [`.normalize("NFKD")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize)
  (when supported).
  */
  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);
  }
  /**
  Look for the next match. Updates the iterator's
  [`value`](https://codemirror.net/6/docs/ref/#search.SearchCursor.value) and
  [`done`](https://codemirror.net/6/docs/ref/#search.SearchCursor.done) properties. Should be called
  at least once before using the cursor.
  */
  next() {
    while (this.matches.length)
      this.matches.pop();
    return this.nextOverlapping();
  }
  /**
  The `next` method will ignore matches that partially overlap a
  previous match. This method behaves like `next`, but includes
  such matches.
  */
  nextOverlapping() {
    for (; ; ) {
      let next = this.peek();
      if (next < 0) {
        this.done = true;
        return this;
      }
      let str = fromCodePoint(next), start2 = this.bufferStart + this.bufferPos;
      this.bufferPos += codePointSize(next);
      let norm = this.normalize(str);
      for (let i = 0, pos = start2; ; i++) {
        let code = norm.charCodeAt(i);
        let match = this.match(code, pos, this.bufferPos + this.bufferStart);
        if (i == norm.length - 1) {
          if (match) {
            this.value = match;
            return this;
          }
          break;
        }
        if (pos == start2 && i < str.length && str.charCodeAt(i) == code)
          pos++;
      }
    }
  }
  match(code, pos, end) {
    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: end };
        } 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: end };
      else
        this.matches.push(1, pos);
    }
    if (match && this.test && !this.test(match.from, match.to, this.buffer, this.bufferStart))
      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 {
  /**
  Create a cursor that will search the given range in the given
  document. `query` should be the raw pattern (as you'd pass it to
  `new RegExp`).
  */
  constructor(text2, query, options3, 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, options3, from, to);
    this.re = new RegExp(query, baseFlags + ((options3 === null || options3 === void 0 ? void 0 : options3.ignoreCase) ? "i" : ""));
    this.test = options3 === null || options3 === void 0 ? void 0 : options3.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);
  }
  /**
  Move to the next match, if there is one.
  */
  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 _FlattenedDoc {
  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, options3, 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 + ((options3 === null || options3 === void 0 ? void 0 : options3.ignoreCase) ? "i" : ""));
    this.test = options3 === null || options3 === void 0 ? void 0 : options3.test;
    this.flat = FlattenedDoc.get(text2, from, this.chunkEnd(
      from + 5e3
      /* Chunk.Base */
    ));
  }
  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(source2) {
  try {
    new RegExp(source2, 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 line = String(view.state.doc.lineAt(view.state.selection.main.head).number);
  let input = crelt("input", { class: "cm-textfield", name: "line", value: 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 line2 = ln ? +ln : startLine.number;
    if (ln && percent) {
      let pc = line2 / 100;
      if (sign)
        pc = pc * (sign == "-" ? -1 : 1) + startLine.number / state.doc.lines;
      line2 = Math.round(state.doc.lines * pc);
    } else if (ln && sign) {
      line2 = line2 * (sign == "-" ? -1 : 1) + startLine.number;
    }
    let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line2)));
    let selection2 = EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length)));
    view.dispatch({
      effects: [dialogEffect.of(false), EditorView.scrollIntoView(selection2.from, { y: "center" })],
      selection: selection2
    });
    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").select();
  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(options3) {
    return combineConfig(options3, defaultHighlightOptions, {
      highlightWordAroundCursor: (a, b) => a || b,
      minSelectionLength: Math.min,
      maxMatches: Math.min
    });
  }
});
function highlightSelectionMatches(options3) {
  let ext2 = [defaultTheme, matchHighlighter];
  if (options3)
    ext2.push(highlightConfig.of(options3));
  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);
        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,
      regexp: false,
      wholeWord: false,
      createPanel: (view) => new SearchPanel(view),
      scrollToMatch: (range2) => EditorView.scrollIntoView(range2)
    });
  }
});
var SearchQuery = class {
  /**
  Create a query object.
  */
  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;
  }
  /**
  @internal
  */
  unquote(text2) {
    return this.literal ? text2 : text2.replace(/\\([nrt\\])/g, (_2, ch) => ch == "n" ? "\n" : ch == "r" ? "\r" : ch == "t" ? "	" : "\\");
  }
  /**
  Compare this query to another query.
  */
  eq(other) {
    return this.search == other.search && this.replace == other.replace && this.caseSensitive == other.caseSensitive && this.regexp == other.regexp && this.wholeWord == other.wholeWord;
  }
  /**
  @internal
  */
  create() {
    return this.regexp ? new RegExpQuery(this) : new StringQuery(this);
  }
  /**
  Get a search cursor for this query, searching through the given
  range in the given state.
  */
  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;
  }
  // Searching in reverse is, rather than implementing an inverted search
  // cursor, done by scanning chunk after chunk forward.
  prevMatchInRange(state, from, to) {
    for (let pos = to; ; ) {
      let start2 = Math.max(from, pos - 1e4 - this.spec.unquoted.length);
      let cursor = stringCursor(this.spec, state, start2, pos), range2 = null;
      while (!cursor.nextOverlapping().done)
        range2 = cursor.value;
      if (range2)
        return range2;
      if (start2 == 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 start2 = Math.max(
        from,
        to - size * 1e4
        /* FindPrev.ChunkSize */
      );
      let cursor = regexpCursor(this.spec, state, start2, to), range2 = null;
      while (!cursor.next().done)
        range2 = cursor.value;
      if (range2 && (start2 == from || range2.from > start2 + 10))
        return range2;
      if (start2 == 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
      /* RegExp.HighlightMargin */
    ), 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;
  let selection2 = EditorSelection.single(next.from, next.to);
  let config2 = view.state.facet(searchConfigFacet);
  view.dispatch({
    selection: selection2,
    effects: [announceMatch(view, next), config2.scrollToMatch(selection2.main, view)],
    userEvent: "select.search"
  });
  selectSearchInput(view);
  return true;
});
var findPrevious = /* @__PURE__ */ searchCommand((view, { query }) => {
  let { state } = view, { from } = state.selection.main;
  let prev = query.prevMatch(state, from, from);
  if (!prev)
    return false;
  let selection2 = EditorSelection.single(prev.from, prev.to);
  let config2 = view.state.facet(searchConfigFacet);
  view.dispatch({
    selection: selection2,
    effects: [announceMatch(view, prev), config2.scrollToMatch(selection2.main, view)],
    userEvent: "select.search"
  });
  selectSearchInput(view);
  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 effects = [];
  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);
    effects.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 = EditorSelection.single(next.from - off, next.to - off);
    effects.push(announceMatch(view, next));
    effects.push(state.facet(searchConfigFacet).scrollToMatch(selection2.main, view));
  }
  view.dispatch({
    changes,
    selection: selection2,
    effects,
    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, _e;
  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,
    regexp: (_d = fallback === null || fallback === void 0 ? void 0 : fallback.regexp) !== null && _d !== void 0 ? _d : config2.regexp,
    wholeWord: (_e = fallback === null || fallback === void 0 ? void 0 : fallback.wholeWord) !== null && _e !== void 0 ? _e : config2.wholeWord
  });
}
function getSearchInput(view) {
  let panel = getPanel(view, createSearchPanel);
  return panel && panel.dom.querySelector("[main-field]");
}
function selectSearchInput(view) {
  let input = getSearchInput(view);
  if (input && input == view.root.activeElement)
    input.select();
}
var openSearchPanel = (view) => {
  let state = view.state.field(searchState, false);
  if (state && state.panel) {
    let searchInput = getSearchInput(view);
    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: "Mod-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 start2 = Math.max(line.from, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin);
  let text2 = view.state.sliceDoc(start2, end);
  if (start2 != 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.low(searchHighlighter),
  baseTheme5
];

// src/codemirror/beancount.ts
var import_web_tree_sitter = __toESM(require_tree_sitter());

// node_modules/web-tree-sitter/tree-sitter.wasm
var tree_sitter_default = "./tree-sitter-HVVYECOZ.wasm";

// 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(locale4) {
  var group2 = locale4.grouping === void 0 || locale4.thousands === void 0 ? identity_default : formatGroup_default(map.call(locale4.grouping, Number), locale4.thousands + ""), currencyPrefix = locale4.currency === void 0 ? "" : locale4.currency[0] + "", currencySuffix = locale4.currency === void 0 ? "" : locale4.currency[1] + "", decimal2 = locale4.decimal === void 0 ? "." : locale4.decimal + "", numerals = locale4.numerals === void 0 ? identity_default : formatNumerals_default(map.call(locale4.numerals, String)), percent = locale4.percent === void 0 ? "%" : locale4.percent + "", minus = locale4.minus === void 0 ? "\u2212" : locale4.minus + "", nan = locale4.nan === void 0 ? "NaN" : locale4.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 locale2;
var format2;
var formatPrefix;
defaultLocale({
  thousands: ",",
  grouping: [3],
  currency: ["$", ""]
});
function defaultLocale(definition) {
  locale2 = locale_default(definition);
  format2 = locale2.format;
  formatPrefix = locale2.formatPrefix;
  return locale2;
}

// 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 = /* @__PURE__ */ new Date();
var t1 = /* @__PURE__ */ new Date();
function timeInterval(floori, offseti, count2, field) {
  function interval2(date4) {
    return floori(date4 = arguments.length === 0 ? /* @__PURE__ */ new Date() : /* @__PURE__ */ new Date(+date4)), date4;
  }
  interval2.floor = (date4) => {
    return floori(date4 = /* @__PURE__ */ new Date(+date4)), date4;
  };
  interval2.ceil = (date4) => {
    return floori(date4 = new Date(date4 - 1)), offseti(date4, 1), floori(date4), date4;
  };
  interval2.round = (date4) => {
    const d0 = interval2(date4), d1 = interval2.ceil(date4);
    return date4 - d0 < d1 - date4 ? d0 : d1;
  };
  interval2.offset = (date4, step) => {
    return offseti(date4 = /* @__PURE__ */ new Date(+date4), step == null ? 1 : Math.floor(step)), date4;
  };
  interval2.range = (start2, stop2, step) => {
    const range2 = [];
    start2 = interval2.ceil(start2);
    step = step == null ? 1 : Math.floor(step);
    if (!(start2 < stop2) || !(step > 0))
      return range2;
    let previous;
    do
      range2.push(previous = /* @__PURE__ */ new Date(+start2)), offseti(start2, step), floori(start2);
    while (previous < start2 && start2 < stop2);
    return range2;
  };
  interval2.filter = (test) => {
    return timeInterval((date4) => {
      if (date4 >= date4)
        while (floori(date4), !test(date4))
          date4.setTime(date4 - 1);
    }, (date4, step) => {
      if (date4 >= date4) {
        if (step < 0)
          while (++step <= 0) {
            while (offseti(date4, -1), !test(date4)) {
            }
          }
        else
          while (--step >= 0) {
            while (offseti(date4, 1), !test(date4)) {
            }
          }
      }
    });
  };
  if (count2) {
    interval2.count = (start2, end) => {
      t0.setTime(+start2), t1.setTime(+end);
      floori(t0), floori(t1);
      return Math.floor(count2(t0, t1));
    };
    interval2.every = (step) => {
      step = Math.floor(step);
      return !isFinite(step) || !(step > 0) ? null : !(step > 1) ? interval2 : interval2.filter(field ? (d) => field(d) % step === 0 : (d) => interval2.count(0, d) % step === 0);
    };
  }
  return interval2;
}

// node_modules/d3-time/src/millisecond.js
var millisecond = timeInterval(() => {
}, (date4, step) => {
  date4.setTime(+date4 + step);
}, (start2, end) => {
  return end - start2;
});
millisecond.every = (k) => {
  k = Math.floor(k);
  if (!isFinite(k) || !(k > 0))
    return null;
  if (!(k > 1))
    return millisecond;
  return timeInterval((date4) => {
    date4.setTime(Math.floor(date4 / k) * k);
  }, (date4, step) => {
    date4.setTime(+date4 + step * k);
  }, (start2, end) => {
    return (end - start2) / k;
  });
};
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 = timeInterval((date4) => {
  date4.setTime(date4 - date4.getMilliseconds());
}, (date4, step) => {
  date4.setTime(+date4 + step * durationSecond);
}, (start2, end) => {
  return (end - start2) / durationSecond;
}, (date4) => {
  return date4.getUTCSeconds();
});
var seconds = second.range;

// node_modules/d3-time/src/minute.js
var timeMinute = timeInterval((date4) => {
  date4.setTime(date4 - date4.getMilliseconds() - date4.getSeconds() * durationSecond);
}, (date4, step) => {
  date4.setTime(+date4 + step * durationMinute);
}, (start2, end) => {
  return (end - start2) / durationMinute;
}, (date4) => {
  return date4.getMinutes();
});
var timeMinutes = timeMinute.range;
var utcMinute = timeInterval((date4) => {
  date4.setUTCSeconds(0, 0);
}, (date4, step) => {
  date4.setTime(+date4 + step * durationMinute);
}, (start2, end) => {
  return (end - start2) / durationMinute;
}, (date4) => {
  return date4.getUTCMinutes();
});
var utcMinutes = utcMinute.range;

// node_modules/d3-time/src/hour.js
var timeHour = timeInterval((date4) => {
  date4.setTime(date4 - date4.getMilliseconds() - date4.getSeconds() * durationSecond - date4.getMinutes() * durationMinute);
}, (date4, step) => {
  date4.setTime(+date4 + step * durationHour);
}, (start2, end) => {
  return (end - start2) / durationHour;
}, (date4) => {
  return date4.getHours();
});
var timeHours = timeHour.range;
var utcHour = timeInterval((date4) => {
  date4.setUTCMinutes(0, 0, 0);
}, (date4, step) => {
  date4.setTime(+date4 + step * durationHour);
}, (start2, end) => {
  return (end - start2) / durationHour;
}, (date4) => {
  return date4.getUTCHours();
});
var utcHours = utcHour.range;

// node_modules/d3-time/src/day.js
var timeDay = timeInterval(
  (date4) => date4.setHours(0, 0, 0, 0),
  (date4, step) => date4.setDate(date4.getDate() + step),
  (start2, end) => (end - start2 - (end.getTimezoneOffset() - start2.getTimezoneOffset()) * durationMinute) / durationDay,
  (date4) => date4.getDate() - 1
);
var timeDays = timeDay.range;
var utcDay = timeInterval((date4) => {
  date4.setUTCHours(0, 0, 0, 0);
}, (date4, step) => {
  date4.setUTCDate(date4.getUTCDate() + step);
}, (start2, end) => {
  return (end - start2) / durationDay;
}, (date4) => {
  return date4.getUTCDate() - 1;
});
var utcDays = utcDay.range;
var unixDay = timeInterval((date4) => {
  date4.setUTCHours(0, 0, 0, 0);
}, (date4, step) => {
  date4.setUTCDate(date4.getUTCDate() + step);
}, (start2, end) => {
  return (end - start2) / durationDay;
}, (date4) => {
  return Math.floor(date4 / durationDay);
});
var unixDays = unixDay.range;

// node_modules/d3-time/src/week.js
function timeWeekday(i) {
  return timeInterval((date4) => {
    date4.setDate(date4.getDate() - (date4.getDay() + 7 - i) % 7);
    date4.setHours(0, 0, 0, 0);
  }, (date4, step) => {
    date4.setDate(date4.getDate() + step * 7);
  }, (start2, end) => {
    return (end - start2 - (end.getTimezoneOffset() - start2.getTimezoneOffset()) * durationMinute) / durationWeek;
  });
}
var timeSunday = timeWeekday(0);
var timeMonday = timeWeekday(1);
var timeTuesday = timeWeekday(2);
var timeWednesday = timeWeekday(3);
var timeThursday = timeWeekday(4);
var timeFriday = timeWeekday(5);
var timeSaturday = timeWeekday(6);
var timeSundays = timeSunday.range;
var timeMondays = timeMonday.range;
var timeTuesdays = timeTuesday.range;
var timeWednesdays = timeWednesday.range;
var timeThursdays = timeThursday.range;
var timeFridays = timeFriday.range;
var timeSaturdays = timeSaturday.range;
function utcWeekday(i) {
  return timeInterval((date4) => {
    date4.setUTCDate(date4.getUTCDate() - (date4.getUTCDay() + 7 - i) % 7);
    date4.setUTCHours(0, 0, 0, 0);
  }, (date4, step) => {
    date4.setUTCDate(date4.getUTCDate() + step * 7);
  }, (start2, end) => {
    return (end - start2) / 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/month.js
var timeMonth = timeInterval((date4) => {
  date4.setDate(1);
  date4.setHours(0, 0, 0, 0);
}, (date4, step) => {
  date4.setMonth(date4.getMonth() + step);
}, (start2, end) => {
  return end.getMonth() - start2.getMonth() + (end.getFullYear() - start2.getFullYear()) * 12;
}, (date4) => {
  return date4.getMonth();
});
var timeMonths = timeMonth.range;
var utcMonth = timeInterval((date4) => {
  date4.setUTCDate(1);
  date4.setUTCHours(0, 0, 0, 0);
}, (date4, step) => {
  date4.setUTCMonth(date4.getUTCMonth() + step);
}, (start2, end) => {
  return end.getUTCMonth() - start2.getUTCMonth() + (end.getUTCFullYear() - start2.getUTCFullYear()) * 12;
}, (date4) => {
  return date4.getUTCMonth();
});
var utcMonths = utcMonth.range;

// node_modules/d3-time/src/year.js
var timeYear = timeInterval((date4) => {
  date4.setMonth(0, 1);
  date4.setHours(0, 0, 0, 0);
}, (date4, step) => {
  date4.setFullYear(date4.getFullYear() + step);
}, (start2, end) => {
  return end.getFullYear() - start2.getFullYear();
}, (date4) => {
  return date4.getFullYear();
});
timeYear.every = (k) => {
  return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date4) => {
    date4.setFullYear(Math.floor(date4.getFullYear() / k) * k);
    date4.setMonth(0, 1);
    date4.setHours(0, 0, 0, 0);
  }, (date4, step) => {
    date4.setFullYear(date4.getFullYear() + step * k);
  });
};
var timeYears = timeYear.range;
var utcYear = timeInterval((date4) => {
  date4.setUTCMonth(0, 1);
  date4.setUTCHours(0, 0, 0, 0);
}, (date4, step) => {
  date4.setUTCFullYear(date4.getUTCFullYear() + step);
}, (start2, end) => {
  return end.getUTCFullYear() - start2.getUTCFullYear();
}, (date4) => {
  return date4.getUTCFullYear();
});
utcYear.every = (k) => {
  return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date4) => {
    date4.setUTCFullYear(Math.floor(date4.getUTCFullYear() / k) * k);
    date4.setUTCMonth(0, 1);
    date4.setUTCHours(0, 0, 0, 0);
  }, (date4, step) => {
    date4.setUTCFullYear(date4.getUTCFullYear() + step * k);
  });
};
var utcYears = utcYear.range;

// node_modules/d3-time/src/ticks.js
function ticker(year, month, week, day2, hour, minute) {
  const tickIntervals = [
    [second, 1, durationSecond],
    [second, 5, 5 * durationSecond],
    [second, 15, 15 * durationSecond],
    [second, 30, 30 * durationSecond],
    [minute, 1, durationMinute],
    [minute, 5, 5 * durationMinute],
    [minute, 15, 15 * durationMinute],
    [minute, 30, 30 * durationMinute],
    [hour, 1, durationHour],
    [hour, 3, 3 * durationHour],
    [hour, 6, 6 * durationHour],
    [hour, 12, 12 * durationHour],
    [day2, 1, durationDay],
    [day2, 2, 2 * durationDay],
    [week, 1, durationWeek],
    [month, 1, durationMonth],
    [month, 3, 3 * durationMonth],
    [year, 1, durationYear]
  ];
  function ticks2(start2, stop2, count2) {
    const reverse = stop2 < start2;
    if (reverse)
      [start2, stop2] = [stop2, start2];
    const interval2 = count2 && typeof count2.range === "function" ? count2 : tickInterval(start2, stop2, count2);
    const ticks3 = interval2 ? interval2.range(start2, +stop2 + 1) : [];
    return reverse ? ticks3.reverse() : ticks3;
  }
  function tickInterval(start2, stop2, count2) {
    const target = Math.abs(stop2 - start2) / count2;
    const i = bisector(([, , step2]) => step2).right(tickIntervals, target);
    if (i === tickIntervals.length)
      return year.every(tickStep(start2 / durationYear, stop2 / durationYear, count2));
    if (i === 0)
      return millisecond.every(Math.max(tickStep(start2, stop2, 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, utcMonth, utcSunday, unixDay, utcHour, utcMinute);
var [timeTicks, timeTickInterval] = ticker(timeYear, timeMonth, timeSunday, timeDay, timeHour, timeMinute);

// node_modules/d3-time-format/src/locale.js
function localDate(d) {
  if (0 <= d.y && d.y < 100) {
    var date4 = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
    date4.setFullYear(d.y);
    return date4;
  }
  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 date4 = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
    date4.setUTCFullYear(d.y);
    return date4;
  }
  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(locale4) {
  var locale_dateTime = locale4.dateTime, locale_date = locale4.date, locale_time = locale4.time, locale_periods = locale4.periods, locale_weekdays = locale4.days, locale_shortWeekdays = locale4.shortDays, locale_months = locale4.months, locale_shortMonths = locale4.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(date4) {
      var string4 = [], i = -1, j = 0, n = specifier.length, c, pad2, format3;
      if (!(date4 instanceof Date))
        date4 = /* @__PURE__ */ new Date(+date4);
      while (++i < n) {
        if (specifier.charCodeAt(i) === 37) {
          string4.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(date4, pad2);
          string4.push(c);
          j = i + 1;
        }
      }
      string4.push(specifier.slice(j, i));
      return string4.join("");
    };
  }
  function newParse(specifier, Z) {
    return function(string4) {
      var d = newDate(1900, void 0, 1), i = parseSpecifier(d, specifier, string4 += "", 0), week, day2;
      if (i != string4.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)), day2 = week.getUTCDay();
          week = day2 > 4 || day2 === 0 ? utcMonday.ceil(week) : utcMonday(week);
          week = utcDay.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)), day2 = week.getDay();
          week = day2 > 4 || day2 === 0 ? timeMonday.ceil(week) : timeMonday(week);
          week = timeDay.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;
        day2 = "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 - (day2 + 5) % 7 : d.w + d.U * 7 - (day2 + 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, string4, j) {
    var i = 0, n = specifier.length, m = string4.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, string4, j)) < 0)
          return -1;
      } else if (c != string4.charCodeAt(j++)) {
        return -1;
      }
    }
    return j;
  }
  function parsePeriod(d, string4, i) {
    var n = periodRe.exec(string4.slice(i));
    return n ? (d.p = periodLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }
  function parseShortWeekday(d, string4, i) {
    var n = shortWeekdayRe.exec(string4.slice(i));
    return n ? (d.w = shortWeekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }
  function parseWeekday(d, string4, i) {
    var n = weekdayRe.exec(string4.slice(i));
    return n ? (d.w = weekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }
  function parseShortMonth(d, string4, i) {
    var n = shortMonthRe.exec(string4.slice(i));
    return n ? (d.m = shortMonthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }
  function parseMonth(d, string4, i) {
    var n = monthRe.exec(string4.slice(i));
    return n ? (d.m = monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }
  function parseLocaleDateTime(d, string4, i) {
    return parseSpecifier(d, locale_dateTime, string4, i);
  }
  function parseLocaleDate(d, string4, i) {
    return parseSpecifier(d, locale_date, string4, i);
  }
  function parseLocaleTime(d, string4, i) {
    return parseSpecifier(d, locale_time, string4, 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 ? "-" : "", string4 = (sign ? -value : value) + "", length = string4.length;
  return sign + (length < width ? new Array(width - length + 1).join(fill) + string4 : string4);
}
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, string4, i) {
  var n = numberRe.exec(string4.slice(i, i + 1));
  return n ? (d.w = +n[0], i + n[0].length) : -1;
}
function parseWeekdayNumberMonday(d, string4, i) {
  var n = numberRe.exec(string4.slice(i, i + 1));
  return n ? (d.u = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberSunday(d, string4, i) {
  var n = numberRe.exec(string4.slice(i, i + 2));
  return n ? (d.U = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberISO(d, string4, i) {
  var n = numberRe.exec(string4.slice(i, i + 2));
  return n ? (d.V = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberMonday(d, string4, i) {
  var n = numberRe.exec(string4.slice(i, i + 2));
  return n ? (d.W = +n[0], i + n[0].length) : -1;
}
function parseFullYear(d, string4, i) {
  var n = numberRe.exec(string4.slice(i, i + 4));
  return n ? (d.y = +n[0], i + n[0].length) : -1;
}
function parseYear(d, string4, i) {
  var n = numberRe.exec(string4.slice(i, i + 2));
  return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2e3), i + n[0].length) : -1;
}
function parseZone(d, string4, i) {
  var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string4.slice(i, i + 6));
  return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1;
}
function parseQuarter(d, string4, i) {
  var n = numberRe.exec(string4.slice(i, i + 1));
  return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1;
}
function parseMonthNumber(d, string4, i) {
  var n = numberRe.exec(string4.slice(i, i + 2));
  return n ? (d.m = n[0] - 1, i + n[0].length) : -1;
}
function parseDayOfMonth(d, string4, i) {
  var n = numberRe.exec(string4.slice(i, i + 2));
  return n ? (d.d = +n[0], i + n[0].length) : -1;
}
function parseDayOfYear(d, string4, i) {
  var n = numberRe.exec(string4.slice(i, i + 3));
  return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;
}
function parseHour24(d, string4, i) {
  var n = numberRe.exec(string4.slice(i, i + 2));
  return n ? (d.H = +n[0], i + n[0].length) : -1;
}
function parseMinutes(d, string4, i) {
  var n = numberRe.exec(string4.slice(i, i + 2));
  return n ? (d.M = +n[0], i + n[0].length) : -1;
}
function parseSeconds(d, string4, i) {
  var n = numberRe.exec(string4.slice(i, i + 2));
  return n ? (d.S = +n[0], i + n[0].length) : -1;
}
function parseMilliseconds(d, string4, i) {
  var n = numberRe.exec(string4.slice(i, i + 3));
  return n ? (d.L = +n[0], i + n[0].length) : -1;
}
function parseMicroseconds(d, string4, i) {
  var n = numberRe.exec(string4.slice(i, i + 6));
  return n ? (d.L = Math.floor(n[0] / 1e3), i + n[0].length) : -1;
}
function parseLiteralPercent(d, string4, i) {
  var n = percentRe.exec(string4.slice(i, i + 1));
  return n ? i + n[0].length : -1;
}
function parseUnixTimestamp(d, string4, i) {
  var n = numberRe.exec(string4.slice(i));
  return n ? (d.Q = +n[0], i + n[0].length) : -1;
}
function parseUnixTimestampSeconds(d, string4, i) {
  var n = numberRe.exec(string4.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 + timeDay.count(timeYear(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 day2 = d.getDay();
  return day2 === 0 ? 7 : day2;
}
function formatWeekNumberSunday(d, p) {
  return pad(timeSunday.count(timeYear(d) - 1, d), p, 2);
}
function dISO(d) {
  var day2 = d.getDay();
  return day2 >= 4 || day2 === 0 ? timeThursday(d) : timeThursday.ceil(d);
}
function formatWeekNumberISO(d, p) {
  d = dISO(d);
  return pad(timeThursday.count(timeYear(d), d) + (timeYear(d).getDay() === 4), p, 2);
}
function formatWeekdayNumberSunday(d) {
  return d.getDay();
}
function formatWeekNumberMonday(d, p) {
  return pad(timeMonday.count(timeYear(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 day2 = d.getDay();
  d = day2 >= 4 || day2 === 0 ? timeThursday(d) : timeThursday.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.count(utcYear(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(d) - 1, d), p, 2);
}
function UTCdISO(d) {
  var day2 = d.getUTCDay();
  return day2 >= 4 || day2 === 0 ? utcThursday(d) : utcThursday.ceil(d);
}
function formatUTCWeekNumberISO(d, p) {
  d = UTCdISO(d);
  return pad(utcThursday.count(utcYear(d), d) + (utcYear(d).getUTCDay() === 4), p, 2);
}
function formatUTCWeekdayNumberSunday(d) {
  return d.getUTCDay();
}
function formatUTCWeekNumberMonday(d, p) {
  return pad(utcMonday.count(utcYear(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 day2 = d.getUTCDay();
  d = day2 >= 4 || day2 === 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 locale3;
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) {
  locale3 = formatLocale(definition);
  timeFormat = locale3.format;
  timeParse = locale3.parse;
  utcFormat = locale3.utcFormat;
  utcParse = locale3.utcParse;
  return locale3;
}

// src/format.ts
function localeFormatter(locale4, precision = 2) {
  if (!locale4) {
    return format2(`.${precision}f`);
  }
  const digits = Math.max(0, Math.min(precision, 20));
  const fmt = new Intl.NumberFormat(locale4.replace("_", "-"), {
    minimumFractionDigits: digits,
    maximumFractionDigits: digits
  });
  return fmt.format.bind(fmt);
}
var formatterPer = format2(".2f");
function formatPercentage(number7) {
  return `${formatterPer(Math.abs(number7) * 100)}%`;
}
var day = utcFormat("%Y-%m-%d");
var dateFormat = {
  year: utcFormat("%Y"),
  quarter: (date4) => `${date4.getUTCFullYear()}Q${Math.floor(date4.getUTCMonth() / 3) + 1}`,
  month: utcFormat("%b %Y"),
  week: utcFormat("%YW%W"),
  day
};
var timeFilterDateFormat = {
  year: utcFormat("%Y"),
  quarter: (date4) => `${date4.getUTCFullYear()}-Q${Math.floor(date4.getUTCMonth() / 3) + 1}`,
  month: utcFormat("%Y-%m"),
  week: utcFormat("%Y-W%W"),
  day
};
var local_day = timeFormat("%Y-%m-%d");
function todayAsString() {
  return local_day(/* @__PURE__ */ new Date());
}

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

// src/codemirror/beancount-autocomplete.ts
var undatedDirectives = ["option", "plugin", "include"];
var datedDirectives = [
  "*",
  "open",
  "close",
  "custom",
  "commodity",
  "balance",
  "pad",
  "note",
  "document",
  "price",
  "event",
  "query"
];
var opts = (s) => s.map((label) => ({ label }));
var res = (s, from) => ({
  options: opts(s),
  from
});
var beancountCompletion = (context2) => {
  const tag = context2.matchBefore(/#[A-Za-z0-9\-_/.]*/);
  if (tag) {
    return {
      options: opts(get_store_value(tags)),
      from: tag.from + 1,
      validFor: /\S+/
    };
  }
  const link = context2.matchBefore(/\^[A-Za-z0-9\-_/.]*/);
  if (link) {
    return {
      options: opts(get_store_value(links)),
      from: link.from + 1,
      validFor: /\S+/
    };
  }
  const indented = context2.matchBefore(/^\s+[A-Z]\S*/);
  if (indented) {
    const indentation = indented.text.length - indented.text.trimStart().length;
    return {
      options: opts(get_store_value(accounts)),
      from: indented.from + indentation,
      validFor: /\S+/
    };
  }
  const line = context2.state.doc.lineAt(context2.pos);
  if (context2.matchBefore(/\d+/)) {
    return { options: beancountSnippets(), from: line.from };
  }
  const currentWord = context2.matchBefore(/\S*/);
  if (currentWord?.from === line.from && line.length > 0) {
    return {
      options: opts(undatedDirectives),
      from: line.from,
      validFor: /\S+/
    };
  }
  const tree = syntaxTree(context2.state);
  const before = tree.resolve(context2.pos, -1);
  const nodeTypesBefore = [
    before.name,
    before.prevSibling?.name,
    before.prevSibling?.prevSibling?.name,
    before.prevSibling?.prevSibling?.prevSibling?.name
  ];
  const match = (...types2) => types2.every((t4, i) => {
    const nodeType = nodeTypesBefore[i];
    return typeof t4 === "string" ? nodeType === t4 : t4.some((n) => nodeType === n);
  });
  if (match("string", "flag")) {
    return res(get_store_value(payees), before.from + 1);
  }
  if (match("keyword", "date")) {
    return res(datedDirectives, before.from);
  }
  if (
    // account directly after one of these directives:
    match(
      ["ERROR", "account"],
      ["BALANCE", "CLOSE", "OPEN", "PAD", "NOTE", "DOCUMENT"],
      "date"
    ) || // padding account
    match(["ERROR", "account"], "account", "PAD", "date")
  ) {
    return res(get_store_value(accounts), before.from);
  }
  if (
    // complete currencies after a number.
    match("ERROR", "number") || // account currency
    match(["ERROR", "currency"], "account", "OPEN", "date") || // price or commodity currency
    match(["ERROR", "currency"], ["COMMODITY", "PRICE"], "date")
  ) {
    return res(get_store_value(currencies), before.from);
  }
  return null;
};

// src/codemirror/beancount-fold.ts
var MAXDEPTH = 100;
function headerLevel(line) {
  const match = /^\*+/.exec(line);
  return 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/editor-transactions.ts
function replaceContents(state, value) {
  return {
    changes: { from: 0, to: state.doc.length, insert: value }
  };
}
function scrollToLine(state, line) {
  if (line < 1 || line > state.doc.lines) {
    return {};
  }
  const linePos = state.doc.line(line);
  return {
    selection: { ...linePos, anchor: linePos.from },
    scrollIntoView: true
  };
}
function setErrors(state, errors2) {
  const { doc: doc2 } = state;
  const diagnostics = errors2.map(({ source: source2, message }) => {
    const lineno = Math.min(Math.max(source2?.lineno ?? 1, 1), doc2.lines);
    const line = doc2.line(lineno);
    return {
      from: line.from,
      to: line.to,
      severity: "error",
      message
    };
  });
  return setDiagnostics(state, diagnostics);
}

// src/codemirror/beancount-format.ts
var beancountFormat = (cm) => {
  put("format_source", { source: cm.state.sliceDoc() }).then(
    (data) => {
      cm.dispatch(replaceContents(cm.state, data));
    },
    (error2) => {
      notify_err(error2, (err3) => `Formatting source failed: ${err3.message}`);
    }
  );
  return true;
};

// src/codemirror/beancount-highlight.ts
var beancountHighlight = HighlightStyle.define([
  {
    // Dates
    tag: tags2.special(tags2.number),
    color: "var(--editor-date)"
  },
  {
    // Accounts
    tag: tags2.className,
    color: "var(--editor-account)"
  },
  {
    // Plain comments
    tag: tags2.comment,
    color: "var(--editor-comment)"
  },
  {
    // Sections
    tag: tags2.special(tags2.lineComment),
    color: "var(--editor-comment)",
    border: "solid 1px var(--editor-comment)",
    borderRadius: "2px",
    paddingRight: "10px",
    fontWeight: "500"
  },
  {
    // Currencies
    tag: tags2.unit,
    color: "#708"
  },
  {
    // Directives
    tag: tags2.keyword,
    fontWeight: "500",
    color: "var(--editor-directive)"
  },
  {
    // Option name
    tag: tags2.standard(tags2.string),
    color: "var(--editor-class)"
  },
  {
    // Invalid token
    tag: tags2.invalid,
    color: "var(--editor-invalid)",
    backgroundColor: "var(--editor-invalid-background)"
  }
]);

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

// src/codemirror/tree-sitter-beancount.wasm
var tree_sitter_beancount_default = "./tree-sitter-beancount-CEOB3EN2.wasm";

// src/lib/array.ts
function is_non_empty(array3) {
  return array3.length > 0;
}
function last_element(array3) {
  return array3[array3.length - 1];
}

// src/codemirror/tree-sitter-parser.ts
var error = NodeType.define({
  id: 65535,
  name: "ERROR",
  error: true,
  props: [styleTags({ ERROR: tags2.invalid })]
});
var dummyPosition = { row: 0, column: 0 };
function ts_edit(startIndex, oldEndIndex, newEndIndex) {
  return {
    startIndex,
    oldEndIndex,
    newEndIndex,
    startPosition: dummyPosition,
    oldEndPosition: dummyPosition,
    newEndPosition: dummyPosition
  };
}
var TSTreeProp = new NodeProp({ perNode: true });
var TSParserError = class extends Error {
};
var InvalidRangeError = class extends TSParserError {
  constructor() {
    super("Only one range spanning the whole document is supported.");
  }
};
function input_edit_for_fragments(fragments, input_length) {
  const [fragment] = fragments;
  const { tree } = fragment;
  if (!fragments.every((f) => f.tree === tree)) {
    log_error("expect fragments to all have the same tree", fragments);
    return null;
  }
  if (fragments.length === 1) {
    return fragment.offset === 0 ? ts_edit(fragment.to - 1, tree.length, input_length) : ts_edit(0, fragment.from + fragment.offset + 1, fragment.from + 1);
  }
  const before = [...fragments].reverse().find((f) => !f.openStart && f.openEnd) ?? fragment;
  const after = fragments.find((f) => f.openStart && !f.openEnd) ?? last_element(fragments);
  const from = before.to;
  const { offset } = after;
  const newEndIndex = after.from;
  const oldEndIndex = newEndIndex + offset;
  return ts_edit(from - 1, oldEndIndex + 1, newEndIndex + 1);
}
var PARSE_CACHE = /* @__PURE__ */ new WeakMap();
var Parse2 = class _Parse {
  constructor(ts_parser, node_types, input, fragments, ranges) {
    this.ts_parser = ts_parser;
    this.node_types = node_types;
    this.input = input;
    this.fragments = fragments;
    this.ranges = ranges;
    if (ranges.length !== 1 || ranges[0]?.from !== 0 || ranges[0]?.to !== input.length) {
      throw new InvalidRangeError();
    }
  }
  stoppedAt = null;
  parsedPos = 0;
  /** Walk over the given node and its children, recursively creating Trees. */
  get_tree_for_ts_cursor(ts_cursor) {
    const { nodeTypeId, startIndex, endIndex } = ts_cursor;
    const node_type = this.node_types[nodeTypeId] ?? error;
    const children3 = [];
    const positions = [];
    if (ts_cursor.gotoFirstChild()) {
      do {
        positions.push(ts_cursor.startIndex - startIndex);
        children3.push(this.get_tree_for_ts_cursor(ts_cursor));
      } while (ts_cursor.gotoNextSibling());
      ts_cursor.gotoParent();
    }
    return new Tree2(node_type, children3, positions, endIndex - startIndex);
  }
  /**
   * Walk over the given node and its children, recursively creating Trees.
   *
   * Tries to reuse parts of an old tree.
   */
  get_tree_for_ts_cursor_reuse(ts_cursor, edit, old_tree) {
    const { nodeTypeId, startIndex, endIndex } = ts_cursor;
    const node_type = this.node_types[nodeTypeId] ?? error;
    const children3 = [];
    const positions = [];
    if (ts_cursor.gotoFirstChild()) {
      let ended = false;
      const old_children = old_tree.children;
      let child_index = 0;
      while (!ended && ts_cursor.endIndex < edit.startIndex) {
        positions.push(ts_cursor.startIndex - startIndex);
        children3.push(old_children[child_index]);
        child_index += 1;
        ended = !ts_cursor.gotoNextSibling();
      }
      if (ts_cursor.startIndex < edit.startIndex && edit.newEndIndex < ts_cursor.endIndex) {
        const old_child = old_children[child_index];
        if (old_child) {
          positions.push(ts_cursor.startIndex - startIndex);
          children3.push(
            this.get_tree_for_ts_cursor_reuse(ts_cursor, edit, old_child)
          );
          ended = !ts_cursor.gotoNextSibling();
        }
      }
      while (!ended && ts_cursor.startIndex < edit.newEndIndex) {
        positions.push(ts_cursor.startIndex - startIndex);
        children3.push(this.get_tree_for_ts_cursor(ts_cursor));
        ended = !ts_cursor.gotoNextSibling();
      }
      let children_after_edit = 0;
      while (!ended) {
        positions.push(ts_cursor.startIndex - startIndex);
        children_after_edit += 1;
        ended = !ts_cursor.gotoNextSibling();
      }
      if (children_after_edit > 0) {
        children3.push(...old_children.slice(-children_after_edit));
      }
      ts_cursor.gotoParent();
    }
    return new Tree2(node_type, children3, positions, endIndex - startIndex);
  }
  /** Convert the tree-sitter Tree to a Lezer tree, possibly reusing parts of an old one. */
  convert_tree(ts_tree, change) {
    const ts_tree_cursor = ts_tree.rootNode.walk();
    const tree = change ? this.get_tree_for_ts_cursor_reuse(
      ts_tree_cursor,
      change.edit,
      change.old_tree
    ) : this.get_tree_for_ts_cursor(ts_tree_cursor);
    const tree_with_ts_tree_prop = new Tree2(
      tree.type,
      tree.children,
      tree.positions,
      tree.length,
      [[TSTreeProp, ts_tree]]
    );
    return tree_with_ts_tree_prop;
  }
  /** Gather information about the changes from a previous parse. */
  static change_details(fragments, input_length) {
    if (!is_non_empty(fragments)) {
      return null;
    }
    const edit = input_edit_for_fragments(fragments, input_length);
    const old_tree = fragments[0].tree;
    const edited_old_ts_tree = old_tree.prop(TSTreeProp)?.copy();
    if (edit) {
      if (!edited_old_ts_tree) {
        log_error("expected old tree when there is an edit");
        return null;
      }
      assert2(
        input_length - old_tree.length === edit.newEndIndex - edit.oldEndIndex,
        "expect offset to match change in text length"
      );
      edited_old_ts_tree.edit(edit);
      assert2(
        edited_old_ts_tree.rootNode.endIndex === input_length,
        "expect edited old tree to match text length"
      );
      return { edit, old_tree, edited_old_ts_tree };
    }
    return null;
  }
  /**
   * Extend the changed range using the TS getChangedRanges function.
   *
   * Outside this extended range, nodes from the old tree can be reused since they
   * will have the exact same stack of containing nodes (possibly offset after the edit).
   */
  static extend_change(change, ts_tree) {
    const { edit, edited_old_ts_tree } = change;
    const changed_ranges = edited_old_ts_tree.getChangedRanges(ts_tree);
    if (!is_non_empty(changed_ranges)) {
      return change;
    }
    const newEndIndex = Math.max(
      edit.newEndIndex,
      last_element(changed_ranges).endIndex
    );
    const extended_edit = ts_edit(
      Math.min(edit.startIndex, changed_ranges[0].startIndex),
      newEndIndex + (edit.oldEndIndex - edit.newEndIndex),
      newEndIndex
    );
    return {
      edit: extended_edit,
      old_tree: change.old_tree
    };
  }
  advance() {
    const { fragments, input, stoppedAt, ts_parser } = this;
    const text2 = input.read(0, stoppedAt ?? input.length);
    const input_length = text2.length;
    const cm_text = input instanceof DocInput ? input.doc : null;
    if (cm_text) {
      const cached = PARSE_CACHE.get(cm_text);
      if (cached) {
        return cached;
      }
    }
    const change = _Parse.change_details(fragments, input_length);
    let ts_tree = ts_parser.parse(text2, change?.edited_old_ts_tree);
    if (ts_tree.rootNode.endIndex !== input_length) {
      log_error(
        "Mismatch between tree (%s) and document (%s) lengths; reparsing",
        ts_tree.rootNode.endIndex,
        input_length
      );
      ts_tree = ts_parser.parse(text2);
    }
    const extended_change = change ? _Parse.extend_change(change, ts_tree) : null;
    const tree = this.convert_tree(ts_tree, extended_change);
    this.parsedPos = input_length;
    if (cm_text) {
      PARSE_CACHE.set(cm_text, tree);
    }
    return tree;
  }
  stopAt(pos) {
    this.stoppedAt = pos;
  }
};
var LezerTSParser = class extends Parser2 {
  constructor(ts_parser, props2, top_node) {
    super();
    this.ts_parser = ts_parser;
    const types2 = ts_parser.getLanguage().types;
    this.node_types = types2.map(
      (name2, id2) => NodeType.define({ id: id2, name: name2, props: props2, top: name2 === top_node })
    );
  }
  /** The Lezer NodeTypes - all node types from the TS grammar with props assigned. */
  node_types;
  createParse(input, fragments, ranges) {
    return new Parse2(this.ts_parser, this.node_types, input, fragments, ranges);
  }
};

// src/codemirror/beancount.ts
async function loadBeancountParser() {
  const ts = import.meta.resolve(tree_sitter_default);
  const ts_beancount = import.meta.resolve(tree_sitter_beancount_default);
  await import_web_tree_sitter.default.init({ locateFile: () => ts });
  const lang = await import_web_tree_sitter.default.Language.load(ts_beancount);
  const parser = new import_web_tree_sitter.default();
  parser.setLanguage(lang);
  return parser;
}
var beancountLanguageFacet = defineLanguageFacet();
var beancountLanguageSupportExtensions = [
  beancountFold,
  syntaxHighlighting(beancountHighlight),
  beancountIndent,
  keymap.of([{ key: "Control-d", mac: "Meta-d", run: beancountFormat }]),
  beancountLanguageFacet.of({
    autocomplete: beancountCompletion,
    commentTokens: { line: ";" },
    indentOnInput: /^\s+\d\d\d\d/
  }),
  highlightTrailingWhitespace()
];
var props = [
  styleTags({
    account: tags2.className,
    currency: tags2.unit,
    date: tags2.special(tags2.number),
    string: tags2.string,
    "BALANCE CLOSE COMMODITY CUSTOM DOCUMENT EVENT NOTE OPEN PAD PRICE TRANSACTION QUERY": tags2.keyword,
    "tag link": tags2.labelName,
    number: tags2.number,
    key: tags2.propertyName,
    bool: tags2.bool,
    "PUSHTAG POPTAG PUSHMETA POPMETA OPTION PLUGIN INCLUDE": tags2.standard(
      tags2.string
    )
  }),
  languageDataProp.add(
    (type) => type.isTop ? beancountLanguageFacet : void 0
  )
];
var load_parser = null;
async function getBeancountLanguageSupport() {
  if (!load_parser) {
    load_parser = loadBeancountParser();
  }
  const ts_parser = await load_parser;
  return new LanguageSupport(
    new Language2(
      beancountLanguageFacet,
      new LezerTSParser(ts_parser, props, "beancount_file"),
      [],
      "beancount"
    ),
    beancountLanguageSupportExtensions
  );
}

// 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 = (context2) => {
  const token = context2.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 string3 = /^("[^"]*"|'[^']*')/;
var date2 = /^(?:#(?:"[^"]*"|'[^']*')|\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(string3)) {
      return "string";
    }
    if (stream.match(date2) ?? 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/ruler.ts
var rulerPlugin = (column) => ViewPlugin.define((view) => {
  const ruler = view.dom.appendChild(document.createElement("div"));
  ruler.style.position = "absolute";
  ruler.style.borderRight = "1px dotted black";
  ruler.style.height = "100%";
  ruler.style.opacity = "0.5";
  ruler.style.pointerEvents = "none";
  const updatePosition = () => {
    const firstLine = view.contentDOM.querySelector(".cm-line");
    if (firstLine) {
      const { paddingLeft } = getComputedStyle(firstLine);
      const domRect = view.dom.getBoundingClientRect();
      const contentDOMRect = view.contentDOM.getBoundingClientRect();
      const gutterWidth = contentDOMRect.x - domRect.x;
      const offset = column * view.defaultCharacterWidth + gutterWidth;
      ruler.style.width = paddingLeft;
      ruler.style.left = `${offset}px`;
    }
  };
  view.requestMeasure({ read: updatePosition });
  return {
    update(update2) {
      if (update2.viewportChanged || update2.geometryChanged) {
        view.requestMeasure({ read: updatePosition });
      }
    },
    destroy() {
      ruler.remove();
    }
  };
});

// src/codemirror/setup.ts
var baseExtensions = [
  lineNumbers(),
  highlightSpecialChars(),
  history(),
  foldGutter(),
  drawSelection(),
  EditorState.allowMultipleSelections.of(true),
  indentOnInput(),
  syntaxHighlighting(defaultHighlightStyle),
  bracketMatching(),
  closeBrackets(),
  autocompletion(),
  rectangularSelection(),
  highlightActiveLine(),
  highlightSelectionMatches(),
  lintGutter(),
  keymap.of([
    ...closeBracketsKeymap,
    ...defaultKeymap,
    ...searchKeymap,
    ...historyKeymap,
    ...foldKeymap,
    ...completionKeymap,
    ...lintKeymap,
    indentWithTab
  ])
];
function setup(value, extensions3) {
  const view = new EditorView({
    state: EditorState.create({ doc: value, extensions: extensions3 })
  });
  return {
    editor: view,
    renderEditor: (el) => {
      el.appendChild(view.dom);
    }
  };
}
function initDocumentPreviewEditor(value) {
  return setup(value, [
    baseExtensions,
    EditorState.readOnly.of(true),
    placeholder("Loading...")
  ]);
}
var BeancountTextarea = class extends HTMLTextAreaElement {
  constructor() {
    super();
    getBeancountLanguageSupport().then((beancount) => {
      const { editor: editor2 } = setup(this.value, [
        beancount,
        syntaxHighlighting(defaultHighlightStyle),
        EditorView.editable.of(false)
      ]);
      this.parentNode?.insertBefore(editor2.dom, this);
      this.style.display = "none";
    }).catch(log_error);
  }
};
function initBeancountEditor(value, onDocChanges, commands2, beancount) {
  const { indent, currency_column } = get_store_value(fava_options);
  return setup(value, [
    beancount,
    indentUnit.of(" ".repeat(indent)),
    ...currency_column ? [rulerPlugin(currency_column - 1)] : [],
    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/extensions.ts
var ExtensionApi = class {
  constructor(name2) {
    this.name = name2;
  }
  /** Send a request to an extension endpoint. */
  async request(endpoint, method, params, body2, output = "json") {
    const url = urlFor(`extension/${this.name}/${endpoint}`, params, false);
    let opts2 = {};
    if (body2) {
      opts2 = body2 instanceof FormData ? { body: body2 } : {
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body2)
      };
    }
    const response = await fetch2(url, { method, ...opts2 });
    if (output === "json") {
      return response.json();
    }
    if (output === "string") {
      return response.text();
    }
    return response;
  }
  /** GET an endpoint with parameters and return JSON. */
  get(endpoint, params) {
    return this.request(endpoint, "GET", params, void 0);
  }
  /** GET an endpoint with a body and return JSON. */
  put(endpoint, body2) {
    return this.request(endpoint, "PUT", void 0, body2);
  }
  /** POST to an endpoint with a body and return JSON. */
  post(endpoint, body2) {
    return this.request(endpoint, "POST", void 0, body2);
  }
  /** DELETE an endpoint and return JSON. */
  delete(endpoint) {
    return this.request(endpoint, "DELETE");
  }
};
var ExtensionData = class {
  constructor(extension, context2) {
    this.extension = extension;
    this.context = context2;
  }
  async init() {
    await this.extension.init?.(this.context);
  }
  onPageLoad() {
    this.extension.onPageLoad?.(this.context);
  }
  onExtensionPageLoad() {
    this.extension.onExtensionPageLoad?.(this.context);
  }
};
async function loadExtensionModule(name2) {
  const url = urlFor(`extension_js_module/${name2}.js`, void 0, false);
  const mod = await import(url);
  if (typeof mod.default === "object") {
    return new ExtensionData(mod.default, { api: new ExtensionApi(name2) });
  }
  throw new Error(
    `Error importing module for extension ${name2}: module must export "default" object`
  );
}
var loaded_extensions = /* @__PURE__ */ new Map();
async function getOrInitExtension(name2) {
  const loaded_ext = loaded_extensions.get(name2);
  if (loaded_ext) {
    return loaded_ext;
  }
  const ext_promise = loadExtensionModule(name2);
  loaded_extensions.set(name2, ext_promise);
  await (await ext_promise).init();
  return ext_promise;
}
function handleExtensionPageLoad() {
  const exts = get_store_value(extensions).filter((e3) => e3.has_js_module);
  for (const { name: name2 } of exts) {
    getOrInitExtension(name2).then((m) => {
      m.onPageLoad();
    }).catch(log_error);
  }
  const path2 = getUrlPath(window.location);
  if (path2?.startsWith("extension/")) {
    for (const { name: name2 } of exts) {
      if (path2.startsWith(`extension/${name2}`)) {
        getOrInitExtension(name2).then((m) => {
          m.onExtensionPageLoad();
        }).catch(log_error);
      }
    }
  }
}

// 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/index.ts
var get_direction = (o) => o === "asc" ? 1 : -1;
var collator = Intl.Collator();
var compare_strings = collator.compare.bind(collator);
var Sorter = class _Sorter {
  constructor(column, order) {
    this.column = column;
    this.order = order;
  }
  /** Get a new sorter by switching to a possibly different column. */
  switchColumn(column) {
    if (column === this.column) {
      return new _Sorter(column, this.order === "asc" ? "desc" : "asc");
    }
    return new _Sorter(column, "asc");
  }
  /** Sort the data. */
  sort(data) {
    return this.column.sort(data, get_direction(this.order));
  }
};
function sort_internal(data, value, compare2, direction) {
  const indices = Uint32Array.from(data, (_d, i) => i);
  const values = data.map(value);
  indices.sort((a, b) => direction * compare2(values[a], values[b]));
  return permute(data, indices);
}
var NumberColumn = class {
  constructor(name2, value) {
    this.name = name2;
    this.value = value;
  }
  compare = (a, b) => a - b;
  sort(data, direction) {
    return sort_internal(data, this.value, this.compare, direction);
  }
};
var DateColumn = class extends NumberColumn {
  constructor(name2) {
    super(name2, (d) => new Date(d.date).valueOf());
    this.name = name2;
  }
};
var StringColumn = class {
  constructor(name2, value) {
    this.name = name2;
    this.value = value;
  }
  compare = compare_strings;
  sort(data, direction) {
    return sort_internal(data, this.value, this.compare, direction);
  }
};
function parse_number(num) {
  const cleaned = num.replace(/[^\-?0-9.]/g, "");
  const n = parseFloat(cleaned);
  return Number.isNaN(n) ? 0 : n;
}
function compare_numbers(a, b) {
  return parse_number(a) - parse_number(b);
}
function sortElements(parent2, elements, selector, direction, type) {
  const comparator = type === "num" ? compare_numbers : compare_strings;
  const value = (a) => {
    const el = selector(a);
    return el?.getAttribute("data-sort-value") ?? el?.textContent ?? "";
  };
  const sorted_elements = sort_internal(elements, value, comparator, direction);
  const fragment = document.createDocumentFragment();
  sorted_elements.forEach((el) => {
    fragment.appendChild(el);
  });
  parent2.appendChild(fragment);
}
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 sort2 = (order) => {
      headers.forEach((el) => {
        el.removeAttribute("data-order");
      });
      header.setAttribute("data-order", order);
      sortElements(
        ol,
        [].slice.call(ol.children, 1),
        (li) => li.querySelector(`.${headerClass}`),
        get_direction(order),
        type
      );
    };
    if (name2 === initialColumn) {
      sort2(initialOrder);
    }
    header.addEventListener("click", () => {
      const order = header.getAttribute("data-order") === "asc" ? "desc" : "asc";
      sort2(order);
      journalSortOrder.set([name2, order]);
    });
  });
}
var SortableTable = class extends HTMLTableElement {
  constructor() {
    super();
    const body2 = this.tBodies.item(0);
    if (!this.tHead || !body2) {
      return;
    }
    const headers = [...this.tHead.querySelectorAll("th[data-sort]")];
    headers.forEach((header, index2) => {
      header.addEventListener("click", () => {
        const order = header.getAttribute("data-order") === "asc" ? "desc" : "asc";
        const type = header.getAttribute("data-sort");
        headers.forEach((e3) => {
          e3.removeAttribute("data-order");
        });
        header.setAttribute("data-order", order);
        sortElements(
          body2,
          [...body2.querySelectorAll("tr")],
          (tr) => tr.cells.item(index2),
          get_direction(order),
          type
        );
      });
    });
  }
};

// node_modules/svelte/src/runtime/internal/disclose-version/index.js
if (typeof window !== "undefined")
  (window.__svelte || (window.__svelte = { v: /* @__PURE__ */ new Set() })).v.add(PUBLIC_VERSION);

// src/keyboard-shortcuts.ts
function showTooltip2(target, description) {
  const { hidden } = target;
  if (hidden) {
    target.hidden = false;
  }
  const tooltip2 = document.createElement("div");
  tooltip2.className = "keyboard-tooltip";
  tooltip2.textContent = description;
  document.body.appendChild(tooltip2);
  const targetRect = target.getBoundingClientRect();
  const left2 = targetRect.left + Math.min((target.offsetWidth - tooltip2.offsetWidth) / 2, 10);
  const top3 = targetRect.top + (target.offsetHeight - tooltip2.offsetHeight) / 2;
  tooltip2.style.left = `${left2}px`;
  tooltip2.style.top = `${top3 + window.scrollY}px`;
  return () => {
    tooltip2.remove();
    if (hidden) {
      target.hidden = true;
    }
  };
}
function showTooltips() {
  const removes = [];
  document.querySelectorAll("[data-key]").forEach((el) => {
    const key2 = el.getAttribute("data-key");
    if (el instanceof HTMLElement && key2 !== null) {
      removes.push(showTooltip2(el, key2));
    }
  });
  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) {
  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 = keyboardShortcuts.get(lastTwoKeys) ?? keyboardShortcuts.get(eventKey);
  if (handler) {
    if (handler instanceof HTMLInputElement) {
      event.preventDefault();
      handler.focus();
    } else if (handler instanceof HTMLElement) {
      event.preventDefault();
      handler.click();
    } else {
      handler(event);
    }
  }
  if (event.key !== "Alt" && event.key !== "Control" && event.key !== "Shift") {
    lastChar = eventKey;
  }
}
document.addEventListener("keydown", keydown);
var isMac = (
  // This still seems to be the least bad way to check whether we are running on macOS or iOS
  // eslint-disable-next-line deprecation/deprecation
  navigator.platform.startsWith("Mac") || navigator.platform === "iPhone"
);
var modKey = isMac ? "Cmd" : "Ctrl";
function getKeySpecKey(spec) {
  if (typeof spec === "string") {
    return spec;
  }
  return isMac ? spec.mac ?? spec.key : spec.key;
}
function getKeySpecDescription(spec) {
  if (typeof spec === "string") {
    return spec;
  }
  const key2 = isMac ? spec.mac ?? spec.key : spec.key;
  return spec.note ? `${key2} - ${spec.note}` : key2;
}
function bindKey(spec, handler) {
  const key2 = getKeySpecKey(spec);
  const sequence = key2.split(" ");
  if (sequence.length > 2) {
    console.error("Only key sequences of length <=2 are supported: ", key2);
  }
  if (keyboardShortcuts.has(key2)) {
    console.warn("Duplicate keyboard shortcut: ", key2, handler);
  }
  keyboardShortcuts.set(key2, handler);
  return () => {
    keyboardShortcuts.delete(key2);
  };
}
var keyboardShortcut = (node, spec) => {
  const setup2 = (s) => {
    if (s) {
      node.setAttribute("data-key", getKeySpecDescription(s));
      const unbind = bindKey(s, node);
      return () => {
        unbind();
        node.removeAttribute("data-key");
      };
    }
    return () => {
    };
  };
  let destroy = setup2(spec);
  return {
    destroy,
    update(new_spec) {
      destroy();
      tick().then(() => {
        destroy = setup2(new_spec);
      }).catch(log_error);
    }
  };
};
function initGlobalKeyboardShortcuts() {
  bindKey("?", () => {
    const hide2 = showTooltips();
    const once = () => {
      hide2();
      document.removeEventListener("mousedown", once);
      document.removeEventListener("keydown", once);
      document.removeEventListener("scroll", once);
    };
    document.addEventListener("mousedown", once);
    document.addEventListener("keydown", once);
    document.addEventListener("scroll", 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 = (
    /*button_text*/
    ctx2[5] + ""
  );
  let t03;
  let t13;
  let button_title_value;
  let keyboardShortcut_action;
  let mounted;
  let dispose;
  function click_handler() {
    return (
      /*click_handler*/
      ctx2[3](
        /*type*/
        ctx2[4]
      )
    );
  }
  return {
    c() {
      button = element("button");
      t03 = text(t0_value);
      t13 = space();
      attr(button, "type", "button");
      attr(button, "title", button_title_value = /*title*/
      ctx2[6] ?? format(toggleText, { type: (
        /*button_text*/
        ctx2[5]
      ) }));
      toggle_class(button, "inactive", !/*active*/
      ctx2[0](
        /*type*/
        ctx2[4],
        /*supertype*/
        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,
            /*shortcut*/
            ctx2[7]
          )),
          listen(button, "click", click_handler)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & /*active, buttons*/
      1) {
        toggle_class(button, "inactive", !/*active*/
        ctx2[0](
          /*type*/
          ctx2[4],
          /*supertype*/
          ctx2[8]
        ));
      }
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_fragment(ctx2) {
  let form;
  let each_value = ensure_array_like(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) {
        if (each_blocks[i]) {
          each_blocks[i].m(form, null);
        }
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & /*buttons, toggleText, active, toggle*/
      1) {
        each_value = ensure_array_like(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 set2 = new Set(show);
    const toggle_func = set2.has(type) ? set2.delete.bind(set2) : set2.add.bind(set2);
    toggle_func(type);
    buttons.filter((b) => b[4] === type).forEach((b) => toggle_func(b[0]));
    return [...set2].sort();
  });
}
function instance2($$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 & /*$journalShow*/
    4) {
      $:
        $$invalidate(1, shownSet = new Set($journalShow));
    }
    if ($$self.$$.dirty & /*shownSet*/
    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(options3) {
    super();
    init2(this, options3, instance2, 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 key2 = target.previousElementSibling.innerText;
    const value = `"^${escape(target.innerText)}$"`;
    const expr = `${key2}${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 {
  component;
  unsubscribe;
  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() {
    this.unsubscribe?.();
    this.component?.$destroy();
  }
};

// src/reports/Error.svelte
function create_fragment2(ctx2) {
  let h2;
  let t03;
  let t13;
  let t22;
  let t32;
  let p;
  let t4_value = (
    /*error*/
    ctx2[1].message + ""
  );
  let t4;
  return {
    c() {
      h2 = element("h2");
      t03 = text("Loading ");
      t13 = text(
        /*title*/
        ctx2[0]
      );
      t22 = text(" failed with error:");
      t32 = space();
      p = element("p");
      t4 = text(t4_value);
      attr(p, "class", "svelte-1hq0khr");
    },
    m(target, anchor) {
      insert(target, h2, anchor);
      append(h2, t03);
      append(h2, t13);
      append(h2, t22);
      insert(target, t32, anchor);
      insert(target, p, anchor);
      append(p, t4);
    },
    p(ctx3, [dirty]) {
      if (dirty & /*title*/
      1)
        set_data(
          t13,
          /*title*/
          ctx3[0]
        );
      if (dirty & /*error*/
      2 && t4_value !== (t4_value = /*error*/
      ctx3[1].message + ""))
        set_data(t4, t4_value);
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(h2);
        detach(t32);
        detach(p);
      }
    }
  };
}
function instance3($$self, $$props, $$invalidate) {
  let { title } = $$props;
  let { error: error2 } = $$props;
  $$self.$$set = ($$props2) => {
    if ("title" in $$props2)
      $$invalidate(0, title = $$props2.title);
    if ("error" in $$props2)
      $$invalidate(1, error2 = $$props2.error);
  };
  return [title, error2];
}
var Error2 = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance3, create_fragment2, safe_not_equal, { title: 0, error: 1 });
  }
};
var Error_default = Error2;

// src/reports/route.ts
var Route = class {
  /**
   * Create a new frontend-rendered route.
   * @param report URL slug of this report.
   * @param Component the component to render for this report.
   * @param load function to load the necessary data.
   * @param get_title function to get the page title.
   */
  constructor(report, Component, load, get_title) {
    this.report = report;
    this.Component = Component;
    this.load = load;
    this.get_title = get_title;
  }
  /** The currently rendered instance - if loading failed, we render an error component. */
  instance;
  /** The currently rendered URL. */
  url;
  /** The title of this report. */
  get title() {
    return this.get_title(this);
  }
  /** Destroy any components that might be rendered by this route. */
  destroy() {
    this.instance?.component.$destroy();
    this.instance = void 0;
  }
  /** Load data and render the component for this route to the given target. */
  async render(target, url, previous) {
    if (previous !== this) {
      previous?.destroy();
    }
    try {
      const props2 = await this.load(url);
      if (previous === this && this.instance?.error === false) {
        this.instance.component.$set(props2);
      } else {
        this.destroy();
        target.innerHTML = "";
        this.instance = {
          error: false,
          component: new this.Component({ target, props: props2 })
        };
      }
    } catch (error2) {
      log_error(error2);
      if (error2 instanceof Error) {
        this.destroy();
        target.innerHTML = "";
        this.instance = {
          error: true,
          component: new Error_default({
            target,
            props: { title: this.title, error: error2 }
          })
        };
      }
    } finally {
      this.url = url;
    }
  }
};
var noload = () => ({});

// node_modules/d3-shape/src/constant.js
function constant_default2(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 sqrt = Math.sqrt;
var epsilon = 1e-12;
var pi = Math.PI;
var halfPi = pi / 2;
var tau = 2 * pi;
function acos(x2) {
  return x2 > 1 ? 0 : x2 < -1 ? pi : Math.acos(x2);
}
function asin(x2) {
  return x2 >= 1 ? halfPi : x2 <= -1 ? -halfPi : Math.asin(x2);
}

// node_modules/d3-path/src/path.js
var pi2 = Math.PI;
var tau2 = 2 * pi2;
var epsilon2 = 1e-6;
var tauEpsilon = tau2 - epsilon2;
function append2(strings) {
  this._ += strings[0];
  for (let i = 1, n = strings.length; i < n; ++i) {
    this._ += arguments[i] + strings[i];
  }
}
function appendRound(digits) {
  let d = Math.floor(digits);
  if (!(d >= 0))
    throw new Error(`invalid digits: ${digits}`);
  if (d > 15)
    return append2;
  const k = 10 ** d;
  return function(strings) {
    this._ += strings[0];
    for (let i = 1, n = strings.length; i < n; ++i) {
      this._ += Math.round(arguments[i] * k) / k + strings[i];
    }
  };
}
var Path = class {
  constructor(digits) {
    this._x0 = this._y0 = // start of current subpath
    this._x1 = this._y1 = null;
    this._ = "";
    this._append = digits == null ? append2 : appendRound(digits);
  }
  moveTo(x2, y2) {
    this._append`M${this._x0 = this._x1 = +x2},${this._y0 = this._y1 = +y2}`;
  }
  closePath() {
    if (this._x1 !== null) {
      this._x1 = this._x0, this._y1 = this._y0;
      this._append`Z`;
    }
  }
  lineTo(x2, y2) {
    this._append`L${this._x1 = +x2},${this._y1 = +y2}`;
  }
  quadraticCurveTo(x1, y1, x2, y2) {
    this._append`Q${+x1},${+y1},${this._x1 = +x2},${this._y1 = +y2}`;
  }
  bezierCurveTo(x1, y1, x2, y2, x3, y3) {
    this._append`C${+x1},${+y1},${+x2},${+y2},${this._x1 = +x3},${this._y1 = +y3}`;
  }
  arcTo(x1, y1, x2, y2, r) {
    x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;
    if (r < 0)
      throw new Error(`negative radius: ${r}`);
    let 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 (this._x1 === null) {
      this._append`M${this._x1 = x1},${this._y1 = y1}`;
    } else if (!(l01_2 > epsilon2))
      ;
    else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon2) || !r) {
      this._append`L${this._x1 = x1},${this._y1 = y1}`;
    } else {
      let 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((pi2 - 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._append`L${x1 + t01 * x01},${y1 + t01 * y01}`;
      }
      this._append`A${r},${r},0,0,${+(y01 * x20 > x01 * y20)},${this._x1 = x1 + t21 * x21},${this._y1 = y1 + t21 * y21}`;
    }
  }
  arc(x2, y2, r, a0, a1, ccw) {
    x2 = +x2, y2 = +y2, r = +r, ccw = !!ccw;
    if (r < 0)
      throw new Error(`negative radius: ${r}`);
    let 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 (this._x1 === null) {
      this._append`M${x0},${y0}`;
    } else if (Math.abs(this._x1 - x0) > epsilon2 || Math.abs(this._y1 - y0) > epsilon2) {
      this._append`L${x0},${y0}`;
    }
    if (!r)
      return;
    if (da < 0)
      da = da % tau2 + tau2;
    if (da > tauEpsilon) {
      this._append`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._append`A${r},${r},0,${+(da >= pi2)},${cw},${this._x1 = x2 + r * Math.cos(a1)},${this._y1 = y2 + r * Math.sin(a1)}`;
    }
  }
  rect(x2, y2, w, h) {
    this._append`M${this._x0 = this._x1 = +x2},${this._y0 = this._y1 = +y2}h${w = +w}v${+h}h${-w}Z`;
  }
  toString() {
    return this._;
  }
};
function path() {
  return new Path();
}
path.prototype = Path.prototype;

// node_modules/d3-shape/src/path.js
function withPath(shape) {
  let digits = 3;
  shape.digits = function(_2) {
    if (!arguments.length)
      return digits;
    if (_2 == null) {
      digits = null;
    } else {
      const d = Math.floor(_2);
      if (!(d >= 0))
        throw new RangeError(`invalid digits: ${_2}`);
      digits = d;
    }
    return shape;
  };
  return () => new Path(digits);
}

// 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 < epsilon)
    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) / sqrt(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) * sqrt(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_default2(0), padRadius = null, startAngle = arcStartAngle, endAngle = arcEndAngle, padAngle = arcPadAngle, context2 = null, path2 = withPath(arc);
  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 (!context2)
      context2 = buffer = path2();
    if (r1 < r0)
      r = r1, r1 = r0, r0 = r;
    if (!(r1 > epsilon))
      context2.moveTo(0, 0);
    else if (da > tau - epsilon) {
      context2.moveTo(r1 * cos(a0), r1 * sin(a0));
      context2.arc(0, 0, r1, a0, a1, !cw);
      if (r0 > epsilon) {
        context2.moveTo(r0 * cos(a1), r0 * sin(a1));
        context2.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 > epsilon && (padRadius ? +padRadius.apply(this, arguments) : sqrt(r0 * r0 + r1 * r1)), rc = min2(abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments)), rc0 = rc, rc1 = rc, t03, t13;
      if (rp > epsilon) {
        var p0 = asin(rp / r0 * sin(ap)), p1 = asin(rp / r1 * sin(ap));
        if ((da0 -= p0 * 2) > epsilon)
          p0 *= cw ? 1 : -1, a00 += p0, a10 -= p0;
        else
          da0 = 0, a00 = a10 = (a0 + a1) / 2;
        if ((da1 -= p1 * 2) > epsilon)
          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 > epsilon) {
        var x11 = r1 * cos(a11), y11 = r1 * sin(a11), x00 = r0 * cos(a00), y00 = r0 * sin(a00), oc;
        if (da < pi) {
          if (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) / (sqrt(ax * ax + ay * ay) * sqrt(bx * bx + by * by))) / 2), lc = sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
            rc0 = min2(rc, (r0 - lc) / (kc - 1));
            rc1 = min2(rc, (r1 - lc) / (kc + 1));
          } else {
            rc0 = rc1 = 0;
          }
        }
      }
      if (!(da1 > epsilon))
        context2.moveTo(x01, y01);
      else if (rc1 > epsilon) {
        t03 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw);
        t13 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw);
        context2.moveTo(t03.cx + t03.x01, t03.cy + t03.y01);
        if (rc1 < rc)
          context2.arc(t03.cx, t03.cy, rc1, atan2(t03.y01, t03.x01), atan2(t13.y01, t13.x01), !cw);
        else {
          context2.arc(t03.cx, t03.cy, rc1, atan2(t03.y01, t03.x01), atan2(t03.y11, t03.x11), !cw);
          context2.arc(0, 0, r1, atan2(t03.cy + t03.y11, t03.cx + t03.x11), atan2(t13.cy + t13.y11, t13.cx + t13.x11), !cw);
          context2.arc(t13.cx, t13.cy, rc1, atan2(t13.y11, t13.x11), atan2(t13.y01, t13.x01), !cw);
        }
      } else
        context2.moveTo(x01, y01), context2.arc(0, 0, r1, a01, a11, !cw);
      if (!(r0 > epsilon) || !(da0 > epsilon))
        context2.lineTo(x10, y10);
      else if (rc0 > epsilon) {
        t03 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw);
        t13 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw);
        context2.lineTo(t03.cx + t03.x01, t03.cy + t03.y01);
        if (rc0 < rc)
          context2.arc(t03.cx, t03.cy, rc0, atan2(t03.y01, t03.x01), atan2(t13.y01, t13.x01), !cw);
        else {
          context2.arc(t03.cx, t03.cy, rc0, atan2(t03.y01, t03.x01), atan2(t03.y11, t03.x11), !cw);
          context2.arc(0, 0, r0, atan2(t03.cy + t03.y11, t03.cx + t03.x11), atan2(t13.cy + t13.y11, t13.cx + t13.x11), cw);
          context2.arc(t13.cx, t13.cy, rc0, atan2(t13.y11, t13.x11), atan2(t13.y01, t13.x01), !cw);
        }
      } else
        context2.arc(0, 0, r0, a10, a00, cw);
    }
    context2.closePath();
    if (buffer)
      return context2 = 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 - pi / 2;
    return [cos(a) * r, sin(a) * r];
  };
  arc.innerRadius = function(_2) {
    return arguments.length ? (innerRadius = typeof _2 === "function" ? _2 : constant_default2(+_2), arc) : innerRadius;
  };
  arc.outerRadius = function(_2) {
    return arguments.length ? (outerRadius = typeof _2 === "function" ? _2 : constant_default2(+_2), arc) : outerRadius;
  };
  arc.cornerRadius = function(_2) {
    return arguments.length ? (cornerRadius = typeof _2 === "function" ? _2 : constant_default2(+_2), arc) : cornerRadius;
  };
  arc.padRadius = function(_2) {
    return arguments.length ? (padRadius = _2 == null ? null : typeof _2 === "function" ? _2 : constant_default2(+_2), arc) : padRadius;
  };
  arc.startAngle = function(_2) {
    return arguments.length ? (startAngle = typeof _2 === "function" ? _2 : constant_default2(+_2), arc) : startAngle;
  };
  arc.endAngle = function(_2) {
    return arguments.length ? (endAngle = typeof _2 === "function" ? _2 : constant_default2(+_2), arc) : endAngle;
  };
  arc.padAngle = function(_2) {
    return arguments.length ? (padAngle = typeof _2 === "function" ? _2 : constant_default2(+_2), arc) : padAngle;
  };
  arc.context = function(_2) {
    return arguments.length ? (context2 = _2 == null ? null : _2, arc) : context2;
  };
  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(context2) {
  this._context = context2;
}
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(context2) {
  return new Linear(context2);
}

// 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_default2(true), context2 = null, curve = linear_default, output = null, path2 = withPath(line);
  x2 = typeof x2 === "function" ? x2 : x2 === void 0 ? x : constant_default2(x2);
  y2 = typeof y2 === "function" ? y2 : y2 === void 0 ? y : constant_default2(y2);
  function line(data) {
    var i, n = (data = array_default(data)).length, d, defined0 = false, buffer;
    if (context2 == null)
      output = curve(buffer = path2());
    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_default2(+_2), line) : x2;
  };
  line.y = function(_2) {
    return arguments.length ? (y2 = typeof _2 === "function" ? _2 : constant_default2(+_2), line) : y2;
  };
  line.defined = function(_2) {
    return arguments.length ? (defined = typeof _2 === "function" ? _2 : constant_default2(!!_2), line) : defined;
  };
  line.curve = function(_2) {
    return arguments.length ? (curve = _2, context2 != null && (output = curve(context2)), line) : curve;
  };
  line.context = function(_2) {
    return arguments.length ? (_2 == null ? context2 = output = null : output = curve(context2 = _2), line) : context2;
  };
  return line;
}

// node_modules/d3-shape/src/area.js
function area_default(x0, y0, y1) {
  var x1 = null, defined = constant_default2(true), context2 = null, curve = linear_default, output = null, path2 = withPath(area);
  x0 = typeof x0 === "function" ? x0 : x0 === void 0 ? x : constant_default2(+x0);
  y0 = typeof y0 === "function" ? y0 : y0 === void 0 ? constant_default2(0) : constant_default2(+y0);
  y1 = typeof y1 === "function" ? y1 : y1 === void 0 ? y : constant_default2(+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 (context2 == null)
      output = curve(buffer = path2());
    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(context2);
  }
  area.x = function(_2) {
    return arguments.length ? (x0 = typeof _2 === "function" ? _2 : constant_default2(+_2), x1 = null, area) : x0;
  };
  area.x0 = function(_2) {
    return arguments.length ? (x0 = typeof _2 === "function" ? _2 : constant_default2(+_2), area) : x0;
  };
  area.x1 = function(_2) {
    return arguments.length ? (x1 = _2 == null ? null : typeof _2 === "function" ? _2 : constant_default2(+_2), area) : x1;
  };
  area.y = function(_2) {
    return arguments.length ? (y0 = typeof _2 === "function" ? _2 : constant_default2(+_2), y1 = null, area) : y0;
  };
  area.y0 = function(_2) {
    return arguments.length ? (y0 = typeof _2 === "function" ? _2 : constant_default2(+_2), area) : y0;
  };
  area.y1 = function(_2) {
    return arguments.length ? (y1 = _2 == null ? null : typeof _2 === "function" ? _2 : constant_default2(+_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_default2(!!_2), area) : defined;
  };
  area.curve = function(_2) {
    return arguments.length ? (curve = _2, context2 != null && (output = curve(context2)), area) : curve;
  };
  area.context = function(_2) {
    return arguments.length ? (_2 == null ? context2 = output = null : output = curve(context2 = _2), area) : context2;
  };
  return area;
}

// node_modules/d3-shape/src/curve/step.js
function Step(context2, t4) {
  this._context = context2;
  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(context2) {
  return new Step(context2, 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, key2) {
  return d[key2];
}
function stackSeries(key2) {
  const series = [];
  series.key = key2;
  return series;
}
function stack_default() {
  var keys = constant_default2([]), 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_default2(Array.from(_2)), stack) : keys;
  };
  stack.value = function(_2) {
    return arguments.length ? (value = typeof _2 === "function" ? _2 : constant_default2(+_2), stack) : value;
  };
  stack.order = function(_2) {
    return arguments.length ? (order = _2 == null ? none_default2 : typeof _2 === "function" ? _2 : constant_default2(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;
      }
    }
  }
}

// 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_default3(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, key2) {
  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 = key2.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 = key2.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, key2) {
  if (!arguments.length)
    return Array.from(this, datum);
  var bind2 = key2 ? bindKey2 : bindIndex, parents = this._parents, groups2 = this._groups;
  if (typeof value !== "function")
    value = constant_default3(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, key2);
    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(context2) {
  var selection2 = context2.selection ? context2.selection() : context2;
  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, merge = merges[j] = new Array(n), node, i = 0; i < n; ++i) {
      if (node = group0[i] || group1[i]) {
        merge[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_default2(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_default2(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(string4) {
  return string4.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 create = typeof name2 === "function" ? name2 : creator_default(name2);
  return this.select(function() {
    return this.appendChild(create.apply(this, arguments));
  });
}

// node_modules/d3-selection/src/selection/insert.js
function constantNull() {
  return null;
}
function insert_default(name2, before) {
  var create = 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(create.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, options3) {
  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 = options3);
          o.value = value;
          return;
        }
      }
    this.addEventListener(typename.type, listener, options3);
    o = { type: typename.type, name: typename.name, value, listener, options: options3 };
    if (!on)
      this.__on = [o];
    else
      on.push(o);
  };
}
function on_default(typename, value, options3) {
  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, options3));
  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_default2() {
  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_default2,
  call: call_default,
  nodes: nodes_default,
  node: node_default,
  size: size_default,
  empty: empty_default,
  each: each_default2,
  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_default2
};

// 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/tooltip.ts
var tooltip = /* @__PURE__ */ (() => {
  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 = {
  /** Create a <br> element. */
  br: () => document.createElement("br"),
  /** Create a <em> element with the given content. */
  em: (content2) => {
    const em = document.createElement("em");
    em.textContent = content2;
    return em;
  },
  /** Create a text node for the given text. */
  t: (text2) => document.createTextNode(text2),
  /** Create a <pre> element with the given content. */
  pre: (content2) => {
    const pre = document.createElement("pre");
    pre.textContent = content2;
    return pre;
  }
};
var 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;
    }
  };
};
var 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/bar.ts
var bar_validator = array(
  object({
    date,
    budgets: record(number),
    balance: record(number),
    account_balances: record(record(number))
  })
);
var BarChart = class {
  constructor(name2, currencies2, bar_groups) {
    this.name = name2;
    this.currencies = currencies2;
    this.bar_groups = bar_groups;
    this.accounts = Array.from(
      new Set(bar_groups.map((d) => Object.keys(d.account_balances)).flat(2))
    ).sort();
    this.stacks = currencies2.map((currency) => [
      currency,
      stack_default().keys(this.accounts).value((d, account2) => d.account_balances[account2]?.[currency] ?? 0).offset(diverging_default)(bar_groups).filter((b) => b[0] !== b[1] && !Number.isNaN(b[1]))
    ]);
  }
  type = "barchart";
  /** The accounts that occur in some bar.  */
  accounts;
  /** For each currency, the stacks (one series per account) */
  stacks;
  filter(hidden_names) {
    const hidden_names_set = new Set(hidden_names);
    const currencies2 = new Set(
      this.currencies.filter((c) => !hidden_names_set.has(c))
    );
    const bar_groups = this.bar_groups.map((b) => ({
      ...b,
      values: b.values.filter((v) => currencies2.has(v.currency))
    }));
    const stacks = this.stacks.filter((s) => currencies2.has(s[0]));
    return { currencies: [...currencies2], bar_groups, stacks };
  }
  /** Whether this chart contains any stacks (or is just a single account). */
  get hasStackedData() {
    return this.accounts.length > 1;
  }
  /** The tooltip for a hovered account in the stacked bar chart. */
  tooltipTextAccount(c, d, account2) {
    const content2 = [];
    content2.push(domHelpers.em(account2));
    d.values.forEach((a) => {
      const value = d.account_balances[account2]?.[a.currency] ?? 0;
      content2.push(domHelpers.t(c.amount(value, a.currency)));
      content2.push(domHelpers.br());
    });
    content2.push(domHelpers.em(d.label));
    return content2;
  }
  /** The tooltip for a hovered bar group in the bar chart. */
  tooltipText(c, d) {
    const content2 = [];
    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());
    });
    content2.push(domHelpers.em(d.label));
    return content2;
  }
};
function currencies_to_show(data, $chartContext) {
  const counts = rollup(
    data.flatMap((interval2) => [
      ...Object.keys(interval2.budgets),
      ...Object.keys(interval2.balance)
    ]),
    (v) => v.length,
    (r) => r
  );
  const to_show = $chartContext.currencies.filter((c) => counts.delete(c));
  to_show.push(
    ...[...counts].sort((a, b) => b[1] - a[1]).map((i) => i[0]).slice(0, Math.max(to_show.length, 5) - to_show.length)
  );
  return to_show;
}
function bar(label, json, $chartContext) {
  return bar_validator(json).map((parsedData) => {
    const currencies2 = currencies_to_show(parsedData, $chartContext);
    const bar_groups = parsedData.map((interval2) => ({
      values: currencies2.map((currency) => ({
        currency,
        value: interval2.balance[currency] ?? 0,
        budget: interval2.budgets[currency] ?? 0
      })),
      date: interval2.date,
      label: $chartContext.dateFormat(interval2.date),
      account_balances: interval2.account_balances
    }));
    return new BarChart(label, currencies2, bar_groups);
  });
}

// src/charts/line.ts
var LineChart = class {
  constructor(name2, data, tooltipText) {
    this.name = name2;
    this.data = data;
    this.tooltipText = tooltipText;
    this.data = sort(data, (d) => -d.values.length);
    this.series_names = this.data.map((series) => series.name);
  }
  type = "linechart";
  series_names;
  /** Filter the data of this chart, excluding some series. */
  filter(hidden_names) {
    const hidden_names_set = new Set(hidden_names);
    return this.data.filter((series) => !hidden_names_set.has(series.name));
  }
};
var balances_validator = array(object({ date, balance: record(number) }));
function balances(label, json) {
  return balances_validator(json).map((parsedData) => {
    const groups2 = /* @__PURE__ */ new Map();
    for (const { date: date_val, balance } of parsedData) {
      Object.entries(balance).forEach(([currency, value]) => {
        const group2 = groups2.get(currency);
        const datum2 = { date: date_val, value, name: currency };
        if (group2) {
          group2.push(datum2);
        } else {
          groups2.set(currency, [datum2]);
        }
      });
    }
    const data = [...groups2.entries()].map(([name2, values]) => ({
      name: name2,
      values
    }));
    return new LineChart(label, data, (c, d) => [
      domHelpers.t(c.amount(d.value, d.name)),
      domHelpers.em(day(d.date))
    ]);
  });
}

// src/charts/scatterplot.ts
var ScatterPlot = class {
  constructor(name2, data) {
    this.name = name2;
    this.data = data;
  }
  type = "scatterplot";
};
var scatterplot_validator = array(
  object({ type: string, date, description: string })
);
function scatterplot(label, json) {
  return scatterplot_validator(json).map(
    (value) => new ScatterPlot(label, value)
  );
}

// src/charts/index.ts
var parsers = {
  balances,
  bar,
  hierarchy: hierarchy2,
  scatterplot
};
var chart_data_validator = array(
  object({ label: string, type: string, data: unknown })
);
function parseChartData(data, $chartContext) {
  return chart_data_validator(data).and_then(
    (chartData) => collect(
      chartData.map((chart) => {
        const parser = parsers[chart.type];
        return parser ? parser(chart.label, chart.data, $chartContext).map_err(
          (msg) => `Parsing of data for ${chart.type} chart failed:
${msg}`
        ) : err2(`Unknown chart type ${chart.type}`);
      })
    )
  );
}

// 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 epsilon3 = 1e-6;
function translateX(x2) {
  return "translate(" + x2 + ",0)";
}
function translateY(y2) {
  return "translate(0," + y2 + ")";
}
function number4(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(context2) {
    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 : number4)(scale.copy(), offset), selection2 = context2.selection ? context2.selection() : context2, 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 (context2 !== selection2) {
      path2 = path2.transition(context2);
      tick2 = tick2.transition(context2);
      line = line.transition(context2);
      text2 = text2.transition(context2);
      tickExit = tickExit.transition(context2).attr("opacity", epsilon3).attr("transform", function(d) {
        return isFinite(d = position(d)) ? transform(d + offset) : this.getAttribute("transform");
      });
      tickEnter.attr("opacity", epsilon3).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, start2 = reverse ? r1 : r0, stop2 = reverse ? r0 : r1;
    step = (stop2 - start2) / Math.max(1, n - paddingInner + paddingOuter * 2);
    if (round)
      step = Math.floor(step);
    start2 += (stop2 - start2 - step * (n - paddingInner)) * align;
    bandwidth = step * (1 - paddingInner);
    if (round)
      start2 = Math.round(start2), bandwidth = Math.round(bandwidth);
    var values = range(n).map(function(i) {
      return start2 + 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 key2 in definition)
    prototype[key2] = definition[key2];
  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,
  // Deprecated! Use 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,
  // Deprecated! Use color.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_default4 = (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_default4(isNaN(a) ? b : a);
  };
}
function nogamma(a, b) {
  var d = b - a;
  return d ? linear(a, d) : constant_default4(isNaN(a) ? b : a);
}

// node_modules/d3-interpolate/src/rgb.js
var rgb_default = function rgbGamma(y2) {
  var color2 = gamma(y2);
  function rgb2(start2, end) {
    var r = color2((start2 = rgb(start2)).r, (end = rgb(end)).r), g = color2(start2.g, end.g), b = color2(start2.b, end.b), opacity = nogamma(start2.opacity, end.opacity);
    return function(t4) {
      start2.r = r(t4);
      start2.g = g(t4);
      start2.b = b(t4);
      start2.opacity = opacity(t4);
      return start2 + "";
    };
  }
  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 = /* @__PURE__ */ 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_default4(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_default2(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 number5(x2) {
  return +x2;
}

// node_modules/d3-scale/src/continuous.js
var unit = [0, 1];
function identity3(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(source2, target) {
  return target.domain(source2.domain()).range(source2.range()).interpolate(source2.interpolate()).clamp(source2.clamp()).unknown(source2.unknown());
}
function transformer() {
  var domain = unit, range2 = unit, interpolate = value_default, transform, untransform, unknown2, clamp = identity3, piecewise, output, input;
  function rescale() {
    var n = Math.min(domain.length, range2.length);
    if (clamp !== identity3)
      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, number5), 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_default2, rescale();
  };
  scale.clamp = function(_2) {
    return arguments.length ? (clamp = _2 ? true : identity3, rescale()) : clamp !== identity3;
  };
  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()(identity3, identity3);
}

// node_modules/d3-scale/src/tickFormat.js
function tickFormat(start2, stop2, count2, specifier) {
  var step = tickStep(start2, stop2, count2), precision;
  specifier = formatSpecifier(specifier == null ? ",f" : specifier);
  switch (specifier.type) {
    case "s": {
      var value = Math.max(Math.abs(start2), Math.abs(stop2));
      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(start2), Math.abs(stop2)))))
        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 format2(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 start2 = d[i0];
    var stop2 = d[i1];
    var prestep;
    var step;
    var maxIter = 10;
    if (stop2 < start2) {
      step = start2, start2 = stop2, stop2 = step;
      step = i0, i0 = i1, i1 = step;
    }
    while (maxIter-- > 0) {
      step = tickIncrement(start2, stop2, count2);
      if (step === prestep) {
        d[i0] = start2;
        d[i1] = stop2;
        return domain(d);
      } else if (step > 0) {
        start2 = Math.floor(start2 / step) * step;
        stop2 = Math.ceil(stop2 / step) * step;
      } else if (step < 0) {
        start2 = Math.ceil(start2 * step) / step;
        stop2 = Math.floor(stop2 * 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(identity3, identity3), exponent = 1;
  function rescale() {
    return exponent === 1 ? transform(identity3, identity3) : 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 sqrt2() {
  return pow.apply(null, arguments).exponent(0.5);
}

// node_modules/d3-scale/src/time.js
function date3(t4) {
  return new Date(t4);
}
function number6(t4) {
  return t4 instanceof Date ? +t4 : +/* @__PURE__ */ new Date(+t4);
}
function calendar(ticks2, tickInterval, year, month, week, day2, hour, minute, 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(date4) {
    return (second2(date4) < date4 ? formatMillisecond : minute(date4) < date4 ? formatSecond : hour(date4) < date4 ? formatMinute : day2(date4) < date4 ? formatHour : month(date4) < date4 ? week(date4) < date4 ? formatDay : formatWeek : year(date4) < date4 ? formatMonth : formatYear2)(date4);
  }
  scale.invert = function(y2) {
    return new Date(invert(y2));
  };
  scale.domain = function(_2) {
    return arguments.length ? domain(Array.from(_2, number6)) : domain().map(date3);
  };
  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, year, month, week, day2, hour, minute, second2, format3));
  };
  return scale;
}

// node_modules/d3-scale/src/utcTime.js
function utcTime() {
  return initRange.apply(calendar(utcTicks, utcTickInterval, utcYear, utcMonth, utcSunday, utcDay, utcHour, utcMinute, second, utcFormat).domain([Date.UTC(2e3, 0, 1), Date.UTC(2e3, 0, 2)]), arguments);
}

// src/stores/format.ts
var replaceNumbers = (num) => num.replace(/[0-9]/g, "X");
var short_format = format2(".3s");
var short = derived(
  incognito,
  ($incognito) => $incognito ? (n) => replaceNumbers(short_format(n)) : short_format
);
var ctx = derived(
  [incognito, locale, precisions],
  ([$incognito, $locale, $precisions]) => {
    const formatter = localeFormatter($locale);
    const currencyFormatters = Object.fromEntries(
      Object.entries($precisions).map(([currency, prec2]) => [
        currency,
        localeFormatter($locale, prec2)
      ])
    );
    const num_raw = (n, c) => (currencyFormatters[c] ?? formatter)(n);
    const num = $incognito ? (n, c) => replaceNumbers(num_raw(n, c)) : num_raw;
    return {
      amount: (n, c) => `${num(n, c)} ${c}`,
      num
    };
  }
);
var currentDateFormat = derived(interval, (val) => dateFormat[val]);
var currentTimeFilterDateFormat = derived(
  interval,
  (val) => timeFilterDateFormat[val]
);

// src/charts/Axis.svelte
function create_if_block(ctx2) {
  let g;
  let line;
  let line_x__value;
  let g_transform_value;
  return {
    c() {
      g = svg_element("g");
      line = svg_element("line");
      attr(line, "x2", line_x__value = -/*axis*/
      ctx2[0].tickSizeInner());
      attr(line, "class", "svelte-1spnwv9");
      attr(g, "class", "zero svelte-1spnwv9");
      attr(g, "transform", g_transform_value = `translate(0,${/*lineAtZero*/
      ctx2[2]})`);
    },
    m(target, anchor) {
      insert(target, g, anchor);
      append(g, line);
    },
    p(ctx3, dirty) {
      if (dirty & /*axis*/
      1 && line_x__value !== (line_x__value = -/*axis*/
      ctx3[0].tickSizeInner())) {
        attr(line, "x2", line_x__value);
      }
      if (dirty & /*lineAtZero*/
      4 && g_transform_value !== (g_transform_value = `translate(0,${/*lineAtZero*/
      ctx3[2]})`)) {
        attr(g, "transform", g_transform_value);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(g);
      }
    }
  };
}
function create_fragment3(ctx2) {
  let g;
  let renderAxis_action;
  let mounted;
  let dispose;
  let if_block = (
    /*y*/
    ctx2[1] && /*lineAtZero*/
    ctx2[2] !== null && create_if_block(ctx2)
  );
  return {
    c() {
      g = svg_element("g");
      if (if_block)
        if_block.c();
      attr(
        g,
        "transform",
        /*transform*/
        ctx2[3]
      );
      attr(g, "class", "svelte-1spnwv9");
      toggle_class(
        g,
        "y",
        /*y*/
        ctx2[1]
      );
    },
    m(target, anchor) {
      insert(target, g, anchor);
      if (if_block)
        if_block.m(g, null);
      if (!mounted) {
        dispose = action_destroyer(renderAxis_action = /*renderAxis*/
        ctx2[4].call(
          null,
          g,
          /*axis*/
          ctx2[0]
        ));
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (
        /*y*/
        ctx3[1] && /*lineAtZero*/
        ctx3[2] !== null
      ) {
        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 (dirty & /*transform*/
      8) {
        attr(
          g,
          "transform",
          /*transform*/
          ctx3[3]
        );
      }
      if (renderAxis_action && is_function(renderAxis_action.update) && dirty & /*axis*/
      1)
        renderAxis_action.update.call(
          null,
          /*axis*/
          ctx3[0]
        );
      if (dirty & /*y*/
      2) {
        toggle_class(
          g,
          "y",
          /*y*/
          ctx3[1]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(g);
      }
      if (if_block)
        if_block.d();
      mounted = false;
      dispose();
    }
  };
}
function instance4($$self, $$props, $$invalidate) {
  let transform;
  let { axis: axis2 } = $$props;
  let { x: x2 = false } = $$props;
  let { y: y2 = false } = $$props;
  let { lineAtZero = null } = $$props;
  let { innerHeight: innerHeight2 = 0 } = $$props;
  const renderAxis = (node, ax) => {
    const selection2 = select_default2(node);
    ax(selection2);
    return {
      update(new_ax) {
        new_ax(selection2);
      }
    };
  };
  $$self.$$set = ($$props2) => {
    if ("axis" in $$props2)
      $$invalidate(0, axis2 = $$props2.axis);
    if ("x" in $$props2)
      $$invalidate(5, x2 = $$props2.x);
    if ("y" in $$props2)
      $$invalidate(1, y2 = $$props2.y);
    if ("lineAtZero" in $$props2)
      $$invalidate(2, lineAtZero = $$props2.lineAtZero);
    if ("innerHeight" in $$props2)
      $$invalidate(6, innerHeight2 = $$props2.innerHeight);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*x, innerHeight*/
    96) {
      $:
        $$invalidate(3, transform = x2 ? `translate(0,${innerHeight2})` : void 0);
    }
  };
  return [axis2, y2, lineAtZero, transform, renderAxis, x2, innerHeight2];
}
var Axis = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance4, create_fragment3, safe_not_equal, {
      axis: 0,
      x: 5,
      y: 1,
      lineAtZero: 2,
      innerHeight: 6
    });
  }
};
var Axis_default = Axis;

// src/charts/helpers.ts
function urlForTimeFilter(date4) {
  const url = new URL(window.location.href);
  url.searchParams.set("time", get_store_value(currentTimeFilterDateFormat)(date4));
  return url.toString();
}
function includeZero([from, to]) {
  if (from === void 0) {
    return [0, 1];
  }
  return [Math.min(0, from), Math.max(0, to)];
}
function padExtent([from, to]) {
  if (from === void 0) {
    return [0, 1];
  }
  const diff = to - from;
  return [from - diff * 0.03, to + diff * 0.03];
}
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) => ordinal(colors15).domain($accounts)
);
var sunburstScale = derived(
  accounts,
  ($accounts) => ordinal(colors10).domain($accounts)
);
var currenciesScale = derived(
  [operating_currency, currencies_sorted],
  ([$operating_currency, $currencies_sorted]) => ordinal(colors10).domain([
    ...$operating_currency,
    ...$currencies_sorted
  ])
);

// src/charts/BarChart.svelte
function get_each_context2(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[35] = list[i][0];
  child_ctx[36] = list[i][1];
  return child_ctx;
}
function get_each_context_1(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[39] = list[i];
  const constants_0 = (
    /*stack*/
    child_ctx[39].key
  );
  child_ctx[40] = constants_0;
  return child_ctx;
}
function get_each_context_2(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[43] = list[i];
  return child_ctx;
}
function get_each_context_3(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[46] = list[i];
  return child_ctx;
}
function get_each_context_4(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[35] = list[i].currency;
  child_ctx[49] = list[i].value;
  child_ctx[50] = list[i].budget;
  return child_ctx;
}
function create_if_block_1(ctx2) {
  let each_1_anchor;
  let each_value_4 = ensure_array_like(
    /*group*/
    ctx2[46].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) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx3, dirty) {
      if (dirty[0] & /*x1, bar_groups, y, $currenciesScale*/
      8516) {
        each_value_4 = ensure_array_like(
          /*group*/
          ctx3[46].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) {
      if (detaching) {
        detach(each_1_anchor);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
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 = /*$currenciesScale*/
      ctx2[8](
        /*currency*/
        ctx2[35]
      ));
      attr(rect0, "width", rect0_width_value = /*x1*/
      ctx2[13].bandwidth());
      attr(rect0, "x", rect0_x_value = /*x1*/
      ctx2[13](
        /*currency*/
        ctx2[35]
      ));
      attr(rect0, "y", rect0_y_value = /*y*/
      ctx2[2](Math.max(
        0,
        /*value*/
        ctx2[49]
      )));
      attr(rect0, "height", rect0_height_value = Math.abs(
        /*y*/
        ctx2[2](
          /*value*/
          ctx2[49]
        ) - /*y*/
        ctx2[2](0)
      ));
      attr(rect1, "class", "budget svelte-1azm6ea");
      attr(rect1, "width", rect1_width_value = /*x1*/
      ctx2[13].bandwidth());
      attr(rect1, "x", rect1_x_value = /*x1*/
      ctx2[13](
        /*currency*/
        ctx2[35]
      ));
      attr(rect1, "y", rect1_y_value = /*y*/
      ctx2[2](Math.max(
        0,
        /*budget*/
        ctx2[50]
      )));
      attr(rect1, "height", rect1_height_value = Math.abs(
        /*y*/
        ctx2[2](
          /*budget*/
          ctx2[50]
        ) - /*y*/
        ctx2[2](0)
      ));
    },
    m(target, anchor) {
      insert(target, rect0, anchor);
      insert(target, rect1, anchor);
    },
    p(ctx3, dirty) {
      if (dirty[0] & /*$currenciesScale, bar_groups*/
      320 && rect0_fill_value !== (rect0_fill_value = /*$currenciesScale*/
      ctx3[8](
        /*currency*/
        ctx3[35]
      ))) {
        attr(rect0, "fill", rect0_fill_value);
      }
      if (dirty[0] & /*x1*/
      8192 && rect0_width_value !== (rect0_width_value = /*x1*/
      ctx3[13].bandwidth())) {
        attr(rect0, "width", rect0_width_value);
      }
      if (dirty[0] & /*x1, bar_groups*/
      8256 && rect0_x_value !== (rect0_x_value = /*x1*/
      ctx3[13](
        /*currency*/
        ctx3[35]
      ))) {
        attr(rect0, "x", rect0_x_value);
      }
      if (dirty[0] & /*y, bar_groups*/
      68 && rect0_y_value !== (rect0_y_value = /*y*/
      ctx3[2](Math.max(
        0,
        /*value*/
        ctx3[49]
      )))) {
        attr(rect0, "y", rect0_y_value);
      }
      if (dirty[0] & /*y, bar_groups*/
      68 && rect0_height_value !== (rect0_height_value = Math.abs(
        /*y*/
        ctx3[2](
          /*value*/
          ctx3[49]
        ) - /*y*/
        ctx3[2](0)
      ))) {
        attr(rect0, "height", rect0_height_value);
      }
      if (dirty[0] & /*x1*/
      8192 && rect1_width_value !== (rect1_width_value = /*x1*/
      ctx3[13].bandwidth())) {
        attr(rect1, "width", rect1_width_value);
      }
      if (dirty[0] & /*x1, bar_groups*/
      8256 && rect1_x_value !== (rect1_x_value = /*x1*/
      ctx3[13](
        /*currency*/
        ctx3[35]
      ))) {
        attr(rect1, "x", rect1_x_value);
      }
      if (dirty[0] & /*y, bar_groups*/
      68 && rect1_y_value !== (rect1_y_value = /*y*/
      ctx3[2](Math.max(
        0,
        /*budget*/
        ctx3[50]
      )))) {
        attr(rect1, "y", rect1_y_value);
      }
      if (dirty[0] & /*y, bar_groups*/
      68 && rect1_height_value !== (rect1_height_value = Math.abs(
        /*y*/
        ctx3[2](
          /*budget*/
          ctx3[50]
        ) - /*y*/
        ctx3[2](0)
      ))) {
        attr(rect1, "height", rect1_height_value);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(rect0);
        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 = !/*showStackedBars*/
  ctx2[4] && create_if_block_1(ctx2);
  function followingTooltip_function() {
    return (
      /*followingTooltip_function*/
      ctx2[29](
        /*group*/
        ctx2[46]
      )
    );
  }
  return {
    c() {
      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 = /*x0*/
      (ctx2[3].bandwidth() - /*x0*/
      ctx2[3].step()) / 2);
      attr(rect0, "width", rect0_width_value = /*x0*/
      ctx2[3].step());
      attr(
        rect0,
        "height",
        /*innerHeight*/
        ctx2[5]
      );
      attr(rect1, "class", "axis-group-box svelte-1azm6ea");
      attr(rect1, "transform", rect1_transform_value = `translate(0,${/*innerHeight*/
      ctx2[5]})`);
      attr(rect1, "width", rect1_width_value = /*x0*/
      ctx2[3].bandwidth());
      attr(rect1, "height", rect1_height_value = /*margin*/
      ctx2[18].bottom);
      attr(a, "href", a_href_value = urlForTimeFilter(
        /*group*/
        ctx2[46].date
      ));
      attr(g, "class", "group svelte-1azm6ea");
      attr(g, "transform", g_transform_value = `translate(${/*x0*/
      ctx2[3](
        /*group*/
        ctx2[46].label
      ) ?? 0},0)`);
      toggle_class(
        g,
        "desaturate",
        /*group*/
        ctx2[46].date > /*today*/
        ctx2[17]
      );
    },
    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) {
      ctx2 = new_ctx;
      if (dirty[0] & /*x0*/
      8 && rect0_x_value !== (rect0_x_value = /*x0*/
      (ctx2[3].bandwidth() - /*x0*/
      ctx2[3].step()) / 2)) {
        attr(rect0, "x", rect0_x_value);
      }
      if (dirty[0] & /*x0*/
      8 && rect0_width_value !== (rect0_width_value = /*x0*/
      ctx2[3].step())) {
        attr(rect0, "width", rect0_width_value);
      }
      if (dirty[0] & /*innerHeight*/
      32) {
        attr(
          rect0,
          "height",
          /*innerHeight*/
          ctx2[5]
        );
      }
      if (dirty[0] & /*innerHeight*/
      32 && rect1_transform_value !== (rect1_transform_value = `translate(0,${/*innerHeight*/
      ctx2[5]})`)) {
        attr(rect1, "transform", rect1_transform_value);
      }
      if (dirty[0] & /*x0*/
      8 && rect1_width_value !== (rect1_width_value = /*x0*/
      ctx2[3].bandwidth())) {
        attr(rect1, "width", rect1_width_value);
      }
      if (dirty[0] & /*bar_groups*/
      64 && a_href_value !== (a_href_value = urlForTimeFilter(
        /*group*/
        ctx2[46].date
      ))) {
        attr(a, "href", a_href_value);
      }
      if (!/*showStackedBars*/
      ctx2[4]) {
        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] & /*x0, bar_groups*/
      72 && g_transform_value !== (g_transform_value = `translate(${/*x0*/
      ctx2[3](
        /*group*/
        ctx2[46].label
      ) ?? 0},0)`)) {
        attr(g, "transform", g_transform_value);
      }
      if (followingTooltip_action && is_function(followingTooltip_action.update) && dirty[0] & /*chart, $ctx, bar_groups*/
      32833)
        followingTooltip_action.update.call(null, followingTooltip_function);
      if (dirty[0] & /*bar_groups, today*/
      131136) {
        toggle_class(
          g,
          "desaturate",
          /*group*/
          ctx2[46].date > /*today*/
          ctx2[17]
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(g);
      }
      if (if_block)
        if_block.d();
      mounted = false;
      dispose();
    }
  };
}
function create_if_block2(ctx2) {
  let each_1_anchor;
  let each_value = ensure_array_like(
    /*stacks*/
    ctx2[7]
  );
  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) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx3, dirty) {
      if (dirty[0] & /*stacks, $urlForAccount, highlighted, x1, x0, y, colorScale, chart, $ctx, today*/
      242317) {
        each_value = ensure_array_like(
          /*stacks*/
          ctx3[7]
        );
        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) {
      if (detaching) {
        detach(each_1_anchor);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
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 followingTooltip_function_1() {
    return (
      /*followingTooltip_function_1*/
      ctx2[30](
        /*bar*/
        ctx2[43],
        /*account*/
        ctx2[40]
      )
    );
  }
  return {
    c() {
      rect = svg_element("rect");
      attr(rect, "width", rect_width_value = /*x1*/
      ctx2[13].bandwidth());
      attr(rect, "x", rect_x_value = /*x0*/
      (ctx2[3](
        /*bar*/
        ctx2[43].data.label
      ) ?? 0) + /*x1*/
      (ctx2[13](
        /*currency*/
        ctx2[35]
      ) ?? 0));
      attr(rect, "y", rect_y_value = /*y*/
      ctx2[2](Math.max(
        /*bar*/
        ctx2[43][0],
        /*bar*/
        ctx2[43][1]
      )));
      attr(rect, "height", rect_height_value = Math.abs(
        /*y*/
        ctx2[2](
          /*bar*/
          ctx2[43][1]
        ) - /*y*/
        ctx2[2](
          /*bar*/
          ctx2[43][0]
        )
      ));
      attr(rect, "fill", rect_fill_value = /*colorScale*/
      ctx2[12](
        /*account*/
        ctx2[40]
      ));
      attr(rect, "class", "svelte-1azm6ea");
      toggle_class(
        rect,
        "desaturate",
        /*bar*/
        ctx2[43].data.date > /*today*/
        ctx2[17]
      );
    },
    m(target, anchor) {
      insert(target, rect, anchor);
      if (!mounted) {
        dispose = action_destroyer(followingTooltip_action = followingTooltip.call(null, rect, followingTooltip_function_1));
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty[0] & /*x1*/
      8192 && rect_width_value !== (rect_width_value = /*x1*/
      ctx2[13].bandwidth())) {
        attr(rect, "width", rect_width_value);
      }
      if (dirty[0] & /*x0, stacks, x1*/
      8328 && rect_x_value !== (rect_x_value = /*x0*/
      (ctx2[3](
        /*bar*/
        ctx2[43].data.label
      ) ?? 0) + /*x1*/
      (ctx2[13](
        /*currency*/
        ctx2[35]
      ) ?? 0))) {
        attr(rect, "x", rect_x_value);
      }
      if (dirty[0] & /*y, stacks*/
      132 && rect_y_value !== (rect_y_value = /*y*/
      ctx2[2](Math.max(
        /*bar*/
        ctx2[43][0],
        /*bar*/
        ctx2[43][1]
      )))) {
        attr(rect, "y", rect_y_value);
      }
      if (dirty[0] & /*y, stacks*/
      132 && rect_height_value !== (rect_height_value = Math.abs(
        /*y*/
        ctx2[2](
          /*bar*/
          ctx2[43][1]
        ) - /*y*/
        ctx2[2](
          /*bar*/
          ctx2[43][0]
        )
      ))) {
        attr(rect, "height", rect_height_value);
      }
      if (dirty[0] & /*colorScale, stacks*/
      4224 && rect_fill_value !== (rect_fill_value = /*colorScale*/
      ctx2[12](
        /*account*/
        ctx2[40]
      ))) {
        attr(rect, "fill", rect_fill_value);
      }
      if (followingTooltip_action && is_function(followingTooltip_action.update) && dirty[0] & /*chart, $ctx, stacks*/
      32897)
        followingTooltip_action.update.call(null, followingTooltip_function_1);
      if (dirty[0] & /*stacks, today*/
      131200) {
        toggle_class(
          rect,
          "desaturate",
          /*bar*/
          ctx2[43].data.date > /*today*/
          ctx2[17]
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(rect);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_each_block_1(ctx2) {
  let a;
  let g;
  let a_href_value;
  let t4;
  let mounted;
  let dispose;
  let each_value_2 = ensure_array_like(
    /*stack*/
    ctx2[39]
  );
  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));
  }
  function mouseover_handler() {
    return (
      /*mouseover_handler*/
      ctx2[31](
        /*account*/
        ctx2[40]
      )
    );
  }
  function focus_handler() {
    return (
      /*focus_handler*/
      ctx2[32](
        /*account*/
        ctx2[40]
      )
    );
  }
  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");
      attr(g, "role", "img");
      toggle_class(
        g,
        "faded",
        /*highlighted*/
        ctx2[9] && /*account*/
        ctx2[40] !== /*highlighted*/
        ctx2[9]
      );
      attr(a, "href", a_href_value = /*$urlForAccount*/
      ctx2[16](
        /*account*/
        ctx2[40]
      ));
    },
    m(target, anchor) {
      insert(target, a, anchor);
      append(a, g);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(g, null);
        }
      }
      insert(target, t4, anchor);
      if (!mounted) {
        dispose = [
          listen(g, "mouseover", mouseover_handler),
          listen(g, "focus", focus_handler),
          listen(
            g,
            "mouseout",
            /*mouseout_handler*/
            ctx2[33]
          ),
          listen(
            g,
            "blur",
            /*blur_handler*/
            ctx2[34]
          )
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty[0] & /*x1, x0, stacks, y, colorScale, chart, $ctx, today*/
      176269) {
        each_value_2 = ensure_array_like(
          /*stack*/
          ctx2[39]
        );
        let i;
        for (i = 0; i < each_value_2.length; i += 1) {
          const child_ctx = get_each_context_2(ctx2, 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] & /*highlighted, stacks*/
      640) {
        toggle_class(
          g,
          "faded",
          /*highlighted*/
          ctx2[9] && /*account*/
          ctx2[40] !== /*highlighted*/
          ctx2[9]
        );
      }
      if (dirty[0] & /*$urlForAccount, stacks*/
      65664 && a_href_value !== (a_href_value = /*$urlForAccount*/
      ctx2[16](
        /*account*/
        ctx2[40]
      ))) {
        attr(a, "href", a_href_value);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(a);
        detach(t4);
      }
      destroy_each(each_blocks, detaching);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_each_block2(ctx2) {
  let each_1_anchor;
  let each_value_1 = ensure_array_like(
    /*account_stacks*/
    ctx2[36]
  );
  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) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx3, dirty) {
      if (dirty[0] & /*$urlForAccount, stacks, highlighted, x1, x0, y, colorScale, chart, $ctx, today*/
      242317) {
        each_value_1 = ensure_array_like(
          /*account_stacks*/
          ctx3[36]
        );
        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) {
      if (detaching) {
        detach(each_1_anchor);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_fragment4(ctx2) {
  let svg2;
  let g;
  let axis0;
  let axis1;
  let each_1_anchor;
  let g_transform_value;
  let svg_viewBox_value;
  let current;
  axis0 = new Axis_default({
    props: {
      x: true,
      axis: (
        /*xAxis*/
        ctx2[11]
      ),
      innerHeight: (
        /*innerHeight*/
        ctx2[5]
      )
    }
  });
  axis1 = new Axis_default({
    props: {
      y: true,
      axis: (
        /*yAxis*/
        ctx2[10]
      ),
      lineAtZero: (
        /*y*/
        ctx2[2](0)
      )
    }
  });
  let each_value_3 = ensure_array_like(
    /*bar_groups*/
    ctx2[6]
  );
  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 = (
    /*showStackedBars*/
    ctx2[4] && create_if_block2(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(${/*offset*/
      ctx2[14]},${/*margin*/
      ctx2[18].top})`);
      attr(svg2, "viewBox", svg_viewBox_value = `0 0 ${/*width*/
      ctx2[1]} ${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) {
        if (each_blocks[i]) {
          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] & /*xAxis*/
      2048)
        axis0_changes.axis = /*xAxis*/
        ctx3[11];
      if (dirty[0] & /*innerHeight*/
      32)
        axis0_changes.innerHeight = /*innerHeight*/
        ctx3[5];
      axis0.$set(axis0_changes);
      const axis1_changes = {};
      if (dirty[0] & /*yAxis*/
      1024)
        axis1_changes.axis = /*yAxis*/
        ctx3[10];
      if (dirty[0] & /*y*/
      4)
        axis1_changes.lineAtZero = /*y*/
        ctx3[2](0);
      axis1.$set(axis1_changes);
      if (dirty[0] & /*x0, bar_groups, chart, $ctx, today, x1, y, $currenciesScale, showStackedBars, innerHeight, margin*/
      434557) {
        each_value_3 = ensure_array_like(
          /*bar_groups*/
          ctx3[6]
        );
        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 (
        /*showStackedBars*/
        ctx3[4]
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block2(ctx3);
          if_block.c();
          if_block.m(g, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (!current || dirty[0] & /*offset*/
      16384 && g_transform_value !== (g_transform_value = `translate(${/*offset*/
      ctx3[14]},${/*margin*/
      ctx3[18].top})`)) {
        attr(g, "transform", g_transform_value);
      }
      if (!current || dirty[0] & /*width*/
      2 && svg_viewBox_value !== (svg_viewBox_value = `0 0 ${/*width*/
      ctx3[1]} ${height}`)) {
        attr(svg2, "viewBox", svg_viewBox_value);
      }
    },
    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 instance5($$self, $$props, $$invalidate) {
  let accounts2;
  let filtered;
  let currencies2;
  let bar_groups;
  let stacks;
  let innerHeight2;
  let maxWidth;
  let offset;
  let innerWidth;
  let showStackedBars;
  let x0;
  let x1;
  let yExtent;
  let y2;
  let colorScale;
  let xAxis;
  let yAxis;
  let $short;
  let $currenciesScale;
  let $barChartMode;
  let $chartToggledCurrencies;
  let $ctx;
  let $urlForAccount;
  component_subscribe($$self, short, ($$value) => $$invalidate(26, $short = $$value));
  component_subscribe($$self, currenciesScale, ($$value) => $$invalidate(8, $currenciesScale = $$value));
  component_subscribe($$self, barChartMode, ($$value) => $$invalidate(27, $barChartMode = $$value));
  component_subscribe($$self, chartToggledCurrencies, ($$value) => $$invalidate(28, $chartToggledCurrencies = $$value));
  component_subscribe($$self, ctx, ($$value) => $$invalidate(15, $ctx = $$value));
  component_subscribe($$self, urlForAccount, ($$value) => $$invalidate(16, $urlForAccount = $$value));
  let { chart } = $$props;
  let { width } = $$props;
  let { legend } = $$props;
  const today = /* @__PURE__ */ new Date();
  const margin = { top: 10, right: 10, bottom: 30, left: 40 };
  let highlighted = null;
  const followingTooltip_function = (group2) => chart.tooltipText($ctx, group2);
  const followingTooltip_function_1 = (bar2, account2) => chart.tooltipTextAccount($ctx, bar2.data, account2);
  const mouseover_handler = (account2) => {
    $$invalidate(9, highlighted = account2);
  };
  const focus_handler = (account2) => {
    $$invalidate(9, highlighted = account2);
  };
  const mouseout_handler = () => {
    $$invalidate(9, highlighted = null);
  };
  const blur_handler = () => {
    $$invalidate(9, highlighted = null);
  };
  $$self.$$set = ($$props2) => {
    if ("chart" in $$props2)
      $$invalidate(0, chart = $$props2.chart);
    if ("width" in $$props2)
      $$invalidate(1, width = $$props2.width);
    if ("legend" in $$props2)
      $$invalidate(19, legend = $$props2.legend);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*chart*/
    1) {
      $:
        $$invalidate(21, accounts2 = chart.accounts);
    }
    if ($$self.$$.dirty[0] & /*chart, $chartToggledCurrencies*/
    268435457) {
      $:
        $$invalidate(25, filtered = chart.filter($chartToggledCurrencies));
    }
    if ($$self.$$.dirty[0] & /*filtered*/
    33554432) {
      $:
        $$invalidate(23, currencies2 = filtered.currencies);
    }
    if ($$self.$$.dirty[0] & /*filtered*/
    33554432) {
      $:
        $$invalidate(6, bar_groups = filtered.bar_groups);
    }
    if ($$self.$$.dirty[0] & /*filtered*/
    33554432) {
      $:
        $$invalidate(7, stacks = filtered.stacks);
    }
    if ($$self.$$.dirty[0] & /*bar_groups*/
    64) {
      $:
        $$invalidate(24, maxWidth = bar_groups.length * maxColumnWidth);
    }
    if ($$self.$$.dirty[0] & /*width, maxWidth*/
    16777218) {
      $:
        $$invalidate(14, offset = margin.left + Math.max(0, width - maxWidth) / 2);
    }
    if ($$self.$$.dirty[0] & /*width, maxWidth*/
    16777218) {
      $:
        $$invalidate(20, innerWidth = Math.min(width - margin.left - margin.right, maxWidth));
    }
    if ($$self.$$.dirty[0] & /*$barChartMode, chart*/
    134217729) {
      $:
        $$invalidate(4, showStackedBars = $barChartMode === "stacked" && chart.hasStackedData);
    }
    if ($$self.$$.dirty[0] & /*innerWidth, bar_groups*/
    1048640) {
      $:
        $$invalidate(3, x0 = band([0, innerWidth]).domain(bar_groups.map((d) => d.label)).padding(0.1));
    }
    if ($$self.$$.dirty[0] & /*x0, currencies*/
    8388616) {
      $:
        $$invalidate(13, x1 = band([0, x0.bandwidth()]).domain(currencies2));
    }
    if ($$self.$$.dirty[0] & /*showStackedBars, stacks, bar_groups*/
    208) {
      $:
        $$invalidate(22, yExtent = showStackedBars ? extent(stacks.flatMap(([, s]) => s.flat(2))) : extent(bar_groups.map((d) => d.values).flat(), (d) => d.value));
    }
    if ($$self.$$.dirty[0] & /*innerHeight, yExtent*/
    4194336) {
      $:
        $$invalidate(2, y2 = linear2([innerHeight2, 0]).domain(padExtent(includeZero(yExtent))));
    }
    if ($$self.$$.dirty[0] & /*accounts*/
    2097152) {
      $:
        $$invalidate(12, colorScale = ordinal(hclColorRange(accounts2.length)).domain(accounts2));
    }
    if ($$self.$$.dirty[0] & /*legend, chart, showStackedBars, $currenciesScale*/
    524561) {
      $:
        legend.set(chart.currencies.map((c) => [c, showStackedBars ? null : $currenciesScale(c)]));
    }
    if ($$self.$$.dirty[0] & /*x0, innerWidth*/
    1048584) {
      $:
        $$invalidate(11, xAxis = axisBottom(x0).tickSizeOuter(0).tickValues(filterTicks(x0.domain(), innerWidth / 70)));
    }
    if ($$self.$$.dirty[0] & /*y, innerWidth, $short*/
    68157444) {
      $:
        $$invalidate(10, yAxis = axisLeft(y2).tickPadding(6).tickSize(-innerWidth).tickFormat($short));
    }
  };
  $:
    $$invalidate(5, innerHeight2 = height - margin.top - margin.bottom);
  return [
    chart,
    width,
    y2,
    x0,
    showStackedBars,
    innerHeight2,
    bar_groups,
    stacks,
    $currenciesScale,
    highlighted,
    yAxis,
    xAxis,
    colorScale,
    x1,
    offset,
    $ctx,
    $urlForAccount,
    today,
    margin,
    legend,
    innerWidth,
    accounts2,
    yExtent,
    currencies2,
    maxWidth,
    filtered,
    $short,
    $barChartMode,
    $chartToggledCurrencies,
    followingTooltip_function,
    followingTooltip_function_1,
    mouseover_handler,
    focus_handler,
    mouseout_handler,
    blur_handler
  ];
}
var BarChart2 = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance5, create_fragment4, safe_not_equal, { chart: 0, width: 1, legend: 19 }, null, [-1, -1]);
  }
};
var BarChart_default = BarChart2;

// src/charts/ChartLegend.svelte
function get_each_context3(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[6] = list[i][0];
  child_ctx[7] = list[i][1];
  return child_ctx;
}
function create_each_block3(ctx2) {
  let button;
  let i;
  let t03;
  let span;
  let t1_value = (
    /*item*/
    ctx2[6] + ""
  );
  let t13;
  let t22;
  let mounted;
  let dispose;
  function click_handler() {
    return (
      /*click_handler*/
      ctx2[5](
        /*item*/
        ctx2[6]
      )
    );
  }
  return {
    c() {
      button = element("button");
      i = element("i");
      t03 = space();
      span = element("span");
      t13 = text(t1_value);
      t22 = space();
      set_style(
        i,
        "background-color",
        /*color*/
        ctx2[7] ?? "#bbb"
      );
      attr(i, "class", "svelte-1ba2yj1");
      attr(span, "class", "svelte-1ba2yj1");
      attr(button, "type", "button");
      attr(button, "class", "svelte-1ba2yj1");
      toggle_class(
        button,
        "inactive",
        /*active*/
        ctx2[2] ? (
          /*item*/
          ctx2[6] !== /*$active*/
          ctx2[3]
        ) : (
          /*$toggled*/
          ctx2[4]?.includes(
            /*item*/
            ctx2[6]
          )
        )
      );
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, i);
      append(button, t03);
      append(button, span);
      append(span, t13);
      append(button, t22);
      if (!mounted) {
        dispose = listen(button, "click", click_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & /*legend*/
      1) {
        set_style(
          i,
          "background-color",
          /*color*/
          ctx2[7] ?? "#bbb"
        );
      }
      if (dirty & /*legend*/
      1 && t1_value !== (t1_value = /*item*/
      ctx2[6] + ""))
        set_data(t13, t1_value);
      if (dirty & /*active, legend, $active, $toggled*/
      29) {
        toggle_class(
          button,
          "inactive",
          /*active*/
          ctx2[2] ? (
            /*item*/
            ctx2[6] !== /*$active*/
            ctx2[3]
          ) : (
            /*$toggled*/
            ctx2[4]?.includes(
              /*item*/
              ctx2[6]
            )
          )
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_fragment5(ctx2) {
  let div;
  let each_value = ensure_array_like(
    /*legend*/
    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() {
      div = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
    },
    m(target, anchor) {
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div, null);
        }
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & /*active, legend, $active, $toggled, toggled*/
      31) {
        each_value = ensure_array_like(
          /*legend*/
          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(div, 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(div);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function instance6($$self, $$props, $$invalidate) {
  let $active, $$unsubscribe_active = noop, $$subscribe_active = () => ($$unsubscribe_active(), $$unsubscribe_active = subscribe(active, ($$value) => $$invalidate(3, $active = $$value)), active);
  let $toggled, $$unsubscribe_toggled = noop, $$subscribe_toggled = () => ($$unsubscribe_toggled(), $$unsubscribe_toggled = subscribe(toggled, ($$value) => $$invalidate(4, $toggled = $$value)), toggled);
  $$self.$$.on_destroy.push(() => $$unsubscribe_active());
  $$self.$$.on_destroy.push(() => $$unsubscribe_toggled());
  let { legend } = $$props;
  let { toggled = null } = $$props;
  $$subscribe_toggled();
  let { active = null } = $$props;
  $$subscribe_active();
  const click_handler = (item) => {
    if (active) {
      active.set(item);
    } else if (toggled) {
      toggled.update((v) => v.includes(item) ? v.filter((i) => i !== item) : [...v, item]);
    }
  };
  $$self.$$set = ($$props2) => {
    if ("legend" in $$props2)
      $$invalidate(0, legend = $$props2.legend);
    if ("toggled" in $$props2)
      $$subscribe_toggled($$invalidate(1, toggled = $$props2.toggled));
    if ("active" in $$props2)
      $$subscribe_active($$invalidate(2, active = $$props2.active));
  };
  return [legend, toggled, active, $active, $toggled, click_handler];
}
var ChartLegend = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance6, create_fragment5, safe_not_equal, { legend: 0, toggled: 1, active: 2 });
  }
};
var ChartLegend_default = ChartLegend;

// src/charts/Sunburst.svelte
function get_each_context4(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[18] = 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 (
      /*mouseover_handler*/
      ctx2[13](
        /*d*/
        ctx2[18]
      )
    );
  }
  function focus_handler() {
    return (
      /*focus_handler*/
      ctx2[14](
        /*d*/
        ctx2[18]
      )
    );
  }
  return {
    c() {
      a = svg_element("a");
      path2 = svg_element("path");
      attr(path2, "fill-rule", "evenodd");
      attr(path2, "fill", path_fill_value = /*$sunburstScale*/
      ctx2[8](
        /*d*/
        ctx2[18].data.account
      ));
      attr(path2, "d", path_d_value = /*arcShape*/
      ctx2[5](
        /*d*/
        ctx2[18]
      ));
      attr(path2, "role", "img");
      attr(path2, "class", "svelte-1j2l4ij");
      toggle_class(
        path2,
        "half",
        /*current*/
        ctx2[4] && !/*current*/
        ctx2[4].data.account.startsWith(
          /*d*/
          ctx2[18].data.account
        )
      );
      attr(a, "href", a_href_value = /*$urlForAccount*/
      ctx2[7](
        /*d*/
        ctx2[18].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) {
      ctx2 = new_ctx;
      if (dirty & /*$sunburstScale, nodes*/
      320 && path_fill_value !== (path_fill_value = /*$sunburstScale*/
      ctx2[8](
        /*d*/
        ctx2[18].data.account
      ))) {
        attr(path2, "fill", path_fill_value);
      }
      if (dirty & /*arcShape, nodes*/
      96 && path_d_value !== (path_d_value = /*arcShape*/
      ctx2[5](
        /*d*/
        ctx2[18]
      ))) {
        attr(path2, "d", path_d_value);
      }
      if (dirty & /*current, nodes*/
      80) {
        toggle_class(
          path2,
          "half",
          /*current*/
          ctx2[4] && !/*current*/
          ctx2[4].data.account.startsWith(
            /*d*/
            ctx2[18].data.account
          )
        );
      }
      if (dirty & /*$urlForAccount, nodes*/
      192 && a_href_value !== (a_href_value = /*$urlForAccount*/
      ctx2[7](
        /*d*/
        ctx2[18].data.account
      ))) {
        attr(a, "href", a_href_value);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(a);
      }
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_fragment6(ctx2) {
  let g;
  let circle;
  let text0;
  let t0_value = (
    /*current*/
    (ctx2[4] ?? /*root*/
    ctx2[3]).data.account + ""
  );
  let t03;
  let text1;
  let t1_value = (
    /*balanceText*/
    ctx2[9](
      /*current*/
      ctx2[4] ?? /*root*/
      ctx2[3]
    ) + ""
  );
  let t13;
  let g_transform_value;
  let mounted;
  let dispose;
  let each_value = ensure_array_like(
    /*nodes*/
    ctx2[6]
  );
  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(t0_value);
      text1 = svg_element("text");
      t13 = text(t1_value);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      set_style(circle, "opacity", "0");
      attr(
        circle,
        "r",
        /*radius*/
        ctx2[2]
      );
      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",
        /*width*/
        ctx2[0]
      );
      attr(
        g,
        "height",
        /*height*/
        ctx2[1]
      );
      attr(g, "transform", g_transform_value = `translate(${/*width*/
      ctx2[0] / 2},${/*height*/
      ctx2[1] / 2})`);
      attr(g, "role", "img");
    },
    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) {
        if (each_blocks[i]) {
          each_blocks[i].m(g, null);
        }
      }
      if (!mounted) {
        dispose = listen(
          g,
          "mouseleave",
          /*mouseleave_handler*/
          ctx2[15]
        );
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & /*radius*/
      4) {
        attr(
          circle,
          "r",
          /*radius*/
          ctx3[2]
        );
      }
      if (dirty & /*current, root*/
      24 && t0_value !== (t0_value = /*current*/
      (ctx3[4] ?? /*root*/
      ctx3[3]).data.account + ""))
        set_data(t03, t0_value);
      if (dirty & /*current, root*/
      24 && t1_value !== (t1_value = /*balanceText*/
      ctx3[9](
        /*current*/
        ctx3[4] ?? /*root*/
        ctx3[3]
      ) + ""))
        set_data(t13, t1_value);
      if (dirty & /*$urlForAccount, nodes, $sunburstScale, arcShape, current*/
      496) {
        each_value = ensure_array_like(
          /*nodes*/
          ctx3[6]
        );
        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 & /*width*/
      1) {
        attr(
          g,
          "width",
          /*width*/
          ctx3[0]
        );
      }
      if (dirty & /*height*/
      2) {
        attr(
          g,
          "height",
          /*height*/
          ctx3[1]
        );
      }
      if (dirty & /*width, height*/
      3 && g_transform_value !== (g_transform_value = `translate(${/*width*/
      ctx3[0] / 2},${/*height*/
      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 instance7($$self, $$props, $$invalidate) {
  let radius;
  let root2;
  let nodes;
  let y2;
  let arcShape;
  let $ctx;
  let $urlForAccount;
  let $sunburstScale;
  component_subscribe($$self, ctx, ($$value) => $$invalidate(16, $ctx = $$value));
  component_subscribe($$self, urlForAccount, ($$value) => $$invalidate(7, $urlForAccount = $$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) {
    const val = d.value ?? 0;
    return root2.value ? `${$ctx.amount(val, currency)} (${formatPercentage(val / root2.value)})` : $ctx.amount(val, currency);
  }
  const x2 = linear2([0, 2 * Math.PI]);
  const mouseover_handler = (d) => {
    $$invalidate(4, current = d);
  };
  const focus_handler = (d) => {
    $$invalidate(4, current = d);
  };
  const mouseleave_handler = () => {
    $$invalidate(4, current = null);
  };
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(10, data = $$props2.data);
    if ("currency" in $$props2)
      $$invalidate(11, 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 & /*width, height*/
    3) {
      $:
        $$invalidate(2, radius = Math.min(width, height4) / 2);
    }
    if ($$self.$$.dirty & /*data*/
    1024) {
      $:
        $$invalidate(3, root2 = partition_default()(data));
    }
    if ($$self.$$.dirty & /*root*/
    8) {
      $:
        $$invalidate(6, nodes = root2.descendants().filter((d) => !d.data.dummy && d.depth));
    }
    if ($$self.$$.dirty & /*root*/
    8) {
      $:
        if (root2) {
          $$invalidate(4, current = null);
        }
    }
    if ($$self.$$.dirty & /*radius*/
    4) {
      $:
        $$invalidate(12, y2 = sqrt2([0, radius]));
    }
    if ($$self.$$.dirty & /*y*/
    4096) {
      $:
        $$invalidate(5, 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,
    radius,
    root2,
    current,
    arcShape,
    nodes,
    $urlForAccount,
    $sunburstScale,
    balanceText,
    data,
    currency,
    y2,
    mouseover_handler,
    focus_handler,
    mouseleave_handler
  ];
}
var Sunburst = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance7, create_fragment6, safe_not_equal, {
      data: 10,
      currency: 11,
      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[14] = 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 = (
    /*d*/
    (ctx2[14].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 (
      /*followingTooltip_function*/
      ctx2[10](
        /*d*/
        ctx2[14]
      )
    );
  }
  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 = /*fill*/
      ctx2[4](
        /*d*/
        ctx2[14]
      ));
      attr(rect, "width", rect_width_value = /*d*/
      ctx2[14].x1 - /*d*/
      ctx2[14].x0);
      attr(rect, "height", rect_height_value = /*d*/
      ctx2[14].y1 - /*d*/
      ctx2[14].y0);
      attr(text_1, "dy", ".5em");
      attr(text_1, "x", text_1_x_value = /*d*/
      (ctx2[14].x1 - /*d*/
      ctx2[14].x0) / 2);
      attr(text_1, "y", text_1_y_value = /*d*/
      (ctx2[14].y1 - /*d*/
      ctx2[14].y0) / 2);
      attr(text_1, "text-anchor", "middle");
      attr(text_1, "class", "svelte-1n6q2h8");
      attr(a, "href", a_href_value = /*$urlForAccount*/
      ctx2[3](
        /*d*/
        ctx2[14].data.account
      ));
      attr(g, "transform", g_transform_value = `translate(${/*d*/
      ctx2[14].x0},${/*d*/
      ctx2[14].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*/
          ctx2[6].call(
            null,
            text_1,
            /*d*/
            ctx2[14]
          )),
          action_destroyer(followingTooltip_action = followingTooltip.call(null, g, followingTooltip_function))
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & /*leaves*/
      4 && rect_fill_value !== (rect_fill_value = /*fill*/
      ctx2[4](
        /*d*/
        ctx2[14]
      ))) {
        attr(rect, "fill", rect_fill_value);
      }
      if (dirty & /*leaves*/
      4 && rect_width_value !== (rect_width_value = /*d*/
      ctx2[14].x1 - /*d*/
      ctx2[14].x0)) {
        attr(rect, "width", rect_width_value);
      }
      if (dirty & /*leaves*/
      4 && rect_height_value !== (rect_height_value = /*d*/
      ctx2[14].y1 - /*d*/
      ctx2[14].y0)) {
        attr(rect, "height", rect_height_value);
      }
      if (dirty & /*leaves*/
      4 && t_value !== (t_value = /*d*/
      (ctx2[14].data.account.split(":").pop() ?? "") + ""))
        set_data(t4, t_value);
      if (dirty & /*leaves*/
      4 && text_1_x_value !== (text_1_x_value = /*d*/
      (ctx2[14].x1 - /*d*/
      ctx2[14].x0) / 2)) {
        attr(text_1, "x", text_1_x_value);
      }
      if (dirty & /*leaves*/
      4 && text_1_y_value !== (text_1_y_value = /*d*/
      (ctx2[14].y1 - /*d*/
      ctx2[14].y0) / 2)) {
        attr(text_1, "y", text_1_y_value);
      }
      if (setVisibility_action && is_function(setVisibility_action.update) && dirty & /*leaves*/
      4)
        setVisibility_action.update.call(
          null,
          /*d*/
          ctx2[14]
        );
      if (dirty & /*$urlForAccount, leaves*/
      12 && a_href_value !== (a_href_value = /*$urlForAccount*/
      ctx2[3](
        /*d*/
        ctx2[14].data.account
      ))) {
        attr(a, "href", a_href_value);
      }
      if (dirty & /*leaves*/
      4 && g_transform_value !== (g_transform_value = `translate(${/*d*/
      ctx2[14].x0},${/*d*/
      ctx2[14].y0})`)) {
        attr(g, "transform", g_transform_value);
      }
      if (followingTooltip_action && is_function(followingTooltip_action.update) && dirty & /*leaves*/
      4)
        followingTooltip_action.update.call(null, followingTooltip_function);
    },
    d(detaching) {
      if (detaching) {
        detach(g);
      }
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_fragment7(ctx2) {
  let svg2;
  let svg_viewBox_value;
  let each_value = ensure_array_like(
    /*leaves*/
    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, "viewBox", svg_viewBox_value = `0 0 ${/*width*/
      ctx2[0]} ${/*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) {
        if (each_blocks[i]) {
          each_blocks[i].m(svg2, null);
        }
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & /*leaves, tooltipText, $urlForAccount, fill*/
      60) {
        each_value = ensure_array_like(
          /*leaves*/
          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 & /*width, height*/
      3 && svg_viewBox_value !== (svg_viewBox_value = `0 0 ${/*width*/
      ctx3[0]} ${/*height*/
      ctx3[1]}`)) {
        attr(svg2, "viewBox", svg_viewBox_value);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg2);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function instance8($$self, $$props, $$invalidate) {
  let height4;
  let root2;
  let leaves;
  let $ctx;
  let $treemapScale;
  let $urlForAccount;
  component_subscribe($$self, ctx, ($$value) => $$invalidate(11, $ctx = $$value));
  component_subscribe($$self, treemapScale, ($$value) => $$invalidate(12, $treemapScale = $$value));
  component_subscribe($$self, urlForAccount, ($$value) => $$invalidate(3, $urlForAccount = $$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) {
    const val = d.value ?? 0;
    const rootValue = root2.value ?? 1;
    return [
      domHelpers.t(`${$ctx.amount(val, currency)} (${formatPercentage(val / rootValue)})`),
      domHelpers.em(d.data.account)
    ];
  }
  const 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 };
  };
  const followingTooltip_function = (d) => tooltipText(d);
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(7, data = $$props2.data);
    if ("width" in $$props2)
      $$invalidate(0, width = $$props2.width);
    if ("currency" in $$props2)
      $$invalidate(8, currency = $$props2.currency);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*width*/
    1) {
      $:
        $$invalidate(1, height4 = Math.min(width / 2.5, 400));
    }
    if ($$self.$$.dirty & /*width, height, data*/
    131) {
      $:
        $$invalidate(9, root2 = tree.size([width, height4])(data));
    }
    if ($$self.$$.dirty & /*root*/
    512) {
      $:
        $$invalidate(2, leaves = root2.leaves().filter((d) => d.value));
    }
  };
  return [
    width,
    height4,
    leaves,
    $urlForAccount,
    fill,
    tooltipText,
    setVisibility,
    data,
    currency,
    root2,
    followingTooltip_function
  ];
}
var Treemap = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance8, create_fragment7, safe_not_equal, { data: 7, width: 0, currency: 8 });
  }
};
var Treemap_default = Treemap;

// src/charts/HierarchyContainer.svelte
function get_each_context6(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[10] = list[i][0];
  child_ctx[11] = list[i][1];
  child_ctx[13] = i;
  return child_ctx;
}
function create_if_block_2(ctx2) {
  let svg2;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let svg_viewBox_value;
  let current;
  let each_value = ensure_array_like([.../*data*/
  ctx2[2]]);
  const get_key = (ctx3) => (
    /*chart_currency*/
    ctx3[10]
  );
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context6(ctx2, each_value, i);
    let key2 = get_key(child_ctx);
    each_1_lookup.set(key2, each_blocks[i] = create_each_block6(key2, child_ctx));
  }
  return {
    c() {
      svg2 = svg_element("svg");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(svg2, "viewBox", svg_viewBox_value = `0 0 ${/*width*/
      ctx2[0]} 500`);
    },
    m(target, anchor) {
      insert(target, svg2, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(svg2, null);
        }
      }
      current = true;
    },
    p(ctx3, dirty) {
      if (dirty & /*width, data, currencies*/
      21) {
        each_value = ensure_array_like([.../*data*/
        ctx3[2]]);
        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 & /*width*/
      1 && svg_viewBox_value !== (svg_viewBox_value = `0 0 ${/*width*/
      ctx3[0]} 500`)) {
        attr(svg2, "viewBox", svg_viewBox_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) {
      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_1;
  let current;
  treemap_1 = new Treemap_default({
    props: {
      data: (
        /*treemap*/
        ctx2[5]
      ),
      currency: (
        /*currency*/
        ctx2[1]
      ),
      width: (
        /*width*/
        ctx2[0]
      )
    }
  });
  return {
    c() {
      create_component(treemap_1.$$.fragment);
    },
    m(target, anchor) {
      mount_component(treemap_1, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const treemap_1_changes = {};
      if (dirty & /*treemap*/
      32)
        treemap_1_changes.data = /*treemap*/
        ctx3[5];
      if (dirty & /*currency*/
      2)
        treemap_1_changes.currency = /*currency*/
        ctx3[1];
      if (dirty & /*width*/
      1)
        treemap_1_changes.width = /*width*/
        ctx3[0];
      treemap_1.$set(treemap_1_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(treemap_1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(treemap_1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(treemap_1, detaching);
    }
  };
}
function create_if_block3(ctx2) {
  let svg2;
  let text_1;
  let t_value = _("Chart is empty.") + "";
  let t4;
  let text_1_x_value;
  let text_1_y_value;
  let svg_viewBox_value;
  return {
    c() {
      svg2 = svg_element("svg");
      text_1 = svg_element("text");
      t4 = text(t_value);
      attr(text_1, "x", text_1_x_value = /*width*/
      ctx2[0] / 2);
      attr(text_1, "y", text_1_y_value = 80);
      attr(text_1, "text-anchor", "middle");
      attr(svg2, "viewBox", svg_viewBox_value = `0 0 ${/*width*/
      ctx2[0]} 160`);
    },
    m(target, anchor) {
      insert(target, svg2, anchor);
      append(svg2, text_1);
      append(text_1, t4);
    },
    p(ctx3, dirty) {
      if (dirty & /*width*/
      1 && text_1_x_value !== (text_1_x_value = /*width*/
      ctx3[0] / 2)) {
        attr(text_1, "x", text_1_x_value);
      }
      if (dirty & /*width*/
      1 && svg_viewBox_value !== (svg_viewBox_value = `0 0 ${/*width*/
      ctx3[0]} 160`)) {
        attr(svg2, "viewBox", svg_viewBox_value);
      }
    },
    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: (
        /*d*/
        ctx2[11]
      ),
      currency: (
        /*chart_currency*/
        ctx2[10]
      ),
      width: (
        /*width*/
        ctx2[0] / /*currencies*/
        ctx2[4].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(${/*width*/
      ctx2[0] * /*i*/
      ctx2[13] / /*currencies*/
      ctx2[4].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 & /*data*/
      4)
        sunburst_changes.data = /*d*/
        ctx2[11];
      if (dirty & /*data*/
      4)
        sunburst_changes.currency = /*chart_currency*/
        ctx2[10];
      if (dirty & /*width, currencies*/
      17)
        sunburst_changes.width = /*width*/
        ctx2[0] / /*currencies*/
        ctx2[4].length;
      sunburst.$set(sunburst_changes);
      if (!current || dirty & /*width, data, currencies*/
      21 && g_transform_value !== (g_transform_value = `translate(${/*width*/
      ctx2[0] * /*i*/
      ctx2[13] / /*currencies*/
      ctx2[4].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_fragment8(ctx2) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block3, create_if_block_12, create_if_block_2];
  const if_blocks = [];
  function select_block_type(ctx3, dirty) {
    if (
      /*currencies*/
      ctx3[4].length === 0
    )
      return 0;
    if (
      /*treemap*/
      ctx3[5] && /*currency*/
      ctx3[1]
    )
      return 1;
    if (
      /*mode*/
      ctx3[3] === "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 (detaching) {
        detach(if_block_anchor);
      }
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d(detaching);
      }
    }
  };
}
function instance9($$self, $$props, $$invalidate) {
  let data;
  let currencies2;
  let currency;
  let mode;
  let treemap;
  let $hierarchyChartMode;
  let $treemapCurrency;
  component_subscribe($$self, hierarchyChartMode, ($$value) => $$invalidate(8, $hierarchyChartMode = $$value));
  component_subscribe($$self, treemapCurrency, ($$value) => $$invalidate(9, $treemapCurrency = $$value));
  let { chart } = $$props;
  let { width } = $$props;
  let { treemap_currencies } = $$props;
  $$self.$$set = ($$props2) => {
    if ("chart" in $$props2)
      $$invalidate(6, chart = $$props2.chart);
    if ("width" in $$props2)
      $$invalidate(0, width = $$props2.width);
    if ("treemap_currencies" in $$props2)
      $$invalidate(7, treemap_currencies = $$props2.treemap_currencies);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*chart*/
    64) {
      $:
        $$invalidate(2, data = chart.data);
    }
    if ($$self.$$.dirty & /*data*/
    4) {
      $:
        $$invalidate(4, currencies2 = [...data.keys()]);
    }
    if ($$self.$$.dirty & /*treemap_currencies, currencies*/
    144) {
      $:
        treemap_currencies.set(currencies2);
    }
    if ($$self.$$.dirty & /*$treemapCurrency, currencies*/
    528) {
      $:
        if ($treemapCurrency === null) {
          set_store_value(treemapCurrency, $treemapCurrency = $treemapCurrency ?? currencies2[0] ?? null, $treemapCurrency);
        }
    }
    if ($$self.$$.dirty & /*$treemapCurrency*/
    512) {
      $:
        $$invalidate(1, currency = $treemapCurrency);
    }
    if ($$self.$$.dirty & /*$hierarchyChartMode*/
    256) {
      $:
        $$invalidate(3, mode = $hierarchyChartMode);
    }
    if ($$self.$$.dirty & /*mode, data, currency*/
    14) {
      $:
        $$invalidate(5, treemap = mode === "treemap" && data.get(currency ?? ""));
    }
  };
  return [
    width,
    currency,
    data,
    mode,
    currencies2,
    treemap,
    chart,
    treemap_currencies,
    $hierarchyChartMode,
    $treemapCurrency
  ];
}
var HierarchyContainer = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance9, create_fragment8, safe_not_equal, {
      chart: 6,
      width: 0,
      treemap_currencies: 7
    });
  }
};
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 = ensure_array_like(
    /*data*/
    ctx2[4]
  );
  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",
        /*futureFilter*/
        ctx2[6]
      );
    },
    m(target, anchor) {
      insert(target, g, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(g, null);
        }
      }
    },
    p(ctx3, dirty) {
      if (dirty[0] & /*areaShape, data, $currenciesScale*/
      560) {
        each_value_3 = ensure_array_like(
          /*data*/
          ctx3[4]
        );
        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] & /*futureFilter*/
      64) {
        attr(
          g,
          "filter",
          /*futureFilter*/
          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() {
      path2 = svg_element("path");
      attr(path2, "d", path_d_value = /*areaShape*/
      ctx2[9](
        /*d*/
        ctx2[26].values
      ));
      attr(path2, "fill", path_fill_value = /*$currenciesScale*/
      ctx2[5](
        /*d*/
        ctx2[26].name
      ));
      attr(path2, "class", "svelte-1gzc8m3");
    },
    m(target, anchor) {
      insert(target, path2, anchor);
    },
    p(ctx3, dirty) {
      if (dirty[0] & /*areaShape, data*/
      528 && path_d_value !== (path_d_value = /*areaShape*/
      ctx3[9](
        /*d*/
        ctx3[26].values
      ))) {
        attr(path2, "d", path_d_value);
      }
      if (dirty[0] & /*$currenciesScale, data*/
      48 && path_fill_value !== (path_fill_value = /*$currenciesScale*/
      ctx3[5](
        /*d*/
        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() {
      path2 = svg_element("path");
      attr(path2, "d", path_d_value = /*lineShape*/
      ctx2[10](
        /*d*/
        ctx2[26].values
      ));
      attr(path2, "stroke", path_stroke_value = /*$currenciesScale*/
      ctx2[5](
        /*d*/
        ctx2[26].name
      ));
      attr(path2, "class", "svelte-1gzc8m3");
    },
    m(target, anchor) {
      insert(target, path2, anchor);
    },
    p(ctx3, dirty) {
      if (dirty[0] & /*lineShape, data*/
      1040 && path_d_value !== (path_d_value = /*lineShape*/
      ctx3[10](
        /*d*/
        ctx3[26].values
      ))) {
        attr(path2, "d", path_d_value);
      }
      if (dirty[0] & /*$currenciesScale, data*/
      48 && path_stroke_value !== (path_stroke_value = /*$currenciesScale*/
      ctx3[5](
        /*d*/
        ctx3[26].name
      ))) {
        attr(path2, "stroke", path_stroke_value);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(path2);
      }
    }
  };
}
function create_if_block4(ctx2) {
  let g;
  let each_value = ensure_array_like(
    /*data*/
    ctx2[4]
  );
  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) {
        if (each_blocks[i]) {
          each_blocks[i].m(g, null);
        }
      }
    },
    p(ctx3, dirty) {
      if (dirty[0] & /*$currenciesScale, data, x, y, today*/
      4150) {
        each_value = ensure_array_like(
          /*data*/
          ctx3[4]
        );
        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 = /*x*/
      ctx2[2](
        /*v*/
        ctx2[29].date
      ));
      attr(circle, "cy", circle_cy_value = /*y*/
      ctx2[1](
        /*v*/
        ctx2[29].value
      ));
      attr(circle, "class", "svelte-1gzc8m3");
      toggle_class(
        circle,
        "desaturate",
        /*v*/
        ctx2[29].date > /*today*/
        ctx2[12]
      );
    },
    m(target, anchor) {
      insert(target, circle, anchor);
    },
    p(ctx3, dirty) {
      if (dirty[0] & /*x, data*/
      20 && circle_cx_value !== (circle_cx_value = /*x*/
      ctx3[2](
        /*v*/
        ctx3[29].date
      ))) {
        attr(circle, "cx", circle_cx_value);
      }
      if (dirty[0] & /*y, data*/
      18 && circle_cy_value !== (circle_cy_value = /*y*/
      ctx3[1](
        /*v*/
        ctx3[29].value
      ))) {
        attr(circle, "cy", circle_cy_value);
      }
      if (dirty[0] & /*data, today*/
      4112) {
        toggle_class(
          circle,
          "desaturate",
          /*v*/
          ctx3[29].date > /*today*/
          ctx3[12]
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(circle);
      }
    }
  };
}
function create_each_block7(ctx2) {
  let g;
  let g_fill_value;
  let each_value_1 = ensure_array_like(
    /*d*/
    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 = /*$currenciesScale*/
      ctx2[5](
        /*d*/
        ctx2[26].name
      ));
    },
    m(target, anchor) {
      insert(target, g, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(g, null);
        }
      }
    },
    p(ctx3, dirty) {
      if (dirty[0] & /*x, data, y, today*/
      4118) {
        each_value_1 = ensure_array_like(
          /*d*/
          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] & /*$currenciesScale, data*/
      48 && g_fill_value !== (g_fill_value = /*$currenciesScale*/
      ctx3[5](
        /*d*/
        ctx3[26].name
      ))) {
        attr(g, "fill", g_fill_value);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(g);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_fragment9(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 svg_viewBox_value;
  let current;
  let mounted;
  let dispose;
  axis0 = new Axis_default({
    props: {
      x: true,
      axis: (
        /*xAxis*/
        ctx2[8]
      ),
      innerHeight: (
        /*innerHeight*/
        ctx2[3]
      )
    }
  });
  axis1 = new Axis_default({
    props: { y: true, axis: (
      /*yAxis*/
      ctx2[7]
    ) }
  });
  let if_block0 = (
    /*$lineChartMode*/
    ctx2[11] === "area" && create_if_block_13(ctx2)
  );
  let each_value_2 = ensure_array_like(
    /*data*/
    ctx2[4]
  );
  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 = (
    /*$lineChartMode*/
    ctx2[11] === "line" && create_if_block4(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 = /*x*/
      ctx2[2](
        /*today*/
        ctx2[12]
      ));
      attr(feBlend, "in2", "SourceGraphic");
      attr(filter2, "id", "desaturateFuture");
      attr(g0, "class", "lines svelte-1gzc8m3");
      attr(
        g0,
        "filter",
        /*futureFilter*/
        ctx2[6]
      );
      attr(g1, "transform", g1_transform_value = `translate(${/*margin*/
      ctx2[13].left},${/*margin*/
      ctx2[13].top})`);
      attr(g1, "class", "svelte-1gzc8m3");
      attr(svg2, "viewBox", svg_viewBox_value = `0 0 ${/*width*/
      ctx2[0]} ${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) {
        if (each_blocks[i]) {
          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,
          /*tooltipFindNode*/
          ctx2[14]
        ));
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if (!current || dirty[0] & /*x*/
      4 && feColorMatrix_x_value !== (feColorMatrix_x_value = /*x*/
      ctx3[2](
        /*today*/
        ctx3[12]
      ))) {
        attr(feColorMatrix, "x", feColorMatrix_x_value);
      }
      const axis0_changes = {};
      if (dirty[0] & /*xAxis*/
      256)
        axis0_changes.axis = /*xAxis*/
        ctx3[8];
      if (dirty[0] & /*innerHeight*/
      8)
        axis0_changes.innerHeight = /*innerHeight*/
        ctx3[3];
      axis0.$set(axis0_changes);
      const axis1_changes = {};
      if (dirty[0] & /*yAxis*/
      128)
        axis1_changes.axis = /*yAxis*/
        ctx3[7];
      axis1.$set(axis1_changes);
      if (
        /*$lineChartMode*/
        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] & /*lineShape, data, $currenciesScale*/
      1072) {
        each_value_2 = ensure_array_like(
          /*data*/
          ctx3[4]
        );
        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] & /*futureFilter*/
      64) {
        attr(
          g0,
          "filter",
          /*futureFilter*/
          ctx3[6]
        );
      }
      if (
        /*$lineChartMode*/
        ctx3[11] === "line"
      ) {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
        } else {
          if_block1 = create_if_block4(ctx3);
          if_block1.c();
          if_block1.m(g1, null);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (!current || dirty[0] & /*width*/
      1 && svg_viewBox_value !== (svg_viewBox_value = `0 0 ${/*width*/
      ctx3[0]} ${height2}`)) {
        attr(svg2, "viewBox", svg_viewBox_value);
      }
    },
    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 instance10($$self, $$props, $$invalidate) {
  let innerWidth;
  let innerHeight2;
  let data;
  let series_names;
  let allValues;
  let xExtent;
  let x2;
  let yExtent;
  let y2;
  let quad;
  let lineShape;
  let areaShape;
  let xAxis;
  let yAxis;
  let futureFilter;
  let $ctx;
  let $short;
  let $currenciesScale;
  let $chartToggledCurrencies;
  let $lineChartMode;
  component_subscribe($$self, ctx, ($$value) => $$invalidate(25, $ctx = $$value));
  component_subscribe($$self, short, ($$value) => $$invalidate(22, $short = $$value));
  component_subscribe($$self, currenciesScale, ($$value) => $$invalidate(5, $currenciesScale = $$value));
  component_subscribe($$self, chartToggledCurrencies, ($$value) => $$invalidate(23, $chartToggledCurrencies = $$value));
  component_subscribe($$self, lineChartMode, ($$value) => $$invalidate(11, $lineChartMode = $$value));
  let { chart } = $$props;
  let { width } = $$props;
  let { legend } = $$props;
  const today = /* @__PURE__ */ new Date();
  const margin = { top: 10, right: 10, bottom: 30, left: 40 };
  const tooltipFindNode = (xPos, yPos) => {
    const d = quad.find(xPos, yPos);
    return d && [x2(d.date), y2(d.value), chart.tooltipText($ctx, d)];
  };
  $$self.$$set = ($$props2) => {
    if ("chart" in $$props2)
      $$invalidate(15, chart = $$props2.chart);
    if ("width" in $$props2)
      $$invalidate(0, width = $$props2.width);
    if ("legend" in $$props2)
      $$invalidate(16, legend = $$props2.legend);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*width*/
    1) {
      $:
        $$invalidate(18, innerWidth = width - margin.left - margin.right);
    }
    if ($$self.$$.dirty[0] & /*chart, $chartToggledCurrencies*/
    8421376) {
      $:
        $$invalidate(4, data = chart.filter($chartToggledCurrencies));
    }
    if ($$self.$$.dirty[0] & /*chart*/
    32768) {
      $:
        $$invalidate(21, series_names = chart.series_names);
    }
    if ($$self.$$.dirty[0] & /*legend, series_names, $currenciesScale*/
    2162720) {
      $:
        legend.set(series_names.map((c) => [c, $currenciesScale(c)]));
    }
    if ($$self.$$.dirty[0] & /*data*/
    16) {
      $:
        $$invalidate(19, allValues = data.map((d) => d.values).flat(1));
    }
    if ($$self.$$.dirty[0] & /*data*/
    16) {
      $:
        $$invalidate(17, xExtent = [
          min(data, (s) => s.values[0]?.date) ?? today,
          max(data, (s) => s.values[s.values.length - 1]?.date) ?? today
        ]);
    }
    if ($$self.$$.dirty[0] & /*innerWidth, xExtent*/
    393216) {
      $:
        $$invalidate(2, x2 = utcTime([0, innerWidth]).domain(xExtent));
    }
    if ($$self.$$.dirty[0] & /*allValues*/
    524288) {
      $:
        $$invalidate(20, yExtent = extent(allValues, (v) => v.value));
    }
    if ($$self.$$.dirty[0] & /*innerHeight, yExtent*/
    1048584) {
      $:
        $$invalidate(1, y2 = linear2([innerHeight2, 0]).domain(padExtent(yExtent)));
    }
    if ($$self.$$.dirty[0] & /*allValues, x, y*/
    524294) {
      $:
        quad = quadtree(allValues, (d) => x2(d.date), (d) => y2(d.value));
    }
    if ($$self.$$.dirty[0] & /*x, y*/
    6) {
      $:
        $$invalidate(10, lineShape = line_default().x((d) => x2(d.date)).y((d) => y2(d.value)).curve(stepAfter));
    }
    if ($$self.$$.dirty[0] & /*x, y, innerHeight*/
    14) {
      $:
        $$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] & /*x*/
    4) {
      $:
        $$invalidate(8, xAxis = axisBottom(x2).tickSizeOuter(0));
    }
    if ($$self.$$.dirty[0] & /*y, innerWidth, $short*/
    4456450) {
      $:
        $$invalidate(7, yAxis = axisLeft(y2).tickPadding(6).tickSize(-innerWidth).tickFormat($short));
    }
    if ($$self.$$.dirty[0] & /*xExtent*/
    131072) {
      $:
        $$invalidate(6, futureFilter = xExtent[1] > today ? "url(#desaturateFuture)" : void 0);
    }
  };
  $:
    $$invalidate(3, innerHeight2 = height2 - margin.top - margin.bottom);
  return [
    width,
    y2,
    x2,
    innerHeight2,
    data,
    $currenciesScale,
    futureFilter,
    yAxis,
    xAxis,
    areaShape,
    lineShape,
    $lineChartMode,
    today,
    margin,
    tooltipFindNode,
    chart,
    legend,
    xExtent,
    innerWidth,
    allValues,
    yExtent,
    series_names,
    $short,
    $chartToggledCurrencies
  ];
}
var LineChart2 = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance10, create_fragment9, safe_not_equal, { chart: 15, width: 0, legend: 16 }, null, [-1, -1]);
  }
};
var LineChart_default = LineChart2;

// 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 value_has_changed = false;
  let t03;
  let t1_value = (
    /*name*/
    ctx2[5] + ""
  );
  let t13;
  let t22;
  let binding_group;
  let mounted;
  let dispose;
  binding_group = init_binding_group(
    /*$$binding_groups*/
    ctx2[3][0]
  );
  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 = /*option*/
      ctx2[4];
      set_input_value(input, input.__value);
      attr(input, "class", "svelte-14t26d6");
      attr(label, "class", "button svelte-14t26d6");
      toggle_class(
        label,
        "muted",
        /*$store*/
        ctx2[1] !== /*option*/
        ctx2[4]
      );
      binding_group.p(input);
    },
    m(target, anchor) {
      insert(target, label, anchor);
      append(label, input);
      input.checked = input.__value === /*$store*/
      ctx2[1];
      append(label, t03);
      append(label, t13);
      append(label, t22);
      if (!mounted) {
        dispose = listen(
          input,
          "change",
          /*input_change_handler*/
          ctx2[2]
        );
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if (dirty & /*store*/
      1 && input_value_value !== (input_value_value = /*option*/
      ctx3[4])) {
        input.__value = input_value_value;
        set_input_value(input, input.__value);
        value_has_changed = true;
      }
      if (value_has_changed || dirty & /*$store, store*/
      3) {
        input.checked = input.__value === /*$store*/
        ctx3[1];
      }
      if (dirty & /*store*/
      1 && t1_value !== (t1_value = /*name*/
      ctx3[5] + ""))
        set_data(t13, t1_value);
      if (dirty & /*$store, store*/
      3) {
        toggle_class(
          label,
          "muted",
          /*$store*/
          ctx3[1] !== /*option*/
          ctx3[4]
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(label);
      }
      binding_group.r();
      mounted = false;
      dispose();
    }
  };
}
function create_fragment10(ctx2) {
  let span;
  let each_value = ensure_array_like(
    /*store*/
    ctx2[0].values()
  );
  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) {
        if (each_blocks[i]) {
          each_blocks[i].m(span, null);
        }
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & /*$store, store*/
      3) {
        each_value = ensure_array_like(
          /*store*/
          ctx3[0].values()
        );
        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 instance11($$self, $$props, $$invalidate) {
  let $store, $$unsubscribe_store = noop, $$subscribe_store = () => ($$unsubscribe_store(), $$unsubscribe_store = subscribe(store, ($$value) => $$invalidate(1, $store = $$value)), store);
  $$self.$$.on_destroy.push(() => $$unsubscribe_store());
  let { store } = $$props;
  $$subscribe_store();
  const $$binding_groups = [[]];
  function input_change_handler() {
    $store = this.__value;
    store.set($store);
  }
  $$self.$$set = ($$props2) => {
    if ("store" in $$props2)
      $$subscribe_store($$invalidate(0, store = $$props2.store));
  };
  return [store, $store, input_change_handler, $$binding_groups];
}
var ModeSwitch = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance11, create_fragment10, safe_not_equal, { store: 0 });
  }
};
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(
        /*dot*/
        ctx2[14].type
      ));
      attr(circle, "cx", circle_cx_value = /*x*/
      ctx2[3](
        /*dot*/
        ctx2[14].date
      ));
      attr(circle, "cy", circle_cy_value = /*y*/
      ctx2[2](
        /*dot*/
        ctx2[14].type
      ));
      attr(circle, "class", "svelte-jl8ee");
      toggle_class(
        circle,
        "desaturate",
        /*dot*/
        ctx2[14].date > /*today*/
        ctx2[7]
      );
    },
    m(target, anchor) {
      insert(target, circle, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & /*chart*/
      1 && circle_fill_value !== (circle_fill_value = scatterplotScale(
        /*dot*/
        ctx3[14].type
      ))) {
        attr(circle, "fill", circle_fill_value);
      }
      if (dirty & /*x, chart*/
      9 && circle_cx_value !== (circle_cx_value = /*x*/
      ctx3[3](
        /*dot*/
        ctx3[14].date
      ))) {
        attr(circle, "cx", circle_cx_value);
      }
      if (dirty & /*y, chart*/
      5 && circle_cy_value !== (circle_cy_value = /*y*/
      ctx3[2](
        /*dot*/
        ctx3[14].type
      ))) {
        attr(circle, "cy", circle_cy_value);
      }
      if (dirty & /*chart, today*/
      129) {
        toggle_class(
          circle,
          "desaturate",
          /*dot*/
          ctx3[14].date > /*today*/
          ctx3[7]
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(circle);
      }
    }
  };
}
function create_fragment11(ctx2) {
  let svg2;
  let g1;
  let axis0;
  let axis1;
  let g0;
  let g1_transform_value;
  let positionedTooltip_action;
  let svg_viewBox_value;
  let current;
  let mounted;
  let dispose;
  axis0 = new Axis_default({
    props: {
      x: true,
      axis: (
        /*xAxis*/
        ctx2[6]
      ),
      innerHeight: (
        /*innerHeight*/
        ctx2[4]
      )
    }
  });
  axis1 = new Axis_default({
    props: { y: true, axis: (
      /*yAxis*/
      ctx2[5]
    ) }
  });
  let each_value = ensure_array_like(
    /*chart*/
    ctx2[0].data
  );
  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(${/*margin*/
      ctx2[8].left},${/*margin*/
      ctx2[8].top})`);
      attr(g1, "class", "svelte-jl8ee");
      attr(svg2, "viewBox", svg_viewBox_value = `0 0 ${/*width*/
      ctx2[1]} ${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) {
        if (each_blocks[i]) {
          each_blocks[i].m(g0, null);
        }
      }
      current = true;
      if (!mounted) {
        dispose = action_destroyer(positionedTooltip_action = positionedTooltip.call(
          null,
          g1,
          /*tooltipFindNode*/
          ctx2[9]
        ));
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      const axis0_changes = {};
      if (dirty & /*xAxis*/
      64)
        axis0_changes.axis = /*xAxis*/
        ctx3[6];
      if (dirty & /*innerHeight*/
      16)
        axis0_changes.innerHeight = /*innerHeight*/
        ctx3[4];
      axis0.$set(axis0_changes);
      const axis1_changes = {};
      if (dirty & /*yAxis*/
      32)
        axis1_changes.axis = /*yAxis*/
        ctx3[5];
      axis1.$set(axis1_changes);
      if (dirty & /*chart, x, y, today*/
      141) {
        each_value = ensure_array_like(
          /*chart*/
          ctx3[0].data
        );
        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 & /*width*/
      2 && svg_viewBox_value !== (svg_viewBox_value = `0 0 ${/*width*/
      ctx3[1]} ${height3}`)) {
        attr(svg2, "viewBox", svg_viewBox_value);
      }
    },
    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 instance12($$self, $$props, $$invalidate) {
  let innerWidth;
  let innerHeight2;
  let dateExtent;
  let x2;
  let y2;
  let xAxis;
  let yAxis;
  let quad;
  let { chart } = $$props;
  let { width } = $$props;
  const today = /* @__PURE__ */ new Date();
  const margin = { top: 10, right: 10, bottom: 30, left: 70 };
  function tooltipText(d) {
    return [domHelpers.t(d.description), domHelpers.em(day(d.date))];
  }
  const tooltipFindNode = (xPos, yPos) => {
    const d = quad.find(xPos, yPos);
    return d && [x2(d.date), y2(d.type) ?? 0, tooltipText(d)];
  };
  $$self.$$set = ($$props2) => {
    if ("chart" in $$props2)
      $$invalidate(0, chart = $$props2.chart);
    if ("width" in $$props2)
      $$invalidate(1, width = $$props2.width);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*width*/
    2) {
      $:
        $$invalidate(10, innerWidth = width - margin.left - margin.right);
    }
    if ($$self.$$.dirty & /*chart*/
    1) {
      $:
        $$invalidate(11, dateExtent = extent(chart.data, (d) => d.date));
    }
    if ($$self.$$.dirty & /*innerWidth, dateExtent*/
    3072) {
      $:
        $$invalidate(3, x2 = utcTime([0, innerWidth]).domain(dateExtent[0] ? dateExtent : [0, 1]));
    }
    if ($$self.$$.dirty & /*innerHeight, chart*/
    17) {
      $:
        $$invalidate(2, y2 = point([innerHeight2, 0]).domain(chart.data.map((d) => d.type)).padding(1));
    }
    if ($$self.$$.dirty & /*x*/
    8) {
      $:
        $$invalidate(6, xAxis = axisBottom(x2).tickSizeOuter(0));
    }
    if ($$self.$$.dirty & /*y, innerWidth*/
    1028) {
      $:
        $$invalidate(5, yAxis = axisLeft(y2).tickPadding(6).tickSize(-innerWidth).tickFormat((d) => d));
    }
    if ($$self.$$.dirty & /*chart, x, y*/
    13) {
      $:
        quad = quadtree([...chart.data], (d) => x2(d.date), (d) => y2(d.type) ?? 0);
    }
  };
  $:
    $$invalidate(4, innerHeight2 = height3 - margin.top - margin.bottom);
  return [
    chart,
    width,
    y2,
    x2,
    innerHeight2,
    yAxis,
    xAxis,
    today,
    margin,
    tooltipFindNode,
    innerWidth,
    dateExtent
  ];
}
var ScatterPlot2 = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance12, create_fragment11, safe_not_equal, { chart: 0, width: 1 });
  }
};
var ScatterPlot_default = ScatterPlot2;

// src/charts/Chart.svelte
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_5(ctx2) {
  let t03;
  let t13;
  let span;
  let t22;
  let current_block_type_index;
  let if_block2;
  let if_block2_anchor;
  let current;
  let if_block0 = (
    /*chart*/
    (ctx2[0].type === "barchart" || /*chart*/
    ctx2[0].type === "linechart") && create_if_block_10(ctx2)
  );
  let if_block1 = (
    /*chart*/
    ctx2[0].type === "hierarchy" && /*$hierarchyChartMode*/
    ctx2[4] === "treemap" && create_if_block_9(ctx2)
  );
  const if_block_creators = [create_if_block_6, create_if_block_7, create_if_block_8];
  const if_blocks = [];
  function select_block_type_1(ctx3, dirty) {
    if (
      /*chart*/
      ctx3[0].type === "hierarchy"
    )
      return 0;
    if (
      /*chart*/
      ctx3[0].type === "linechart"
    )
      return 1;
    if (
      /*chart*/
      ctx3[0].type === "barchart" && /*chart*/
      ctx3[0].hasStackedData
    )
      return 2;
    return -1;
  }
  if (~(current_block_type_index = select_block_type_1(ctx2, -1))) {
    if_block2 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
  }
  return {
    c() {
      if (if_block0)
        if_block0.c();
      t03 = space();
      if (if_block1)
        if_block1.c();
      t13 = space();
      span = element("span");
      t22 = space();
      if (if_block2)
        if_block2.c();
      if_block2_anchor = empty();
      attr(span, "class", "spacer");
    },
    m(target, anchor) {
      if (if_block0)
        if_block0.m(target, anchor);
      insert(target, t03, anchor);
      if (if_block1)
        if_block1.m(target, anchor);
      insert(target, t13, anchor);
      insert(target, span, anchor);
      insert(target, t22, anchor);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(target, anchor);
      }
      insert(target, if_block2_anchor, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      if (
        /*chart*/
        ctx3[0].type === "barchart" || /*chart*/
        ctx3[0].type === "linechart"
      ) {
        if (if_block0) {
          if_block0.p(ctx3, dirty);
          if (dirty & /*chart*/
          1) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_10(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();
      }
      if (
        /*chart*/
        ctx3[0].type === "hierarchy" && /*$hierarchyChartMode*/
        ctx3[4] === "treemap"
      ) {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
          if (dirty & /*chart, $hierarchyChartMode*/
          17) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_9(ctx3);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(t13.parentNode, t13);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      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 (if_block2) {
          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_block2 = if_blocks[current_block_type_index];
          if (!if_block2) {
            if_block2 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx3);
            if_block2.c();
          } else {
          }
          transition_in(if_block2, 1);
          if_block2.m(if_block2_anchor.parentNode, if_block2_anchor);
        } else {
          if_block2 = null;
        }
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block0);
      transition_in(if_block1);
      transition_in(if_block2);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(if_block1);
      transition_out(if_block2);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t03);
        detach(t13);
        detach(span);
        detach(t22);
        detach(if_block2_anchor);
      }
      if (if_block0)
        if_block0.d(detaching);
      if (if_block1)
        if_block1.d(detaching);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d(detaching);
      }
    }
  };
}
function create_if_block_10(ctx2) {
  let chartlegend;
  let current;
  chartlegend = new ChartLegend_default({
    props: {
      legend: (
        /*$legend*/
        ctx2[3]
      ),
      toggled: chartToggledCurrencies
    }
  });
  return {
    c() {
      create_component(chartlegend.$$.fragment);
    },
    m(target, anchor) {
      mount_component(chartlegend, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const chartlegend_changes = {};
      if (dirty & /*$legend*/
      8)
        chartlegend_changes.legend = /*$legend*/
        ctx3[3];
      chartlegend.$set(chartlegend_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(chartlegend.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(chartlegend.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(chartlegend, detaching);
    }
  };
}
function create_if_block_9(ctx2) {
  let chartlegend;
  let current;
  chartlegend = new ChartLegend_default({
    props: {
      legend: (
        /*$treemap_currencies*/
        ctx2[5].map(func2)
      ),
      active: treemapCurrency
    }
  });
  return {
    c() {
      create_component(chartlegend.$$.fragment);
    },
    m(target, anchor) {
      mount_component(chartlegend, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const chartlegend_changes = {};
      if (dirty & /*$treemap_currencies*/
      32)
        chartlegend_changes.legend = /*$treemap_currencies*/
        ctx3[5].map(func2);
      chartlegend.$set(chartlegend_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(chartlegend.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(chartlegend.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(chartlegend, detaching);
    }
  };
}
function create_if_block_8(ctx2) {
  let modeswitch;
  let current;
  modeswitch = new ModeSwitch_default({ props: { store: barChartMode } });
  return {
    c() {
      create_component(modeswitch.$$.fragment);
    },
    m(target, anchor) {
      mount_component(modeswitch, target, anchor);
      current = true;
    },
    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_7(ctx2) {
  let modeswitch;
  let current;
  modeswitch = new ModeSwitch_default({ props: { store: lineChartMode } });
  return {
    c() {
      create_component(modeswitch.$$.fragment);
    },
    m(target, anchor) {
      mount_component(modeswitch, target, anchor);
      current = true;
    },
    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_6(ctx2) {
  let modeswitch;
  let current;
  modeswitch = new ModeSwitch_default({ props: { store: hierarchyChartMode } });
  return {
    c() {
      create_component(modeswitch.$$.fragment);
    },
    m(target, anchor) {
      mount_component(modeswitch, target, anchor);
      current = true;
    },
    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_block5(ctx2) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block_14, create_if_block_22, create_if_block_3, create_if_block_4];
  const if_blocks = [];
  function select_block_type_2(ctx3, dirty) {
    if (
      /*chart*/
      ctx3[0].type === "barchart"
    )
      return 0;
    if (
      /*chart*/
      ctx3[0].type === "hierarchy"
    )
      return 1;
    if (
      /*chart*/
      ctx3[0].type === "linechart"
    )
      return 2;
    if (
      /*chart*/
      ctx3[0].type === "scatterplot"
    )
      return 3;
    return -1;
  }
  if (~(current_block_type_index = select_block_type_2(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_2(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 (detaching) {
        detach(if_block_anchor);
      }
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d(detaching);
      }
    }
  };
}
function create_if_block_4(ctx2) {
  let scatterplot2;
  let current;
  scatterplot2 = new ScatterPlot_default({
    props: {
      chart: (
        /*chart*/
        ctx2[0]
      ),
      width: (
        /*width*/
        ctx2[1]
      )
    }
  });
  return {
    c() {
      create_component(scatterplot2.$$.fragment);
    },
    m(target, anchor) {
      mount_component(scatterplot2, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const scatterplot_changes = {};
      if (dirty & /*chart*/
      1)
        scatterplot_changes.chart = /*chart*/
        ctx3[0];
      if (dirty & /*width*/
      2)
        scatterplot_changes.width = /*width*/
        ctx3[1];
      scatterplot2.$set(scatterplot_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(scatterplot2.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(scatterplot2.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(scatterplot2, detaching);
    }
  };
}
function create_if_block_3(ctx2) {
  let linechart;
  let current;
  linechart = new LineChart_default({
    props: {
      chart: (
        /*chart*/
        ctx2[0]
      ),
      width: (
        /*width*/
        ctx2[1]
      ),
      legend: (
        /*legend*/
        ctx2[7]
      )
    }
  });
  return {
    c() {
      create_component(linechart.$$.fragment);
    },
    m(target, anchor) {
      mount_component(linechart, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const linechart_changes = {};
      if (dirty & /*chart*/
      1)
        linechart_changes.chart = /*chart*/
        ctx3[0];
      if (dirty & /*width*/
      2)
        linechart_changes.width = /*width*/
        ctx3[1];
      linechart.$set(linechart_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(linechart.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(linechart.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(linechart, detaching);
    }
  };
}
function create_if_block_22(ctx2) {
  let hierarchycontainer;
  let current;
  hierarchycontainer = new HierarchyContainer_default({
    props: {
      chart: (
        /*chart*/
        ctx2[0]
      ),
      width: (
        /*width*/
        ctx2[1]
      ),
      treemap_currencies: (
        /*treemap_currencies*/
        ctx2[6]
      )
    }
  });
  return {
    c() {
      create_component(hierarchycontainer.$$.fragment);
    },
    m(target, anchor) {
      mount_component(hierarchycontainer, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const hierarchycontainer_changes = {};
      if (dirty & /*chart*/
      1)
        hierarchycontainer_changes.chart = /*chart*/
        ctx3[0];
      if (dirty & /*width*/
      2)
        hierarchycontainer_changes.width = /*width*/
        ctx3[1];
      hierarchycontainer.$set(hierarchycontainer_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(hierarchycontainer.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(hierarchycontainer.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(hierarchycontainer, detaching);
    }
  };
}
function create_if_block_14(ctx2) {
  let barchart;
  let current;
  barchart = new BarChart_default({
    props: {
      chart: (
        /*chart*/
        ctx2[0]
      ),
      width: (
        /*width*/
        ctx2[1]
      ),
      legend: (
        /*legend*/
        ctx2[7]
      )
    }
  });
  return {
    c() {
      create_component(barchart.$$.fragment);
    },
    m(target, anchor) {
      mount_component(barchart, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const barchart_changes = {};
      if (dirty & /*chart*/
      1)
        barchart_changes.chart = /*chart*/
        ctx3[0];
      if (dirty & /*width*/
      2)
        barchart_changes.width = /*width*/
        ctx3[1];
      barchart.$set(barchart_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(barchart.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(barchart.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(barchart, detaching);
    }
  };
}
function create_fragment12(ctx2) {
  let div0;
  let current_block_type_index;
  let if_block0;
  let t03;
  let t13;
  let button;
  let t2_value = (
    /*$showCharts*/
    ctx2[2] ? "\u25BC" : "\u25C0"
  );
  let t22;
  let t32;
  let div1;
  let div1_hidden_value;
  let div1_resize_listener;
  let current;
  let mounted;
  let dispose;
  const if_block_creators = [create_if_block_5, create_else_block];
  const if_blocks = [];
  function select_block_type(ctx3, dirty) {
    if (
      /*$showCharts*/
      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 = (
    /*#slots*/
    ctx2[9].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx2,
    /*$$scope*/
    ctx2[8],
    null
  );
  let if_block1 = (
    /*width*/
    ctx2[1] && create_if_block5(ctx2)
  );
  return {
    c() {
      div0 = element("div");
      if_block0.c();
      t03 = space();
      if (default_slot)
        default_slot.c();
      t13 = space();
      button = element("button");
      t22 = text(t2_value);
      t32 = space();
      div1 = element("div");
      if (if_block1)
        if_block1.c();
      attr(button, "type", "button");
      attr(button, "class", "show-charts svelte-wpmxoo");
      attr(div0, "class", "flex-row");
      div1.hidden = div1_hidden_value = !/*$showCharts*/
      ctx2[2];
      add_render_callback(() => (
        /*div1_elementresize_handler*/
        ctx2[11].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);
      append(button, t22);
      insert(target, t32, anchor);
      insert(target, div1, anchor);
      if (if_block1)
        if_block1.m(div1, null);
      div1_resize_listener = add_iframe_resize_listener(
        div1,
        /*div1_elementresize_handler*/
        ctx2[11].bind(div1)
      );
      current = true;
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler*/
          ctx2[10]
        );
        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 & /*$$scope*/
        256)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx3,
            /*$$scope*/
            ctx3[8],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx3[8]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx3[8],
              dirty,
              null
            ),
            null
          );
        }
      }
      if ((!current || dirty & /*$showCharts*/
      4) && t2_value !== (t2_value = /*$showCharts*/
      ctx3[2] ? "\u25BC" : "\u25C0"))
        set_data(t22, t2_value);
      if (
        /*width*/
        ctx3[1]
      ) {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
          if (dirty & /*width*/
          2) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block5(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 & /*$showCharts*/
      4 && div1_hidden_value !== (div1_hidden_value = !/*$showCharts*/
      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);
        detach(t32);
        detach(div1);
      }
      if_blocks[current_block_type_index].d();
      if (default_slot)
        default_slot.d(detaching);
      if (if_block1)
        if_block1.d();
      div1_resize_listener();
      mounted = false;
      dispose();
    }
  };
}
var func2 = (c) => [c, null];
function instance13($$self, $$props, $$invalidate) {
  let $showCharts;
  let $legend;
  let $hierarchyChartMode;
  let $treemap_currencies;
  component_subscribe($$self, showCharts, ($$value) => $$invalidate(2, $showCharts = $$value));
  component_subscribe($$self, hierarchyChartMode, ($$value) => $$invalidate(4, $hierarchyChartMode = $$value));
  let { $$slots: slots = {}, $$scope } = $$props;
  let { chart } = $$props;
  let width;
  const treemap_currencies = writable([]);
  component_subscribe($$self, treemap_currencies, (value) => $$invalidate(5, $treemap_currencies = value));
  const legend = writable([]);
  component_subscribe($$self, legend, (value) => $$invalidate(3, $legend = value));
  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(8, $$scope = $$props2.$$scope);
  };
  return [
    chart,
    width,
    $showCharts,
    $legend,
    $hierarchyChartMode,
    $treemap_currencies,
    treemap_currencies,
    legend,
    $$scope,
    slots,
    click_handler,
    div1_elementresize_handler
  ];
}
var Chart = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance13, create_fragment12, safe_not_equal, { chart: 0 });
  }
};
var Chart_default = Chart;

// src/charts/SelectCombobox.svelte
function get_each_context10(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[14] = list[i];
  child_ctx[16] = i;
  return child_ctx;
}
function create_each_block10(ctx2) {
  let li;
  let t0_value = (
    /*description*/
    ctx2[2](
      /*option*/
      ctx2[14]
    ) + ""
  );
  let t03;
  let t13;
  let li_aria_selected_value;
  let mounted;
  let dispose;
  function mousedown_handler(...args2) {
    return (
      /*mousedown_handler*/
      ctx2[12](
        /*option*/
        ctx2[14],
        ...args2
      )
    );
  }
  return {
    c() {
      li = element("li");
      t03 = text(t0_value);
      t13 = space();
      attr(li, "role", "option");
      attr(li, "aria-selected", li_aria_selected_value = /*values*/
      ctx2[6].includes(
        /*option*/
        ctx2[14]
      ));
      attr(li, "class", "svelte-qt53xf");
      toggle_class(
        li,
        "current",
        /*i*/
        ctx2[16] === /*index*/
        ctx2[4]
      );
    },
    m(target, anchor) {
      insert(target, li, anchor);
      append(li, t03);
      append(li, t13);
      if (!mounted) {
        dispose = listen(li, "mousedown", mousedown_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & /*description, options*/
      6 && t0_value !== (t0_value = /*description*/
      ctx2[2](
        /*option*/
        ctx2[14]
      ) + ""))
        set_data(t03, t0_value);
      if (dirty & /*values, options*/
      66 && li_aria_selected_value !== (li_aria_selected_value = /*values*/
      ctx2[6].includes(
        /*option*/
        ctx2[14]
      ))) {
        attr(li, "aria-selected", li_aria_selected_value);
      }
      if (dirty & /*index*/
      16) {
        toggle_class(
          li,
          "current",
          /*i*/
          ctx2[16] === /*index*/
          ctx2[4]
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(li);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_fragment13(ctx2) {
  let span;
  let button;
  let t0_value = (
    /*description*/
    ctx2[2](
      /*value*/
      ctx2[0]
    ) + ""
  );
  let t03;
  let button_aria_expanded_value;
  let t13;
  let ul_1;
  let mounted;
  let dispose;
  let each_value = ensure_array_like(
    /*options*/
    ctx2[1]
  );
  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() {
      span = element("span");
      button = element("button");
      t03 = text(t0_value);
      t13 = space();
      ul_1 = element("ul");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(button, "type", "button");
      attr(button, "role", "combobox");
      attr(button, "aria-expanded", button_aria_expanded_value = !/*hidden*/
      ctx2[3]);
      attr(
        button,
        "aria-controls",
        /*listbox_id*/
        ctx2[7]
      );
      attr(button, "class", "muted");
      ul_1.hidden = /*hidden*/
      ctx2[3];
      attr(ul_1, "role", "listbox");
      attr(
        ul_1,
        "id",
        /*listbox_id*/
        ctx2[7]
      );
      attr(ul_1, "class", "svelte-qt53xf");
      attr(span, "class", "svelte-qt53xf");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, button);
      append(button, t03);
      append(span, t13);
      append(span, ul_1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(ul_1, null);
        }
      }
      ctx2[13](ul_1);
      if (!mounted) {
        dispose = [
          listen(
            button,
            "click",
            /*actions*/
            ctx2[8].toggle
          ),
          listen(
            button,
            "blur",
            /*actions*/
            ctx2[8].close
          ),
          listen(
            button,
            "keydown",
            /*keydown_handler*/
            ctx2[11]
          )
        ];
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & /*description, value*/
      5 && t0_value !== (t0_value = /*description*/
      ctx3[2](
        /*value*/
        ctx3[0]
      ) + ""))
        set_data(t03, t0_value);
      if (dirty & /*hidden*/
      8 && button_aria_expanded_value !== (button_aria_expanded_value = !/*hidden*/
      ctx3[3])) {
        attr(button, "aria-expanded", button_aria_expanded_value);
      }
      if (dirty & /*values, options, index, actions, description*/
      342) {
        each_value = ensure_array_like(
          /*options*/
          ctx3[1]
        );
        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(ul_1, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
      if (dirty & /*hidden*/
      8) {
        ul_1.hidden = /*hidden*/
        ctx3[3];
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(span);
      }
      destroy_each(each_blocks, detaching);
      ctx2[13](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
var id = 0;
var SEPARATOR = ",";
function instance14($$self, $$props, $$invalidate) {
  let values;
  let { value } = $$props;
  let { options: options3 } = $$props;
  let { description } = $$props;
  let { multiple_select = void 0 } = $$props;
  let hidden = true;
  let index2 = options3.indexOf(value) ?? 0;
  let ul;
  id += 1;
  const listbox_id = `combobox-listbox-${id}`;
  const actions = {
    /** Close the popup list. */
    close: () => {
      $$invalidate(3, hidden = true);
    },
    /** Find the first element matching the typed letter and focus it. */
    find_letter: (key2, event) => {
      const match = options3.findIndex((o) => o.toLowerCase().startsWith(key2));
      if (match > -1) {
        event.stopPropagation();
        $$invalidate(4, index2 = match);
        $$invalidate(3, hidden = false);
      }
    },
    /** Focus the first element and open if not open yet. */
    first: () => {
      $$invalidate(4, index2 = 0);
      $$invalidate(3, hidden = false);
    },
    /** Focus the last element and open if not open yet. */
    last: () => {
      $$invalidate(4, index2 = 0);
      $$invalidate(3, hidden = false);
    },
    /** Focus the previous element in the popup. */
    next: () => {
      $$invalidate(4, index2 = index2 === 0 ? options3.length - 1 : index2 - 1);
    },
    /** Open the popup list. */
    open: () => {
      $$invalidate(3, hidden = false);
    },
    /** Focus the previous element in the popup. */
    previous: () => {
      $$invalidate(4, index2 = index2 === options3.length - 1 ? 0 : index2 + 1);
    },
    /** Select the given or the focused element in the options list. */
    select: (o) => {
      const option = o ?? options3[index2];
      if (option) {
        if (multiple_select?.(option) && values.every(multiple_select)) {
          $$invalidate(0, value = values.includes(option) ? values.filter((v) => v !== option).join(SEPARATOR) : [...values, option].join(SEPARATOR));
        } else {
          $$invalidate(0, value = option);
        }
        $$invalidate(4, index2 = options3.indexOf(option));
        $$invalidate(3, hidden = true);
      }
    },
    /** Toggle the popup list. */
    toggle: () => {
      $$invalidate(3, hidden = !hidden);
    }
  };
  function key_action(event) {
    const { key: key2 } = event;
    const modifier = event.altKey || event.ctrlKey || event.metaKey;
    if (key2.match(/^[\w]$/) && !modifier) {
      return actions.find_letter.bind(null, key2, event);
    }
    if (key2 === "Home") {
      return actions.first;
    }
    if (key2 === "End") {
      return actions.last;
    }
    if ((key2 === "Enter" || key2 === " ") && !hidden) {
      return actions.select;
    }
    if (key2 === "Escape" && !hidden) {
      return actions.close;
    }
    if (key2 === "ArrowUp") {
      return hidden ? actions.open : actions.next;
    }
    if (key2 === "ArrowDown") {
      return hidden ? actions.open : actions.previous;
    }
    return null;
  }
  const keydown_handler = (event) => {
    const action = key_action(event);
    if (action) {
      event.preventDefault();
      action();
    }
  };
  const mousedown_handler = (option, ev) => {
    if (ev.button === 0) {
      actions.select(option);
    }
  };
  function ul_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      ul = $$value;
      $$invalidate(5, ul);
    });
  }
  $$self.$$set = ($$props2) => {
    if ("value" in $$props2)
      $$invalidate(0, value = $$props2.value);
    if ("options" in $$props2)
      $$invalidate(1, options3 = $$props2.options);
    if ("description" in $$props2)
      $$invalidate(2, description = $$props2.description);
    if ("multiple_select" in $$props2)
      $$invalidate(10, multiple_select = $$props2.multiple_select);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*value*/
    1) {
      $:
        $$invalidate(6, values = value.split(SEPARATOR));
    }
    if ($$self.$$.dirty & /*hidden, index, ul*/
    56) {
      $:
        if (!hidden && index2) {
          ul?.children[index2]?.scrollIntoView({ block: "nearest", inline: "nearest" });
        }
    }
  };
  return [
    value,
    options3,
    description,
    hidden,
    index2,
    ul,
    values,
    listbox_id,
    actions,
    key_action,
    multiple_select,
    keydown_handler,
    mousedown_handler,
    ul_1_binding
  ];
}
var SelectCombobox = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance14, create_fragment13, safe_not_equal, {
      value: 0,
      options: 1,
      description: 2,
      multiple_select: 10
    });
  }
};
var SelectCombobox_default = SelectCombobox;

// src/charts/ConversionAndInterval.svelte
function create_fragment14(ctx2) {
  let selectcombobox0;
  let updating_value;
  let t4;
  let selectcombobox1;
  let updating_value_1;
  let current;
  function selectcombobox0_value_binding(value) {
    ctx2[5](value);
  }
  let selectcombobox0_props = {
    options: (
      /*$conversions*/
      ctx2[1]
    ),
    description: (
      /*conversion_description*/
      ctx2[3]
    ),
    multiple_select: (
      /*is_currency_conversion*/
      ctx2[4]
    )
  };
  if (
    /*$conversion*/
    ctx2[0] !== void 0
  ) {
    selectcombobox0_props.value = /*$conversion*/
    ctx2[0];
  }
  selectcombobox0 = new SelectCombobox_default({ props: selectcombobox0_props });
  binding_callbacks.push(() => bind(selectcombobox0, "value", selectcombobox0_value_binding));
  function selectcombobox1_value_binding(value) {
    ctx2[7](value);
  }
  let selectcombobox1_props = {
    options: INTERVALS,
    description: (
      /*func*/
      ctx2[6]
    )
  };
  if (
    /*$interval*/
    ctx2[2] !== void 0
  ) {
    selectcombobox1_props.value = /*$interval*/
    ctx2[2];
  }
  selectcombobox1 = new SelectCombobox_default({ props: selectcombobox1_props });
  binding_callbacks.push(() => bind(selectcombobox1, "value", selectcombobox1_value_binding));
  return {
    c() {
      create_component(selectcombobox0.$$.fragment);
      t4 = space();
      create_component(selectcombobox1.$$.fragment);
    },
    m(target, anchor) {
      mount_component(selectcombobox0, target, anchor);
      insert(target, t4, anchor);
      mount_component(selectcombobox1, target, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      const selectcombobox0_changes = {};
      if (dirty & /*$conversions*/
      2)
        selectcombobox0_changes.options = /*$conversions*/
        ctx3[1];
      if (!updating_value && dirty & /*$conversion*/
      1) {
        updating_value = true;
        selectcombobox0_changes.value = /*$conversion*/
        ctx3[0];
        add_flush_callback(() => updating_value = false);
      }
      selectcombobox0.$set(selectcombobox0_changes);
      const selectcombobox1_changes = {};
      if (!updating_value_1 && dirty & /*$interval*/
      4) {
        updating_value_1 = true;
        selectcombobox1_changes.value = /*$interval*/
        ctx3[2];
        add_flush_callback(() => updating_value_1 = false);
      }
      selectcombobox1.$set(selectcombobox1_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(selectcombobox0.$$.fragment, local);
      transition_in(selectcombobox1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(selectcombobox0.$$.fragment, local);
      transition_out(selectcombobox1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t4);
      }
      destroy_component(selectcombobox0, detaching);
      destroy_component(selectcombobox1, detaching);
    }
  };
}
function instance15($$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 conversion_description = (option) => {
    switch (option) {
      case "at_cost":
        return _("At Cost");
      case "at_value":
        return _("At Market Value");
      case "units":
        return _("Units");
      default:
        return format(_("Converted to %(currency)s"), { currency: option });
    }
  };
  const is_currency_conversion = (option) => !["at_cost", "at_value", "units"].includes(option);
  function selectcombobox0_value_binding(value) {
    $conversion = value;
    conversion.set($conversion);
  }
  const func3 = (o) => intervalLabel(getInterval(o));
  function selectcombobox1_value_binding(value) {
    $interval = value;
    interval.set($interval);
  }
  return [
    $conversion,
    $conversions,
    $interval,
    conversion_description,
    is_currency_conversion,
    selectcombobox0_value_binding,
    func3,
    selectcombobox1_value_binding
  ];
}
var ConversionAndInterval = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance15, create_fragment14, safe_not_equal, {});
  }
};
var ConversionAndInterval_default = ConversionAndInterval;

// src/charts/ChartSwitcher.svelte
function get_each_context11(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[7] = list[i];
  child_ctx[9] = i;
  return child_ctx;
}
function create_if_block6(ctx2) {
  let chart_1;
  let t4;
  let div;
  let div_hidden_value;
  let current;
  chart_1 = new Chart_default({
    props: {
      chart: (
        /*active_chart*/
        ctx2[1]
      ),
      $$slots: { default: [create_default_slot] },
      $$scope: { ctx: ctx2 }
    }
  });
  let each_value = ensure_array_like(
    /*charts*/
    ctx2[0]
  );
  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() {
      create_component(chart_1.$$.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 = !/*$showCharts*/
      ctx2[5];
      attr(div, "class", "svelte-13m80wt");
    },
    m(target, anchor) {
      mount_component(chart_1, target, anchor);
      insert(target, t4, anchor);
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div, null);
        }
      }
      current = true;
    },
    p(ctx3, dirty) {
      const chart_1_changes = {};
      if (dirty & /*active_chart*/
      2)
        chart_1_changes.chart = /*active_chart*/
        ctx3[1];
      if (dirty & /*$$scope*/
      1024) {
        chart_1_changes.$$scope = { dirty, ctx: ctx3 };
      }
      chart_1.$set(chart_1_changes);
      if (dirty & /*shortcutPrevious, shortcutNext, charts, active_chart, $lastActiveChartName*/
      31) {
        each_value = ensure_array_like(
          /*charts*/
          ctx3[0]
        );
        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(div, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
      if (!current || dirty & /*$showCharts*/
      32 && div_hidden_value !== (div_hidden_value = !/*$showCharts*/
      ctx3[5])) {
        div.hidden = div_hidden_value;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(chart_1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(chart_1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t4);
        detach(div);
      }
      destroy_component(chart_1, detaching);
      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_block11(ctx2) {
  let button;
  let t0_value = (
    /*chart*/
    ctx2[7].name + ""
  );
  let t03;
  let t13;
  let keyboardShortcut_action;
  let keyboardShortcut_action_1;
  let mounted;
  let dispose;
  function click_handler() {
    return (
      /*click_handler*/
      ctx2[6](
        /*chart*/
        ctx2[7]
      )
    );
  }
  return {
    c() {
      button = element("button");
      t03 = text(t0_value);
      t13 = space();
      attr(button, "type", "button");
      attr(button, "class", "unset svelte-13m80wt");
      toggle_class(
        button,
        "selected",
        /*chart*/
        ctx2[7] === /*active_chart*/
        ctx2[1]
      );
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, t03);
      append(button, t13);
      if (!mounted) {
        dispose = [
          listen(button, "click", click_handler),
          action_destroyer(keyboardShortcut_action = keyboardShortcut.call(
            null,
            button,
            /*shortcutPrevious*/
            ctx2[4](
              /*index*/
              ctx2[9]
            )
          )),
          action_destroyer(keyboardShortcut_action_1 = keyboardShortcut.call(
            null,
            button,
            /*shortcutNext*/
            ctx2[3](
              /*index*/
              ctx2[9]
            )
          ))
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & /*charts*/
      1 && t0_value !== (t0_value = /*chart*/
      ctx2[7].name + ""))
        set_data(t03, t0_value);
      if (keyboardShortcut_action && is_function(keyboardShortcut_action.update) && dirty & /*shortcutPrevious*/
      16)
        keyboardShortcut_action.update.call(
          null,
          /*shortcutPrevious*/
          ctx2[4](
            /*index*/
            ctx2[9]
          )
        );
      if (keyboardShortcut_action_1 && is_function(keyboardShortcut_action_1.update) && dirty & /*shortcutNext*/
      8)
        keyboardShortcut_action_1.update.call(
          null,
          /*shortcutNext*/
          ctx2[3](
            /*index*/
            ctx2[9]
          )
        );
      if (dirty & /*charts, active_chart*/
      3) {
        toggle_class(
          button,
          "selected",
          /*chart*/
          ctx2[7] === /*active_chart*/
          ctx2[1]
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_fragment15(ctx2) {
  let if_block_anchor;
  let current;
  let if_block = (
    /*active_chart*/
    ctx2[1] && create_if_block6(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 (
        /*active_chart*/
        ctx3[1]
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & /*active_chart*/
          2) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block6(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 (detaching) {
        detach(if_block_anchor);
      }
      if (if_block)
        if_block.d(detaching);
    }
  };
}
function instance16($$self, $$props, $$invalidate) {
  let active_chart;
  let shortcutPrevious;
  let shortcutNext;
  let $lastActiveChartName;
  let $showCharts;
  component_subscribe($$self, lastActiveChartName, ($$value) => $$invalidate(2, $lastActiveChartName = $$value));
  component_subscribe($$self, showCharts, ($$value) => $$invalidate(5, $showCharts = $$value));
  let { charts } = $$props;
  const click_handler = (chart) => {
    set_store_value(lastActiveChartName, $lastActiveChartName = chart.name, $lastActiveChartName);
  };
  $$self.$$set = ($$props2) => {
    if ("charts" in $$props2)
      $$invalidate(0, charts = $$props2.charts);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*charts, $lastActiveChartName*/
    5) {
      $:
        $$invalidate(1, active_chart = charts.find((c) => c.name === $lastActiveChartName) ?? charts?.[0]);
    }
    if ($$self.$$.dirty & /*active_chart, charts*/
    3) {
      $:
        $$invalidate(4, shortcutPrevious = (index2) => {
          const current = active_chart ? charts.indexOf(active_chart) : -1;
          return index2 === (current - 1 + charts.length) % charts.length ? { key: "C", note: _("Previous") } : void 0;
        });
    }
    if ($$self.$$.dirty & /*active_chart, charts*/
    3) {
      $:
        $$invalidate(3, shortcutNext = (index2) => {
          const current = active_chart ? charts.indexOf(active_chart) : -1;
          return index2 === (current + 1 + charts.length) % charts.length ? { key: "c", note: _("Next") } : void 0;
        });
    }
  };
  return [
    charts,
    active_chart,
    $lastActiveChartName,
    shortcutNext,
    shortcutPrevious,
    $showCharts,
    click_handler
  ];
}
var ChartSwitcher = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance16, create_fragment15, safe_not_equal, { charts: 0 });
  }
};
var ChartSwitcher_default = ChartSwitcher;

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

// src/stores/accounts.ts
var collapse_account = derived(fava_options, ($fava_options) => {
  const matchers = $fava_options.collapse_pattern.map((p) => new RegExp(p));
  return (name2) => matchers.some((p) => p.test(name2));
});
var invert_account = derived(
  [fava_options, options],
  ([$fava_options, $options]) => $fava_options.invert_income_liabilities_equity ? (name2) => name2.startsWith($options.name_income) || name2.startsWith($options.name_liabilities) || name2.startsWith($options.name_equity) || name2 === _("Net Profit") : () => false
);
var is_closed_account = derived(
  [account_details],
  ([$account_details]) => (name2, date4) => {
    const close_date = $account_details[name2]?.close_date;
    if (!close_date) {
      return false;
    }
    return date4 === null ? true : close_date < date4;
  }
);

// src/tree-table/helpers.ts
var key = Symbol("tree-table");
var setTreeTableContext = (ctx2) => setContext(key, ctx2);
var getTreeTableContext = () => getContext(key);
var get_not_shown = derived(
  [fava_options, accounts, is_closed_account],
  ([$fava_options, $accounts, $is_closed_account]) => (node, end) => {
    const {
      show_accounts_with_zero_balance,
      show_accounts_with_zero_transactions,
      show_closed_accounts
    } = $fava_options;
    const not_shown = /* @__PURE__ */ new Set();
    const should_show_recursive = (n) => {
      if (
        // We need to evaluate this for all descendants recursively
        // the .map().some() ensures it does not short-circuit
        n.children.map(should_show_recursive).some((b) => b) || !is_empty2(n.balance_children)
      ) {
        return true;
      }
      if (!$accounts.includes(n.account) || !show_closed_accounts && $is_closed_account(n.account, end) || !show_accounts_with_zero_balance && is_empty2(n.balance) || !show_accounts_with_zero_transactions && !n.has_txns) {
        not_shown.add(n.account);
        return false;
      }
      return true;
    };
    should_show_recursive(node);
    return not_shown;
  }
);
function get_collapsed(root2, $collapse_account) {
  const s = /* @__PURE__ */ new Set();
  const get_collapsed_recursive = ({ children: children3, account: account2 }) => {
    if (children3.length && $collapse_account(account2)) {
      s.add(account2);
    }
    children3.forEach(get_collapsed_recursive);
  };
  get_collapsed_recursive(root2);
  return s;
}

// src/tree-table/AccountCellHeader.svelte
function create_if_block7(ctx2) {
  let button;
  let button_title_value;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      button.textContent = `${_("Expand all")}`;
      attr(button, "type", "button");
      attr(button, "class", "link svelte-1ihav4y");
      attr(button, "title", button_title_value = _("Expand all accounts"));
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler*/
          ctx2[3]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_fragment16(ctx2) {
  let span;
  let if_block = (
    /*$toggled*/
    ctx2[0].size && create_if_block7(ctx2)
  );
  return {
    c() {
      span = element("span");
      if (if_block)
        if_block.c();
      attr(
        span,
        "title",
        /*help_title*/
        ctx2[2]
      );
      attr(span, "class", "svelte-1ihav4y");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      if (if_block)
        if_block.m(span, null);
    },
    p(ctx3, [dirty]) {
      if (
        /*$toggled*/
        ctx3[0].size
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block7(ctx3);
          if_block.c();
          if_block.m(span, null);
        }
      } 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 instance17($$self, $$props, $$invalidate) {
  let $toggled;
  const { toggled } = getTreeTableContext();
  component_subscribe($$self, toggled, (value) => $$invalidate(0, $toggled = value));
  const help_title = _("Hold Shift while clicking to expand all children.\nHold Ctrl or Cmd while clicking to expand one level.");
  const click_handler = () => {
    toggled.set(/* @__PURE__ */ new Set());
  };
  return [$toggled, toggled, help_title, click_handler];
}
var AccountCellHeader = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance17, create_fragment16, safe_not_equal, {});
  }
};
var AccountCellHeader_default = AccountCellHeader;

// 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/sidebar/AccountIndicator.svelte
function create_if_block8(ctx2) {
  let t4;
  let if_block1_anchor;
  function select_block_type(ctx3, dirty) {
    if (
      /*status*/
      ctx3[3] === "green"
    )
      return create_if_block_23;
    return create_else_block2;
  }
  let current_block_type = select_block_type(ctx2, -1);
  let if_block0 = current_block_type(ctx2);
  let if_block1 = (
    /*last_account_activity*/
    ctx2[1] > /*$fava_options*/
    ctx2[4].uptodate_indicator_grey_lookback_days && create_if_block_15(ctx2)
  );
  return {
    c() {
      if_block0.c();
      t4 = space();
      if (if_block1)
        if_block1.c();
      if_block1_anchor = empty();
    },
    m(target, anchor) {
      if_block0.m(target, anchor);
      insert(target, t4, anchor);
      if (if_block1)
        if_block1.m(target, anchor);
      insert(target, if_block1_anchor, anchor);
    },
    p(ctx3, dirty) {
      if (current_block_type === (current_block_type = select_block_type(ctx3, dirty)) && if_block0) {
        if_block0.p(ctx3, dirty);
      } else {
        if_block0.d(1);
        if_block0 = current_block_type(ctx3);
        if (if_block0) {
          if_block0.c();
          if_block0.m(t4.parentNode, t4);
        }
      }
      if (
        /*last_account_activity*/
        ctx3[1] > /*$fava_options*/
        ctx3[4].uptodate_indicator_grey_lookback_days
      ) {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
        } else {
          if_block1 = create_if_block_15(ctx3);
          if_block1.c();
          if_block1.m(if_block1_anchor.parentNode, if_block1_anchor);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(t4);
        detach(if_block1_anchor);
      }
      if_block0.d(detaching);
      if (if_block1)
        if_block1.d(detaching);
    }
  };
}
function create_else_block2(ctx2) {
  let copyable_text;
  let copyable_text_class_value;
  let copyable_text_title_value;
  return {
    c() {
      copyable_text = element("copyable-text");
      set_custom_element_data(copyable_text, "class", copyable_text_class_value = "status-indicator status-" + /*status*/
      ctx2[3] + " svelte-eoatdy");
      set_custom_element_data(copyable_text, "title", copyable_text_title_value = `${/*status*/
      ctx2[3] === "yellow" ? "The last entry is not a balance check." : "The last entry is a failing balance check."}

Click to copy the balance directives to the clipboard:

${/*balance*/
      ctx2[2]}`);
      set_custom_element_data(
        copyable_text,
        "data-clipboard-text",
        /*balance*/
        ctx2[2]
      );
      toggle_class(
        copyable_text,
        "small",
        /*small*/
        ctx2[0]
      );
    },
    m(target, anchor) {
      insert(target, copyable_text, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & /*status*/
      8 && copyable_text_class_value !== (copyable_text_class_value = "status-indicator status-" + /*status*/
      ctx3[3] + " svelte-eoatdy")) {
        set_custom_element_data(copyable_text, "class", copyable_text_class_value);
      }
      if (dirty & /*status, balance*/
      12 && copyable_text_title_value !== (copyable_text_title_value = `${/*status*/
      ctx3[3] === "yellow" ? "The last entry is not a balance check." : "The last entry is a failing balance check."}

Click to copy the balance directives to the clipboard:

${/*balance*/
      ctx3[2]}`)) {
        set_custom_element_data(copyable_text, "title", copyable_text_title_value);
      }
      if (dirty & /*balance*/
      4) {
        set_custom_element_data(
          copyable_text,
          "data-clipboard-text",
          /*balance*/
          ctx3[2]
        );
      }
      if (dirty & /*status, small*/
      9) {
        toggle_class(
          copyable_text,
          "small",
          /*small*/
          ctx3[0]
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(copyable_text);
      }
    }
  };
}
function create_if_block_23(ctx2) {
  let span;
  return {
    c() {
      span = element("span");
      attr(span, "class", "status-indicator status-green svelte-eoatdy");
      attr(span, "title", "The last entry is a passing balance check.");
      toggle_class(
        span,
        "small",
        /*small*/
        ctx2[0]
      );
    },
    m(target, anchor) {
      insert(target, span, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & /*small*/
      1) {
        toggle_class(
          span,
          "small",
          /*small*/
          ctx3[0]
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
    }
  };
}
function create_if_block_15(ctx2) {
  let span;
  let span_title_value;
  return {
    c() {
      span = element("span");
      attr(span, "class", "status-indicator status-gray svelte-eoatdy");
      attr(span, "title", span_title_value = "This account has not been updated in a while. (" + /*last_account_activity*/
      ctx2[1] + " days ago)");
      toggle_class(
        span,
        "small",
        /*small*/
        ctx2[0]
      );
    },
    m(target, anchor) {
      insert(target, span, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & /*last_account_activity*/
      2 && span_title_value !== (span_title_value = "This account has not been updated in a while. (" + /*last_account_activity*/
      ctx3[1] + " days ago)")) {
        attr(span, "title", span_title_value);
      }
      if (dirty & /*small*/
      1) {
        toggle_class(
          span,
          "small",
          /*small*/
          ctx3[0]
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
    }
  };
}
function create_fragment17(ctx2) {
  let if_block_anchor;
  let if_block = (
    /*status*/
    ctx2[3] && create_if_block8(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 (
        /*status*/
        ctx3[3]
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block8(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(if_block_anchor);
      }
      if (if_block)
        if_block.d(detaching);
    }
  };
}
function instance18($$self, $$props, $$invalidate) {
  let details;
  let status;
  let balance;
  let last_entry;
  let last_account_activity;
  let $account_details;
  let $fava_options;
  component_subscribe($$self, account_details, ($$value) => $$invalidate(8, $account_details = $$value));
  component_subscribe($$self, fava_options, ($$value) => $$invalidate(4, $fava_options = $$value));
  let { account: account2 } = $$props;
  let { small = false } = $$props;
  $$self.$$set = ($$props2) => {
    if ("account" in $$props2)
      $$invalidate(5, account2 = $$props2.account);
    if ("small" in $$props2)
      $$invalidate(0, small = $$props2.small);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$account_details, account*/
    288) {
      $:
        $$invalidate(7, details = $account_details[account2]);
    }
    if ($$self.$$.dirty & /*details*/
    128) {
      $:
        $$invalidate(3, status = details?.uptodate_status);
    }
    if ($$self.$$.dirty & /*details*/
    128) {
      $:
        $$invalidate(2, balance = details?.balance_string ?? "");
    }
    if ($$self.$$.dirty & /*details*/
    128) {
      $:
        $$invalidate(6, last_entry = details?.last_entry);
    }
    if ($$self.$$.dirty & /*last_entry*/
    64) {
      $:
        $$invalidate(1, last_account_activity = last_entry ? timeDay.count(last_entry.date, /* @__PURE__ */ new Date()) : 0);
    }
  };
  return [
    small,
    last_account_activity,
    balance,
    status,
    $fava_options,
    account2,
    last_entry,
    details,
    $account_details
  ];
}
var AccountIndicator = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance18, create_fragment17, safe_not_equal, { account: 5, small: 0 });
  }
};
var AccountIndicator_default = AccountIndicator;

// src/tree-table/AccountCell.svelte
function create_if_block9(ctx2) {
  let button;
  let t_value = (
    /*$toggled*/
    ctx2[3].has(
      /*account*/
      ctx2[1]
    ) ? "\u25B8" : "\u25BE"
  );
  let t4;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      t4 = text(t_value);
      attr(button, "type", "button");
      attr(button, "class", "unset svelte-c3bl36");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, t4);
      if (!mounted) {
        dispose = listen(button, "click", function() {
          if (is_function(
            /*on_click*/
            ctx2[2]
          ))
            ctx2[2].apply(this, arguments);
        });
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & /*$toggled, account*/
      10 && t_value !== (t_value = /*$toggled*/
      ctx2[3].has(
        /*account*/
        ctx2[1]
      ) ? "\u25B8" : "\u25BE"))
        set_data(t4, t_value);
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_fragment18(ctx2) {
  let span;
  let t03;
  let a;
  let t1_value = leaf(
    /*account*/
    ctx2[1]
  ) + "";
  let t13;
  let a_href_value;
  let t22;
  let accountindicator;
  let current;
  let if_block = (
    /*children*/
    ctx2[0].length > 0 && create_if_block9(ctx2)
  );
  accountindicator = new AccountIndicator_default({
    props: { account: (
      /*account*/
      ctx2[1]
    ), small: true }
  });
  return {
    c() {
      span = element("span");
      if (if_block)
        if_block.c();
      t03 = space();
      a = element("a");
      t13 = text(t1_value);
      t22 = space();
      create_component(accountindicator.$$.fragment);
      attr(a, "href", a_href_value = /*$urlForAccount*/
      ctx2[4](
        /*account*/
        ctx2[1]
      ));
      attr(a, "class", "account svelte-c3bl36");
      attr(span, "class", "droptarget svelte-c3bl36");
      attr(
        span,
        "data-account-name",
        /*account*/
        ctx2[1]
      );
    },
    m(target, anchor) {
      insert(target, span, anchor);
      if (if_block)
        if_block.m(span, null);
      append(span, t03);
      append(span, a);
      append(a, t13);
      append(span, t22);
      mount_component(accountindicator, span, null);
      current = true;
    },
    p(ctx3, [dirty]) {
      if (
        /*children*/
        ctx3[0].length > 0
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block9(ctx3);
          if_block.c();
          if_block.m(span, t03);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if ((!current || dirty & /*account*/
      2) && t1_value !== (t1_value = leaf(
        /*account*/
        ctx3[1]
      ) + ""))
        set_data(t13, t1_value);
      if (!current || dirty & /*$urlForAccount, account*/
      18 && a_href_value !== (a_href_value = /*$urlForAccount*/
      ctx3[4](
        /*account*/
        ctx3[1]
      ))) {
        attr(a, "href", a_href_value);
      }
      const accountindicator_changes = {};
      if (dirty & /*account*/
      2)
        accountindicator_changes.account = /*account*/
        ctx3[1];
      accountindicator.$set(accountindicator_changes);
      if (!current || dirty & /*account*/
      2) {
        attr(
          span,
          "data-account-name",
          /*account*/
          ctx3[1]
        );
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(accountindicator.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(accountindicator.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
      if (if_block)
        if_block.d();
      destroy_component(accountindicator);
    }
  };
}
function instance19($$self, $$props, $$invalidate) {
  let account2;
  let children3;
  let on_click;
  let $toggled;
  let $urlForAccount;
  component_subscribe($$self, urlForAccount, ($$value) => $$invalidate(4, $urlForAccount = $$value));
  let { node } = $$props;
  const { toggled } = getTreeTableContext();
  component_subscribe($$self, toggled, (value) => $$invalidate(3, $toggled = value));
  $$self.$$set = ($$props2) => {
    if ("node" in $$props2)
      $$invalidate(6, node = $$props2.node);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*node*/
    64) {
      $:
        $$invalidate(1, { account: account2, children: children3 } = node, account2, ($$invalidate(0, children3), $$invalidate(6, node)));
    }
    if ($$self.$$.dirty & /*account, children*/
    3) {
      $:
        $$invalidate(2, on_click = (event) => {
          toggled.update((t4) => {
            const new_t = new Set(t4);
            const is_toggled = new_t.has(account2);
            if (is_toggled) {
              new_t.delete(account2);
            } else {
              new_t.add(account2);
            }
            if (event.shiftKey) {
              const toggle_all = (n) => {
                if (is_toggled) {
                  new_t.delete(n.account);
                } else {
                  new_t.add(n.account);
                }
                n.children.filter((c) => c.children.length).forEach(toggle_all);
              };
              children3.forEach(toggle_all);
            }
            if (is_toggled && (event.ctrlKey || event.metaKey)) {
              children3.filter((c) => c.children.length).forEach((n) => {
                new_t.add(n.account);
              });
            }
            return new_t;
          });
        });
    }
  };
  return [children3, account2, on_click, $toggled, $urlForAccount, toggled, node];
}
var AccountCell = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance19, create_fragment18, safe_not_equal, { node: 6 });
  }
};
var AccountCell_default = AccountCell;

// src/tree-table/Diff.svelte
function create_fragment19(ctx2) {
  let br;
  let t03;
  let span;
  let t13;
  let t2_value = (
    /*$ctx*/
    ctx2[3].num(
      /*diff*/
      ctx2[0],
      /*currency*/
      ctx2[2]
    ) + ""
  );
  let t22;
  let t32;
  let span_title_value;
  return {
    c() {
      br = element("br");
      t03 = space();
      span = element("span");
      t13 = text("(");
      t22 = text(t2_value);
      t32 = text(")");
      attr(span, "title", span_title_value = /*$ctx*/
      ctx2[3].amount(
        /*num*/
        ctx2[1],
        /*currency*/
        ctx2[2]
      ));
      attr(span, "class", "svelte-16zx9ty");
      toggle_class(
        span,
        "positive",
        /*diff*/
        ctx2[0] > 0
      );
    },
    m(target, anchor) {
      insert(target, br, anchor);
      insert(target, t03, anchor);
      insert(target, span, anchor);
      append(span, t13);
      append(span, t22);
      append(span, t32);
    },
    p(ctx3, [dirty]) {
      if (dirty & /*$ctx, diff, currency*/
      13 && t2_value !== (t2_value = /*$ctx*/
      ctx3[3].num(
        /*diff*/
        ctx3[0],
        /*currency*/
        ctx3[2]
      ) + ""))
        set_data(t22, t2_value);
      if (dirty & /*$ctx, num, currency*/
      14 && span_title_value !== (span_title_value = /*$ctx*/
      ctx3[3].amount(
        /*num*/
        ctx3[1],
        /*currency*/
        ctx3[2]
      ))) {
        attr(span, "title", span_title_value);
      }
      if (dirty & /*diff*/
      1) {
        toggle_class(
          span,
          "positive",
          /*diff*/
          ctx3[0] > 0
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(br);
        detach(t03);
        detach(span);
      }
    }
  };
}
function instance20($$self, $$props, $$invalidate) {
  let $ctx;
  component_subscribe($$self, ctx, ($$value) => $$invalidate(3, $ctx = $$value));
  let { diff } = $$props;
  let { num } = $$props;
  let { currency } = $$props;
  $$self.$$set = ($$props2) => {
    if ("diff" in $$props2)
      $$invalidate(0, diff = $$props2.diff);
    if ("num" in $$props2)
      $$invalidate(1, num = $$props2.num);
    if ("currency" in $$props2)
      $$invalidate(2, currency = $$props2.currency);
  };
  return [diff, num, currency, $ctx];
}
var Diff = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance20, create_fragment19, safe_not_equal, { diff: 0, num: 1, currency: 2 });
  }
};
var Diff_default = Diff;

// src/tree-table/IntervalTreeTableNode.svelte
function get_each_context12(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[16] = list[i];
  child_ctx[18] = i;
  return child_ctx;
}
function get_each_context_13(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[19] = list[i];
  child_ctx[18] = i;
  const constants_0 = (
    /*account_budgets*/
    child_ctx[4]?.[
      /*index*/
      child_ctx[18]
    ]
  );
  child_ctx[20] = constants_0;
  const constants_1 = !is_empty2(
    /*n*/
    child_ctx[19].balance
  ) || /*account_budget*/
  child_ctx[20] && !is_empty2(
    /*account_budget*/
    child_ctx[20].budget
  );
  child_ctx[21] = constants_1;
  const constants_2 = !/*is_toggled*/
  child_ctx[3] && /*has_balance*/
  child_ctx[21];
  child_ctx[22] = constants_2;
  const constants_3 = (
    /*show_balance*/
    child_ctx[22] ? (
      /*n*/
      child_ctx[19].balance
    ) : (
      /*n*/
      child_ctx[19].balance_children
    )
  );
  child_ctx[23] = constants_3;
  const constants_4 = (
    /*show_balance*/
    child_ctx[22] ? (
      /*account_budget*/
      child_ctx[20]?.budget
    ) : (
      /*account_budget*/
      child_ctx[20]?.budget_children
    )
  );
  child_ctx[24] = constants_4;
  return child_ctx;
}
function get_each_context_23(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[26] = list[i][0];
  child_ctx[27] = list[i][1];
  return child_ctx;
}
function get_each_context_33(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[26] = list[i][0];
  child_ctx[30] = list[i][1];
  const constants_0 = (
    /*shown_budget*/
    child_ctx[24]?.[
      /*currency*/
      child_ctx[26]
    ]
  );
  child_ctx[27] = constants_0;
  return child_ctx;
}
function create_if_block_32(ctx2) {
  let diff;
  let current;
  diff = new Diff_default({
    props: {
      diff: (
        /*budget*/
        ctx2[27] - /*number*/
        ctx2[30]
      ),
      num: (
        /*budget*/
        ctx2[27]
      ),
      currency: (
        /*currency*/
        ctx2[26]
      )
    }
  });
  return {
    c() {
      create_component(diff.$$.fragment);
    },
    m(target, anchor) {
      mount_component(diff, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const diff_changes = {};
      if (dirty[0] & /*is_toggled, nodes, account_budgets*/
      25)
        diff_changes.diff = /*budget*/
        ctx3[27] - /*number*/
        ctx3[30];
      if (dirty[0] & /*is_toggled, nodes, account_budgets*/
      25)
        diff_changes.num = /*budget*/
        ctx3[27];
      if (dirty[0] & /*is_toggled, nodes, account_budgets*/
      25)
        diff_changes.currency = /*currency*/
        ctx3[26];
      diff.$set(diff_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(diff.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(diff.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(diff, detaching);
    }
  };
}
function create_each_block_33(ctx2) {
  let span;
  let t0_value = (
    /*$ctx*/
    ctx2[7].amount(
      /*number*/
      ctx2[30],
      /*currency*/
      ctx2[26]
    ) + ""
  );
  let t03;
  let span_title_value;
  let t13;
  let t22;
  let br;
  let current;
  let if_block = (
    /*budget*/
    ctx2[27] && create_if_block_32(ctx2)
  );
  return {
    c() {
      span = element("span");
      t03 = text(t0_value);
      t13 = space();
      if (if_block)
        if_block.c();
      t22 = space();
      br = element("br");
      attr(span, "title", span_title_value = /*$currency_name*/
      ctx2[6](
        /*currency*/
        ctx2[26]
      ));
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t03);
      insert(target, t13, anchor);
      if (if_block)
        if_block.m(target, anchor);
      insert(target, t22, anchor);
      insert(target, br, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      if ((!current || dirty[0] & /*$ctx, is_toggled, nodes, account_budgets*/
      153) && t0_value !== (t0_value = /*$ctx*/
      ctx3[7].amount(
        /*number*/
        ctx3[30],
        /*currency*/
        ctx3[26]
      ) + ""))
        set_data(t03, t0_value);
      if (!current || dirty[0] & /*$currency_name, is_toggled, nodes, account_budgets*/
      89 && span_title_value !== (span_title_value = /*$currency_name*/
      ctx3[6](
        /*currency*/
        ctx3[26]
      ))) {
        attr(span, "title", span_title_value);
      }
      if (
        /*budget*/
        ctx3[27]
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty[0] & /*is_toggled, nodes, account_budgets*/
          25) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_32(ctx3);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(t22.parentNode, t22);
        }
      } 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 (detaching) {
        detach(span);
        detach(t13);
        detach(t22);
        detach(br);
      }
      if (if_block)
        if_block.d(detaching);
    }
  };
}
function create_if_block_24(ctx2) {
  let each_1_anchor;
  let current;
  function func_1(...args2) {
    return (
      /*func_1*/
      ctx2[14](
        /*shown_balance*/
        ctx2[23],
        ...args2
      )
    );
  }
  let each_value_2 = ensure_array_like(Object.entries(
    /*shown_budget*/
    ctx2[24]
  ).filter(func_1));
  let each_blocks = [];
  for (let i = 0; i < each_value_2.length; i += 1) {
    each_blocks[i] = create_each_block_23(get_each_context_23(ctx2, each_value_2, i));
  }
  const out2 = (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) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty[0] & /*is_toggled, nodes, account_budgets, $currency_name, $ctx*/
      217) {
        each_value_2 = ensure_array_like(Object.entries(
          /*shown_budget*/
          ctx2[24]
        ).filter(func_1));
        let i;
        for (i = 0; i < each_value_2.length; i += 1) {
          const child_ctx = get_each_context_23(ctx2, each_value_2, 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_23(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_2.length; i < each_blocks.length; i += 1) {
          out2(i);
        }
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_2.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(each_1_anchor);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_each_block_23(ctx2) {
  let span;
  let t0_value = (
    /*$ctx*/
    ctx2[7].amount(
      0,
      /*currency*/
      ctx2[26]
    ) + ""
  );
  let t03;
  let span_title_value;
  let t13;
  let diff;
  let t22;
  let br;
  let current;
  diff = new Diff_default({
    props: {
      diff: (
        /*budget*/
        ctx2[27]
      ),
      num: (
        /*budget*/
        ctx2[27]
      ),
      currency: (
        /*currency*/
        ctx2[26]
      )
    }
  });
  return {
    c() {
      span = element("span");
      t03 = text(t0_value);
      t13 = space();
      create_component(diff.$$.fragment);
      t22 = space();
      br = element("br");
      attr(span, "title", span_title_value = /*$currency_name*/
      ctx2[6](
        /*currency*/
        ctx2[26]
      ));
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t03);
      insert(target, t13, anchor);
      mount_component(diff, target, anchor);
      insert(target, t22, anchor);
      insert(target, br, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      if ((!current || dirty[0] & /*$ctx, is_toggled, nodes, account_budgets*/
      153) && t0_value !== (t0_value = /*$ctx*/
      ctx3[7].amount(
        0,
        /*currency*/
        ctx3[26]
      ) + ""))
        set_data(t03, t0_value);
      if (!current || dirty[0] & /*$currency_name, is_toggled, nodes, account_budgets*/
      89 && span_title_value !== (span_title_value = /*$currency_name*/
      ctx3[6](
        /*currency*/
        ctx3[26]
      ))) {
        attr(span, "title", span_title_value);
      }
      const diff_changes = {};
      if (dirty[0] & /*is_toggled, nodes, account_budgets*/
      25)
        diff_changes.diff = /*budget*/
        ctx3[27];
      if (dirty[0] & /*is_toggled, nodes, account_budgets*/
      25)
        diff_changes.num = /*budget*/
        ctx3[27];
      if (dirty[0] & /*is_toggled, nodes, account_budgets*/
      25)
        diff_changes.currency = /*currency*/
        ctx3[26];
      diff.$set(diff_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(diff.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(diff.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(span);
        detach(t13);
        detach(t22);
        detach(br);
      }
      destroy_component(diff, detaching);
    }
  };
}
function create_each_block_13(ctx2) {
  let span;
  let t03;
  let t13;
  let current;
  let each_value_3 = ensure_array_like(Object.entries(
    /*shown_balance*/
    ctx2[23]
  ));
  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));
  }
  const out2 = (i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  });
  let if_block = (
    /*shown_budget*/
    ctx2[24] && create_if_block_24(ctx2)
  );
  return {
    c() {
      span = element("span");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t03 = space();
      if (if_block)
        if_block.c();
      t13 = space();
      attr(span, "class", "num other");
      toggle_class(span, "dimmed", !/*is_toggled*/
      ctx2[3] && !/*has_balance*/
      ctx2[21]);
    },
    m(target, anchor) {
      insert(target, span, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(span, null);
        }
      }
      append(span, t03);
      if (if_block)
        if_block.m(span, null);
      append(span, t13);
      current = true;
    },
    p(ctx3, dirty) {
      if (dirty[0] & /*is_toggled, nodes, account_budgets, $currency_name, $ctx*/
      217) {
        each_value_3 = ensure_array_like(Object.entries(
          /*shown_balance*/
          ctx3[23]
        ));
        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);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block_33(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(span, t03);
          }
        }
        group_outros();
        for (i = each_value_3.length; i < each_blocks.length; i += 1) {
          out2(i);
        }
        check_outros();
      }
      if (
        /*shown_budget*/
        ctx3[24]
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty[0] & /*is_toggled, nodes, account_budgets*/
          25) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_24(ctx3);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(span, t13);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
      if (!current || dirty[0] & /*is_toggled, nodes, account_budgets*/
      25) {
        toggle_class(span, "dimmed", !/*is_toggled*/
        ctx3[3] && !/*has_balance*/
        ctx3[21]);
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_3.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      transition_in(if_block);
      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]);
      }
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
      destroy_each(each_blocks, detaching);
      if (if_block)
        if_block.d();
    }
  };
}
function create_if_block10(ctx2) {
  let ol;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let current;
  let each_value = ensure_array_like(
    /*children*/
    ctx2[5]
  );
  const get_key = (ctx3) => (
    /*child*/
    ctx3[16].account
  );
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context12(ctx2, each_value, i);
    let key2 = get_key(child_ctx);
    each_1_lookup.set(key2, each_blocks[i] = create_each_block12(key2, child_ctx));
  }
  return {
    c() {
      ol = element("ol");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
    },
    m(target, anchor) {
      insert(target, ol, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(ol, null);
        }
      }
      current = true;
    },
    p(ctx3, dirty) {
      if (dirty[0] & /*nodes, children, budgets, $not_shown*/
      291) {
        each_value = ensure_array_like(
          /*children*/
          ctx3[5]
        );
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx3, each_value, each_1_lookup, ol, outro_and_destroy_block, create_each_block12, null, get_each_context12);
        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) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(ol);
      }
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
function create_if_block_16(ctx2) {
  let intervaltreetablenode;
  let current;
  function func_2(...args2) {
    return (
      /*func_2*/
      ctx2[15](
        /*index*/
        ctx2[18],
        ...args2
      )
    );
  }
  intervaltreetablenode = new IntervalTreeTableNode({
    props: {
      nodes: (
        /*nodes*/
        ctx2[0].map(func_2)
      ),
      budgets: (
        /*budgets*/
        ctx2[1]
      )
    }
  });
  return {
    c() {
      create_component(intervaltreetablenode.$$.fragment);
    },
    m(target, anchor) {
      mount_component(intervaltreetablenode, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      const intervaltreetablenode_changes = {};
      if (dirty[0] & /*nodes, children*/
      33)
        intervaltreetablenode_changes.nodes = /*nodes*/
        ctx2[0].map(func_2);
      if (dirty[0] & /*budgets*/
      2)
        intervaltreetablenode_changes.budgets = /*budgets*/
        ctx2[1];
      intervaltreetablenode.$set(intervaltreetablenode_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(intervaltreetablenode.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(intervaltreetablenode.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(intervaltreetablenode, detaching);
    }
  };
}
function create_each_block12(key_1, ctx2) {
  let first;
  let show_if = !/*$not_shown*/
  ctx2[8].has(
    /*child*/
    ctx2[16].account
  );
  let if_block_anchor;
  let current;
  let if_block = show_if && create_if_block_16(ctx2);
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty[0] & /*$not_shown, children*/
      288)
        show_if = !/*$not_shown*/
        ctx2[8].has(
          /*child*/
          ctx2[16].account
        );
      if (show_if) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty[0] & /*$not_shown, children*/
          288) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_16(ctx2);
          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 (detaching) {
        detach(first);
        detach(if_block_anchor);
      }
      if (if_block)
        if_block.d(detaching);
    }
  };
}
function create_fragment20(ctx2) {
  let li;
  let p;
  let accountcell;
  let t03;
  let t13;
  let show_if = !/*is_toggled*/
  ctx2[3] && /*children*/
  ctx2[5].some(
    /*func*/
    ctx2[13]
  );
  let current;
  accountcell = new AccountCell_default({ props: { node: (
    /*node*/
    ctx2[2]
  ) } });
  let each_value_1 = ensure_array_like(
    /*nodes*/
    ctx2[0]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks[i] = create_each_block_13(get_each_context_13(ctx2, each_value_1, i));
  }
  const out2 = (i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  });
  let if_block = show_if && create_if_block10(ctx2);
  return {
    c() {
      li = element("li");
      p = element("p");
      create_component(accountcell.$$.fragment);
      t03 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t13 = space();
      if (if_block)
        if_block.c();
    },
    m(target, anchor) {
      insert(target, li, anchor);
      append(li, p);
      mount_component(accountcell, p, null);
      append(p, t03);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(p, null);
        }
      }
      append(li, t13);
      if (if_block)
        if_block.m(li, null);
      current = true;
    },
    p(ctx3, dirty) {
      const accountcell_changes = {};
      if (dirty[0] & /*node*/
      4)
        accountcell_changes.node = /*node*/
        ctx3[2];
      accountcell.$set(accountcell_changes);
      if (dirty[0] & /*is_toggled, nodes, account_budgets, $currency_name, $ctx*/
      217) {
        each_value_1 = ensure_array_like(
          /*nodes*/
          ctx3[0]
        );
        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[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block_13(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(p, null);
          }
        }
        group_outros();
        for (i = each_value_1.length; i < each_blocks.length; i += 1) {
          out2(i);
        }
        check_outros();
      }
      if (dirty[0] & /*is_toggled, children, $not_shown*/
      296)
        show_if = !/*is_toggled*/
        ctx3[3] && /*children*/
        ctx3[5].some(
          /*func*/
          ctx3[13]
        );
      if (show_if) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty[0] & /*is_toggled, children, $not_shown*/
          296) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block10(ctx3);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(li, null);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(accountcell.$$.fragment, local);
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(accountcell.$$.fragment, local);
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(li);
      }
      destroy_component(accountcell);
      destroy_each(each_blocks, detaching);
      if (if_block)
        if_block.d();
    }
  };
}
function instance21($$self, $$props, $$invalidate) {
  let node;
  let account2;
  let children3;
  let account_budgets;
  let is_toggled;
  let $toggled;
  let $currency_name;
  let $ctx;
  let $not_shown;
  component_subscribe($$self, currency_name, ($$value) => $$invalidate(6, $currency_name = $$value));
  component_subscribe($$self, ctx, ($$value) => $$invalidate(7, $ctx = $$value));
  let { nodes } = $$props;
  let { budgets } = $$props;
  const { toggled, not_shown } = getTreeTableContext();
  component_subscribe($$self, toggled, (value) => $$invalidate(12, $toggled = value));
  component_subscribe($$self, not_shown, (value) => $$invalidate(8, $not_shown = value));
  const func3 = (n) => !$not_shown.has(n.account);
  const func_1 = (shown_balance, [c]) => !shown_balance[c];
  const func_2 = (index2, n) => n.children[index2];
  $$self.$$set = ($$props2) => {
    if ("nodes" in $$props2)
      $$invalidate(0, nodes = $$props2.nodes);
    if ("budgets" in $$props2)
      $$invalidate(1, budgets = $$props2.budgets);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*nodes*/
    1) {
      $:
        $$invalidate(2, [node] = nodes, node);
    }
    if ($$self.$$.dirty[0] & /*node*/
    4) {
      $:
        $$invalidate(11, { account: account2, children: children3 } = node, account2, ($$invalidate(5, children3), $$invalidate(2, node), $$invalidate(0, nodes)));
    }
    if ($$self.$$.dirty[0] & /*budgets, account*/
    2050) {
      $:
        $$invalidate(4, account_budgets = budgets[account2]);
    }
    if ($$self.$$.dirty[0] & /*$toggled, account*/
    6144) {
      $:
        $$invalidate(3, is_toggled = $toggled.has(account2));
    }
  };
  return [
    nodes,
    budgets,
    node,
    is_toggled,
    account_budgets,
    children3,
    $currency_name,
    $ctx,
    $not_shown,
    toggled,
    not_shown,
    account2,
    $toggled,
    func3,
    func_1,
    func_2
  ];
}
var IntervalTreeTableNode = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance21, create_fragment20, safe_not_equal, { nodes: 0, budgets: 1 }, null, [-1, -1]);
  }
};
var IntervalTreeTableNode_default = IntervalTreeTableNode;

// src/tree-table/IntervalTreeTable.svelte
function get_each_context13(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[15] = list[i][0];
  child_ctx[16] = list[i][1];
  return child_ctx;
}
function create_each_block13(ctx2) {
  let span;
  let a;
  let t0_value = (
    /*title*/
    ctx2[15] + ""
  );
  let t03;
  let a_href_value;
  let t13;
  return {
    c() {
      span = element("span");
      a = element("a");
      t03 = text(t0_value);
      t13 = space();
      attr(a, "href", a_href_value = /*$urlForAccount*/
      ctx2[4](
        /*account*/
        ctx2[3],
        { time: (
          /*time*/
          ctx2[16]
        ) }
      ));
      attr(span, "class", "num other");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, a);
      append(a, t03);
      append(span, t13);
    },
    p(ctx3, dirty) {
      if (dirty & /*time_filters*/
      4 && t0_value !== (t0_value = /*title*/
      ctx3[15] + ""))
        set_data(t03, t0_value);
      if (dirty & /*$urlForAccount, account, time_filters*/
      28 && a_href_value !== (a_href_value = /*$urlForAccount*/
      ctx3[4](
        /*account*/
        ctx3[3],
        { time: (
          /*time*/
          ctx3[16]
        ) }
      ))) {
        attr(a, "href", a_href_value);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
    }
  };
}
function create_fragment21(ctx2) {
  let ol;
  let li;
  let p;
  let accountcellheader;
  let t03;
  let t13;
  let intervaltreetablenode;
  let current;
  accountcellheader = new AccountCellHeader_default({});
  let each_value = ensure_array_like(
    /*time_filters*/
    ctx2[2]
  );
  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));
  }
  intervaltreetablenode = new IntervalTreeTableNode_default({
    props: {
      nodes: (
        /*trees*/
        ctx2[0]
      ),
      budgets: (
        /*budgets*/
        ctx2[1]
      )
    }
  });
  return {
    c() {
      ol = element("ol");
      li = element("li");
      p = element("p");
      create_component(accountcellheader.$$.fragment);
      t03 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t13 = space();
      create_component(intervaltreetablenode.$$.fragment);
      attr(li, "class", "head");
      attr(ol, "class", "flex-table tree-table-new svelte-o61rw3");
    },
    m(target, anchor) {
      insert(target, ol, anchor);
      append(ol, li);
      append(li, p);
      mount_component(accountcellheader, p, null);
      append(p, t03);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(p, null);
        }
      }
      append(ol, t13);
      mount_component(intervaltreetablenode, ol, null);
      current = true;
    },
    p(ctx3, [dirty]) {
      if (dirty & /*$urlForAccount, account, time_filters*/
      28) {
        each_value = ensure_array_like(
          /*time_filters*/
          ctx3[2]
        );
        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(p, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
      const intervaltreetablenode_changes = {};
      if (dirty & /*trees*/
      1)
        intervaltreetablenode_changes.nodes = /*trees*/
        ctx3[0];
      if (dirty & /*budgets*/
      2)
        intervaltreetablenode_changes.budgets = /*budgets*/
        ctx3[1];
      intervaltreetablenode.$set(intervaltreetablenode_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(accountcellheader.$$.fragment, local);
      transition_in(intervaltreetablenode.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(accountcellheader.$$.fragment, local);
      transition_out(intervaltreetablenode.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(ol);
      }
      destroy_component(accountcellheader);
      destroy_each(each_blocks, detaching);
      destroy_component(intervaltreetablenode);
    }
  };
}
function instance22($$self, $$props, $$invalidate) {
  let account2;
  let start_date;
  let start_date_filter;
  let time_filters;
  let $currentTimeFilterDateFormat;
  let $get_not_shown;
  let $not_shown;
  let $collapse_account;
  let $urlForAccount;
  component_subscribe($$self, currentTimeFilterDateFormat, ($$value) => $$invalidate(10, $currentTimeFilterDateFormat = $$value));
  component_subscribe($$self, get_not_shown, ($$value) => $$invalidate(11, $get_not_shown = $$value));
  component_subscribe($$self, collapse_account, ($$value) => $$invalidate(13, $collapse_account = $$value));
  component_subscribe($$self, urlForAccount, ($$value) => $$invalidate(4, $urlForAccount = $$value));
  let { trees } = $$props;
  let { dates } = $$props;
  let { budgets } = $$props;
  let { accumulate } = $$props;
  const toggled = writable(get_collapsed(trees[0], $collapse_account));
  const not_shown = writable(/* @__PURE__ */ new Set());
  component_subscribe($$self, not_shown, (value) => $$invalidate(12, $not_shown = value));
  setTreeTableContext({ toggled, not_shown });
  $$self.$$set = ($$props2) => {
    if ("trees" in $$props2)
      $$invalidate(0, trees = $$props2.trees);
    if ("dates" in $$props2)
      $$invalidate(6, dates = $$props2.dates);
    if ("budgets" in $$props2)
      $$invalidate(1, budgets = $$props2.budgets);
    if ("accumulate" in $$props2)
      $$invalidate(7, accumulate = $$props2.accumulate);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*trees, $get_not_shown, dates*/
    2113) {
      $:
        set_store_value(not_shown, $not_shown = intersection(...trees.map((n, index2) => $get_not_shown(n, dates[index2]?.end ?? null))), $not_shown);
    }
    if ($$self.$$.dirty & /*trees*/
    1) {
      $:
        $$invalidate(3, account2 = trees[0].account);
    }
    if ($$self.$$.dirty & /*accumulate, dates*/
    192) {
      $:
        $$invalidate(9, start_date = accumulate ? min(dates, (d) => d.begin) : void 0);
    }
    if ($$self.$$.dirty & /*start_date, $currentTimeFilterDateFormat*/
    1536) {
      $:
        $$invalidate(8, start_date_filter = start_date ? $currentTimeFilterDateFormat(start_date) : void 0);
    }
    if ($$self.$$.dirty & /*dates, $currentTimeFilterDateFormat, start_date_filter*/
    1344) {
      $:
        $$invalidate(2, time_filters = dates.map((date_range2) => {
          const title = $currentTimeFilterDateFormat(date_range2.begin);
          return start_date_filter ? [title, `${start_date_filter}-${title}`] : [title, title];
        }));
    }
  };
  return [
    trees,
    budgets,
    time_filters,
    account2,
    $urlForAccount,
    not_shown,
    dates,
    accumulate,
    start_date_filter,
    start_date,
    $currentTimeFilterDateFormat,
    $get_not_shown
  ];
}
var IntervalTreeTable = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance22, create_fragment21, safe_not_equal, {
      trees: 0,
      dates: 6,
      budgets: 1,
      accumulate: 7
    });
  }
};
var IntervalTreeTable_default = IntervalTreeTable;

// src/reports/accounts/AccountReport.svelte
function create_if_block_52(ctx2) {
  let chartswitcher;
  let current;
  chartswitcher = new ChartSwitcher_default({ props: { charts: (
    /*chartData*/
    ctx2[7]
  ) } });
  return {
    c() {
      create_component(chartswitcher.$$.fragment);
    },
    m(target, anchor) {
      mount_component(chartswitcher, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const chartswitcher_changes = {};
      if (dirty & /*chartData*/
      128)
        chartswitcher_changes.charts = /*chartData*/
        ctx3[7];
      chartswitcher.$set(chartswitcher_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(chartswitcher.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(chartswitcher.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(chartswitcher, detaching);
    }
  };
}
function create_else_block_2(ctx2) {
  let t_value = _("Account Journal") + "";
  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_if_block_42(ctx2) {
  let a;
  let t_value = _("Account Journal") + "";
  let t4;
  let a_href_value;
  let a_title_value;
  return {
    c() {
      a = element("a");
      t4 = text(t_value);
      attr(a, "href", a_href_value = /*$urlForAccount*/
      ctx2[9](
        /*account*/
        ctx2[0]
      ));
      attr(a, "title", a_title_value = _("Journal of all entries for this Account and Sub-Accounts"));
    },
    m(target, anchor) {
      insert(target, a, anchor);
      append(a, t4);
    },
    p(ctx3, dirty) {
      if (dirty & /*$urlForAccount, account*/
      513 && a_href_value !== (a_href_value = /*$urlForAccount*/
      ctx3[9](
        /*account*/
        ctx3[0]
      ))) {
        attr(a, "href", a_href_value);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(a);
      }
    }
  };
}
function create_else_block_1(ctx2) {
  let t0_value = _("Changes") + "";
  let t03;
  let t13;
  let t22;
  let t32;
  return {
    c() {
      t03 = text(t0_value);
      t13 = text(" (");
      t22 = text(
        /*interval_label*/
        ctx2[6]
      );
      t32 = text(")");
    },
    m(target, anchor) {
      insert(target, t03, anchor);
      insert(target, t13, anchor);
      insert(target, t22, anchor);
      insert(target, t32, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & /*interval_label*/
      64)
        set_data(
          t22,
          /*interval_label*/
          ctx3[6]
        );
    },
    d(detaching) {
      if (detaching) {
        detach(t03);
        detach(t13);
        detach(t22);
        detach(t32);
      }
    }
  };
}
function create_if_block_33(ctx2) {
  let a;
  let t0_value = _("Changes") + "";
  let t03;
  let t13;
  let t22;
  let t32;
  let a_href_value;
  return {
    c() {
      a = element("a");
      t03 = text(t0_value);
      t13 = text(" (");
      t22 = text(
        /*interval_label*/
        ctx2[6]
      );
      t32 = text(")");
      attr(a, "href", a_href_value = /*$urlForAccount*/
      ctx2[9](
        /*account*/
        ctx2[0],
        { r: "changes" }
      ));
    },
    m(target, anchor) {
      insert(target, a, anchor);
      append(a, t03);
      append(a, t13);
      append(a, t22);
      append(a, t32);
    },
    p(ctx3, dirty) {
      if (dirty & /*interval_label*/
      64)
        set_data(
          t22,
          /*interval_label*/
          ctx3[6]
        );
      if (dirty & /*$urlForAccount, account*/
      513 && a_href_value !== (a_href_value = /*$urlForAccount*/
      ctx3[9](
        /*account*/
        ctx3[0],
        { r: "changes" }
      ))) {
        attr(a, "href", a_href_value);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(a);
      }
    }
  };
}
function create_else_block3(ctx2) {
  let t0_value = _("Balances") + "";
  let t03;
  let t13;
  let t22;
  let t32;
  return {
    c() {
      t03 = text(t0_value);
      t13 = text(" (");
      t22 = text(
        /*interval_label*/
        ctx2[6]
      );
      t32 = text(")");
    },
    m(target, anchor) {
      insert(target, t03, anchor);
      insert(target, t13, anchor);
      insert(target, t22, anchor);
      insert(target, t32, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & /*interval_label*/
      64)
        set_data(
          t22,
          /*interval_label*/
          ctx3[6]
        );
    },
    d(detaching) {
      if (detaching) {
        detach(t03);
        detach(t13);
        detach(t22);
        detach(t32);
      }
    }
  };
}
function create_if_block_25(ctx2) {
  let a;
  let t0_value = _("Balances") + "";
  let t03;
  let t13;
  let t22;
  let t32;
  let a_href_value;
  return {
    c() {
      a = element("a");
      t03 = text(t0_value);
      t13 = text(" (");
      t22 = text(
        /*interval_label*/
        ctx2[6]
      );
      t32 = text(")");
      attr(a, "href", a_href_value = /*$urlForAccount*/
      ctx2[9](
        /*account*/
        ctx2[0],
        { r: "balances" }
      ));
    },
    m(target, anchor) {
      insert(target, a, anchor);
      append(a, t03);
      append(a, t13);
      append(a, t22);
      append(a, t32);
    },
    p(ctx3, dirty) {
      if (dirty & /*interval_label*/
      64)
        set_data(
          t22,
          /*interval_label*/
          ctx3[6]
        );
      if (dirty & /*$urlForAccount, account*/
      513 && a_href_value !== (a_href_value = /*$urlForAccount*/
      ctx3[9](
        /*account*/
        ctx3[0],
        { r: "balances" }
      ))) {
        attr(a, "href", a_href_value);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(a);
      }
    }
  };
}
function create_if_block_17(ctx2) {
  let intervaltreetable;
  let current;
  intervaltreetable = new IntervalTreeTable_default({
    props: {
      trees: (
        /*interval_balances*/
        ctx2[3]
      ),
      dates: (
        /*dates*/
        ctx2[4]
      ),
      budgets: (
        /*budgets*/
        ctx2[5]
      ),
      accumulate: (
        /*accumulate*/
        ctx2[8]
      )
    }
  });
  return {
    c() {
      create_component(intervaltreetable.$$.fragment);
    },
    m(target, anchor) {
      mount_component(intervaltreetable, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const intervaltreetable_changes = {};
      if (dirty & /*interval_balances*/
      8)
        intervaltreetable_changes.trees = /*interval_balances*/
        ctx3[3];
      if (dirty & /*dates*/
      16)
        intervaltreetable_changes.dates = /*dates*/
        ctx3[4];
      if (dirty & /*budgets*/
      32)
        intervaltreetable_changes.budgets = /*budgets*/
        ctx3[5];
      if (dirty & /*accumulate*/
      256)
        intervaltreetable_changes.accumulate = /*accumulate*/
        ctx3[8];
      intervaltreetable.$set(intervaltreetable_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(intervaltreetable.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(intervaltreetable.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(intervaltreetable, detaching);
    }
  };
}
function create_if_block11(ctx2) {
  let html_tag;
  let html_anchor;
  return {
    c() {
      html_tag = new HtmlTag(false);
      html_anchor = empty();
      html_tag.a = html_anchor;
    },
    m(target, anchor) {
      html_tag.m(
        /*journal*/
        ctx2[2],
        target,
        anchor
      );
      insert(target, html_anchor, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & /*journal*/
      4)
        html_tag.p(
          /*journal*/
          ctx3[2]
        );
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(html_anchor);
        html_tag.d();
      }
    }
  };
}
function create_fragment22(ctx2) {
  let t03;
  let div1;
  let div0;
  let h30;
  let t13;
  let h31;
  let t22;
  let h32;
  let t32;
  let show_if;
  let current_block_type_index;
  let if_block4;
  let current;
  let if_block0 = (
    /*chartData*/
    ctx2[7] && create_if_block_52(ctx2)
  );
  function select_block_type(ctx3, dirty) {
    if (
      /*report_type*/
      ctx3[1] !== "journal"
    )
      return create_if_block_42;
    return create_else_block_2;
  }
  let current_block_type = select_block_type(ctx2, -1);
  let if_block1 = current_block_type(ctx2);
  function select_block_type_1(ctx3, dirty) {
    if (
      /*report_type*/
      ctx3[1] !== "changes"
    )
      return create_if_block_33;
    return create_else_block_1;
  }
  let current_block_type_1 = select_block_type_1(ctx2, -1);
  let if_block2 = current_block_type_1(ctx2);
  function select_block_type_2(ctx3, dirty) {
    if (
      /*report_type*/
      ctx3[1] !== "balances"
    )
      return create_if_block_25;
    return create_else_block3;
  }
  let current_block_type_2 = select_block_type_2(ctx2, -1);
  let if_block3 = current_block_type_2(ctx2);
  const if_block_creators = [create_if_block11, create_if_block_17];
  const if_blocks = [];
  function select_block_type_3(ctx3, dirty) {
    if (dirty & /*interval_balances, budgets, dates*/
    56)
      show_if = null;
    if (
      /*report_type*/
      ctx3[1] === "journal"
    )
      return 0;
    if (show_if == null)
      show_if = !!/*interval_balances*/
      (ctx3[3] && is_non_empty(
        /*interval_balances*/
        ctx3[3]
      ) && /*budgets*/
      ctx3[5] && /*dates*/
      ctx3[4]);
    if (show_if)
      return 1;
    return -1;
  }
  if (~(current_block_type_index = select_block_type_3(ctx2, -1))) {
    if_block4 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
  }
  return {
    c() {
      if (if_block0)
        if_block0.c();
      t03 = space();
      div1 = element("div");
      div0 = element("div");
      h30 = element("h3");
      if_block1.c();
      t13 = space();
      h31 = element("h3");
      if_block2.c();
      t22 = space();
      h32 = element("h3");
      if_block3.c();
      t32 = space();
      if (if_block4)
        if_block4.c();
      attr(div0, "class", "headerline");
      attr(div1, "class", "droptarget");
      attr(
        div1,
        "data-account-name",
        /*account*/
        ctx2[0]
      );
    },
    m(target, anchor) {
      if (if_block0)
        if_block0.m(target, anchor);
      insert(target, t03, anchor);
      insert(target, div1, anchor);
      append(div1, div0);
      append(div0, h30);
      if_block1.m(h30, null);
      append(div0, t13);
      append(div0, h31);
      if_block2.m(h31, null);
      append(div0, t22);
      append(div0, h32);
      if_block3.m(h32, null);
      append(div1, t32);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(div1, null);
      }
      current = true;
    },
    p(ctx3, [dirty]) {
      if (
        /*chartData*/
        ctx3[7]
      ) {
        if (if_block0) {
          if_block0.p(ctx3, dirty);
          if (dirty & /*chartData*/
          128) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_52(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();
      }
      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(h30, null);
        }
      }
      if (current_block_type_1 === (current_block_type_1 = select_block_type_1(ctx3, dirty)) && if_block2) {
        if_block2.p(ctx3, dirty);
      } else {
        if_block2.d(1);
        if_block2 = current_block_type_1(ctx3);
        if (if_block2) {
          if_block2.c();
          if_block2.m(h31, null);
        }
      }
      if (current_block_type_2 === (current_block_type_2 = select_block_type_2(ctx3, dirty)) && if_block3) {
        if_block3.p(ctx3, dirty);
      } else {
        if_block3.d(1);
        if_block3 = current_block_type_2(ctx3);
        if (if_block3) {
          if_block3.c();
          if_block3.m(h32, null);
        }
      }
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type_3(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_block4) {
          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_block4 = if_blocks[current_block_type_index];
          if (!if_block4) {
            if_block4 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx3);
            if_block4.c();
          } else {
            if_block4.p(ctx3, dirty);
          }
          transition_in(if_block4, 1);
          if_block4.m(div1, null);
        } else {
          if_block4 = null;
        }
      }
      if (!current || dirty & /*account*/
      1) {
        attr(
          div1,
          "data-account-name",
          /*account*/
          ctx3[0]
        );
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block0);
      transition_in(if_block4);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(if_block4);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t03);
        detach(div1);
      }
      if (if_block0)
        if_block0.d(detaching);
      if_block1.d();
      if_block2.d();
      if_block3.d();
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d();
      }
    }
  };
}
function instance23($$self, $$props, $$invalidate) {
  let accumulate;
  let chartData;
  let interval_label;
  let $interval;
  let $chartContext;
  let $urlForAccount;
  component_subscribe($$self, interval, ($$value) => $$invalidate(11, $interval = $$value));
  component_subscribe($$self, chartContext, ($$value) => $$invalidate(12, $chartContext = $$value));
  component_subscribe($$self, urlForAccount, ($$value) => $$invalidate(9, $urlForAccount = $$value));
  let { account: account2 } = $$props;
  let { report_type } = $$props;
  let { charts } = $$props;
  let { journal } = $$props;
  let { interval_balances } = $$props;
  let { dates } = $$props;
  let { budgets } = $$props;
  $$self.$$set = ($$props2) => {
    if ("account" in $$props2)
      $$invalidate(0, account2 = $$props2.account);
    if ("report_type" in $$props2)
      $$invalidate(1, report_type = $$props2.report_type);
    if ("charts" in $$props2)
      $$invalidate(10, charts = $$props2.charts);
    if ("journal" in $$props2)
      $$invalidate(2, journal = $$props2.journal);
    if ("interval_balances" in $$props2)
      $$invalidate(3, interval_balances = $$props2.interval_balances);
    if ("dates" in $$props2)
      $$invalidate(4, dates = $$props2.dates);
    if ("budgets" in $$props2)
      $$invalidate(5, budgets = $$props2.budgets);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*report_type*/
    2) {
      $:
        $$invalidate(8, accumulate = report_type === "balances");
    }
    if ($$self.$$.dirty & /*charts, $chartContext*/
    5120) {
      $:
        $$invalidate(7, chartData = parseChartData(charts, $chartContext).unwrap_or(null));
    }
    if ($$self.$$.dirty & /*$interval*/
    2048) {
      $:
        $$invalidate(6, interval_label = intervalLabel($interval).toLowerCase());
    }
  };
  return [
    account2,
    report_type,
    journal,
    interval_balances,
    dates,
    budgets,
    interval_label,
    chartData,
    accumulate,
    $urlForAccount,
    charts,
    $interval,
    $chartContext
  ];
}
var AccountReport = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance23, create_fragment22, safe_not_equal, {
      account: 0,
      report_type: 1,
      charts: 10,
      journal: 2,
      interval_balances: 3,
      dates: 4,
      budgets: 5
    });
  }
};
var AccountReport_default = AccountReport;

// src/reports/accounts/index.ts
var to_report_type = (s) => s === "balances" || s === "changes" ? s : "journal";
var account_report = new Route(
  "account",
  AccountReport_default,
  async (url) => {
    const [, account2 = ""] = getUrlPath(url)?.split("/") ?? [];
    const report_type = to_report_type(url.searchParams.get("r"));
    const res2 = await get("account_report", {
      ...getURLFilters(url),
      a: account2,
      r: report_type
    });
    return {
      ...res2,
      account: account2,
      report_type: to_report_type(report_type)
    };
  },
  (route) => {
    if (route.url) {
      const [, account2] = getUrlPath(route.url)?.split("/") ?? [];
      return `account:${account2}`;
    }
    throw new Error("Internal error: Expected route to have URL.");
  }
);

// src/sort/SortHeader.svelte
function create_fragment23(ctx2) {
  let th;
  let t_value = (
    /*column*/
    ctx2[1].name + ""
  );
  let t4;
  let th_data_order_value;
  let mounted;
  let dispose;
  return {
    c() {
      th = element("th");
      t4 = text(t_value);
      attr(th, "data-order", th_data_order_value = /*column*/
      ctx2[1] === /*sorter*/
      ctx2[0].column ? (
        /*sorter*/
        ctx2[0].order
      ) : void 0);
      attr(th, "data-sort", "");
    },
    m(target, anchor) {
      insert(target, th, anchor);
      append(th, t4);
      if (!mounted) {
        dispose = listen(
          th,
          "click",
          /*click_handler*/
          ctx2[2]
        );
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & /*column*/
      2 && t_value !== (t_value = /*column*/
      ctx3[1].name + ""))
        set_data(t4, t_value);
      if (dirty & /*column, sorter*/
      3 && th_data_order_value !== (th_data_order_value = /*column*/
      ctx3[1] === /*sorter*/
      ctx3[0].column ? (
        /*sorter*/
        ctx3[0].order
      ) : void 0)) {
        attr(th, "data-order", th_data_order_value);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(th);
      }
      mounted = false;
      dispose();
    }
  };
}
function instance24($$self, $$props, $$invalidate) {
  let { sorter } = $$props;
  let { column } = $$props;
  const click_handler = () => {
    $$invalidate(0, sorter = sorter.switchColumn(column));
  };
  $$self.$$set = ($$props2) => {
    if ("sorter" in $$props2)
      $$invalidate(0, sorter = $$props2.sorter);
    if ("column" in $$props2)
      $$invalidate(1, column = $$props2.column);
  };
  return [sorter, column, click_handler];
}
var SortHeader = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance24, create_fragment23, safe_not_equal, { sorter: 0, column: 1 });
  }
};
var SortHeader_default = SortHeader;

// src/reports/commodities/CommodityTable.svelte
function get_each_context14(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[7] = list[i][0];
  child_ctx[8] = list[i][1];
  return child_ctx;
}
function get_each_context_14(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[11] = list[i];
  return child_ctx;
}
function create_each_block_14(ctx2) {
  let sortheader;
  let updating_sorter;
  let current;
  function sortheader_sorter_binding(value) {
    ctx2[6](value);
  }
  let sortheader_props = { column: (
    /*column*/
    ctx2[11]
  ) };
  if (
    /*sorter*/
    ctx2[1] !== void 0
  ) {
    sortheader_props.sorter = /*sorter*/
    ctx2[1];
  }
  sortheader = new SortHeader_default({ props: sortheader_props });
  binding_callbacks.push(() => bind(sortheader, "sorter", sortheader_sorter_binding));
  return {
    c() {
      create_component(sortheader.$$.fragment);
    },
    m(target, anchor) {
      mount_component(sortheader, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const sortheader_changes = {};
      if (!updating_sorter && dirty & /*sorter*/
      2) {
        updating_sorter = true;
        sortheader_changes.sorter = /*sorter*/
        ctx3[1];
        add_flush_callback(() => updating_sorter = false);
      }
      sortheader.$set(sortheader_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(sortheader.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(sortheader.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(sortheader, detaching);
    }
  };
}
function create_each_block14(key_1, ctx2) {
  let tr;
  let td0;
  let t0_value = day(
    /*date*/
    ctx2[7]
  ) + "";
  let t03;
  let t13;
  let td1;
  let t2_value = (
    /*$ctx*/
    ctx2[3].amount(
      /*value*/
      ctx2[8],
      /*quote*/
      ctx2[0]
    ) + ""
  );
  let t22;
  let t32;
  return {
    key: key_1,
    first: null,
    c() {
      tr = element("tr");
      td0 = element("td");
      t03 = text(t0_value);
      t13 = space();
      td1 = element("td");
      t22 = text(t2_value);
      t32 = space();
      attr(td1, "class", "num");
      this.first = tr;
    },
    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);
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & /*sorted_prices*/
      4 && t0_value !== (t0_value = day(
        /*date*/
        ctx2[7]
      ) + ""))
        set_data(t03, t0_value);
      if (dirty & /*$ctx, sorted_prices, quote*/
      13 && t2_value !== (t2_value = /*$ctx*/
      ctx2[3].amount(
        /*value*/
        ctx2[8],
        /*quote*/
        ctx2[0]
      ) + ""))
        set_data(t22, t2_value);
    },
    d(detaching) {
      if (detaching) {
        detach(tr);
      }
    }
  };
}
function create_fragment24(ctx2) {
  let table;
  let thead;
  let tr;
  let t4;
  let tbody;
  let each_blocks = [];
  let each1_lookup = /* @__PURE__ */ new Map();
  let current;
  let each_value_1 = ensure_array_like(
    /*columns*/
    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));
  }
  const out2 = (i) => transition_out(each_blocks_1[i], 1, 1, () => {
    each_blocks_1[i] = null;
  });
  let each_value = ensure_array_like(
    /*sorted_prices*/
    ctx2[2]
  );
  const get_key = (ctx3) => (
    /*date*/
    ctx3[7]
  );
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context14(ctx2, each_value, i);
    let key2 = get_key(child_ctx);
    each1_lookup.set(key2, each_blocks[i] = create_each_block14(key2, child_ctx));
  }
  return {
    c() {
      table = 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();
      }
    },
    m(target, anchor) {
      insert(target, table, anchor);
      append(table, thead);
      append(thead, tr);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(tr, null);
        }
      }
      append(table, t4);
      append(table, tbody);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(tbody, null);
        }
      }
      current = true;
    },
    p(ctx3, [dirty]) {
      if (dirty & /*columns, sorter*/
      18) {
        each_value_1 = ensure_array_like(
          /*columns*/
          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);
            transition_in(each_blocks_1[i], 1);
          } else {
            each_blocks_1[i] = create_each_block_14(child_ctx);
            each_blocks_1[i].c();
            transition_in(each_blocks_1[i], 1);
            each_blocks_1[i].m(tr, null);
          }
        }
        group_outros();
        for (i = each_value_1.length; i < each_blocks_1.length; i += 1) {
          out2(i);
        }
        check_outros();
      }
      if (dirty & /*$ctx, sorted_prices, quote*/
      13) {
        each_value = ensure_array_like(
          /*sorted_prices*/
          ctx3[2]
        );
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx3, each_value, each1_lookup, tbody, destroy_block, create_each_block14, null, get_each_context14);
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks_1[i]);
      }
      current = true;
    },
    o(local) {
      each_blocks_1 = each_blocks_1.filter(Boolean);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        transition_out(each_blocks_1[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(table);
      }
      destroy_each(each_blocks_1, detaching);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
function instance25($$self, $$props, $$invalidate) {
  let sorted_prices;
  let $ctx;
  component_subscribe($$self, ctx, ($$value) => $$invalidate(3, $ctx = $$value));
  let { prices } = $$props;
  let { quote } = $$props;
  const columns3 = [
    new NumberColumn(_("Date"), (d) => d[0].valueOf()),
    new NumberColumn(_("Price"), (d) => d[1])
  ];
  let sorter = new Sorter(columns3[0], "desc");
  function sortheader_sorter_binding(value) {
    sorter = value;
    $$invalidate(1, sorter);
  }
  $$self.$$set = ($$props2) => {
    if ("prices" in $$props2)
      $$invalidate(5, prices = $$props2.prices);
    if ("quote" in $$props2)
      $$invalidate(0, quote = $$props2.quote);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*sorter, prices*/
    34) {
      $:
        $$invalidate(2, sorted_prices = sorter.sort(prices));
    }
  };
  return [quote, sorter, sorted_prices, $ctx, columns3, prices, sortheader_sorter_binding];
}
var CommodityTable = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance25, create_fragment24, safe_not_equal, { prices: 5, quote: 0 });
  }
};
var CommodityTable_default = CommodityTable;

// src/reports/commodities/Commodities.svelte
function get_each_context15(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[2] = list[i].base;
  child_ctx[3] = list[i].quote;
  child_ctx[4] = list[i].prices;
  return child_ctx;
}
function create_each_block15(ctx2) {
  let div;
  let h3;
  let t0_value = (
    /*base*/
    ctx2[2] + ""
  );
  let t03;
  let t13;
  let t2_value = (
    /*quote*/
    ctx2[3] + ""
  );
  let t22;
  let t32;
  let commoditytable;
  let t4;
  let current;
  commoditytable = new CommodityTable_default({
    props: {
      prices: (
        /*prices*/
        ctx2[4]
      ),
      quote: (
        /*quote*/
        ctx2[3]
      )
    }
  });
  return {
    c() {
      div = element("div");
      h3 = element("h3");
      t03 = text(t0_value);
      t13 = text(" / ");
      t22 = text(t2_value);
      t32 = space();
      create_component(commoditytable.$$.fragment);
      t4 = space();
      attr(div, "class", "left");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, h3);
      append(h3, t03);
      append(h3, t13);
      append(h3, t22);
      append(div, t32);
      mount_component(commoditytable, div, null);
      append(div, t4);
      current = true;
    },
    p(ctx3, dirty) {
      if ((!current || dirty & /*commodities*/
      2) && t0_value !== (t0_value = /*base*/
      ctx3[2] + ""))
        set_data(t03, t0_value);
      if ((!current || dirty & /*commodities*/
      2) && t2_value !== (t2_value = /*quote*/
      ctx3[3] + ""))
        set_data(t22, t2_value);
      const commoditytable_changes = {};
      if (dirty & /*commodities*/
      2)
        commoditytable_changes.prices = /*prices*/
        ctx3[4];
      if (dirty & /*commodities*/
      2)
        commoditytable_changes.quote = /*quote*/
        ctx3[3];
      commoditytable.$set(commoditytable_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(commoditytable.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(commoditytable.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      destroy_component(commoditytable);
    }
  };
}
function create_fragment25(ctx2) {
  let chartswitcher;
  let t4;
  let each_1_anchor;
  let current;
  chartswitcher = new ChartSwitcher_default({ props: { charts: (
    /*charts*/
    ctx2[0]
  ) } });
  let each_value = ensure_array_like(
    /*commodities*/
    ctx2[1]
  );
  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));
  }
  const out2 = (i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  });
  return {
    c() {
      create_component(chartswitcher.$$.fragment);
      t4 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      mount_component(chartswitcher, target, anchor);
      insert(target, t4, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      const chartswitcher_changes = {};
      if (dirty & /*charts*/
      1)
        chartswitcher_changes.charts = /*charts*/
        ctx3[0];
      chartswitcher.$set(chartswitcher_changes);
      if (dirty & /*commodities*/
      2) {
        each_value = ensure_array_like(
          /*commodities*/
          ctx3[1]
        );
        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);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block15(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) {
          out2(i);
        }
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(chartswitcher.$$.fragment, local);
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      transition_out(chartswitcher.$$.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(t4);
        detach(each_1_anchor);
      }
      destroy_component(chartswitcher, detaching);
      destroy_each(each_blocks, detaching);
    }
  };
}
function instance26($$self, $$props, $$invalidate) {
  let { charts } = $$props;
  let { commodities: commodities3 } = $$props;
  $$self.$$set = ($$props2) => {
    if ("charts" in $$props2)
      $$invalidate(0, charts = $$props2.charts);
    if ("commodities" in $$props2)
      $$invalidate(1, commodities3 = $$props2.commodities);
  };
  return [charts, commodities3];
}
var Commodities = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance26, create_fragment25, safe_not_equal, { charts: 0, commodities: 1 });
  }
};
var Commodities_default = Commodities;

// src/reports/commodities/index.ts
var commodities2 = new Route(
  "commodities",
  Commodities_default,
  (url) => get("commodities", getURLFilters(url)).then((cs) => {
    const charts = cs.map(({ base: base2, quote, prices }) => {
      const name2 = `${base2} / ${quote}`;
      const values = prices.map((d) => ({ name: name2, date: d[0], value: d[1] }));
      return new LineChart(name2, [{ name: name2, values }], (c, d) => [
        domHelpers.t(`1 ${base2} = ${c.amount(d.value, quote)}`),
        domHelpers.em(day(d.date))
      ]);
    });
    return { commodities: cs, charts };
  }),
  () => _("Commodities")
);

// 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 (const char of text2) {
    const search2 = pattern[pindex];
    if (char === search2 || char.toLowerCase() === search2) {
      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] ?? 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 (const char of text2) {
    const search2 = pattern[pindex];
    if (char === search2 || char.toLowerCase() === search2) {
      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_context16(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_18(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-u6g7t7");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler*/
          ctx2[23]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_if_block12(ctx2) {
  let ul;
  let each_value = ensure_array_like(
    /*filteredSuggestions*/
    ctx2[5]
  );
  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() {
      ul = element("ul");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      ul.hidden = /*hidden*/
      ctx2[8];
      attr(ul, "class", "svelte-u6g7t7");
    },
    m(target, anchor) {
      insert(target, ul, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(ul, null);
        }
      }
    },
    p(ctx3, dirty) {
      if (dirty & /*index, mousedown, filteredSuggestions*/
      2144) {
        each_value = ensure_array_like(
          /*filteredSuggestions*/
          ctx3[5]
        );
        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(ul, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
      if (dirty & /*hidden*/
      256) {
        ul.hidden = /*hidden*/
        ctx3[8];
      }
    },
    d(detaching) {
      if (detaching) {
        detach(ul);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_each_block16(ctx2) {
  let li;
  let html_tag;
  let raw_value = (
    /*innerHTML*/
    ctx2[26] + ""
  );
  let t4;
  let mounted;
  let dispose;
  function mousedown_handler(...args2) {
    return (
      /*mousedown_handler*/
      ctx2[24](
        /*suggestion*/
        ctx2[27],
        ...args2
      )
    );
  }
  return {
    c() {
      li = element("li");
      html_tag = new HtmlTag(false);
      t4 = space();
      html_tag.a = t4;
      attr(li, "class", "svelte-u6g7t7");
      toggle_class(
        li,
        "selected",
        /*i*/
        ctx2[29] === /*index*/
        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 & /*filteredSuggestions*/
      32 && raw_value !== (raw_value = /*innerHTML*/
      ctx2[26] + ""))
        html_tag.p(raw_value);
      if (dirty & /*index*/
      64) {
        toggle_class(
          li,
          "selected",
          /*i*/
          ctx2[29] === /*index*/
          ctx2[6]
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(li);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_fragment26(ctx2) {
  let span;
  let input_1;
  let keyboardShortcut_action;
  let t03;
  let t13;
  let span_class_value;
  let mounted;
  let dispose;
  let if_block0 = (
    /*clearButton*/
    ctx2[4] && /*value*/
    ctx2[0] && create_if_block_18(ctx2)
  );
  let if_block1 = (
    /*filteredSuggestions*/
    ctx2[5].length && create_if_block12(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",
        /*placeholder*/
        ctx2[1]
      );
      attr(
        input_1,
        "size",
        /*size*/
        ctx2[9]
      );
      attr(input_1, "class", "svelte-u6g7t7");
      attr(span, "class", span_class_value = null_to_empty(
        /*className*/
        ctx2[2]
      ) + " svelte-u6g7t7");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, input_1);
      set_input_value(
        input_1,
        /*value*/
        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",
            /*input_1_input_handler*/
            ctx2[18]
          ),
          action_destroyer(keyboardShortcut_action = keyboardShortcut.call(
            null,
            input_1,
            /*key*/
            ctx2[3]
          )),
          listen(
            input_1,
            "blur",
            /*blur_handler*/
            ctx2[20]
          ),
          listen(
            input_1,
            "focus",
            /*focus_handler*/
            ctx2[21]
          ),
          listen(
            input_1,
            "input",
            /*input_handler*/
            ctx2[22]
          ),
          listen(
            input_1,
            "keydown",
            /*keydown*/
            ctx2[12]
          )
        ];
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & /*placeholder*/
      2) {
        attr(
          input_1,
          "placeholder",
          /*placeholder*/
          ctx3[1]
        );
      }
      if (dirty & /*size*/
      512) {
        attr(
          input_1,
          "size",
          /*size*/
          ctx3[9]
        );
      }
      if (dirty & /*value*/
      1 && input_1.value !== /*value*/
      ctx3[0]) {
        set_input_value(
          input_1,
          /*value*/
          ctx3[0]
        );
      }
      if (keyboardShortcut_action && is_function(keyboardShortcut_action.update) && dirty & /*key*/
      8)
        keyboardShortcut_action.update.call(
          null,
          /*key*/
          ctx3[3]
        );
      if (
        /*clearButton*/
        ctx3[4] && /*value*/
        ctx3[0]
      ) {
        if (if_block0) {
          if_block0.p(ctx3, dirty);
        } else {
          if_block0 = create_if_block_18(ctx3);
          if_block0.c();
          if_block0.m(span, t13);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*filteredSuggestions*/
        ctx3[5].length
      ) {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
        } else {
          if_block1 = create_if_block12(ctx3);
          if_block1.c();
          if_block1.m(span, null);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (dirty & /*className*/
      4 && span_class_value !== (span_class_value = null_to_empty(
        /*className*/
        ctx3[2]
      ) + " svelte-u6g7t7")) {
        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 instance27($$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: key2 = 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") {
      const suggestion = filteredSuggestions[index2]?.suggestion;
      if (index2 > -1 && !hidden && suggestion) {
        event.preventDefault();
        select(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", input);
  };
  const focus_handler = () => {
    $$invalidate(8, hidden = false);
  };
  const input_handler = () => {
    $$invalidate(8, hidden = false);
  };
  const click_handler = () => {
    $$invalidate(0, value = "");
    dispatch("select", input);
  };
  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, key2 = $$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 & /*setSize, value, placeholder*/
    65539) {
      $:
        $$invalidate(9, size = setSize ? Math.max(value.length, placeholder2.length) + 1 : void 0);
    }
    if ($$self.$$.dirty & /*input, checkValidity, value*/
    131201) {
      $:
        if (input && checkValidity) {
          input.setCustomValidity(checkValidity(value));
        }
    }
    if ($$self.$$.dirty & /*input, valueExtractor, value, suggestions, index, filteredSuggestions*/
    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,
    key2,
    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(options3) {
    super();
    init2(this, options3, instance27, create_fragment26, 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_fragment27(ctx2) {
  let autocompleteinput;
  let updating_value;
  let current;
  function autocompleteinput_value_binding(value) {
    ctx2[10](value);
  }
  let autocompleteinput_props = {
    placeholder: _("Account"),
    className: (
      /*className*/
      ctx2[1]
    ),
    checkValidity: (
      /*checkValidity*/
      ctx2[3]
    ),
    suggestions: (
      /*filtered_suggestions*/
      ctx2[2]
    )
  };
  if (
    /*value*/
    ctx2[0] !== void 0
  ) {
    autocompleteinput_props.value = /*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 & /*className*/
      2)
        autocompleteinput_changes.className = /*className*/
        ctx3[1];
      if (dirty & /*checkValidity*/
      8)
        autocompleteinput_changes.checkValidity = /*checkValidity*/
        ctx3[3];
      if (dirty & /*filtered_suggestions*/
      4)
        autocompleteinput_changes.suggestions = /*filtered_suggestions*/
        ctx3[2];
      if (!updating_value && dirty & /*value*/
      1) {
        updating_value = true;
        autocompleteinput_changes.value = /*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 instance28($$self, $$props, $$invalidate) {
  let checkValidity;
  let parsed_date;
  let account_suggestions;
  let filtered_suggestions;
  let $is_closed_account;
  let $accounts;
  component_subscribe($$self, is_closed_account, ($$value) => $$invalidate(8, $is_closed_account = $$value));
  component_subscribe($$self, accounts, ($$value) => $$invalidate(9, $accounts = $$value));
  let { value } = $$props;
  let { suggestions = void 0 } = $$props;
  let { date: date4 = void 0 } = $$props;
  let { className = void 0 } = $$props;
  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, date4 = $$props2.date);
    if ("className" in $$props2)
      $$invalidate(1, className = $$props2.className);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$accounts*/
    512) {
      $:
        $$invalidate(3, checkValidity = (val) => !$accounts.length || $accounts.includes(val) || !val ? "" : _("Should be one of the declared accounts"));
    }
    if ($$self.$$.dirty & /*date*/
    32) {
      $:
        $$invalidate(7, parsed_date = date(date4).unwrap_or(null));
    }
    if ($$self.$$.dirty & /*suggestions, $accounts*/
    528) {
      $:
        $$invalidate(6, account_suggestions = suggestions ?? $accounts);
    }
    if ($$self.$$.dirty & /*parsed_date, account_suggestions, $is_closed_account*/
    448) {
      $:
        $$invalidate(2, filtered_suggestions = parsed_date ? account_suggestions.filter((account2) => !$is_closed_account(account2, parsed_date)) : account_suggestions);
    }
  };
  return [
    value,
    className,
    filtered_suggestions,
    checkValidity,
    suggestions,
    date4,
    account_suggestions,
    parsed_date,
    $is_closed_account,
    $accounts,
    autocompleteinput_value_binding
  ];
}
var AccountInput = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance28, create_fragment27, 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?.[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/tree.ts
function stratify(data, id2, init4) {
  const root2 = { children: [], ...init4("") };
  const map2 = /* @__PURE__ */ new Map();
  map2.set("", root2);
  function addAccount(name2, datum2) {
    const existing = map2.get(name2);
    if (existing) {
      Object.assign(existing, init4(name2, datum2));
      return existing;
    }
    const node = { children: [], ...init4(name2, datum2) };
    map2.set(name2, node);
    const parentName = parent(name2);
    const parentNode = map2.get(parentName) ?? addAccount(parentName);
    parentNode.children.push(node);
    return node;
  }
  [...data].sort((a, b) => id2(a).localeCompare(id2(b))).forEach((datum2) => addAccount(id2(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_block13(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 = (
    /*#slots*/
    ctx2[5].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx2,
    /*$$scope*/
    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-1g27cpc");
      attr(div0, "aria-hidden", "true");
      attr(button, "type", "button");
      attr(button, "class", "muted close svelte-1g27cpc");
      attr(div1, "class", "content svelte-1g27cpc");
      attr(div1, "role", "dialog");
      attr(div1, "aria-modal", "true");
      attr(div2, "class", "overlay svelte-1g27cpc");
    },
    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(
              /*closeHandler*/
              ctx2[1]
            ))
              ctx2[1].apply(this, arguments);
          }),
          listen(button, "click", function() {
            if (is_function(
              /*closeHandler*/
              ctx2[1]
            ))
              ctx2[1].apply(this, arguments);
          }),
          action_destroyer(handleFocus_action = /*handleFocus*/
          ctx2[2].call(null, div1))
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (default_slot) {
        if (default_slot.p && (!current || dirty & /*$$scope*/
        16)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[4],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[4]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              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_fragment28(ctx2) {
  let if_block_anchor;
  let current;
  let if_block = (
    /*shown*/
    ctx2[0] && create_if_block13(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 (
        /*shown*/
        ctx3[0]
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & /*shown*/
          1) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block13(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 (detaching) {
        detach(if_block_anchor);
      }
      if (if_block)
        if_block.d(detaching);
    }
  };
}
function instance29($$self, $$props, $$invalidate) {
  let { $$slots: slots = {}, $$scope } = $$props;
  let { shown = false } = $$props;
  let { focus = void 0 } = $$props;
  let { closeHandler = closeOverlay } = $$props;
  const handleFocus = (el) => {
    const 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 && last) {
          ev.preventDefault();
          attemptFocus(last);
        } else if (!ev.shiftKey && document.activeElement === last && first) {
          ev.preventDefault();
          attemptFocus(first);
        }
      } else if (ev.key === "Escape") {
        ev.preventDefault();
        closeHandler();
      }
    };
    document.addEventListener("keydown", keydown2);
    const selectorFocusEl = focus ? el.querySelector(focus) : void 0;
    const focusEl = selectorFocusEl ?? getFocusableElements(el)[0];
    if (focusEl) {
      attemptFocus(focusEl);
    }
    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(options3) {
    super();
    init2(this, options3, instance29, create_fragment28, safe_not_equal, { shown: 0, focus: 3, closeHandler: 1 });
  }
};
var ModalBase_default = ModalBase;

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

// src/reports/documents/Accounts.svelte
function get_each_context17(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[12] = list[i];
  return child_ctx;
}
function create_if_block_19(ctx2) {
  let p;
  let t03;
  let button;
  let t1_value = leaf(
    /*node*/
    ctx2[0].name
  ) + "";
  let t13;
  let t22;
  let p_title_value;
  let p_data_account_name_value;
  let mounted;
  let dispose;
  let if_block0 = (
    /*hasChildren*/
    ctx2[6] && create_if_block_34(ctx2)
  );
  let if_block1 = (
    /*node*/
    ctx2[0].count > 0 && create_if_block_26(ctx2)
  );
  return {
    c() {
      p = element("p");
      if (if_block0)
        if_block0.c();
      t03 = space();
      button = element("button");
      t13 = text(t1_value);
      t22 = space();
      if (if_block1)
        if_block1.c();
      attr(button, "type", "button");
      attr(button, "class", "unset leaf svelte-8xh817");
      attr(p, "title", p_title_value = /*node*/
      ctx2[0].name);
      attr(p, "class", "droptarget svelte-8xh817");
      attr(p, "data-account-name", p_data_account_name_value = /*node*/
      ctx2[0].name);
      toggle_class(
        p,
        "selected",
        /*selected*/
        ctx2[5]
      );
      toggle_class(
        p,
        "drag",
        /*drag*/
        ctx2[4]
      );
    },
    m(target, anchor) {
      insert(target, p, anchor);
      if (if_block0)
        if_block0.m(p, null);
      append(p, t03);
      append(p, button);
      append(button, t13);
      append(p, t22);
      if (if_block1)
        if_block1.m(p, null);
      if (!mounted) {
        dispose = [
          listen(
            button,
            "click",
            /*click_handler_1*/
            ctx2[10]
          ),
          listen(
            p,
            "dragenter",
            /*dragenter*/
            ctx2[7]
          ),
          listen(
            p,
            "dragover",
            /*dragenter*/
            ctx2[7]
          ),
          listen(
            p,
            "dragleave",
            /*dragleave_handler*/
            ctx2[11]
          ),
          listen(p, "drop", prevent_default(
            /*drop*/
            ctx2[8]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if (
        /*hasChildren*/
        ctx3[6]
      ) {
        if (if_block0) {
          if_block0.p(ctx3, dirty);
        } else {
          if_block0 = create_if_block_34(ctx3);
          if_block0.c();
          if_block0.m(p, t03);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (dirty & /*node*/
      1 && t1_value !== (t1_value = leaf(
        /*node*/
        ctx3[0].name
      ) + ""))
        set_data(t13, t1_value);
      if (
        /*node*/
        ctx3[0].count > 0
      ) {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
        } else {
          if_block1 = create_if_block_26(ctx3);
          if_block1.c();
          if_block1.m(p, null);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (dirty & /*node*/
      1 && p_title_value !== (p_title_value = /*node*/
      ctx3[0].name)) {
        attr(p, "title", p_title_value);
      }
      if (dirty & /*node*/
      1 && p_data_account_name_value !== (p_data_account_name_value = /*node*/
      ctx3[0].name)) {
        attr(p, "data-account-name", p_data_account_name_value);
      }
      if (dirty & /*selected*/
      32) {
        toggle_class(
          p,
          "selected",
          /*selected*/
          ctx3[5]
        );
      }
      if (dirty & /*drag*/
      16) {
        toggle_class(
          p,
          "drag",
          /*drag*/
          ctx3[4]
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(p);
      }
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_if_block_34(ctx2) {
  let button;
  let t_value = (
    /*expanded*/
    ctx2[3] ? "\u25BE" : "\u25B8"
  );
  let t4;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      t4 = text(t_value);
      attr(button, "type", "button");
      attr(button, "class", "unset toggle svelte-8xh817");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, t4);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler*/
          ctx2[9]
        );
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if (dirty & /*expanded*/
      8 && t_value !== (t_value = /*expanded*/
      ctx3[3] ? "\u25BE" : "\u25B8"))
        set_data(t4, t_value);
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_26(ctx2) {
  let span;
  let t_value = (
    /*node*/
    ctx2[0].count + ""
  );
  let t4;
  return {
    c() {
      span = element("span");
      t4 = text(t_value);
      attr(span, "class", "count svelte-8xh817");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t4);
    },
    p(ctx3, dirty) {
      if (dirty & /*node*/
      1 && t_value !== (t_value = /*node*/
      ctx3[0].count + ""))
        set_data(t4, t_value);
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
    }
  };
}
function create_if_block14(ctx2) {
  let ul;
  let ul_hidden_value;
  let current;
  let each_value = ensure_array_like(
    /*node*/
    ctx2[0].children
  );
  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 out2 = (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();
      }
      ul.hidden = ul_hidden_value = !/*expanded*/
      ctx2[3];
      attr(ul, "class", "svelte-8xh817");
    },
    m(target, anchor) {
      insert(target, ul, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(ul, null);
        }
      }
      current = true;
    },
    p(ctx3, dirty) {
      if (dirty & /*node, move*/
      3) {
        each_value = ensure_array_like(
          /*node*/
          ctx3[0].children
        );
        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(ul, null);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out2(i);
        }
        check_outros();
      }
      if (!current || dirty & /*expanded*/
      8 && ul_hidden_value !== (ul_hidden_value = !/*expanded*/
      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_block17(ctx2) {
  let li;
  let accounts2;
  let t4;
  let current;
  accounts2 = new Accounts({
    props: {
      node: (
        /*child*/
        ctx2[12]
      ),
      move: (
        /*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 & /*node*/
      1)
        accounts_changes.node = /*child*/
        ctx3[12];
      if (dirty & /*move*/
      2)
        accounts_changes.move = /*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_fragment29(ctx2) {
  let t4;
  let if_block1_anchor;
  let current;
  let if_block0 = (
    /*node*/
    ctx2[0].name && create_if_block_19(ctx2)
  );
  let if_block1 = (
    /*hasChildren*/
    ctx2[6] && create_if_block14(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 (
        /*node*/
        ctx3[0].name
      ) {
        if (if_block0) {
          if_block0.p(ctx3, dirty);
        } else {
          if_block0 = create_if_block_19(ctx3);
          if_block0.c();
          if_block0.m(t4.parentNode, t4);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*hasChildren*/
        ctx3[6]
      ) {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
          if (dirty & /*hasChildren*/
          64) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block14(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 (detaching) {
        detach(t4);
        detach(if_block1_anchor);
      }
      if (if_block0)
        if_block0.d(detaching);
      if (if_block1)
        if_block1.d(detaching);
    }
  };
}
function instance30($$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) {
    if (event.dataTransfer?.types.includes("fava/filename")) {
      event.preventDefault();
      $$invalidate(4, drag = true);
    }
  }
  function drop2(event) {
    const filename = event.dataTransfer?.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 & /*node*/
    1) {
      $:
        $$invalidate(6, hasChildren = node.children.length > 0);
    }
    if ($$self.$$.dirty & /*$selectedAccount, node*/
    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(options3) {
    super();
    init2(this, options3, instance30, create_fragment29, safe_not_equal, { node: 0, move: 1 });
  }
};
var Accounts_default = Accounts;

// src/editor/DocumentPreviewEditor.svelte
function create_fragment30(ctx2) {
  let div;
  let renderEditor_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(renderEditor_action = /*renderEditor*/
        ctx2[0].call(null, div));
        mounted = true;
      }
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      mounted = false;
      dispose();
    }
  };
}
function instance31($$self, $$props, $$invalidate) {
  let { url } = $$props;
  let value = "";
  const { editor: editor2, renderEditor } = initDocumentPreviewEditor(value);
  $$self.$$set = ($$props2) => {
    if ("url" in $$props2)
      $$invalidate(1, url = $$props2.url);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*url*/
    2) {
      $:
        fetch2(url).then(handleText).then((v) => {
          $$invalidate(2, value = v);
        }).catch(() => {
          $$invalidate(2, value = `Loading ${url} failed...`);
        });
    }
    if ($$self.$$.dirty & /*value*/
    4) {
      $:
        if (value !== editor2.state.sliceDoc()) {
          editor2.dispatch(replaceContents(editor2.state, value));
        }
    }
  };
  return [renderEditor, url, value];
}
var DocumentPreviewEditor = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance31, create_fragment30, safe_not_equal, { url: 1 });
  }
};
var DocumentPreviewEditor_default = DocumentPreviewEditor;

// src/reports/documents/DocumentPreview.svelte
function create_else_block4(ctx2) {
  let t03;
  let t13;
  let t22;
  let t32;
  let t4;
  return {
    c() {
      t03 = text("Preview for file `");
      t13 = text(
        /*filename*/
        ctx2[0]
      );
      t22 = text("` with file type `");
      t32 = text(
        /*extension*/
        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 & /*filename*/
      1)
        set_data(
          t13,
          /*filename*/
          ctx3[0]
        );
      if (dirty & /*extension*/
      4)
        set_data(
          t32,
          /*extension*/
          ctx3[2]
        );
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(t03);
        detach(t13);
        detach(t22);
        detach(t32);
        detach(t4);
      }
    }
  };
}
function create_if_block_35(ctx2) {
  let iframe;
  let iframe_src_value;
  return {
    c() {
      iframe = element("iframe");
      if (!src_url_equal(iframe.src, iframe_src_value = /*url*/
      ctx2[1]))
        attr(iframe, "src", iframe_src_value);
      attr(
        iframe,
        "title",
        /*filename*/
        ctx2[0]
      );
      attr(iframe, "sandbox", "");
      attr(iframe, "class", "svelte-586ug7");
    },
    m(target, anchor) {
      insert(target, iframe, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & /*url*/
      2 && !src_url_equal(iframe.src, iframe_src_value = /*url*/
      ctx3[1])) {
        attr(iframe, "src", iframe_src_value);
      }
      if (dirty & /*filename*/
      1) {
        attr(
          iframe,
          "title",
          /*filename*/
          ctx3[0]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(iframe);
      }
    }
  };
}
function create_if_block_27(ctx2) {
  let img;
  let img_src_value;
  return {
    c() {
      img = element("img");
      if (!src_url_equal(img.src, img_src_value = /*url*/
      ctx2[1]))
        attr(img, "src", img_src_value);
      attr(
        img,
        "alt",
        /*filename*/
        ctx2[0]
      );
      attr(img, "class", "svelte-586ug7");
    },
    m(target, anchor) {
      insert(target, img, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & /*url*/
      2 && !src_url_equal(img.src, img_src_value = /*url*/
      ctx3[1])) {
        attr(img, "src", img_src_value);
      }
      if (dirty & /*filename*/
      1) {
        attr(
          img,
          "alt",
          /*filename*/
          ctx3[0]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(img);
      }
    }
  };
}
function create_if_block_110(ctx2) {
  let documentprevieweditor;
  let current;
  documentprevieweditor = new DocumentPreviewEditor_default({ props: { url: (
    /*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 & /*url*/
      2)
        documentprevieweditor_changes.url = /*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_block15(ctx2) {
  let object2;
  return {
    c() {
      object2 = element("object");
      attr(
        object2,
        "title",
        /*filename*/
        ctx2[0]
      );
      attr(
        object2,
        "data",
        /*url*/
        ctx2[1]
      );
      attr(object2, "class", "svelte-586ug7");
    },
    m(target, anchor) {
      insert(target, object2, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & /*filename*/
      1) {
        attr(
          object2,
          "title",
          /*filename*/
          ctx3[0]
        );
      }
      if (dirty & /*url*/
      2) {
        attr(
          object2,
          "data",
          /*url*/
          ctx3[1]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(object2);
      }
    }
  };
}
function create_fragment31(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_block15,
    create_if_block_110,
    create_if_block_27,
    create_if_block_35,
    create_else_block4
  ];
  const if_blocks = [];
  function select_block_type(ctx3, dirty) {
    if (dirty & /*extension*/
    4)
      show_if = null;
    if (dirty & /*extension*/
    4)
      show_if_1 = null;
    if (dirty & /*extension*/
    4)
      show_if_2 = null;
    if (
      /*extension*/
      ctx3[2] === "pdf"
    )
      return 0;
    if (show_if == null)
      show_if = !!plainTextExtensions.includes(
        /*extension*/
        ctx3[2]
      );
    if (show_if)
      return 1;
    if (show_if_1 == null)
      show_if_1 = !!imageExtensions.includes(
        /*extension*/
        ctx3[2]
      );
    if (show_if_1)
      return 2;
    if (show_if_2 == null)
      show_if_2 = !!["html", "htm"].includes(
        /*extension*/
        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 (detaching) {
        detach(if_block_anchor);
      }
      if_blocks[current_block_type_index].d(detaching);
    }
  };
}
var plainTextExtensions = ["csv", "json", "qfx", "txt", "xml"];
var imageExtensions = ["gif", "jpg", "jpeg", "png", "svg", "webp", "bmp", "ico"];
function instance32($$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 & /*filename*/
    1) {
      $:
        $$invalidate(2, extension = ext(filename).toLowerCase());
    }
    if ($$self.$$.dirty & /*$base_url, filename*/
    9) {
      $:
        $$invalidate(1, url = `${$base_url}document/?filename=${encodeURIComponent(filename)}`);
    }
  };
  return [filename, url, extension, $base_url];
}
var DocumentPreview = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance32, create_fragment31, safe_not_equal, { filename: 0 });
  }
};
var DocumentPreview_default = DocumentPreview;

// src/reports/documents/Table.svelte
function get_each_context18(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[11] = list[i];
  return child_ctx;
}
function get_each_context_15(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[14] = list[i];
  return child_ctx;
}
function create_each_block_15(ctx2) {
  let sortheader;
  let updating_sorter;
  let current;
  function sortheader_sorter_binding(value) {
    ctx2[8](value);
  }
  let sortheader_props = { column: (
    /*column*/
    ctx2[14]
  ) };
  if (
    /*sorter*/
    ctx2[1] !== void 0
  ) {
    sortheader_props.sorter = /*sorter*/
    ctx2[1];
  }
  sortheader = new SortHeader_default({ props: sortheader_props });
  binding_callbacks.push(() => bind(sortheader, "sorter", sortheader_sorter_binding));
  return {
    c() {
      create_component(sortheader.$$.fragment);
    },
    m(target, anchor) {
      mount_component(sortheader, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const sortheader_changes = {};
      if (!updating_sorter && dirty & /*sorter*/
      2) {
        updating_sorter = true;
        sortheader_changes.sorter = /*sorter*/
        ctx3[1];
        add_flush_callback(() => updating_sorter = false);
      }
      sortheader.$set(sortheader_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(sortheader.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(sortheader.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(sortheader, detaching);
    }
  };
}
function create_each_block18(ctx2) {
  let tr;
  let td0;
  let t0_value = (
    /*doc*/
    ctx2[11].date + ""
  );
  let t03;
  let t13;
  let td1;
  let t2_value = (
    /*name*/
    ctx2[3](
      /*doc*/
      ctx2[11]
    ) + ""
  );
  let t22;
  let t32;
  let tr_draggable_value;
  let tr_title_value;
  let mounted;
  let dispose;
  function dragstart_handler(...args2) {
    return (
      /*dragstart_handler*/
      ctx2[9](
        /*doc*/
        ctx2[11],
        ...args2
      )
    );
  }
  function click_handler() {
    return (
      /*click_handler*/
      ctx2[10](
        /*doc*/
        ctx2[11]
      )
    );
  }
  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 = /*doc*/
      ctx2[11].filename);
      attr(tr, "class", "svelte-1511gpj");
      toggle_class(
        tr,
        "selected",
        /*selected*/
        ctx2[0] === /*doc*/
        ctx2[11]
      );
    },
    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)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & /*sorted_documents*/
      4 && t0_value !== (t0_value = /*doc*/
      ctx2[11].date + ""))
        set_data(t03, t0_value);
      if (dirty & /*sorted_documents*/
      4 && t2_value !== (t2_value = /*name*/
      ctx2[3](
        /*doc*/
        ctx2[11]
      ) + ""))
        set_data(t22, t2_value);
      if (dirty & /*sorted_documents*/
      4 && tr_title_value !== (tr_title_value = /*doc*/
      ctx2[11].filename)) {
        attr(tr, "title", tr_title_value);
      }
      if (dirty & /*selected, sorted_documents*/
      5) {
        toggle_class(
          tr,
          "selected",
          /*selected*/
          ctx2[0] === /*doc*/
          ctx2[11]
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(tr);
      }
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_fragment32(ctx2) {
  let table;
  let thead;
  let tr;
  let t4;
  let tbody;
  let current;
  let each_value_1 = ensure_array_like(
    /*columns*/
    ctx2[4]
  );
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks_1[i] = create_each_block_15(get_each_context_15(ctx2, each_value_1, i));
  }
  const out2 = (i) => transition_out(each_blocks_1[i], 1, 1, () => {
    each_blocks_1[i] = null;
  });
  let each_value = ensure_array_like(
    /*sorted_documents*/
    ctx2[2]
  );
  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() {
      table = 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, "class", "svelte-1511gpj");
    },
    m(target, anchor) {
      insert(target, table, anchor);
      append(table, thead);
      append(thead, tr);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(tr, null);
        }
      }
      append(table, t4);
      append(table, tbody);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(tbody, null);
        }
      }
      current = true;
    },
    p(ctx3, [dirty]) {
      if (dirty & /*columns, sorter*/
      18) {
        each_value_1 = ensure_array_like(
          /*columns*/
          ctx3[4]
        );
        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_1[i]) {
            each_blocks_1[i].p(child_ctx, dirty);
            transition_in(each_blocks_1[i], 1);
          } else {
            each_blocks_1[i] = create_each_block_15(child_ctx);
            each_blocks_1[i].c();
            transition_in(each_blocks_1[i], 1);
            each_blocks_1[i].m(tr, null);
          }
        }
        group_outros();
        for (i = each_value_1.length; i < each_blocks_1.length; i += 1) {
          out2(i);
        }
        check_outros();
      }
      if (dirty & /*sorted_documents, selected, name*/
      13) {
        each_value = ensure_array_like(
          /*sorted_documents*/
          ctx3[2]
        );
        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(tbody, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks_1[i]);
      }
      current = true;
    },
    o(local) {
      each_blocks_1 = each_blocks_1.filter(Boolean);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        transition_out(each_blocks_1[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(table);
      }
      destroy_each(each_blocks_1, detaching);
      destroy_each(each_blocks, detaching);
    }
  };
}
function instance33($$self, $$props, $$invalidate) {
  let filtered_documents;
  let sorted_documents;
  let $selectedAccount;
  component_subscribe($$self, selectedAccount, ($$value) => $$invalidate(7, $selectedAccount = $$value));
  let { data } = $$props;
  let { selected = null } = $$props;
  function name2(doc2) {
    const base2 = basename(doc2.filename);
    return base2.startsWith(doc2.date) ? base2.substring(11) : base2;
  }
  const columns3 = [new DateColumn(_("Date")), new StringColumn(_("Name"), (d) => name2(d))];
  let sorter = new Sorter(columns3[0], "desc");
  function sortheader_sorter_binding(value) {
    sorter = value;
    $$invalidate(1, sorter);
  }
  const dragstart_handler = (doc2, ev) => {
    ev.dataTransfer?.setData("fava/filename", doc2.filename);
  };
  const click_handler = (doc2) => {
    $$invalidate(0, selected = doc2);
  };
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(5, data = $$props2.data);
    if ("selected" in $$props2)
      $$invalidate(0, selected = $$props2.selected);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*data, $selectedAccount*/
    160) {
      $:
        $$invalidate(6, filtered_documents = data.filter((doc2) => isDescendant(doc2.account, $selectedAccount)));
    }
    if ($$self.$$.dirty & /*sorter, filtered_documents*/
    66) {
      $:
        $$invalidate(2, sorted_documents = sorter.sort(filtered_documents));
    }
  };
  return [
    selected,
    sorter,
    sorted_documents,
    name2,
    columns3,
    data,
    filtered_documents,
    $selectedAccount,
    sortheader_sorter_binding,
    dragstart_handler,
    click_handler
  ];
}
var Table = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance33, create_fragment32, safe_not_equal, { data: 5, selected: 0 });
  }
};
var Table_default = Table;

// src/reports/documents/Documents.svelte
function create_if_block_111(ctx2) {
  let modalbase;
  let current;
  modalbase = new ModalBase_default({
    props: {
      shown: true,
      closeHandler: (
        /*func*/
        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 & /*moving*/
      4)
        modalbase_changes.closeHandler = /*func*/
        ctx3[9];
      if (dirty & /*$$scope, moving*/
      4100) {
        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 = (
    /*moving*/
    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 (
    /*moving*/
    ctx2[2].account !== void 0
  ) {
    accountinput_props.value = /*moving*/
    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,
        /*moving*/
        ctx2[2].newName
      );
      append(p1, t5);
      append(p1, button);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            input,
            "input",
            /*input_input_handler*/
            ctx2[8]
          ),
          listen(form, "submit", prevent_default(
            /*move*/
            ctx2[5]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if ((!current || dirty & /*moving*/
      4) && t2_value !== (t2_value = /*moving*/
      ctx3[2].filename + ""))
        set_data(t22, t2_value);
      const accountinput_changes = {};
      if (!updating_value && dirty & /*moving*/
      4) {
        updating_value = true;
        accountinput_changes.value = /*moving*/
        ctx3[2].account;
        add_flush_callback(() => updating_value = false);
      }
      accountinput.$set(accountinput_changes);
      if (dirty & /*moving*/
      4 && input.value !== /*moving*/
      ctx3[2].newName) {
        set_input_value(
          input,
          /*moving*/
          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_block16(ctx2) {
  let documentpreview;
  let current;
  documentpreview = new DocumentPreview_default({
    props: { filename: (
      /*selected*/
      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 & /*selected*/
      2)
        documentpreview_changes.filename = /*selected*/
        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_fragment33(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 = (
    /*moving*/
    ctx2[2] && create_if_block_111(ctx2)
  );
  accounts2 = new Accounts_default({
    props: {
      node: (
        /*node*/
        ctx2[3]
      ),
      move: (
        /*func_1*/
        ctx2[10]
      )
    }
  });
  function table_selected_binding(value) {
    ctx2[11](value);
  }
  let table_props = { data: (
    /*documents*/
    ctx2[0]
  ) };
  if (
    /*selected*/
    ctx2[1] !== void 0
  ) {
    table_props.selected = /*selected*/
    ctx2[1];
  }
  table = new Table_default({ props: table_props });
  binding_callbacks.push(() => bind(table, "selected", table_selected_binding));
  let if_block1 = (
    /*selected*/
    ctx2[1] && create_if_block16(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",
          /*keyup*/
          ctx2[4]
        );
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (
        /*moving*/
        ctx3[2]
      ) {
        if (if_block0) {
          if_block0.p(ctx3, dirty);
          if (dirty & /*moving*/
          4) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_111(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 & /*node*/
      8)
        accounts_changes.node = /*node*/
        ctx3[3];
      if (dirty & /*moving*/
      4)
        accounts_changes.move = /*func_1*/
        ctx3[10];
      accounts2.$set(accounts_changes);
      const table_changes = {};
      if (dirty & /*documents*/
      1)
        table_changes.data = /*documents*/
        ctx3[0];
      if (!updating_selected && dirty & /*selected*/
      2) {
        updating_selected = true;
        table_changes.selected = /*selected*/
        ctx3[1];
        add_flush_callback(() => updating_selected = false);
      }
      table.$set(table_changes);
      if (
        /*selected*/
        ctx3[1]
      ) {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
          if (dirty & /*selected*/
          2) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block16(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 (detaching) {
        detach(t03);
        detach(div1);
      }
      if (if_block0)
        if_block0.d(detaching);
      destroy_component(accounts2);
      destroy_component(table);
      if (if_block1)
        if_block1.d();
      mounted = false;
      dispose();
    }
  };
}
function instance34($$self, $$props, $$invalidate) {
  let grouped;
  let node;
  let { documents: documents2 } = $$props;
  let selected;
  let moving = null;
  function keyup(ev) {
    if (ev.key === "F2" && selected && !moving) {
      $$invalidate(2, moving = {
        ...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 func3 = () => {
    $$invalidate(2, moving = null);
  };
  const func_1 = (arg) => {
    $$invalidate(2, moving = { ...arg, newName: basename(arg.filename) });
  };
  function table_selected_binding(value) {
    selected = value;
    $$invalidate(1, selected);
  }
  $$self.$$set = ($$props2) => {
    if ("documents" in $$props2)
      $$invalidate(0, documents2 = $$props2.documents);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*documents*/
    1) {
      $:
        $$invalidate(6, grouped = group(documents2, (d) => d.account));
    }
    if ($$self.$$.dirty & /*grouped*/
    64) {
      $:
        $$invalidate(3, node = stratify(grouped.entries(), ([s]) => s, (name2, d) => ({ name: name2, count: d?.[1].length ?? 0 })));
    }
  };
  return [
    documents2,
    selected,
    moving,
    node,
    keyup,
    move,
    grouped,
    accountinput_value_binding,
    input_input_handler,
    func3,
    func_1,
    table_selected_binding
  ];
}
var Documents = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance34, create_fragment33, safe_not_equal, { documents: 0 });
  }
};
var Documents_default = Documents;

// src/reports/documents/index.ts
var documents = new Route(
  "documents",
  Documents_default,
  (url) => get("documents", getURLFilters(url)).then((data) => ({
    documents: data
  })),
  () => _("Documents")
);

// src/editor/SaveButton.svelte
function create_fragment34(ctx2) {
  let button;
  let t4;
  let button_disabled_value;
  let keyboardShortcut_action;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      t4 = text(
        /*buttonContent*/
        ctx2[1]
      );
      attr(button, "type", "submit");
      button.disabled = button_disabled_value = !/*changed*/
      ctx2[0];
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, t4);
      if (!mounted) {
        dispose = action_destroyer(keyboardShortcut_action = keyboardShortcut.call(null, button, { key: "Control+s", mac: "Meta+s" }));
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & /*buttonContent*/
      2)
        set_data(
          t4,
          /*buttonContent*/
          ctx3[1]
        );
      if (dirty & /*changed*/
      1 && button_disabled_value !== (button_disabled_value = !/*changed*/
      ctx3[0])) {
        button.disabled = button_disabled_value;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      mounted = false;
      dispose();
    }
  };
}
function instance35($$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 & /*saving*/
    4) {
      $:
        $$invalidate(1, buttonContent = saving ? _("Saving...") : _("Save"));
    }
  };
  return [changed, buttonContent, saving];
}
var SaveButton = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance35, create_fragment34, safe_not_equal, { changed: 0, saving: 2 });
  }
};
var SaveButton_default = SaveButton;

// src/reports/editor/AppMenu.svelte
function create_fragment35(ctx2) {
  let div;
  let current;
  const default_slot_template = (
    /*#slots*/
    ctx2[1].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx2,
    /*$$scope*/
    ctx2[0],
    null
  );
  return {
    c() {
      div = element("div");
      if (default_slot)
        default_slot.c();
      attr(div, "role", "menubar");
      attr(div, "class", "svelte-5ozbeh");
    },
    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 & /*$$scope*/
        1)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx3,
            /*$$scope*/
            ctx3[0],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx3[0]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              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 instance36($$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(options3) {
    super();
    init2(this, options3, instance36, create_fragment35, safe_not_equal, {});
  }
};
var AppMenu_default = AppMenu;

// src/reports/editor/AppMenuItem.svelte
function create_fragment36(ctx2) {
  let span;
  let t03;
  let t13;
  let ul;
  let current;
  let mounted;
  let dispose;
  const default_slot_template = (
    /*#slots*/
    ctx2[3].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx2,
    /*$$scope*/
    ctx2[2],
    null
  );
  return {
    c() {
      span = element("span");
      t03 = text(
        /*name*/
        ctx2[0]
      );
      t13 = space();
      ul = element("ul");
      if (default_slot)
        default_slot.c();
      attr(ul, "class", "svelte-hpa0bh");
      attr(span, "tabindex", "0");
      attr(span, "role", "menuitem");
      attr(span, "class", "svelte-hpa0bh");
      toggle_class(
        span,
        "open",
        /*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",
          /*keydown_handler*/
          ctx2[4]
        );
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (!current || dirty & /*name*/
      1)
        set_data(
          t03,
          /*name*/
          ctx3[0]
        );
      if (default_slot) {
        if (default_slot.p && (!current || dirty & /*$$scope*/
        4)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx3,
            /*$$scope*/
            ctx3[2],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx3[2]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx3[2],
              dirty,
              null
            ),
            null
          );
        }
      }
      if (!current || dirty & /*open*/
      2) {
        toggle_class(
          span,
          "open",
          /*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 instance37($$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(options3) {
    super();
    init2(this, options3, instance37, create_fragment36, safe_not_equal, { name: 0 });
  }
};
var AppMenuItem_default = AppMenuItem;

// src/reports/editor/AppMenuSubItem.svelte
var get_right_slot_changes = (dirty) => ({});
var get_right_slot_context = (ctx2) => ({});
function create_if_block17(ctx2) {
  let span;
  let current;
  const right_slot_template = (
    /*#slots*/
    ctx2[5].right
  );
  const right_slot = create_slot(
    right_slot_template,
    ctx2,
    /*$$scope*/
    ctx2[4],
    get_right_slot_context
  );
  return {
    c() {
      span = element("span");
      if (right_slot)
        right_slot.c();
      attr(span, "class", "svelte-1od4h3r");
    },
    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 & /*$$scope*/
        16)) {
          update_slot_base(
            right_slot,
            right_slot_template,
            ctx3,
            /*$$scope*/
            ctx3[4],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx3[4]
            ) : get_slot_changes(
              right_slot_template,
              /*$$scope*/
              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_fragment37(ctx2) {
  let li;
  let button;
  let t4;
  let current;
  let mounted;
  let dispose;
  const default_slot_template = (
    /*#slots*/
    ctx2[5].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx2,
    /*$$scope*/
    ctx2[4],
    null
  );
  let if_block = (
    /*$$slots*/
    ctx2[3].right && create_if_block17(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-1od4h3r");
      attr(
        li,
        "title",
        /*title*/
        ctx2[0]
      );
      attr(li, "class", "svelte-1od4h3r");
      toggle_class(
        li,
        "selected",
        /*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(
            /*action*/
            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 & /*$$scope*/
        16)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[4],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[4]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx2[4],
              dirty,
              null
            ),
            null
          );
        }
      }
      if (
        /*$$slots*/
        ctx2[3].right
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty & /*$$slots*/
          8) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block17(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 & /*title*/
      1) {
        attr(
          li,
          "title",
          /*title*/
          ctx2[0]
        );
      }
      if (!current || dirty & /*selected*/
      2) {
        toggle_class(
          li,
          "selected",
          /*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 instance38($$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(options3) {
    super();
    init2(this, options3, instance38, create_fragment37, safe_not_equal, { title: 0, selected: 1, action: 2 });
  }
};
var AppMenuSubItem_default = AppMenuSubItem;

// src/reports/editor/Key.svelte
function get_each_context19(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[1] = list[i];
  child_ctx[3] = i;
  return child_ctx;
}
function create_each_block19(ctx2) {
  let kbd;
  let t0_value = (
    /*part*/
    ctx2[1] + ""
  );
  let t03;
  let t1_value = (
    /*index*/
    ctx2[3] === /*key*/
    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 & /*key*/
      1 && t0_value !== (t0_value = /*part*/
      ctx3[1] + ""))
        set_data(t03, t0_value);
      if (dirty & /*key*/
      1 && t1_value !== (t1_value = /*index*/
      ctx3[3] === /*key*/
      ctx3[0].length - 1 ? "" : "+"))
        set_data(t13, t1_value);
    },
    d(detaching) {
      if (detaching) {
        detach(kbd);
        detach(t13);
      }
    }
  };
}
function create_fragment38(ctx2) {
  let each_1_anchor;
  let each_value = ensure_array_like(
    /*key*/
    ctx2[0]
  );
  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));
  }
  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) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx3, [dirty]) {
      if (dirty & /*key*/
      1) {
        each_value = ensure_array_like(
          /*key*/
          ctx3[0]
        );
        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);
          } else {
            each_blocks[i] = create_each_block19(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) {
      if (detaching) {
        detach(each_1_anchor);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function instance39($$self, $$props, $$invalidate) {
  let { key: key2 } = $$props;
  $$self.$$set = ($$props2) => {
    if ("key" in $$props2)
      $$invalidate(0, key2 = $$props2.key);
  };
  return [key2];
}
var Key = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance39, create_fragment38, safe_not_equal, { key: 0 });
  }
};
var Key_default = Key;

// src/reports/editor/EditorMenu.svelte
function get_each_context20(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[15] = list[i];
  return child_ctx;
}
function get_each_context_16(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 = (
    /*source*/
    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 & /*sources*/
      8 && t0_value !== (t0_value = /*source*/
      ctx3[18] + ""))
        set_data(t03, t0_value);
    },
    d(detaching) {
      if (detaching) {
        detach(t03);
        detach(t13);
      }
    }
  };
}
function create_each_block_16(ctx2) {
  let appmenusubitem;
  let current;
  function func3() {
    return (
      /*func*/
      ctx2[8](
        /*source*/
        ctx2[18]
      )
    );
  }
  appmenusubitem = new AppMenuSubItem_default({
    props: {
      action: func3,
      selected: (
        /*source*/
        ctx2[18] === /*file_path*/
        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 & /*sources*/
      8)
        appmenusubitem_changes.action = func3;
      if (dirty & /*sources, file_path*/
      9)
        appmenusubitem_changes.selected = /*source*/
        ctx2[18] === /*file_path*/
        ctx2[0];
      if (dirty & /*$$scope, sources*/
      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 = ensure_array_like(
    /*sources*/
    ctx2[3]
  );
  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 out2 = (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) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      if (dirty & /*goToFileAndLine, sources, file_path*/
      25) {
        each_value_1 = ensure_array_like(
          /*sources*/
          ctx3[3]
        );
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_16(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_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) {
          out2(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(each_1_anchor);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
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 key2;
  let current;
  key2 = new Key_default({
    props: { slot: "right", key: [modKey, "d"] }
  });
  return {
    c() {
      create_component(key2.$$.fragment);
    },
    m(target, anchor) {
      mount_component(key2, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current)
        return;
      transition_in(key2.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(key2.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(key2, 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 key2;
  let current;
  key2 = new Key_default({
    props: { slot: "right", key: [modKey, "/"] }
  });
  return {
    c() {
      create_component(key2.$$.fragment);
    },
    m(target, anchor) {
      mount_component(key2, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current)
        return;
      transition_in(key2.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(key2.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(key2, 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 key2;
  let current;
  key2 = new Key_default({
    props: { slot: "right", key: ["Ctrl", "Alt", "]"] }
  });
  return {
    c() {
      create_component(key2.$$.fragment);
    },
    m(target, anchor) {
      mount_component(key2, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current)
        return;
      transition_in(key2.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(key2.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(key2, 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 key2;
  let current;
  key2 = new Key_default({
    props: { slot: "right", key: ["Ctrl", "Alt", "["] }
  });
  return {
    c() {
      create_component(key2.$$.fragment);
    },
    m(target, anchor) {
      mount_component(key2, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current)
        return;
      transition_in(key2.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(key2.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(key2, 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: (
        /*func_1*/
        ctx2[9]
      ),
      $$slots: {
        right: [create_right_slot_4],
        default: [create_default_slot_7]
      },
      $$scope: { ctx: ctx2 }
    }
  });
  appmenusubitem1 = new AppMenuSubItem_default({
    props: {
      action: (
        /*func_2*/
        ctx2[10]
      ),
      $$slots: {
        right: [create_right_slot_3],
        default: [create_default_slot_6]
      },
      $$scope: { ctx: ctx2 }
    }
  });
  appmenusubitem2 = new AppMenuSubItem_default({
    props: {
      action: (
        /*func_3*/
        ctx2[11]
      ),
      $$slots: {
        right: [create_right_slot_2],
        default: [create_default_slot_5]
      },
      $$scope: { ctx: ctx2 }
    }
  });
  appmenusubitem3 = new AppMenuSubItem_default({
    props: {
      action: (
        /*func_4*/
        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 & /*editor*/
      2)
        appmenusubitem0_changes.action = /*func_1*/
        ctx3[9];
      if (dirty & /*$$scope*/
      16384) {
        appmenusubitem0_changes.$$scope = { dirty, ctx: ctx3 };
      }
      appmenusubitem0.$set(appmenusubitem0_changes);
      const appmenusubitem1_changes = {};
      if (dirty & /*editor*/
      2)
        appmenusubitem1_changes.action = /*func_2*/
        ctx3[10];
      if (dirty & /*$$scope*/
      16384) {
        appmenusubitem1_changes.$$scope = { dirty, ctx: ctx3 };
      }
      appmenusubitem1.$set(appmenusubitem1_changes);
      const appmenusubitem2_changes = {};
      if (dirty & /*editor*/
      2)
        appmenusubitem2_changes.action = /*func_3*/
        ctx3[11];
      if (dirty & /*$$scope*/
      16384) {
        appmenusubitem2_changes.$$scope = { dirty, ctx: ctx3 };
      }
      appmenusubitem2.$set(appmenusubitem2_changes);
      const appmenusubitem3_changes = {};
      if (dirty & /*editor*/
      2)
        appmenusubitem3_changes.action = /*func_4*/
        ctx3[12];
      if (dirty & /*$$scope*/
      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) {
      if (detaching) {
        detach(t03);
        detach(t13);
        detach(t22);
      }
      destroy_component(appmenusubitem0, detaching);
      destroy_component(appmenusubitem1, detaching);
      destroy_component(appmenusubitem2, detaching);
      destroy_component(appmenusubitem3, detaching);
    }
  };
}
function create_if_block18(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 & /*$$scope, insertEntryOptions*/
      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 = (
    /*opt*/
    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 & /*insertEntryOptions*/
      4 && t0_value !== (t0_value = /*opt*/
      ctx3[15].re + ""))
        set_data(t03, t0_value);
    },
    d(detaching) {
      if (detaching) {
        detach(t03);
        detach(t13);
      }
    }
  };
}
function create_right_slot(ctx2) {
  let span;
  let t_value = (
    /*opt*/
    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 & /*insertEntryOptions*/
      4 && t_value !== (t_value = /*opt*/
      ctx3[15].date + ""))
        set_data(t4, t_value);
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
    }
  };
}
function create_each_block20(ctx2) {
  let appmenusubitem;
  let current;
  function func_5() {
    return (
      /*func_5*/
      ctx2[13](
        /*opt*/
        ctx2[15]
      )
    );
  }
  appmenusubitem = new AppMenuSubItem_default({
    props: {
      title: `${/*opt*/
      ctx2[15].filename}:${/*opt*/
      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 & /*insertEntryOptions*/
      4)
        appmenusubitem_changes.title = `${/*opt*/
        ctx2[15].filename}:${/*opt*/
        ctx2[15].lineno}`;
      if (dirty & /*insertEntryOptions*/
      4)
        appmenusubitem_changes.action = func_5;
      if (dirty & /*$$scope, insertEntryOptions*/
      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 = ensure_array_like(
    /*insertEntryOptions*/
    ctx2[2]
  );
  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 out2 = (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) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      if (dirty & /*insertEntryOptions, goToFileAndLine*/
      20) {
        each_value = ensure_array_like(
          /*insertEntryOptions*/
          ctx3[2]
        );
        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) {
          out2(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) {
      if (detaching) {
        detach(each_1_anchor);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
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 = (
    /*insertEntryOptions*/
    ctx2[2].length && create_if_block18(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 & /*$$scope, sources, file_path*/
      16393) {
        appmenuitem0_changes.$$scope = { dirty, ctx: ctx3 };
      }
      appmenuitem0.$set(appmenuitem0_changes);
      const appmenuitem1_changes = {};
      if (dirty & /*$$scope, editor*/
      16386) {
        appmenuitem1_changes.$$scope = { dirty, ctx: ctx3 };
      }
      appmenuitem1.$set(appmenuitem1_changes);
      if (
        /*insertEntryOptions*/
        ctx3[2].length
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & /*insertEntryOptions*/
          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(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) {
      if (detaching) {
        detach(t03);
        detach(t13);
        detach(if_block_anchor);
      }
      destroy_component(appmenuitem0, detaching);
      destroy_component(appmenuitem1, detaching);
      if (if_block)
        if_block.d(detaching);
    }
  };
}
function create_fragment39(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 = (
    /*#slots*/
    ctx2[7].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx2,
    /*$$scope*/
    ctx2[14],
    null
  );
  return {
    c() {
      div = element("div");
      create_component(appmenu.$$.fragment);
      t4 = space();
      if (default_slot)
        default_slot.c();
      attr(div, "class", "svelte-1b7r65z");
    },
    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 & /*$$scope, insertEntryOptions, editor, sources, file_path*/
      16399) {
        appmenu_changes.$$scope = { dirty, ctx: ctx3 };
      }
      appmenu.$set(appmenu_changes);
      if (default_slot) {
        if (default_slot.p && (!current || dirty & /*$$scope*/
        16384)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx3,
            /*$$scope*/
            ctx3[14],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx3[14]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              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 instance40($$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: editor2 } = $$props;
  function goToFileAndLine(filename, line) {
    const url = urlFor("editor/", { file_path: filename, line });
    router_default.navigate(url);
    if (filename === file_path && line) {
      editor2.dispatch(scrollToLine(editor2.state, line));
      editor2.focus();
    }
  }
  const func3 = (source2) => {
    goToFileAndLine(source2);
  };
  const func_1 = () => beancountFormat(editor2);
  const func_2 = () => toggleComment(editor2);
  const func_3 = () => unfoldAll(editor2);
  const func_4 = () => foldAll(editor2);
  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, editor2 = $$props2.editor);
    if ("$$scope" in $$props2)
      $$invalidate(14, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$options*/
    64) {
      $:
        $$invalidate(3, sources = [
          $options.filename,
          ...$options.include.filter((f) => f !== $options.filename)
        ]);
    }
    if ($$self.$$.dirty & /*$fava_options*/
    32) {
      $:
        $$invalidate(2, insertEntryOptions = $fava_options.insert_entry);
    }
  };
  return [
    file_path,
    editor2,
    insertEntryOptions,
    sources,
    goToFileAndLine,
    $fava_options,
    $options,
    slots,
    func3,
    func_1,
    func_2,
    func_3,
    func_4,
    func_5,
    $$scope
  ];
}
var EditorMenu = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance40, create_fragment39, safe_not_equal, { file_path: 0, editor: 1 });
  }
};
var EditorMenu_default = EditorMenu;

// src/reports/editor/Editor.svelte
function create_default_slot4(ctx2) {
  let savebutton;
  let current;
  savebutton = new SaveButton_default({
    props: {
      changed: (
        /*changed*/
        ctx2[1]
      ),
      saving: (
        /*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 & /*changed*/
      2)
        savebutton_changes.changed = /*changed*/
        ctx3[1];
      if (dirty & /*saving*/
      4)
        savebutton_changes.saving = /*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_fragment40(ctx2) {
  let form;
  let editormenu;
  let t4;
  let div;
  let renderEditor_action;
  let current;
  let mounted;
  let dispose;
  editormenu = new EditorMenu_default({
    props: {
      file_path: (
        /*file_path*/
        ctx2[0]
      ),
      editor: (
        /*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-llllbf");
      attr(form, "class", "fixed-fullsize-container svelte-llllbf");
    },
    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(renderEditor_action = /*renderEditor*/
          ctx2[5].call(null, div)),
          listen(form, "submit", prevent_default(
            /*submit_handler*/
            ctx2[11]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      const editormenu_changes = {};
      if (dirty & /*file_path*/
      1)
        editormenu_changes.file_path = /*file_path*/
        ctx3[0];
      if (dirty & /*$$scope, changed, saving*/
      32774) {
        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 instance41($$self, $$props, $$invalidate) {
  let file_path;
  let $errors;
  let $searchParams;
  let $fava_options;
  component_subscribe($$self, errors, ($$value) => $$invalidate(8, $errors = $$value));
  component_subscribe($$self, searchParams, ($$value) => $$invalidate(9, $searchParams = $$value));
  component_subscribe($$self, fava_options, ($$value) => $$invalidate(10, $fava_options = $$value));
  let { source: source2 } = $$props;
  let { beancount_language_support } = $$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,
        source: cm.state.sliceDoc(),
        sha256sum
      });
      $$invalidate(1, changed = false);
      cm.focus();
      get("errors").then(
        (v) => {
          errors.set(v);
        },
        log_error
      );
    } catch (error2) {
      notify_err(error2, (e3) => e3.message);
    } finally {
      $$invalidate(2, saving = false);
    }
  }
  const { editor: editor2, renderEditor } = initBeancountEditor(
    "",
    onDocChanges,
    [
      {
        key: "Control-s",
        mac: "Meta-s",
        run: () => {
          save(editor2).catch(() => {
          });
          return true;
        }
      }
    ],
    beancount_language_support
  );
  const checkEditorChanges = () => changed ? "There are unsaved changes. Are you sure you want to leave?" : null;
  onMount(() => router_default.addInteruptHandler(checkEditorChanges));
  const submit_handler = () => save(editor2);
  $$self.$$set = ($$props2) => {
    if ("source" in $$props2)
      $$invalidate(6, source2 = $$props2.source);
    if ("beancount_language_support" in $$props2)
      $$invalidate(7, beancount_language_support = $$props2.beancount_language_support);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*source*/
    64) {
      $:
        $$invalidate(0, file_path = source2.file_path);
    }
    if ($$self.$$.dirty & /*source*/
    64) {
      $:
        if (source2) {
          editor2.dispatch(replaceContents(editor2.state, source2.source));
          sha256sum = source2.sha256sum;
          editor2.focus();
          $$invalidate(1, changed = false);
        }
    }
    if ($$self.$$.dirty & /*file_path, $fava_options, $searchParams*/
    1537) {
      $:
        if (file_path) {
          const opts2 = $fava_options.insert_entry.filter((f) => f.filename === file_path);
          const line = parseInt($searchParams.get("line") ?? "0", 10);
          const last_insert_opt = opts2[opts2.length - 1];
          const lineToScrollTo = (() => {
            if (line > 0) {
              return line;
            }
            if (last_insert_opt) {
              return last_insert_opt.lineno - 1;
            }
            return editor2.state.doc.lines;
          })();
          editor2.dispatch(scrollToLine(editor2.state, lineToScrollTo));
        }
    }
    if ($$self.$$.dirty & /*$errors, file_path*/
    257) {
      $: {
        const errorsForFile = $errors.filter((err3) => err3.source === null || err3.source.filename === file_path);
        editor2.dispatch(setErrors(editor2.state, errorsForFile));
      }
    }
  };
  return [
    file_path,
    changed,
    saving,
    save,
    editor2,
    renderEditor,
    source2,
    beancount_language_support,
    $errors,
    $searchParams,
    $fava_options,
    submit_handler
  ];
}
var Editor = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance41, create_fragment40, safe_not_equal, { source: 6, beancount_language_support: 7 });
  }
};
var Editor_default = Editor;

// src/reports/editor/index.ts
var editor = new Route(
  "editor",
  Editor_default,
  (url) => Promise.all([
    get("source", {
      filename: url.searchParams.get("file_path") ?? ""
    }),
    getBeancountLanguageSupport()
  ]).then(([source2, beancount_language_support]) => ({
    source: source2,
    beancount_language_support
  })),
  () => _("Editor")
);

// src/reports/errors/Errors.svelte
function get_each_context21(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[9] = list[i].message;
  child_ctx[10] = list[i].source;
  return child_ctx;
}
function get_if_ctx(ctx2) {
  const child_ctx = ctx2.slice();
  const constants_0 = urlForSource(
    /*source*/
    child_ctx[10].filename,
    `${/*source*/
    child_ctx[10].lineno}`
  );
  child_ctx[13] = constants_0;
  const constants_1 = format(_("Show source %(file)s:%(lineno)s"), {
    file: (
      /*source*/
      child_ctx[10].filename
    ),
    lineno: `${/*source*/
    child_ctx[10].lineno}`
  });
  child_ctx[14] = constants_1;
  return child_ctx;
}
function get_each_context_17(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[15] = list[i];
  return child_ctx;
}
function create_else_block_12(ctx2) {
  let p;
  return {
    c() {
      p = element("p");
      p.textContent = `${_("No errors.")}`;
    },
    m(target, anchor) {
      insert(target, p, anchor);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(p);
      }
    }
  };
}
function create_if_block19(ctx2) {
  let table;
  let thead;
  let tr;
  let t4;
  let tbody;
  let current;
  let each_value_1 = ensure_array_like(
    /*columns*/
    ctx2[4]
  );
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks_1[i] = create_each_block_17(get_each_context_17(ctx2, each_value_1, i));
  }
  const out2 = (i) => transition_out(each_blocks_1[i], 1, 1, () => {
    each_blocks_1[i] = null;
  });
  let each_value = ensure_array_like(
    /*sorted_errors*/
    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));
  }
  return {
    c() {
      table = 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(table, "class", "errors");
    },
    m(target, anchor) {
      insert(target, table, anchor);
      append(table, thead);
      append(thead, tr);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(tr, null);
        }
      }
      append(table, t4);
      append(table, tbody);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(tbody, null);
        }
      }
      current = true;
    },
    p(ctx3, dirty) {
      if (dirty & /*columns, sorter*/
      17) {
        each_value_1 = ensure_array_like(
          /*columns*/
          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_1[i]) {
            each_blocks_1[i].p(child_ctx, dirty);
            transition_in(each_blocks_1[i], 1);
          } else {
            each_blocks_1[i] = create_each_block_17(child_ctx);
            each_blocks_1[i].c();
            transition_in(each_blocks_1[i], 1);
            each_blocks_1[i].m(tr, null);
          }
        }
        group_outros();
        for (i = each_value_1.length; i < each_blocks_1.length; i += 1) {
          out2(i);
        }
        check_outros();
      }
      if (dirty & /*addAccountLinks, sorted_errors*/
      12) {
        each_value = ensure_array_like(
          /*sorted_errors*/
          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(tbody, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks_1[i]);
      }
      current = true;
    },
    o(local) {
      each_blocks_1 = each_blocks_1.filter(Boolean);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        transition_out(each_blocks_1[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(table);
      }
      destroy_each(each_blocks_1, detaching);
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_each_block_17(ctx2) {
  let sortheader;
  let updating_sorter;
  let current;
  function sortheader_sorter_binding(value) {
    ctx2[6](value);
  }
  let sortheader_props = { column: (
    /*column*/
    ctx2[15]
  ) };
  if (
    /*sorter*/
    ctx2[0] !== void 0
  ) {
    sortheader_props.sorter = /*sorter*/
    ctx2[0];
  }
  sortheader = new SortHeader_default({ props: sortheader_props });
  binding_callbacks.push(() => bind(sortheader, "sorter", sortheader_sorter_binding));
  return {
    c() {
      create_component(sortheader.$$.fragment);
    },
    m(target, anchor) {
      mount_component(sortheader, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const sortheader_changes = {};
      if (!updating_sorter && dirty & /*sorter*/
      1) {
        updating_sorter = true;
        sortheader_changes.sorter = /*sorter*/
        ctx3[0];
        add_flush_callback(() => updating_sorter = false);
      }
      sortheader.$set(sortheader_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(sortheader.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(sortheader.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(sortheader, detaching);
    }
  };
}
function create_else_block5(ctx2) {
  let td0;
  let t4;
  let td1;
  return {
    c() {
      td0 = element("td");
      t4 = space();
      td1 = element("td");
      attr(td1, "class", "num");
    },
    m(target, anchor) {
      insert(target, td0, anchor);
      insert(target, t4, anchor);
      insert(target, td1, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching) {
        detach(td0);
        detach(t4);
        detach(td1);
      }
    }
  };
}
function create_if_block_112(ctx2) {
  let td0;
  let t0_value = (
    /*source*/
    ctx2[10].filename + ""
  );
  let t03;
  let t13;
  let td1;
  let a;
  let t2_value = (
    /*source*/
    ctx2[10].lineno + ""
  );
  let t22;
  let a_href_value;
  let a_title_value;
  return {
    c() {
      td0 = element("td");
      t03 = text(t0_value);
      t13 = space();
      td1 = element("td");
      a = element("a");
      t22 = text(t2_value);
      attr(a, "class", "source");
      attr(a, "href", a_href_value = /*url*/
      ctx2[13]);
      attr(a, "title", a_title_value = /*title*/
      ctx2[14]);
      attr(td1, "class", "num");
    },
    m(target, anchor) {
      insert(target, td0, anchor);
      append(td0, t03);
      insert(target, t13, anchor);
      insert(target, td1, anchor);
      append(td1, a);
      append(a, t22);
    },
    p(ctx3, dirty) {
      if (dirty & /*sorted_errors*/
      4 && t0_value !== (t0_value = /*source*/
      ctx3[10].filename + ""))
        set_data(t03, t0_value);
      if (dirty & /*sorted_errors*/
      4 && t2_value !== (t2_value = /*source*/
      ctx3[10].lineno + ""))
        set_data(t22, t2_value);
      if (dirty & /*sorted_errors*/
      4 && a_href_value !== (a_href_value = /*url*/
      ctx3[13])) {
        attr(a, "href", a_href_value);
      }
      if (dirty & /*sorted_errors*/
      4 && a_title_value !== (a_title_value = /*title*/
      ctx3[14])) {
        attr(a, "title", a_title_value);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(td0);
        detach(t13);
        detach(td1);
      }
    }
  };
}
function create_each_block21(ctx2) {
  let tr;
  let t03;
  let td;
  let raw_value = (
    /*addAccountLinks*/
    ctx2[3](
      /*message*/
      ctx2[9]
    ) + ""
  );
  let t13;
  function select_block_type_1(ctx3, dirty) {
    if (
      /*source*/
      ctx3[10]
    )
      return create_if_block_112;
    return create_else_block5;
  }
  function select_block_ctx(ctx3, type) {
    if (type === create_if_block_112)
      return get_if_ctx(ctx3);
    return ctx3;
  }
  let current_block_type = select_block_type_1(ctx2, -1);
  let if_block = current_block_type(select_block_ctx(ctx2, current_block_type));
  return {
    c() {
      tr = element("tr");
      if_block.c();
      t03 = space();
      td = element("td");
      t13 = space();
      attr(td, "class", "pre");
    },
    m(target, anchor) {
      insert(target, tr, anchor);
      if_block.m(tr, null);
      append(tr, t03);
      append(tr, td);
      td.innerHTML = raw_value;
      append(tr, t13);
    },
    p(ctx3, dirty) {
      if (current_block_type === (current_block_type = select_block_type_1(ctx3, dirty)) && if_block) {
        if_block.p(select_block_ctx(ctx3, current_block_type), dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(select_block_ctx(ctx3, current_block_type));
        if (if_block) {
          if_block.c();
          if_block.m(tr, t03);
        }
      }
      if (dirty & /*sorted_errors*/
      4 && raw_value !== (raw_value = /*addAccountLinks*/
      ctx3[3](
        /*message*/
        ctx3[9]
      ) + ""))
        td.innerHTML = raw_value;
      ;
    },
    d(detaching) {
      if (detaching) {
        detach(tr);
      }
      if_block.d();
    }
  };
}
function create_fragment41(ctx2) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block19, create_else_block_12];
  const if_blocks = [];
  function select_block_type(ctx3, dirty) {
    if (
      /*$errors*/
      ctx3[1].length
    )
      return 0;
    return 1;
  }
  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 (detaching) {
        detach(if_block_anchor);
      }
      if_blocks[current_block_type_index].d(detaching);
    }
  };
}
function instance42($$self, $$props, $$invalidate) {
  let account_re;
  let sorted_errors;
  let $errors;
  let $urlForAccount;
  let $accounts;
  component_subscribe($$self, errors, ($$value) => $$invalidate(1, $errors = $$value));
  component_subscribe($$self, urlForAccount, ($$value) => $$invalidate(8, $urlForAccount = $$value));
  component_subscribe($$self, accounts, ($$value) => $$invalidate(5, $accounts = $$value));
  function addAccountLinks(msg) {
    return msg.split(account_re).map((s, idx) => {
      if (idx % 2 === 0) {
        const el2 = document.createElement("span");
        el2.textContent = s;
        return el2;
      }
      const el = document.createElement("a");
      el.href = $urlForAccount(s);
      el.textContent = s;
      return el;
    }).map((el) => el.outerHTML).join("");
  }
  const columns3 = [
    new StringColumn(_("File"), (d) => d.source?.filename ?? ""),
    new NumberColumn(_("Line"), (d) => d.source?.lineno ?? 0),
    new StringColumn(_("Error"), (d) => d.message)
  ];
  let sorter = new Sorter(columns3[0], "desc");
  function sortheader_sorter_binding(value) {
    sorter = value;
    $$invalidate(0, sorter);
  }
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$accounts*/
    32) {
      $:
        account_re = new RegExp(`(${$accounts.join("|")})`);
    }
    if ($$self.$$.dirty & /*sorter, $errors*/
    3) {
      $:
        $$invalidate(2, sorted_errors = sorter.sort($errors));
    }
  };
  return [
    sorter,
    $errors,
    sorted_errors,
    addAccountLinks,
    columns3,
    $accounts,
    sortheader_sorter_binding
  ];
}
var Errors = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance42, create_fragment41, safe_not_equal, {});
  }
};
var Errors_default = Errors;

// src/reports/events/EventTable.svelte
function get_each_context22(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[5] = list[i];
  return child_ctx;
}
function get_each_context_18(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[8] = list[i];
  return child_ctx;
}
function create_each_block_18(ctx2) {
  let sortheader;
  let updating_sorter;
  let current;
  function sortheader_sorter_binding(value) {
    ctx2[4](value);
  }
  let sortheader_props = { column: (
    /*column*/
    ctx2[8]
  ) };
  if (
    /*sorter*/
    ctx2[0] !== void 0
  ) {
    sortheader_props.sorter = /*sorter*/
    ctx2[0];
  }
  sortheader = new SortHeader_default({ props: sortheader_props });
  binding_callbacks.push(() => bind(sortheader, "sorter", sortheader_sorter_binding));
  return {
    c() {
      create_component(sortheader.$$.fragment);
    },
    m(target, anchor) {
      mount_component(sortheader, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const sortheader_changes = {};
      if (!updating_sorter && dirty & /*sorter*/
      1) {
        updating_sorter = true;
        sortheader_changes.sorter = /*sorter*/
        ctx3[0];
        add_flush_callback(() => updating_sorter = false);
      }
      sortheader.$set(sortheader_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(sortheader.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(sortheader.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(sortheader, detaching);
    }
  };
}
function create_each_block22(key_1, ctx2) {
  let tr;
  let td0;
  let t0_value = (
    /*event*/
    ctx2[5].date + ""
  );
  let t03;
  let t13;
  let td1;
  let t2_value = (
    /*event*/
    ctx2[5].description + ""
  );
  let t22;
  let t32;
  return {
    key: key_1,
    first: null,
    c() {
      tr = element("tr");
      td0 = element("td");
      t03 = text(t0_value);
      t13 = space();
      td1 = element("td");
      t22 = text(t2_value);
      t32 = space();
      this.first = tr;
    },
    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);
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & /*sorted_events*/
      2 && t0_value !== (t0_value = /*event*/
      ctx2[5].date + ""))
        set_data(t03, t0_value);
      if (dirty & /*sorted_events*/
      2 && t2_value !== (t2_value = /*event*/
      ctx2[5].description + ""))
        set_data(t22, t2_value);
    },
    d(detaching) {
      if (detaching) {
        detach(tr);
      }
    }
  };
}
function create_fragment42(ctx2) {
  let table;
  let thead;
  let tr;
  let t4;
  let tbody;
  let each_blocks = [];
  let each1_lookup = /* @__PURE__ */ new Map();
  let current;
  let each_value_1 = ensure_array_like(
    /*columns*/
    ctx2[2]
  );
  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));
  }
  const out2 = (i) => transition_out(each_blocks_1[i], 1, 1, () => {
    each_blocks_1[i] = null;
  });
  let each_value = ensure_array_like(
    /*sorted_events*/
    ctx2[1]
  );
  const get_key = (ctx3) => (
    /*event*/
    ctx3[5].date
  );
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context22(ctx2, each_value, i);
    let key2 = get_key(child_ctx);
    each1_lookup.set(key2, each_blocks[i] = create_each_block22(key2, child_ctx));
  }
  return {
    c() {
      table = 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();
      }
    },
    m(target, anchor) {
      insert(target, table, anchor);
      append(table, thead);
      append(thead, tr);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(tr, null);
        }
      }
      append(table, t4);
      append(table, tbody);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(tbody, null);
        }
      }
      current = true;
    },
    p(ctx3, [dirty]) {
      if (dirty & /*columns, sorter*/
      5) {
        each_value_1 = ensure_array_like(
          /*columns*/
          ctx3[2]
        );
        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);
            transition_in(each_blocks_1[i], 1);
          } else {
            each_blocks_1[i] = create_each_block_18(child_ctx);
            each_blocks_1[i].c();
            transition_in(each_blocks_1[i], 1);
            each_blocks_1[i].m(tr, null);
          }
        }
        group_outros();
        for (i = each_value_1.length; i < each_blocks_1.length; i += 1) {
          out2(i);
        }
        check_outros();
      }
      if (dirty & /*sorted_events*/
      2) {
        each_value = ensure_array_like(
          /*sorted_events*/
          ctx3[1]
        );
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx3, each_value, each1_lookup, tbody, destroy_block, create_each_block22, null, get_each_context22);
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks_1[i]);
      }
      current = true;
    },
    o(local) {
      each_blocks_1 = each_blocks_1.filter(Boolean);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        transition_out(each_blocks_1[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(table);
      }
      destroy_each(each_blocks_1, detaching);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
function instance43($$self, $$props, $$invalidate) {
  let sorted_events;
  let { events: events2 } = $$props;
  const columns3 = [
    new DateColumn(_("Date")),
    new StringColumn(_("Description"), (d) => d.description)
  ];
  let sorter = new Sorter(columns3[0], "desc");
  function sortheader_sorter_binding(value) {
    sorter = value;
    $$invalidate(0, sorter);
  }
  $$self.$$set = ($$props2) => {
    if ("events" in $$props2)
      $$invalidate(3, events2 = $$props2.events);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*sorter, events*/
    9) {
      $:
        $$invalidate(1, sorted_events = sorter.sort(events2));
    }
  };
  return [sorter, sorted_events, columns3, events2, sortheader_sorter_binding];
}
var EventTable = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance43, create_fragment42, safe_not_equal, { events: 3 });
  }
};
var EventTable_default = EventTable;

// src/reports/events/Events.svelte
function get_each_context23(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[3] = list[i][0];
  child_ctx[4] = list[i][1];
  return child_ctx;
}
function create_else_block6(ctx2) {
  let p;
  return {
    c() {
      p = element("p");
      p.textContent = `${_("No events.")}`;
    },
    m(target, anchor) {
      insert(target, p, anchor);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(p);
      }
    }
  };
}
function create_if_block20(ctx2) {
  let chartswitcher;
  let t4;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let each_1_anchor;
  let current;
  chartswitcher = new ChartSwitcher_default({ props: { charts: (
    /*charts*/
    ctx2[0]
  ) } });
  let each_value = ensure_array_like(
    /*groups*/
    ctx2[1]
  );
  const get_key = (ctx3) => (
    /*type*/
    ctx3[3]
  );
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context23(ctx2, each_value, i);
    let key2 = get_key(child_ctx);
    each_1_lookup.set(key2, each_blocks[i] = create_each_block23(key2, child_ctx));
  }
  return {
    c() {
      create_component(chartswitcher.$$.fragment);
      t4 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      mount_component(chartswitcher, target, anchor);
      insert(target, t4, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const chartswitcher_changes = {};
      if (dirty & /*charts*/
      1)
        chartswitcher_changes.charts = /*charts*/
        ctx3[0];
      chartswitcher.$set(chartswitcher_changes);
      if (dirty & /*groups*/
      2) {
        each_value = ensure_array_like(
          /*groups*/
          ctx3[1]
        );
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx3, each_value, each_1_lookup, each_1_anchor.parentNode, outro_and_destroy_block, create_each_block23, each_1_anchor, get_each_context23);
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(chartswitcher.$$.fragment, local);
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      transition_out(chartswitcher.$$.fragment, local);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t4);
        detach(each_1_anchor);
      }
      destroy_component(chartswitcher, detaching);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d(detaching);
      }
    }
  };
}
function create_each_block23(key_1, ctx2) {
  let div;
  let h3;
  let t0_value = format(_("Event: %(type)s"), { type: (
    /*type*/
    ctx2[3]
  ) }) + "";
  let t03;
  let t13;
  let eventtable;
  let t22;
  let current;
  eventtable = new EventTable_default({
    props: { events: (
      /*events_in_group*/
      ctx2[4]
    ) }
  });
  return {
    key: key_1,
    first: null,
    c() {
      div = element("div");
      h3 = element("h3");
      t03 = text(t0_value);
      t13 = space();
      create_component(eventtable.$$.fragment);
      t22 = space();
      attr(div, "class", "left");
      this.first = div;
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, h3);
      append(h3, t03);
      append(div, t13);
      mount_component(eventtable, div, null);
      append(div, t22);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if ((!current || dirty & /*groups*/
      2) && t0_value !== (t0_value = format(_("Event: %(type)s"), { type: (
        /*type*/
        ctx2[3]
      ) }) + ""))
        set_data(t03, t0_value);
      const eventtable_changes = {};
      if (dirty & /*groups*/
      2)
        eventtable_changes.events = /*events_in_group*/
        ctx2[4];
      eventtable.$set(eventtable_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(eventtable.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(eventtable.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      destroy_component(eventtable);
    }
  };
}
function create_fragment43(ctx2) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block20, create_else_block6];
  const if_blocks = [];
  function select_block_type(ctx3, dirty) {
    if (
      /*groups*/
      ctx3[1].length
    )
      return 0;
    return 1;
  }
  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 (detaching) {
        detach(if_block_anchor);
      }
      if_blocks[current_block_type_index].d(detaching);
    }
  };
}
function instance44($$self, $$props, $$invalidate) {
  let groups2;
  let charts;
  let { events: events2 } = $$props;
  $$self.$$set = ($$props2) => {
    if ("events" in $$props2)
      $$invalidate(2, events2 = $$props2.events);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*events*/
    4) {
      $:
        $$invalidate(1, groups2 = [...group(events2, (e3) => e3.type)]);
    }
    if ($$self.$$.dirty & /*events*/
    4) {
      $:
        $$invalidate(0, charts = [
          new ScatterPlot(_("Events"), events2.map(({ date: date4, type, description }) => ({ date: new Date(date4), type, description })))
        ]);
    }
  };
  return [charts, groups2, events2];
}
var Events2 = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance44, create_fragment43, safe_not_equal, { events: 2 });
  }
};
var Events_default = Events2;

// src/reports/events/index.ts
var events = new Route(
  "events",
  Events_default,
  (url) => get("events", getURLFilters(url)).then((data) => ({ events: data })),
  () => _("Events")
);

// src/entry-forms/AddMetadataButton.svelte
function create_fragment44(ctx2) {
  let button;
  let button_tabindex_value;
  let button_title_value;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      button.textContent = "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);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*addMetadata*/
          ctx2[0]
        );
        mounted = true;
      }
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      mounted = false;
      dispose();
    }
  };
}
function instance45($$self, $$props, $$invalidate) {
  let { meta: meta2 } = $$props;
  function addMetadata() {
    $$invalidate(1, meta2[""] = "", meta2);
    $$invalidate(1, meta2);
  }
  $$self.$$set = ($$props2) => {
    if ("meta" in $$props2)
      $$invalidate(1, meta2 = $$props2.meta);
  };
  return [addMetadata, meta2];
}
var AddMetadataButton = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance45, create_fragment44, 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_context24(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[8] = list[i];
  child_ctx[10] = i;
  return child_ctx;
}
function create_if_block21(ctx2) {
  let button;
  let button_title_value;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      button.textContent = "+";
      attr(button, "type", "button");
      attr(button, "class", "muted round");
      attr(button, "title", button_title_value = _("Add metadata"));
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*addMetadata*/
          ctx2[4]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_each_block24(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 (
      /*click_handler*/
      ctx2[5](
        /*metakey*/
        ctx2[8]
      )
    );
  }
  function change_handler(...args2) {
    return (
      /*change_handler*/
      ctx2[6](
        /*metakey*/
        ctx2[8],
        ...args2
      )
    );
  }
  function change_handler_1(...args2) {
    return (
      /*change_handler_1*/
      ctx2[7](
        /*metakey*/
        ctx2[8],
        ...args2
      )
    );
  }
  let if_block = (
    /*i*/
    ctx2[10] === /*metakeys*/
    ctx2[1].length - 1 && create_if_block21(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-1jx208h");
      attr(input0, "placeholder", input0_placeholder_value = _("Key"));
      input0.value = input0_value_value = /*metakey*/
      ctx2[8];
      input0.required = true;
      attr(input1, "type", "text");
      attr(input1, "class", "value svelte-1jx208h");
      attr(input1, "placeholder", input1_placeholder_value = _("Value"));
      input1.value = input1_value_value = metaValueToString(
        /*meta*/
        ctx2[0][
          /*metakey*/
          ctx2[8]
        ] ?? ""
      );
      attr(div, "class", "flex-row svelte-1jx208h");
    },
    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 & /*metakeys*/
      2 && input0_value_value !== (input0_value_value = /*metakey*/
      ctx2[8]) && input0.value !== input0_value_value) {
        input0.value = input0_value_value;
      }
      if (dirty & /*meta, metakeys*/
      3 && input1_value_value !== (input1_value_value = metaValueToString(
        /*meta*/
        ctx2[0][
          /*metakey*/
          ctx2[8]
        ] ?? ""
      )) && input1.value !== input1_value_value) {
        input1.value = input1_value_value;
      }
      if (
        /*i*/
        ctx2[10] === /*metakeys*/
        ctx2[1].length - 1
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block21(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_fragment45(ctx2) {
  let each_1_anchor;
  let each_value = ensure_array_like(
    /*metakeys*/
    ctx2[1]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block24(get_each_context24(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) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx3, [dirty]) {
      if (dirty & /*addMetadata, metakeys, meta, updateMetakey, removeMetadata*/
      31) {
        each_value = ensure_array_like(
          /*metakeys*/
          ctx3[1]
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context24(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block24(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) {
      if (detaching) {
        detach(each_1_anchor);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function instance46($$self, $$props, $$invalidate) {
  let metakeys;
  let { meta: meta2 } = $$props;
  function removeMetadata(metakey) {
    const { [metakey]: ignored, ...rest } = meta2;
    $$invalidate(0, meta2 = rest);
  }
  function updateMetakey(currentKey, newKey) {
    $$invalidate(0, meta2 = Object.keys(meta2).reduce(
      (m, key2) => {
        if (key2 === currentKey) {
          const val = meta2[currentKey];
          if (val !== void 0) {
            m[newKey] = val;
          }
        } else {
          const val = meta2[key2];
          if (val) {
            m[key2] = val;
          }
        }
        return m;
      },
      {}
    ));
  }
  function addMetadata() {
    $$invalidate(0, meta2[""] = "", meta2);
    $$invalidate(0, meta2);
  }
  const click_handler = (metakey) => {
    removeMetadata(metakey);
  };
  const change_handler = (metakey, event) => {
    updateMetakey(metakey, event.currentTarget.value);
  };
  const change_handler_1 = (metakey, event) => {
    $$invalidate(0, meta2[metakey] = stringToMetaValue(event.currentTarget.value), meta2);
  };
  $$self.$$set = ($$props2) => {
    if ("meta" in $$props2)
      $$invalidate(0, meta2 = $$props2.meta);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*meta*/
    1) {
      $:
        $$invalidate(1, metakeys = Object.keys(meta2).filter((key2) => !key2.startsWith("_") && key2 !== "filename" && key2 !== "lineno"));
    }
  };
  return [
    meta2,
    metakeys,
    removeMetadata,
    updateMetakey,
    addMetadata,
    click_handler,
    change_handler,
    change_handler_1
  ];
}
var EntryMetadata = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance46, create_fragment45, safe_not_equal, { meta: 0 });
  }
};
var EntryMetadata_default = EntryMetadata;

// src/entry-forms/Balance.svelte
function create_fragment46(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: (
      /*entry*/
      ctx2[0].date
    )
  };
  if (
    /*entry*/
    ctx2[0].account !== void 0
  ) {
    accountinput_props.value = /*entry*/
    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: (
      /*$currencies*/
      ctx2[1]
    )
  };
  if (
    /*entry*/
    ctx2[0].amount.currency !== void 0
  ) {
    autocompleteinput_props.value = /*entry*/
    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 (
    /*entry*/
    ctx2[0].meta !== void 0
  ) {
    addmetadatabutton_props.meta = /*entry*/
    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 (
    /*entry*/
    ctx2[0].meta !== void 0
  ) {
    entrymetadata_props.meta = /*entry*/
    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,
        /*entry*/
        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,
        /*entry*/
        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",
            /*input0_input_handler*/
            ctx2[2]
          ),
          listen(
            input1,
            "input",
            /*input1_input_handler*/
            ctx2[4]
          )
        ];
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & /*entry*/
      1) {
        set_input_value(
          input0,
          /*entry*/
          ctx3[0].date
        );
      }
      const accountinput_changes = {};
      if (dirty & /*entry*/
      1)
        accountinput_changes.date = /*entry*/
        ctx3[0].date;
      if (!updating_value && dirty & /*entry*/
      1) {
        updating_value = true;
        accountinput_changes.value = /*entry*/
        ctx3[0].account;
        add_flush_callback(() => updating_value = false);
      }
      accountinput.$set(accountinput_changes);
      if (dirty & /*entry*/
      1) {
        set_input_value(
          input1,
          /*entry*/
          ctx3[0].amount.number
        );
      }
      const autocompleteinput_changes = {};
      if (dirty & /*$currencies*/
      2)
        autocompleteinput_changes.suggestions = /*$currencies*/
        ctx3[1];
      if (!updating_value_1 && dirty & /*entry*/
      1) {
        updating_value_1 = true;
        autocompleteinput_changes.value = /*entry*/
        ctx3[0].amount.currency;
        add_flush_callback(() => updating_value_1 = false);
      }
      autocompleteinput.$set(autocompleteinput_changes);
      const addmetadatabutton_changes = {};
      if (!updating_meta && dirty & /*entry*/
      1) {
        updating_meta = true;
        addmetadatabutton_changes.meta = /*entry*/
        ctx3[0].meta;
        add_flush_callback(() => updating_meta = false);
      }
      addmetadatabutton.$set(addmetadatabutton_changes);
      const entrymetadata_changes = {};
      if (!updating_meta_1 && dirty & /*entry*/
      1) {
        updating_meta_1 = true;
        entrymetadata_changes.meta = /*entry*/
        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 instance47($$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(options3) {
    super();
    init2(this, options3, instance47, create_fragment46, safe_not_equal, { entry: 0 });
  }
};
var Balance_default = Balance2;

// src/entry-forms/Note.svelte
function create_fragment47(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: (
      /*entry*/
      ctx2[0].date
    )
  };
  if (
    /*entry*/
    ctx2[0].account !== void 0
  ) {
    accountinput_props.value = /*entry*/
    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 (
    /*entry*/
    ctx2[0].meta !== void 0
  ) {
    addmetadatabutton_props.meta = /*entry*/
    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 (
    /*entry*/
    ctx2[0].meta !== void 0
  ) {
    entrymetadata_props.meta = /*entry*/
    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,
        /*entry*/
        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,
        /*entry*/
        ctx2[0].comment
      );
      append(div1, t5);
      mount_component(entrymetadata, div1, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            input,
            "input",
            /*input_input_handler*/
            ctx2[1]
          ),
          listen(
            textarea,
            "input",
            /*textarea_input_handler*/
            ctx2[4]
          )
        ];
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & /*entry*/
      1) {
        set_input_value(
          input,
          /*entry*/
          ctx3[0].date
        );
      }
      const accountinput_changes = {};
      if (dirty & /*entry*/
      1)
        accountinput_changes.date = /*entry*/
        ctx3[0].date;
      if (!updating_value && dirty & /*entry*/
      1) {
        updating_value = true;
        accountinput_changes.value = /*entry*/
        ctx3[0].account;
        add_flush_callback(() => updating_value = false);
      }
      accountinput.$set(accountinput_changes);
      const addmetadatabutton_changes = {};
      if (!updating_meta && dirty & /*entry*/
      1) {
        updating_meta = true;
        addmetadatabutton_changes.meta = /*entry*/
        ctx3[0].meta;
        add_flush_callback(() => updating_meta = false);
      }
      addmetadatabutton.$set(addmetadatabutton_changes);
      if (dirty & /*entry*/
      1) {
        set_input_value(
          textarea,
          /*entry*/
          ctx3[0].comment
        );
      }
      const entrymetadata_changes = {};
      if (!updating_meta_1 && dirty & /*entry*/
      1) {
        updating_meta_1 = true;
        entrymetadata_changes.meta = /*entry*/
        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 instance48($$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(options3) {
    super();
    init2(this, options3, instance48, create_fragment47, safe_not_equal, { entry: 0 });
  }
};
var Note_default = Note2;

// src/entry-forms/Posting.svelte
function create_fragment48(ctx2) {
  let div;
  let button;
  let button_tabindex_value;
  let t13;
  let accountinput;
  let updating_value;
  let t22;
  let autocompleteinput;
  let updating_value_1;
  let t32;
  let addmetadatabutton;
  let updating_meta;
  let t4;
  let entrymetadata;
  let updating_meta_1;
  let current;
  let mounted;
  let dispose;
  function accountinput_value_binding(value) {
    ctx2[16](value);
  }
  let accountinput_props = {
    className: "grow",
    suggestions: (
      /*suggestions*/
      ctx2[1]
    ),
    date: (
      /*date*/
      ctx2[2]
    )
  };
  if (
    /*posting*/
    ctx2[0].account !== void 0
  ) {
    accountinput_props.value = /*posting*/
    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[17](value);
  }
  let autocompleteinput_props = {
    className: "amount",
    placeholder: _("Amount"),
    suggestions: (
      /*amountSuggestions*/
      ctx2[6]
    )
  };
  if (
    /*posting*/
    ctx2[0].amount !== void 0
  ) {
    autocompleteinput_props.value = /*posting*/
    ctx2[0].amount;
  }
  autocompleteinput = new AutocompleteInput_default({ props: autocompleteinput_props });
  binding_callbacks.push(() => bind(autocompleteinput, "value", autocompleteinput_value_binding));
  function addmetadatabutton_meta_binding(value) {
    ctx2[18](value);
  }
  let addmetadatabutton_props = {};
  if (
    /*posting*/
    ctx2[0].meta !== void 0
  ) {
    addmetadatabutton_props.meta = /*posting*/
    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[19](value);
  }
  let entrymetadata_props = {};
  if (
    /*posting*/
    ctx2[0].meta !== void 0
  ) {
    entrymetadata_props.meta = /*posting*/
    ctx2[0].meta;
  }
  entrymetadata = new EntryMetadata_default({ props: entrymetadata_props });
  binding_callbacks.push(() => bind(entrymetadata, "meta", entrymetadata_meta_binding));
  return {
    c() {
      div = element("div");
      button = element("button");
      button.textContent = "\xD7";
      t13 = space();
      create_component(accountinput.$$.fragment);
      t22 = space();
      create_component(autocompleteinput.$$.fragment);
      t32 = space();
      create_component(addmetadatabutton.$$.fragment);
      t4 = space();
      create_component(entrymetadata.$$.fragment);
      attr(button, "type", "button");
      attr(button, "class", "muted round remove-row svelte-192x5jl");
      attr(button, "tabindex", button_tabindex_value = -1);
      attr(div, "class", "flex-row svelte-192x5jl");
      attr(
        div,
        "draggable",
        /*draggable*/
        ctx2[5]
      );
      attr(div, "role", "group");
      toggle_class(
        div,
        "drag",
        /*drag*/
        ctx2[4]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, button);
      append(div, t13);
      mount_component(accountinput, div, null);
      append(div, t22);
      mount_component(autocompleteinput, div, null);
      append(div, t32);
      mount_component(addmetadatabutton, div, null);
      append(div, t4);
      mount_component(entrymetadata, div, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(button, "click", function() {
            if (is_function(
              /*remove*/
              ctx2[3]
            ))
              ctx2[3].apply(this, arguments);
          }),
          listen(
            div,
            "mousemove",
            /*mousemove*/
            ctx2[7]
          ),
          listen(
            div,
            "dragstart",
            /*dragstart*/
            ctx2[8]
          ),
          listen(
            div,
            "dragenter",
            /*dragenter*/
            ctx2[9]
          ),
          listen(
            div,
            "dragover",
            /*dragenter*/
            ctx2[9]
          ),
          listen(
            div,
            "dragleave",
            /*dragleave*/
            ctx2[10]
          ),
          listen(div, "drop", prevent_default(
            /*drop*/
            ctx2[11]
          ))
        ];
        mounted = true;
      }
    },
    p(new_ctx, [dirty]) {
      ctx2 = new_ctx;
      const accountinput_changes = {};
      if (dirty & /*suggestions*/
      2)
        accountinput_changes.suggestions = /*suggestions*/
        ctx2[1];
      if (dirty & /*date*/
      4)
        accountinput_changes.date = /*date*/
        ctx2[2];
      if (!updating_value && dirty & /*posting*/
      1) {
        updating_value = true;
        accountinput_changes.value = /*posting*/
        ctx2[0].account;
        add_flush_callback(() => updating_value = false);
      }
      accountinput.$set(accountinput_changes);
      const autocompleteinput_changes = {};
      if (dirty & /*amountSuggestions*/
      64)
        autocompleteinput_changes.suggestions = /*amountSuggestions*/
        ctx2[6];
      if (!updating_value_1 && dirty & /*posting*/
      1) {
        updating_value_1 = true;
        autocompleteinput_changes.value = /*posting*/
        ctx2[0].amount;
        add_flush_callback(() => updating_value_1 = false);
      }
      autocompleteinput.$set(autocompleteinput_changes);
      const addmetadatabutton_changes = {};
      if (!updating_meta && dirty & /*posting*/
      1) {
        updating_meta = true;
        addmetadatabutton_changes.meta = /*posting*/
        ctx2[0].meta;
        add_flush_callback(() => updating_meta = false);
      }
      addmetadatabutton.$set(addmetadatabutton_changes);
      const entrymetadata_changes = {};
      if (!updating_meta_1 && dirty & /*posting*/
      1) {
        updating_meta_1 = true;
        entrymetadata_changes.meta = /*posting*/
        ctx2[0].meta;
        add_flush_callback(() => updating_meta_1 = false);
      }
      entrymetadata.$set(entrymetadata_changes);
      if (!current || dirty & /*draggable*/
      32) {
        attr(
          div,
          "draggable",
          /*draggable*/
          ctx2[5]
        );
      }
      if (!current || dirty & /*drag*/
      16) {
        toggle_class(
          div,
          "drag",
          /*drag*/
          ctx2[4]
        );
      }
    },
    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(div);
      }
      destroy_component(accountinput);
      destroy_component(autocompleteinput);
      destroy_component(addmetadatabutton);
      destroy_component(entrymetadata);
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance49($$self, $$props, $$invalidate) {
  let amount_number;
  let amountSuggestions;
  let $currencies;
  component_subscribe($$self, currencies, ($$value) => $$invalidate(15, $currencies = $$value));
  let { posting } = $$props;
  let { index: index2 } = $$props;
  let { suggestions } = $$props;
  let { date: date4 } = $$props;
  let { move } = $$props;
  let { remove: remove3 } = $$props;
  let drag = false;
  let draggable = true;
  function mousemove(event) {
    $$invalidate(5, draggable = !(event.target instanceof HTMLInputElement));
  }
  function dragstart(event) {
    event.dataTransfer?.setData("fava/posting", `${index2}`);
  }
  function dragenter(event) {
    if (event.dataTransfer?.types.includes("fava/posting")) {
      event.preventDefault();
      $$invalidate(4, drag = true);
    }
  }
  function dragleave2() {
    $$invalidate(4, drag = false);
  }
  function drop2(event) {
    const from = event.dataTransfer?.getData("fava/posting");
    if (from) {
      move({ from: +from, to: index2 });
      $$invalidate(4, 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);
    }
  }
  function addmetadatabutton_meta_binding(value) {
    if ($$self.$$.not_equal(posting.meta, value)) {
      posting.meta = value;
      $$invalidate(0, posting);
    }
  }
  function entrymetadata_meta_binding(value) {
    if ($$self.$$.not_equal(posting.meta, value)) {
      posting.meta = value;
      $$invalidate(0, posting);
    }
  }
  $$self.$$set = ($$props2) => {
    if ("posting" in $$props2)
      $$invalidate(0, posting = $$props2.posting);
    if ("index" in $$props2)
      $$invalidate(12, index2 = $$props2.index);
    if ("suggestions" in $$props2)
      $$invalidate(1, suggestions = $$props2.suggestions);
    if ("date" in $$props2)
      $$invalidate(2, date4 = $$props2.date);
    if ("move" in $$props2)
      $$invalidate(13, move = $$props2.move);
    if ("remove" in $$props2)
      $$invalidate(3, remove3 = $$props2.remove);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*posting*/
    1) {
      $:
        $$invalidate(14, amount_number = posting.amount.replace(/[^\-?0-9.]/g, ""));
    }
    if ($$self.$$.dirty & /*$currencies, amount_number*/
    49152) {
      $:
        $$invalidate(6, amountSuggestions = $currencies.map((c) => `${amount_number} ${c}`));
    }
  };
  return [
    posting,
    suggestions,
    date4,
    remove3,
    drag,
    draggable,
    amountSuggestions,
    mousemove,
    dragstart,
    dragenter,
    dragleave2,
    drop2,
    index2,
    move,
    amount_number,
    $currencies,
    accountinput_value_binding,
    autocompleteinput_value_binding,
    addmetadatabutton_meta_binding,
    entrymetadata_meta_binding
  ];
}
var Posting2 = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance49, create_fragment48, safe_not_equal, {
      posting: 0,
      index: 12,
      suggestions: 1,
      date: 2,
      move: 13,
      remove: 3
    });
  }
};
var Posting_default = Posting2;

// src/entry-forms/Transaction.svelte
function get_each_context25(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_each_block25(ctx2) {
  let postingsvelte;
  let updating_posting;
  let current;
  function func3() {
    return (
      /*func*/
      ctx2[14](
        /*posting*/
        ctx2[16]
      )
    );
  }
  function postingsvelte_posting_binding(value) {
    ctx2[15](
      value,
      /*posting*/
      ctx2[16],
      /*each_value*/
      ctx2[17],
      /*index*/
      ctx2[18]
    );
  }
  let postingsvelte_props = {
    index: (
      /*index*/
      ctx2[18]
    ),
    suggestions: (
      /*suggestions*/
      ctx2[2]
    ),
    date: (
      /*entry*/
      ctx2[0].date
    ),
    move: (
      /*movePosting*/
      ctx2[7]
    ),
    remove: func3
  };
  if (
    /*posting*/
    ctx2[16] !== void 0
  ) {
    postingsvelte_props.posting = /*posting*/
    ctx2[16];
  }
  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 & /*suggestions*/
      4)
        postingsvelte_changes.suggestions = /*suggestions*/
        ctx2[2];
      if (dirty & /*entry*/
      1)
        postingsvelte_changes.date = /*entry*/
        ctx2[0].date;
      if (dirty & /*entry*/
      1)
        postingsvelte_changes.remove = func3;
      if (!updating_posting && dirty & /*entry*/
      1) {
        updating_posting = true;
        postingsvelte_changes.posting = /*posting*/
        ctx2[16];
        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_fragment49(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 entrymetadata;
  let updating_meta_1;
  let t11;
  let div1;
  let span3;
  let span2;
  let t14;
  let current;
  let mounted;
  let dispose;
  function autocompleteinput_value_binding(value) {
    ctx2[11](value);
  }
  let autocompleteinput_props = {
    className: "payee",
    placeholder: _("Payee"),
    suggestions: (
      /*$payees*/
      ctx2[1]
    )
  };
  if (
    /*entry*/
    ctx2[0].payee !== void 0
  ) {
    autocompleteinput_props.value = /*entry*/
    ctx2[0].payee;
  }
  autocompleteinput = new AutocompleteInput_default({ props: autocompleteinput_props });
  binding_callbacks.push(() => bind(autocompleteinput, "value", autocompleteinput_value_binding));
  autocompleteinput.$on(
    "select",
    /*autocompleteSelectPayee*/
    ctx2[6]
  );
  function addmetadatabutton_meta_binding(value) {
    ctx2[12](value);
  }
  let addmetadatabutton_props = {};
  if (
    /*entry*/
    ctx2[0].meta !== void 0
  ) {
    addmetadatabutton_props.meta = /*entry*/
    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[13](value);
  }
  let entrymetadata_props = {};
  if (
    /*entry*/
    ctx2[0].meta !== void 0
  ) {
    entrymetadata_props.meta = /*entry*/
    ctx2[0].meta;
  }
  entrymetadata = new EntryMetadata_default({ props: entrymetadata_props });
  binding_callbacks.push(() => bind(entrymetadata, "meta", entrymetadata_meta_binding));
  let each_value = ensure_array_like(
    /*entry*/
    ctx2[0].postings
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block25(get_each_context25(ctx2, each_value, i));
  }
  const out2 = (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();
      create_component(entrymetadata.$$.fragment);
      t11 = space();
      div1 = element("div");
      span3 = element("span");
      span2 = element("span");
      span2.textContent = `${_("Postings")}:`;
      t14 = 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-1y4x27n");
      attr(span0, "class", "svelte-1y4x27n");
      attr(label0, "class", "svelte-1y4x27n");
      attr(span1, "class", "svelte-1y4x27n");
      attr(input2, "type", "text");
      attr(input2, "name", "narration");
      attr(input2, "placeholder", input2_placeholder_value = _("Narration"));
      input2.value = /*narration*/
      ctx2[3];
      attr(input2, "class", "svelte-1y4x27n");
      attr(label1, "class", "svelte-1y4x27n");
      attr(div0, "class", "flex-row svelte-1y4x27n");
      attr(span2, "class", "svelte-1y4x27n");
      attr(span3, "class", "label svelte-1y4x27n");
      attr(div1, "class", "flex-row svelte-1y4x27n");
      attr(div2, "class", "svelte-1y4x27n");
    },
    m(target, anchor) {
      insert(target, div2, anchor);
      append(div2, div0);
      append(div0, input0);
      set_input_value(
        input0,
        /*entry*/
        ctx2[0].date
      );
      append(div0, t03);
      append(div0, input1);
      set_input_value(
        input1,
        /*entry*/
        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(div2, t10);
      mount_component(entrymetadata, div2, null);
      append(div2, t11);
      append(div2, div1);
      append(div1, span3);
      append(span3, span2);
      append(div2, t14);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div2, null);
        }
      }
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            input0,
            "input",
            /*input0_input_handler*/
            ctx2[9]
          ),
          listen(
            input1,
            "input",
            /*input1_input_handler*/
            ctx2[10]
          ),
          listen(
            input2,
            "change",
            /*onNarrationChange*/
            ctx2[5]
          )
        ];
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & /*entry*/
      1) {
        set_input_value(
          input0,
          /*entry*/
          ctx3[0].date
        );
      }
      if (dirty & /*entry*/
      1 && input1.value !== /*entry*/
      ctx3[0].flag) {
        set_input_value(
          input1,
          /*entry*/
          ctx3[0].flag
        );
      }
      const autocompleteinput_changes = {};
      if (dirty & /*$payees*/
      2)
        autocompleteinput_changes.suggestions = /*$payees*/
        ctx3[1];
      if (!updating_value && dirty & /*entry*/
      1) {
        updating_value = true;
        autocompleteinput_changes.value = /*entry*/
        ctx3[0].payee;
        add_flush_callback(() => updating_value = false);
      }
      autocompleteinput.$set(autocompleteinput_changes);
      if (!current || dirty & /*narration*/
      8 && input2.value !== /*narration*/
      ctx3[3]) {
        input2.value = /*narration*/
        ctx3[3];
      }
      const addmetadatabutton_changes = {};
      if (!updating_meta && dirty & /*entry*/
      1) {
        updating_meta = true;
        addmetadatabutton_changes.meta = /*entry*/
        ctx3[0].meta;
        add_flush_callback(() => updating_meta = false);
      }
      addmetadatabutton.$set(addmetadatabutton_changes);
      const entrymetadata_changes = {};
      if (!updating_meta_1 && dirty & /*entry*/
      1) {
        updating_meta_1 = true;
        entrymetadata_changes.meta = /*entry*/
        ctx3[0].meta;
        add_flush_callback(() => updating_meta_1 = false);
      }
      entrymetadata.$set(entrymetadata_changes);
      if (dirty & /*suggestions, entry, movePosting, removePosting*/
      149) {
        each_value = ensure_array_like(
          /*entry*/
          ctx3[0].postings
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context25(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_block25(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) {
          out2(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 instance50($$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 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 });
    data.date = entry.date;
    $$invalidate(0, entry = data);
  }
  function movePosting({ from, to }) {
    const moved = entry.postings[from];
    if (moved) {
      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 func3 = (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 & /*entry*/
    1) {
      $:
        if (!entry.postings.some((p) => p.is_empty())) {
          $$invalidate(0, entry.postings = entry.postings.concat(new Posting()), entry);
        }
    }
    if ($$self.$$.dirty & /*entry*/
    1) {
      $:
        $$invalidate(8, payee = entry.payee);
    }
    if ($$self.$$.dirty & /*payee, $payees*/
    258) {
      $:
        if (payee) {
          $$invalidate(2, suggestions = void 0);
          if ($payees.includes(payee)) {
            get("payee_accounts", { payee }).then((s) => {
              $$invalidate(2, suggestions = s);
            }).catch((error2) => {
              notify_err(error2, (err3) => `Fetching account suggestions for payee ${payee} failed: ${err3.message}`);
            });
          }
        }
    }
    if ($$self.$$.dirty & /*entry*/
    1) {
      $:
        $$invalidate(3, narration = combineNarrationTagsLinks(entry));
    }
  };
  return [
    entry,
    $payees,
    suggestions,
    narration,
    removePosting,
    onNarrationChange,
    autocompleteSelectPayee,
    movePosting,
    payee,
    input0_input_handler,
    input1_input_handler,
    autocompleteinput_value_binding,
    addmetadatabutton_meta_binding,
    entrymetadata_meta_binding,
    func3,
    postingsvelte_posting_binding
  ];
}
var Transaction3 = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance50, create_fragment49, safe_not_equal, { entry: 0 });
  }
};
var Transaction_default = Transaction3;

// src/entry-forms/Entry.svelte
function create_else_block7(ctx2) {
  let t4;
  return {
    c() {
      t4 = text("Entry type unsupported for editing.");
    },
    m(target, anchor) {
      insert(target, t4, anchor);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(t4);
      }
    }
  };
}
function create_if_block_28(ctx2) {
  let transactionsvelte;
  let updating_entry;
  let current;
  function transactionsvelte_entry_binding(value) {
    ctx2[3](value);
  }
  let transactionsvelte_props = {};
  if (
    /*entry*/
    ctx2[0] !== void 0
  ) {
    transactionsvelte_props.entry = /*entry*/
    ctx2[0];
  }
  transactionsvelte = new Transaction_default({ props: transactionsvelte_props });
  binding_callbacks.push(() => bind(transactionsvelte, "entry", transactionsvelte_entry_binding));
  return {
    c() {
      create_component(transactionsvelte.$$.fragment);
    },
    m(target, anchor) {
      mount_component(transactionsvelte, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const transactionsvelte_changes = {};
      if (!updating_entry && dirty & /*entry*/
      1) {
        updating_entry = true;
        transactionsvelte_changes.entry = /*entry*/
        ctx3[0];
        add_flush_callback(() => updating_entry = false);
      }
      transactionsvelte.$set(transactionsvelte_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(transactionsvelte.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(transactionsvelte.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(transactionsvelte, detaching);
    }
  };
}
function create_if_block_113(ctx2) {
  let notesvelte;
  let updating_entry;
  let current;
  function notesvelte_entry_binding(value) {
    ctx2[2](value);
  }
  let notesvelte_props = {};
  if (
    /*entry*/
    ctx2[0] !== void 0
  ) {
    notesvelte_props.entry = /*entry*/
    ctx2[0];
  }
  notesvelte = new Note_default({ props: notesvelte_props });
  binding_callbacks.push(() => bind(notesvelte, "entry", notesvelte_entry_binding));
  return {
    c() {
      create_component(notesvelte.$$.fragment);
    },
    m(target, anchor) {
      mount_component(notesvelte, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const notesvelte_changes = {};
      if (!updating_entry && dirty & /*entry*/
      1) {
        updating_entry = true;
        notesvelte_changes.entry = /*entry*/
        ctx3[0];
        add_flush_callback(() => updating_entry = false);
      }
      notesvelte.$set(notesvelte_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(notesvelte.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(notesvelte.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(notesvelte, detaching);
    }
  };
}
function create_if_block22(ctx2) {
  let balancesvelte;
  let updating_entry;
  let current;
  function balancesvelte_entry_binding(value) {
    ctx2[1](value);
  }
  let balancesvelte_props = {};
  if (
    /*entry*/
    ctx2[0] !== void 0
  ) {
    balancesvelte_props.entry = /*entry*/
    ctx2[0];
  }
  balancesvelte = new Balance_default({ props: balancesvelte_props });
  binding_callbacks.push(() => bind(balancesvelte, "entry", balancesvelte_entry_binding));
  return {
    c() {
      create_component(balancesvelte.$$.fragment);
    },
    m(target, anchor) {
      mount_component(balancesvelte, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const balancesvelte_changes = {};
      if (!updating_entry && dirty & /*entry*/
      1) {
        updating_entry = true;
        balancesvelte_changes.entry = /*entry*/
        ctx3[0];
        add_flush_callback(() => updating_entry = false);
      }
      balancesvelte.$set(balancesvelte_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(balancesvelte.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(balancesvelte.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(balancesvelte, detaching);
    }
  };
}
function create_fragment50(ctx2) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block22, create_if_block_113, create_if_block_28, create_else_block7];
  const if_blocks = [];
  function select_block_type(ctx3, dirty) {
    if (
      /*entry*/
      ctx3[0] instanceof Balance
    )
      return 0;
    if (
      /*entry*/
      ctx3[0] instanceof Note
    )
      return 1;
    if (
      /*entry*/
      ctx3[0] instanceof Transaction
    )
      return 2;
    return 3;
  }
  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 (detaching) {
        detach(if_block_anchor);
      }
      if_blocks[current_block_type_index].d(detaching);
    }
  };
}
function instance51($$self, $$props, $$invalidate) {
  let { entry } = $$props;
  function balancesvelte_entry_binding(value) {
    entry = value;
    $$invalidate(0, entry);
  }
  function notesvelte_entry_binding(value) {
    entry = value;
    $$invalidate(0, entry);
  }
  function transactionsvelte_entry_binding(value) {
    entry = value;
    $$invalidate(0, entry);
  }
  $$self.$$set = ($$props2) => {
    if ("entry" in $$props2)
      $$invalidate(0, entry = $$props2.entry);
  };
  return [
    entry,
    balancesvelte_entry_binding,
    notesvelte_entry_binding,
    transactionsvelte_entry_binding
  ];
}
var Entry = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance51, create_fragment50, safe_not_equal, { entry: 0 });
  }
};
var Entry_default = Entry;

// src/reports/import/Extract.svelte
function create_if_block23(ctx2) {
  let div0;
  let h3;
  let t03;
  let t1_value = (
    /*currentIndex*/
    ctx2[2] + 1 + ""
  );
  let t13;
  let t22;
  let t3_value = (
    /*entries*/
    ctx2[0].length + ""
  );
  let t32;
  let t4;
  let t5_value = (
    /*entries*/
    ctx2[0].length - /*duplicates*/
    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 (
    /*entry*/
    ctx2[3] !== void 0
  ) {
    entry_1_props.entry = /*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 = (
    /*currentIndex*/
    ctx2[2] > 0 && create_if_block_43(ctx2)
  );
  function select_block_type(ctx3, dirty) {
    if (
      /*currentIndex*/
      ctx3[2] < /*entries*/
      ctx3[0].length - 1
    )
      return create_if_block_36;
    return create_else_block8;
  }
  let current_block_type = select_block_type(ctx2, -1);
  let if_block1 = current_block_type(ctx2);
  let if_block2 = (
    /*entry*/
    ctx2[3].meta.__source__ && create_if_block_114(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 = /*duplicate*/
      ctx2[5];
      attr(label, "class", "button muted");
      attr(div0, "class", "flex-row");
      attr(div1, "class", "svelte-kordbm");
      toggle_class(
        div1,
        "duplicate",
        /*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",
          /*toggleDuplicate*/
          ctx2[9]
        );
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if ((!current || dirty & /*currentIndex*/
      4) && t1_value !== (t1_value = /*currentIndex*/
      ctx3[2] + 1 + ""))
        set_data(t13, t1_value);
      if ((!current || dirty & /*entries*/
      1) && t3_value !== (t3_value = /*entries*/
      ctx3[0].length + ""))
        set_data(t32, t3_value);
      if ((!current || dirty & /*entries, duplicates*/
      17) && t5_value !== (t5_value = /*entries*/
      ctx3[0].length - /*duplicates*/
      ctx3[4] + ""))
        set_data(t5, t5_value);
      if (!current || dirty & /*duplicate*/
      32) {
        input.checked = /*duplicate*/
        ctx3[5];
      }
      const entry_1_changes = {};
      if (!updating_entry && dirty & /*entry*/
      8) {
        updating_entry = true;
        entry_1_changes.entry = /*entry*/
        ctx3[3];
        add_flush_callback(() => updating_entry = false);
      }
      entry_1.$set(entry_1_changes);
      if (!current || dirty & /*duplicate*/
      32) {
        toggle_class(
          div1,
          "duplicate",
          /*duplicate*/
          ctx3[5]
        );
      }
      if (
        /*currentIndex*/
        ctx3[2] > 0
      ) {
        if (if_block0) {
          if_block0.p(ctx3, dirty);
        } else {
          if_block0 = create_if_block_43(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 (
        /*entry*/
        ctx3[3].meta.__source__
      ) {
        if (if_block2) {
          if_block2.p(ctx3, dirty);
        } else {
          if_block2 = create_if_block_114(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);
        detach(t10);
        detach(div1);
        detach(t11);
        detach(div2);
        detach(t14);
        detach(hr);
        detach(t15);
        detach(if_block2_anchor);
      }
      destroy_component(entry_1);
      if (if_block0)
        if_block0.d();
      if_block1.d();
      if (if_block2)
        if_block2.d(detaching);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_43(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",
            /*click_handler*/
            ctx2[12]
          ),
          listen(
            button1,
            "click",
            /*previousEntry*/
            ctx2[8]
          )
        ];
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching) {
        detach(button0);
        detach(t13);
        detach(button1);
      }
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_else_block8(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_36(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",
          /*click_handler_1*/
          ctx2[13]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching) {
        detach(button0);
        detach(t13);
        detach(button1);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_114(ctx2) {
  let h3;
  let t0_value = _("Source") + "";
  let t03;
  let t13;
  let t22;
  let pre;
  let t3_value = (
    /*entry*/
    ctx2[3].meta.__source__ + ""
  );
  let t32;
  let if_block = (
    /*entry*/
    ctx2[3].meta.lineno && create_if_block_29(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 (
        /*entry*/
        ctx3[3].meta.lineno
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block_29(ctx3);
          if_block.c();
          if_block.m(h3, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty & /*entry*/
      8 && t3_value !== (t3_value = /*entry*/
      ctx3[3].meta.__source__ + ""))
        set_data(t32, t3_value);
    },
    d(detaching) {
      if (detaching) {
        detach(h3);
        detach(t22);
        detach(pre);
      }
      if (if_block)
        if_block.d();
    }
  };
}
function create_if_block_29(ctx2) {
  let t03;
  let t1_value = _("Line") + "";
  let t13;
  let t22;
  let t3_value = (
    /*entry*/
    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 & /*entry*/
      8 && t3_value !== (t3_value = /*entry*/
      ctx3[3].meta.lineno + ""))
        set_data(t32, t3_value);
    },
    d(detaching) {
      if (detaching) {
        detach(t03);
        detach(t13);
        detach(t22);
        detach(t32);
        detach(t4);
      }
    }
  };
}
function create_default_slot5(ctx2) {
  let form;
  let h3;
  let t13;
  let current;
  let mounted;
  let dispose;
  let if_block = (
    /*entry*/
    ctx2[3] && create_if_block23(ctx2)
  );
  return {
    c() {
      form = element("form");
      h3 = element("h3");
      h3.textContent = `${_("Import")}`;
      t13 = space();
      if (if_block)
        if_block.c();
      form.noValidate = /*duplicate*/
      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(
          /*submitOrNext*/
          ctx2[7]
        ));
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if (
        /*entry*/
        ctx3[3]
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & /*entry*/
          8) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block23(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 & /*duplicate*/
      32) {
        form.noValidate = /*duplicate*/
        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_fragment51(ctx2) {
  let modalbase;
  let current;
  modalbase = new ModalBase_default({
    props: {
      shown: (
        /*shown*/
        ctx2[6]
      ),
      closeHandler: (
        /*close*/
        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 & /*shown*/
      64)
        modalbase_changes.shown = /*shown*/
        ctx3[6];
      if (dirty & /*close*/
      2)
        modalbase_changes.closeHandler = /*close*/
        ctx3[1];
      if (dirty & /*$$scope, duplicate, entry, currentIndex, entries, duplicates*/
      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 instance52($$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() {
    if (entry) {
      $$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 & /*entries*/
    1) {
      $:
        $$invalidate(6, shown = entries.length > 0);
    }
    if ($$self.$$.dirty & /*entries, currentIndex*/
    5) {
      $:
        if (entries.length > 0 && currentIndex >= entries.length) {
          $$invalidate(2, currentIndex = 0);
        }
    }
    if ($$self.$$.dirty & /*entries, currentIndex*/
    5) {
      $:
        $$invalidate(3, entry = entries[currentIndex]);
    }
    if ($$self.$$.dirty & /*entry*/
    8) {
      $:
        $$invalidate(5, duplicate = entry && isDuplicate(entry));
    }
    if ($$self.$$.dirty & /*entries*/
    1) {
      $:
        $$invalidate(4, duplicates = entries.filter(isDuplicate).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(options3) {
    super();
    init2(this, options3, instance52, create_fragment51, safe_not_equal, { entries: 0, save: 10, close: 1 });
  }
};
var Extract_default = Extract;

// src/reports/import/FileList.svelte
function get_each_context26(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[13] = list[i];
  return child_ctx;
}
function get_each_context_19(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_block24(ctx2) {
  let button;
  let t0_value = (
    /*extractCache*/
    (ctx2[1].get(`${/*file*/
    ctx2[13].name}:${/*info*/
    ctx2[16].importer_name}`) ? _("Continue") : _("Extract")) + ""
  );
  let t03;
  let button_title_value;
  let t13;
  let show_if = (
    /*extractCache*/
    ctx2[1].get(`${/*file*/
    ctx2[13].name}:${/*info*/
    ctx2[16].importer_name}`)
  );
  let t22;
  let t3_value = (
    /*info*/
    ctx2[16].importer_name + ""
  );
  let t32;
  let mounted;
  let dispose;
  function click_handler_3() {
    return (
      /*click_handler_3*/
      ctx2[11](
        /*file*/
        ctx2[13],
        /*info*/
        ctx2[16]
      )
    );
  }
  let if_block = show_if && create_if_block_115(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 " + /*info*/
      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 & /*extractCache, files*/
      3 && t0_value !== (t0_value = /*extractCache*/
      (ctx2[1].get(`${/*file*/
      ctx2[13].name}:${/*info*/
      ctx2[16].importer_name}`) ? _("Continue") : _("Extract")) + ""))
        set_data(t03, t0_value);
      if (dirty & /*files*/
      1 && button_title_value !== (button_title_value = _("Extract") + " with importer " + /*info*/
      ctx2[16].importer_name)) {
        attr(button, "title", button_title_value);
      }
      if (dirty & /*extractCache, files*/
      3)
        show_if = /*extractCache*/
        ctx2[1].get(`${/*file*/
        ctx2[13].name}:${/*info*/
        ctx2[16].importer_name}`);
      if (show_if) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_115(ctx2);
          if_block.c();
          if_block.m(t22.parentNode, t22);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty & /*files*/
      1 && t3_value !== (t3_value = /*info*/
      ctx2[16].importer_name + ""))
        set_data(t32, t3_value);
    },
    d(detaching) {
      if (detaching) {
        detach(button);
        detach(t13);
        detach(t22);
        detach(t32);
      }
      if (if_block)
        if_block.d(detaching);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_115(ctx2) {
  let button;
  let mounted;
  let dispose;
  function click_handler_4() {
    return (
      /*click_handler_4*/
      ctx2[12](
        /*file*/
        ctx2[13],
        /*info*/
        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_19(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,
      /*info*/
      ctx2[16]
    );
  }
  let accountinput_props = {};
  if (
    /*info*/
    ctx2[16].account !== void 0
  ) {
    accountinput_props.value = /*info*/
    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,
      /*each_value_1*/
      ctx2[17],
      /*info_index*/
      ctx2[18]
    );
  }
  function click_handler_2() {
    return (
      /*click_handler_2*/
      ctx2[10](
        /*file*/
        ctx2[13],
        /*info*/
        ctx2[16]
      )
    );
  }
  let if_block = (
    /*info*/
    ctx2[16].importer_name && create_if_block24(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,
        /*info*/
        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 & /*files*/
      1) {
        updating_value = true;
        accountinput_changes.value = /*info*/
        ctx2[16].account;
        add_flush_callback(() => updating_value = false);
      }
      accountinput.$set(accountinput_changes);
      if (dirty & /*files*/
      1 && input.value !== /*info*/
      ctx2[16].newName) {
        set_input_value(
          input,
          /*info*/
          ctx2[16].newName
        );
      }
      if (
        /*info*/
        ctx2[16].importer_name
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block24(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_block26(ctx2) {
  let div;
  let button0;
  let t0_value = (
    /*file*/
    ctx2[13].basename + ""
  );
  let t03;
  let t13;
  let button1;
  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 (
      /*click_handler*/
      ctx2[6](
        /*file*/
        ctx2[13]
      )
    );
  }
  function click_handler_1() {
    return (
      /*click_handler_1*/
      ctx2[7](
        /*file*/
        ctx2[13]
      )
    );
  }
  let each_value_1 = ensure_array_like(
    /*file*/
    ctx2[13].importers
  );
  let each_blocks = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks[i] = create_each_block_19(get_each_context_19(ctx2, each_value_1, i));
  }
  const out2 = (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");
      button1.textContent = "\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", "unset svelte-1m0su6q");
      attr(button1, "type", "button");
      attr(button1, "class", "round svelte-1m0su6q");
      attr(button1, "title", button1_title_value = _("Delete"));
      attr(button1, "tabindex", button1_tabindex_value = -1);
      attr(div, "class", "header svelte-1m0su6q");
      attr(div, "title", div_title_value = /*file*/
      ctx2[13].name);
      toggle_class(
        div,
        "selected",
        /*selected*/
        ctx2[2] === /*file*/
        ctx2[13].name
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, button0);
      append(button0, t03);
      append(div, t13);
      append(div, button1);
      insert(target, t32, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          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 & /*files*/
      1) && t0_value !== (t0_value = /*file*/
      ctx2[13].basename + ""))
        set_data(t03, t0_value);
      if (!current || dirty & /*files*/
      1 && div_title_value !== (div_title_value = /*file*/
      ctx2[13].name)) {
        attr(div, "title", div_title_value);
      }
      if (!current || dirty & /*selected, files*/
      5) {
        toggle_class(
          div,
          "selected",
          /*selected*/
          ctx2[2] === /*file*/
          ctx2[13].name
        );
      }
      if (dirty & /*files, extractCache, extract, move*/
      51) {
        each_value_1 = ensure_array_like(
          /*file*/
          ctx2[13].importers
        );
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_19(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_19(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) {
          out2(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);
        detach(t32);
        detach(each_1_anchor);
      }
      destroy_each(each_blocks, detaching);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_fragment52(ctx2) {
  let each_1_anchor;
  let current;
  let each_value = ensure_array_like(
    /*files*/
    ctx2[0]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block26(get_each_context26(ctx2, each_value, i));
  }
  const out2 = (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) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      if (dirty & /*files, extractCache, extract, move, selected, remove*/
      63) {
        each_value = ensure_array_like(
          /*files*/
          ctx3[0]
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context26(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_block26(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) {
          out2(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) {
      if (detaching) {
        detach(each_1_anchor);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function instance53($$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, info2) {
    if ($$self.$$.not_equal(info2.account, value)) {
      info2.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, info2) => move(file.name, info2.account, info2.newName);
  const click_handler_3 = (file, info2) => extract(file.name, info2.importer_name);
  const click_handler_4 = (file, info2) => {
    extractCache.delete(`${file.name}:${info2.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(options3) {
    super();
    init2(this, options3, instance53, create_fragment52, safe_not_equal, {
      files: 0,
      extractCache: 1,
      selected: 2,
      remove: 3,
      move: 4,
      extract: 5
    });
  }
};
var FileList_default = FileList;

// src/reports/import/Import.svelte
function create_else_block9(ctx2) {
  let extract_1;
  let t03;
  let div2;
  let div1;
  let t13;
  let t22;
  let t32;
  let div0;
  let form;
  let h2;
  let t5;
  let input;
  let t6;
  let button;
  let t8;
  let current;
  let mounted;
  let dispose;
  extract_1 = new Extract_default({
    props: {
      entries: (
        /*entries*/
        ctx2[1]
      ),
      close: (
        /*func*/
        ctx2[14]
      ),
      save: (
        /*save*/
        ctx2[11]
      )
    }
  });
  let if_block0 = (
    /*files*/
    ctx2[0].length === 0 && create_if_block_44(ctx2)
  );
  let if_block1 = (
    /*importableFiles*/
    ctx2[6].length > 0 && create_if_block_37(ctx2)
  );
  let if_block2 = (
    /*otherFiles*/
    ctx2[5].length > 0 && create_if_block_210(ctx2)
  );
  let if_block3 = (
    /*selected*/
    ctx2[2] && create_if_block_116(ctx2)
  );
  return {
    c() {
      create_component(extract_1.$$.fragment);
      t03 = space();
      div2 = element("div");
      div1 = 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();
      div0 = element("div");
      form = element("form");
      h2 = element("h2");
      h2.textContent = `${_("Upload files for import")}`;
      t5 = space();
      input = element("input");
      t6 = space();
      button = element("button");
      button.textContent = `${_("Upload")}`;
      t8 = space();
      if (if_block3)
        if_block3.c();
      input.multiple = true;
      attr(input, "type", "file");
      attr(button, "type", "submit");
      attr(div1, "class", "filelist svelte-9ktust");
      attr(div2, "class", "fixed-fullsize-container svelte-9ktust");
    },
    m(target, anchor) {
      mount_component(extract_1, target, anchor);
      insert(target, t03, anchor);
      insert(target, div2, anchor);
      append(div2, div1);
      if (if_block0)
        if_block0.m(div1, null);
      append(div1, t13);
      if (if_block1)
        if_block1.m(div1, null);
      append(div1, t22);
      if (if_block2)
        if_block2.m(div1, null);
      append(div1, t32);
      append(div1, div0);
      append(div0, form);
      append(form, h2);
      append(form, t5);
      append(form, input);
      ctx2[17](input);
      append(form, t6);
      append(form, button);
      append(div2, t8);
      if (if_block3)
        if_block3.m(div2, null);
      current = true;
      if (!mounted) {
        dispose = listen(form, "submit", prevent_default(
          /*uploadImports*/
          ctx2[12]
        ));
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      const extract_1_changes = {};
      if (dirty & /*entries*/
      2)
        extract_1_changes.entries = /*entries*/
        ctx3[1];
      if (dirty & /*entries*/
      2)
        extract_1_changes.close = /*func*/
        ctx3[14];
      extract_1.$set(extract_1_changes);
      if (
        /*files*/
        ctx3[0].length === 0
      ) {
        if (if_block0) {
        } else {
          if_block0 = create_if_block_44(ctx3);
          if_block0.c();
          if_block0.m(div1, t13);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*importableFiles*/
        ctx3[6].length > 0
      ) {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
          if (dirty & /*importableFiles*/
          64) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_37(ctx3);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(div1, t22);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      if (
        /*otherFiles*/
        ctx3[5].length > 0
      ) {
        if (if_block2) {
          if_block2.p(ctx3, dirty);
          if (dirty & /*otherFiles*/
          32) {
            transition_in(if_block2, 1);
          }
        } else {
          if_block2 = create_if_block_210(ctx3);
          if_block2.c();
          transition_in(if_block2, 1);
          if_block2.m(div1, t32);
        }
      } else if (if_block2) {
        group_outros();
        transition_out(if_block2, 1, 1, () => {
          if_block2 = null;
        });
        check_outros();
      }
      if (
        /*selected*/
        ctx3[2]
      ) {
        if (if_block3) {
          if_block3.p(ctx3, dirty);
          if (dirty & /*selected*/
          4) {
            transition_in(if_block3, 1);
          }
        } else {
          if_block3 = create_if_block_116(ctx3);
          if_block3.c();
          transition_in(if_block3, 1);
          if_block3.m(div2, 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) {
      if (detaching) {
        detach(t03);
        detach(div2);
      }
      destroy_component(extract_1, detaching);
      if (if_block0)
        if_block0.d();
      if (if_block1)
        if_block1.d();
      if (if_block2)
        if_block2.d();
      ctx2[17](null);
      if (if_block3)
        if_block3.d();
      mounted = false;
      dispose();
    }
  };
}
function create_if_block25(ctx2) {
  let p;
  return {
    c() {
      p = element("p");
      p.innerHTML = `No importers configured. See <a href="${urlFor("help/import")}">Help (Import)</a> for more information.`;
    },
    m(target, anchor) {
      insert(target, p, anchor);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(p);
      }
    }
  };
}
function create_if_block_44(ctx2) {
  let p;
  return {
    c() {
      p = element("p");
      p.textContent = `${_("No files were found for import.")}`;
    },
    m(target, anchor) {
      insert(target, p, anchor);
    },
    d(detaching) {
      if (detaching) {
        detach(p);
      }
    }
  };
}
function create_if_block_37(ctx2) {
  let div;
  let h2;
  let t13;
  let filelist;
  let updating_selected;
  let t22;
  let hr;
  let current;
  function filelist_selected_binding(value) {
    ctx2[15](value);
  }
  let filelist_props = {
    files: (
      /*importableFiles*/
      ctx2[6]
    ),
    extractCache: (
      /*extractCache*/
      ctx2[3]
    ),
    move: (
      /*move*/
      ctx2[8]
    ),
    remove: (
      /*remove*/
      ctx2[9]
    ),
    extract: (
      /*extract*/
      ctx2[10]
    )
  };
  if (
    /*selected*/
    ctx2[2] !== void 0
  ) {
    filelist_props.selected = /*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 & /*importableFiles*/
      64)
        filelist_changes.files = /*importableFiles*/
        ctx3[6];
      if (dirty & /*extractCache*/
      8)
        filelist_changes.extractCache = /*extractCache*/
        ctx3[3];
      if (!updating_selected && dirty & /*selected*/
      4) {
        updating_selected = true;
        filelist_changes.selected = /*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);
        detach(t22);
        detach(hr);
      }
      destroy_component(filelist);
    }
  };
}
function create_if_block_210(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[16](value);
  }
  let filelist_props = {
    files: (
      /*otherFiles*/
      ctx2[5]
    ),
    extractCache: (
      /*extractCache*/
      ctx2[3]
    ),
    move: (
      /*move*/
      ctx2[8]
    ),
    remove: (
      /*remove*/
      ctx2[9]
    ),
    extract: (
      /*extract*/
      ctx2[10]
    )
  };
  if (
    /*selected*/
    ctx2[2] !== void 0
  ) {
    filelist_props.selected = /*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 = /*importableFiles*/
      ctx2[6].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 & /*otherFiles*/
      32)
        filelist_changes.files = /*otherFiles*/
        ctx3[5];
      if (dirty & /*extractCache*/
      8)
        filelist_changes.extractCache = /*extractCache*/
        ctx3[3];
      if (!updating_selected && dirty & /*selected*/
      4) {
        updating_selected = true;
        filelist_changes.selected = /*selected*/
        ctx3[2];
        add_flush_callback(() => updating_selected = false);
      }
      filelist.$set(filelist_changes);
      if (!current || dirty & /*importableFiles*/
      64 && details_open_value !== (details_open_value = /*importableFiles*/
      ctx3[6].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_block_116(ctx2) {
  let div;
  let documentpreview;
  let current;
  documentpreview = new DocumentPreview_default({ props: { filename: (
    /*selected*/
    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 & /*selected*/
      4)
        documentpreview_changes.filename = /*selected*/
        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_fragment53(ctx2) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block25, create_else_block9];
  const if_blocks = [];
  function select_block_type(ctx3, dirty) {
    if (!/*$fava_options*/
    ctx3[7].import_config)
      return 0;
    return 1;
  }
  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 (detaching) {
        detach(if_block_anchor);
      }
      if_blocks[current_block_type_index].d(detaching);
    }
  };
}
function instance54($$self, $$props, $$invalidate) {
  let importableFiles;
  let otherFiles;
  let $fava_options;
  component_subscribe($$self, fava_options, ($$value) => $$invalidate(7, $fava_options = $$value));
  let { data } = $$props;
  let entries = [];
  let selected = null;
  let files2 = [];
  let extractCache = /* @__PURE__ */ new Map();
  const preventNavigation = () => extractCache.size > 0 ? "There are unfinished imports, are you sure you want to continue?" : null;
  onMount(() => router_default.addInteruptHandler(preventNavigation));
  async function move(filename, account2, newName) {
    const moved = await moveDocument(filename, account2, newName);
    if (moved) {
      router_default.reload();
    }
  }
  async function remove3(filename) {
    if (!window.confirm(_("Delete this file?"))) {
      return;
    }
    const removed = await deleteDocument(filename);
    if (removed) {
      router_default.reload();
    }
  }
  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() {
    const withoutDuplicates = entries.filter((e3) => !isDuplicate(e3));
    const key2 = [...extractCache].find(([, e3]) => e3 === entries)?.[0];
    if (key2) {
      extractCache.delete(key2);
      $$invalidate(3, extractCache);
    }
    $$invalidate(1, entries = []);
    await saveEntries(withoutDuplicates);
  }
  let fileUpload;
  async function uploadImports() {
    if (fileUpload.files == null) {
      return;
    }
    await Promise.all(Array.from(fileUpload.files).map((file) => {
      const formData = new FormData();
      formData.append("file", file, file.name);
      return put("upload_import_file", formData).then(notify, (error2) => {
        notify_err(error2, (err3) => `Upload error: ${err3.message}`);
      });
    }));
    $$invalidate(4, fileUpload.value = "", fileUpload);
    router_default.reload();
  }
  const func3 = () => {
    $$invalidate(1, entries = []);
  };
  function filelist_selected_binding(value) {
    selected = value;
    $$invalidate(2, selected);
  }
  function filelist_selected_binding_1(value) {
    selected = value;
    $$invalidate(2, selected);
  }
  function input_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      fileUpload = $$value;
      $$invalidate(4, fileUpload);
    });
  }
  $$self.$$set = ($$props2) => {
    if ("data" in $$props2)
      $$invalidate(13, data = $$props2.data);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*files, data*/
    8193) {
      $: {
        const existingFiles = Object.fromEntries(files2.map((file) => [file.name, file]));
        $$invalidate(0, files2 = data.map((file) => {
          const importers = existingFiles[file.name]?.importers ?? file.importers;
          return { ...file, importers };
        }));
      }
    }
    if ($$self.$$.dirty & /*files*/
    1) {
      $:
        $$invalidate(6, importableFiles = files2.filter((i) => i.importers[0]?.importer_name !== ""));
    }
    if ($$self.$$.dirty & /*files*/
    1) {
      $:
        $$invalidate(5, otherFiles = files2.filter((i) => i.importers[0]?.importer_name === ""));
    }
  };
  return [
    files2,
    entries,
    selected,
    extractCache,
    fileUpload,
    otherFiles,
    importableFiles,
    $fava_options,
    move,
    remove3,
    extract,
    save,
    uploadImports,
    data,
    func3,
    filelist_selected_binding,
    filelist_selected_binding_1,
    input_binding
  ];
}
var Import = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance54, create_fragment53, safe_not_equal, { data: 13 });
  }
};
var Import_default = Import;

// src/reports/import/index.ts
function newFilename(date4, basename2) {
  if (!date4 || !basename2) {
    return "";
  }
  if (/^\d{4}-\d{2}-\d{2}/.test(basename2)) {
    return basename2;
  }
  return `${date4} ${basename2}`;
}
function preprocessData(arr) {
  const today = todayAsString();
  return arr.map((file) => {
    const importers = file.importers.map(
      ({ account: account2, importer_name, date: date4, name: name2 }) => ({
        account: account2,
        importer_name,
        newName: newFilename(date4, name2)
      })
    );
    if (importers.length === 0) {
      const newName = newFilename(today, file.basename);
      importers.push({ account: "", newName, importer_name: "" });
    }
    return { ...file, importers };
  });
}
var import_report = new Route(
  "import",
  Import_default,
  () => get("imports", void 0).then(preprocessData).then((data) => ({ data })),
  () => _("Import")
);

// src/charts/query-charts.ts
var grouped_chart_validator = array(
  object({ group: string, balance: record(number) })
);
function parseGroupedQueryChart(json, $chartContext) {
  return grouped_chart_validator(json).map_err(() => "No grouped query data").map((grouped) => {
    const root2 = stratify(
      grouped,
      (d) => d.group,
      (account2, d) => ({ account: account2, balance: d?.balance ?? {} })
    );
    root2.account = "(root)";
    return hierarchy_from_parsed_data(null, root2, $chartContext);
  });
}
function parseQueryChart(json, $chartContext) {
  return parseGroupedQueryChart(json, $chartContext).or_else(() => balances(null, json)).map_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) => [.../* @__PURE__ */ new Set([query, ...hist])]);
  }
}
function removeFromHistory(query) {
  if (query) {
    query_shell_history.update((hist) => hist.filter((item) => item !== query));
  }
}
function clearHistory() {
  query_shell_history.set([]);
}

// src/reports/query/QueryEditor.svelte
function create_fragment54(ctx2) {
  let form;
  let div;
  let renderEditor_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(renderEditor_action = /*renderEditor*/
          ctx2[1].call(null, div)),
          action_destroyer(keyboardShortcut_action = keyboardShortcut.call(null, button, "Control+Enter")),
          listen(form, "submit", prevent_default(function() {
            if (is_function(
              /*submit*/
              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 instance55($$self, $$props, $$invalidate) {
  let { value } = $$props;
  let { submit } = $$props;
  const { editor: editor2, renderEditor } = initQueryEditor(
    value,
    (state) => {
      $$invalidate(2, value = state.sliceDoc());
    },
    _("...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 & /*value*/
    4) {
      $:
        if (value !== editor2.state.sliceDoc()) {
          editor2.dispatch(replaceContents(editor2.state, value));
        }
    }
  };
  return [submit, renderEditor, value];
}
var QueryEditor = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance55, create_fragment54, safe_not_equal, { value: 2, submit: 0 });
  }
};
var QueryEditor_default = QueryEditor;

// src/reports/query/QueryLinks.svelte
function create_if_block26(ctx2) {
  let t03;
  let a0;
  let t13;
  let a0_href_value;
  let t22;
  let a1;
  let t32;
  let a1_href_value;
  return {
    c() {
      t03 = text(",\n    ");
      a0 = element("a");
      t13 = text("XLSX");
      t22 = text("\n    , or\n    ");
      a1 = element("a");
      t32 = text("ODS");
      attr(a0, "href", a0_href_value = /*queryUrl*/
      ctx2[2](
        /*query*/
        ctx2[0],
        "xlsx"
      ));
      attr(a0, "data-remote", "");
      attr(a1, "href", a1_href_value = /*queryUrl*/
      ctx2[2](
        /*query*/
        ctx2[0],
        "ods"
      ));
      attr(a1, "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);
    },
    p(ctx3, dirty) {
      if (dirty & /*query*/
      1 && a0_href_value !== (a0_href_value = /*queryUrl*/
      ctx3[2](
        /*query*/
        ctx3[0],
        "xlsx"
      ))) {
        attr(a0, "href", a0_href_value);
      }
      if (dirty & /*query*/
      1 && a1_href_value !== (a1_href_value = /*queryUrl*/
      ctx3[2](
        /*query*/
        ctx3[0],
        "ods"
      ))) {
        attr(a1, "href", a1_href_value);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(t03);
        detach(a0);
        detach(t22);
        detach(a1);
      }
    }
  };
}
function create_fragment55(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 = (
    /*$HAVE_EXCEL*/
    ctx2[1] && create_if_block26(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 = /*queryUrl*/
      ctx2[2](
        /*query*/
        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 & /*query*/
      1 && a_href_value !== (a_href_value = /*queryUrl*/
      ctx3[2](
        /*query*/
        ctx3[0],
        "csv"
      ))) {
        attr(a, "href", a_href_value);
      }
      if (
        /*$HAVE_EXCEL*/
        ctx3[1]
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block26(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 instance56($$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(options3) {
    super();
    init2(this, options3, instance56, create_fragment55, safe_not_equal, { query: 0 });
  }
};
var QueryLinks_default = QueryLinks;

// src/reports/query/ReadonlyQueryEditor.svelte
function create_fragment56(ctx2) {
  let pre;
  let renderEditor_action;
  let mounted;
  let dispose;
  return {
    c() {
      pre = element("pre");
      attr(pre, "class", "svelte-tsbqgk");
      toggle_class(
        pre,
        "error",
        /*error*/
        ctx2[0]
      );
    },
    m(target, anchor) {
      insert(target, pre, anchor);
      if (!mounted) {
        dispose = action_destroyer(renderEditor_action = /*renderEditor*/
        ctx2[1].call(null, pre));
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & /*error*/
      1) {
        toggle_class(
          pre,
          "error",
          /*error*/
          ctx3[0]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(pre);
      }
      mounted = false;
      dispose();
    }
  };
}
function instance57($$self, $$props, $$invalidate) {
  let { value } = $$props;
  let { error: error2 = false } = $$props;
  const { renderEditor } = initReadonlyQueryEditor(value);
  $$self.$$set = ($$props2) => {
    if ("value" in $$props2)
      $$invalidate(2, value = $$props2.value);
    if ("error" in $$props2)
      $$invalidate(0, error2 = $$props2.error);
  };
  return [error2, renderEditor, value];
}
var ReadonlyQueryEditor = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance57, create_fragment56, safe_not_equal, { value: 2, error: 0 });
  }
};
var ReadonlyQueryEditor_default = ReadonlyQueryEditor;

// src/reports/query/Query.svelte
function get_each_context27(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[17] = list[i][0];
  child_ctx[18] = list[i][1].result;
  child_ctx[19] = list[i][1].error;
  child_ctx[20] = list;
  child_ctx[21] = i;
  return child_ctx;
}
function create_if_block_38(ctx2) {
  let querylinks;
  let current;
  querylinks = new QueryLinks_default({
    props: { query: (
      /*history_item*/
      ctx2[17]
    ) }
  });
  return {
    c() {
      create_component(querylinks.$$.fragment);
    },
    m(target, anchor) {
      mount_component(querylinks, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const querylinks_changes = {};
      if (dirty & /*query_result_array*/
      4)
        querylinks_changes.query = /*history_item*/
        ctx3[17];
      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) {
      destroy_component(querylinks, detaching);
    }
  };
}
function create_if_block_211(ctx2) {
  let pre;
  let t_value = (
    /*error*/
    ctx2[19] + ""
  );
  let t4;
  return {
    c() {
      pre = element("pre");
      t4 = text(t_value);
    },
    m(target, anchor) {
      insert(target, pre, anchor);
      append(pre, t4);
    },
    p(ctx3, dirty) {
      if (dirty & /*query_result_array*/
      4 && t_value !== (t_value = /*error*/
      ctx3[19] + ""))
        set_data(t4, t_value);
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(pre);
      }
    }
  };
}
function create_if_block27(ctx2) {
  let t4;
  let html_tag;
  let raw_value = (
    /*result*/
    ctx2[18].table + ""
  );
  let html_anchor;
  let current;
  let if_block = (
    /*result*/
    ctx2[18].chart && create_if_block_117(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 (
        /*result*/
        ctx3[18].chart
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & /*query_result_array*/
          4) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_117(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 & /*query_result_array*/
      4) && raw_value !== (raw_value = /*result*/
      ctx3[18].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 (detaching) {
        detach(t4);
        detach(html_anchor);
        html_tag.d();
      }
      if (if_block)
        if_block.d(detaching);
    }
  };
}
function create_if_block_117(ctx2) {
  let chart;
  let current;
  chart = new Chart_default({
    props: { chart: (
      /*result*/
      ctx2[18].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 & /*query_result_array*/
      4)
        chart_changes.chart = /*result*/
        ctx3[18].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_block27(key_1, ctx2) {
  let details;
  let summary;
  let readonlyqueryeditor;
  let t03;
  let span;
  let t13;
  let t22;
  let button;
  let t4;
  let div;
  let current_block_type_index;
  let if_block1;
  let t5;
  let history_item = (
    /*history_item*/
    ctx2[17]
  );
  let current;
  let mounted;
  let dispose;
  readonlyqueryeditor = new ReadonlyQueryEditor_default({
    props: {
      value: (
        /*history_item*/
        ctx2[17]
      ),
      error: !!/*error*/
      ctx2[19]
    }
  });
  let if_block0 = (
    /*result*/
    ctx2[18] && create_if_block_38(ctx2)
  );
  function click_handler() {
    return (
      /*click_handler*/
      ctx2[9](
        /*history_item*/
        ctx2[17]
      )
    );
  }
  function click_handler_1() {
    return (
      /*click_handler_1*/
      ctx2[10](
        /*history_item*/
        ctx2[17]
      )
    );
  }
  const if_block_creators = [create_if_block27, create_if_block_211];
  const if_blocks = [];
  function select_block_type(ctx3, dirty) {
    if (
      /*result*/
      ctx3[18]
    )
      return 0;
    if (
      /*error*/
      ctx3[19]
    )
      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 = () => (
    /*details_binding*/
    ctx2[11](details, history_item)
  );
  const unassign_details = () => (
    /*details_binding*/
    ctx2[11](null, history_item)
  );
  return {
    key: key_1,
    first: null,
    c() {
      details = element("details");
      summary = element("summary");
      create_component(readonlyqueryeditor.$$.fragment);
      t03 = space();
      span = element("span");
      t13 = space();
      if (if_block0)
        if_block0.c();
      t22 = space();
      button = element("button");
      button.textContent = "x";
      t4 = space();
      div = element("div");
      if (if_block1)
        if_block1.c();
      t5 = space();
      attr(span, "class", "spacer");
      attr(button, "type", "button");
      attr(button, "class", "svelte-ja7zaa");
      attr(summary, "class", "svelte-ja7zaa");
      toggle_class(summary, "inactive", !/*result*/
      ctx2[18] && !/*error*/
      ctx2[19]);
      attr(div, "class", "svelte-ja7zaa");
      attr(details, "class", "svelte-ja7zaa");
      this.first = details;
    },
    m(target, anchor) {
      insert(target, details, anchor);
      append(details, summary);
      mount_component(readonlyqueryeditor, summary, null);
      append(summary, t03);
      append(summary, span);
      append(summary, t13);
      if (if_block0)
        if_block0.m(summary, null);
      append(summary, t22);
      append(summary, button);
      append(details, t4);
      append(details, div);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(div, null);
      }
      append(details, t5);
      assign_details();
      current = true;
      if (!mounted) {
        dispose = [
          listen(button, "click", stop_propagation(click_handler)),
          listen(summary, "click", click_handler_1)
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      const readonlyqueryeditor_changes = {};
      if (dirty & /*query_result_array*/
      4)
        readonlyqueryeditor_changes.value = /*history_item*/
        ctx2[17];
      if (dirty & /*query_result_array*/
      4)
        readonlyqueryeditor_changes.error = !!/*error*/
        ctx2[19];
      readonlyqueryeditor.$set(readonlyqueryeditor_changes);
      if (
        /*result*/
        ctx2[18]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty & /*query_result_array*/
          4) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_38(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(summary, t22);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      if (!current || dirty & /*query_result_array*/
      4) {
        toggle_class(summary, "inactive", !/*result*/
        ctx2[18] && !/*error*/
        ctx2[19]);
      }
      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 !== /*history_item*/
      ctx2[17]) {
        unassign_details();
        history_item = /*history_item*/
        ctx2[17];
        assign_details();
      }
    },
    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;
      run_all(dispose);
    }
  };
}
function create_fragment57(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[8](value);
  }
  let queryeditor_props = { submit: (
    /*submit*/
    ctx2[3]
  ) };
  if (
    /*query_string*/
    ctx2[0] !== void 0
  ) {
    queryeditor_props.value = /*query_string*/
    ctx2[0];
  }
  queryeditor = new QueryEditor_default({ props: queryeditor_props });
  binding_callbacks.push(() => bind(queryeditor, "value", queryeditor_value_binding));
  let each_value = ensure_array_like(
    /*query_result_array*/
    ctx2[2]
  );
  const get_key = (ctx3) => (
    /*history_item*/
    ctx3[17]
  );
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context27(ctx2, each_value, i);
    let key2 = get_key(child_ctx);
    each_1_lookup.set(key2, each_blocks[i] = create_each_block27(key2, 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-ja7zaa");
    },
    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) {
        if (each_blocks[i]) {
          each_blocks[i].m(div, null);
        }
      }
      current = true;
    },
    p(ctx3, [dirty]) {
      const queryeditor_changes = {};
      if (!updating_value && dirty & /*query_string*/
      1) {
        updating_value = true;
        queryeditor_changes.value = /*query_string*/
        ctx3[0];
        add_flush_callback(() => updating_value = false);
      }
      queryeditor.$set(queryeditor_changes);
      if (dirty & /*resultElems, query_result_array, click, deleteItem*/
      54) {
        each_value = ensure_array_like(
          /*query_result_array*/
          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_block27, null, get_each_context27);
        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) {
      if (detaching) {
        detach(t4);
        detach(div);
      }
      destroy_component(queryeditor, detaching);
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
function instance58($$self, $$props, $$invalidate) {
  let query_result_array;
  let $chartContext;
  let $filter_params;
  let $query_shell_history;
  component_subscribe($$self, chartContext, ($$value) => $$invalidate(12, $chartContext = $$value));
  component_subscribe($$self, filter_params, ($$value) => $$invalidate(13, $filter_params = $$value));
  component_subscribe($$self, query_shell_history, ($$value) => $$invalidate(7, $query_shell_history = $$value));
  let query_string = "";
  const resultElems = {};
  const query_results = {};
  async function setResult(query, res2) {
    addToHistory(query);
    $$invalidate(6, 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");
  }
  function clearQueryString() {
    const url = new URL(window.location.href);
    $$invalidate(0, query_string = "");
    url.searchParams.set("query_string", query_string);
    window.history.replaceState(null, "", url.toString());
  }
  async function clearResults() {
    clearHistory();
    await tick();
    clearQueryString();
  }
  function submit() {
    const query = query_string;
    if (!query) {
      return;
    }
    if (query.trim().toUpperCase() === "CLEAR") {
      clearResults().catch(log_error);
      return;
    }
    get("query_result", { query_string: query, ...$filter_params }).then(
      (res2) => {
        const chart = parseQueryChart(res2.chart, $chartContext).unwrap_or(null);
        setResult(query, { result: { chart, table: res2.table } }).catch(log_error);
        window.scroll(0, 0);
      },
      (error2) => {
        if (error2 instanceof Error) {
          setResult(query, { error: error2.message }).catch(log_error);
          window.scroll(0, 0);
        } 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();
    }
  }
  async function deleteItem(query) {
    removeFromHistory(query);
    if (query_string === query) {
      await tick();
      clearQueryString();
    }
  }
  onMount(() => router_default.on("page-loaded", () => {
    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) => deleteItem(history_item);
  const click_handler_1 = (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 & /*$query_shell_history, query_results*/
    192) {
      $:
        $$invalidate(2, query_result_array = $query_shell_history.map((item) => [item, query_results[item] ?? {}]));
    }
  };
  return [
    query_string,
    resultElems,
    query_result_array,
    submit,
    click,
    deleteItem,
    query_results,
    $query_shell_history,
    queryeditor_value_binding,
    click_handler,
    click_handler_1,
    details_binding
  ];
}
var Query2 = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance58, create_fragment57, safe_not_equal, {});
  }
};
var Query_default = Query2;

// src/tree-table/TreeTableNode.svelte
function get_each_context28(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[20] = list[i];
  return child_ctx;
}
function get_each_context_110(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[23] = list[i][0];
  child_ctx[24] = list[i][1];
  const constants_0 = (
    /*shown_cost*/
    child_ctx[7]?.[
      /*currency*/
      child_ctx[23]
    ]
  );
  child_ctx[25] = constants_0;
  return child_ctx;
}
function get_if_ctx2(ctx2) {
  const child_ctx = ctx2.slice();
  const constants_0 = (
    /*invert*/
    child_ctx[1] * /*num*/
    (child_ctx[24] - /*cost_num*/
    child_ctx[25])
  );
  child_ctx[28] = constants_0;
  return child_ctx;
}
function get_each_context_24(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[23] = list[i];
  const constants_0 = (
    /*shown_balance*/
    child_ctx[3][
      /*currency*/
      child_ctx[23]
    ]
  );
  child_ctx[24] = constants_0;
  const constants_1 = (
    /*shown_cost*/
    child_ctx[7]?.[
      /*currency*/
      child_ctx[23]
    ]
  );
  child_ctx[25] = constants_1;
  return child_ctx;
}
function get_if_ctx_1(ctx2) {
  const child_ctx = ctx2.slice();
  const constants_0 = (
    /*invert*/
    child_ctx[1] * /*num*/
    (child_ctx[24] - /*cost_num*/
    child_ctx[25])
  );
  child_ctx[28] = constants_0;
  return child_ctx;
}
function create_if_block_212(ctx2) {
  let t0_value = (
    /*$ctx*/
    ctx2[9].num(
      /*invert*/
      ctx2[1] * /*num*/
      ctx2[24],
      /*currency*/
      ctx2[23]
    ) + ""
  );
  let t03;
  let t13;
  let if_block_anchor;
  let current;
  let if_block = (
    /*cost_num*/
    ctx2[25] && /*num*/
    ctx2[24] - /*cost_num*/
    ctx2[25] && create_if_block_39(get_if_ctx_1(ctx2))
  );
  return {
    c() {
      t03 = text(t0_value);
      t13 = space();
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      insert(target, t03, anchor);
      insert(target, t13, anchor);
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      if ((!current || dirty & /*$ctx, invert, shown_balance, $operating_currency*/
      538) && t0_value !== (t0_value = /*$ctx*/
      ctx3[9].num(
        /*invert*/
        ctx3[1] * /*num*/
        ctx3[24],
        /*currency*/
        ctx3[23]
      ) + ""))
        set_data(t03, t0_value);
      if (
        /*cost_num*/
        ctx3[25] && /*num*/
        ctx3[24] - /*cost_num*/
        ctx3[25]
      ) {
        if (if_block) {
          if_block.p(get_if_ctx_1(ctx3), dirty);
          if (dirty & /*shown_cost, $operating_currency, shown_balance*/
          152) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_39(get_if_ctx_1(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 (detaching) {
        detach(t03);
        detach(t13);
        detach(if_block_anchor);
      }
      if (if_block)
        if_block.d(detaching);
    }
  };
}
function create_if_block_39(ctx2) {
  let diff_1;
  let current;
  diff_1 = new Diff_default({
    props: {
      diff: (
        /*diff*/
        ctx2[28]
      ),
      num: (
        /*invert*/
        ctx2[1] * /*cost_num*/
        ctx2[25]
      ),
      currency: (
        /*currency*/
        ctx2[23]
      )
    }
  });
  return {
    c() {
      create_component(diff_1.$$.fragment);
    },
    m(target, anchor) {
      mount_component(diff_1, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const diff_1_changes = {};
      if (dirty & /*invert, shown_balance, $operating_currency, shown_cost*/
      154)
        diff_1_changes.diff = /*diff*/
        ctx3[28];
      if (dirty & /*invert, shown_cost, $operating_currency*/
      146)
        diff_1_changes.num = /*invert*/
        ctx3[1] * /*cost_num*/
        ctx3[25];
      if (dirty & /*$operating_currency*/
      16)
        diff_1_changes.currency = /*currency*/
        ctx3[23];
      diff_1.$set(diff_1_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(diff_1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(diff_1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(diff_1, detaching);
    }
  };
}
function create_each_block_24(ctx2) {
  let span;
  let current;
  let if_block = (
    /*num*/
    ctx2[24] && create_if_block_212(ctx2)
  );
  return {
    c() {
      span = element("span");
      if (if_block)
        if_block.c();
      attr(span, "class", "num");
      toggle_class(
        span,
        "dimmed",
        /*dimmed*/
        ctx2[5]
      );
    },
    m(target, anchor) {
      insert(target, span, anchor);
      if (if_block)
        if_block.m(span, null);
      current = true;
    },
    p(ctx3, dirty) {
      if (
        /*num*/
        ctx3[24]
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & /*shown_balance, $operating_currency*/
          24) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_212(ctx3);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(span, null);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
      if (!current || dirty & /*dimmed*/
      32) {
        toggle_class(
          span,
          "dimmed",
          /*dimmed*/
          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(span);
      }
      if (if_block)
        if_block.d();
    }
  };
}
function create_if_block_118(ctx2) {
  let diff_1;
  let current;
  diff_1 = new Diff_default({
    props: {
      diff: (
        /*diff*/
        ctx2[28]
      ),
      num: (
        /*invert*/
        ctx2[1] * /*cost_num*/
        ctx2[25]
      ),
      currency: (
        /*currency*/
        ctx2[23]
      )
    }
  });
  return {
    c() {
      create_component(diff_1.$$.fragment);
    },
    m(target, anchor) {
      mount_component(diff_1, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const diff_1_changes = {};
      if (dirty & /*invert, shown_balance_other, shown_cost*/
      194)
        diff_1_changes.diff = /*diff*/
        ctx3[28];
      if (dirty & /*invert, shown_cost, shown_balance_other*/
      194)
        diff_1_changes.num = /*invert*/
        ctx3[1] * /*cost_num*/
        ctx3[25];
      if (dirty & /*shown_balance_other*/
      64)
        diff_1_changes.currency = /*currency*/
        ctx3[23];
      diff_1.$set(diff_1_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(diff_1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(diff_1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(diff_1, detaching);
    }
  };
}
function create_each_block_110(ctx2) {
  let span;
  let t0_value = (
    /*$ctx*/
    ctx2[9].amount(
      /*invert*/
      ctx2[1] * /*num*/
      ctx2[24],
      /*currency*/
      ctx2[23]
    ) + ""
  );
  let t03;
  let span_title_value;
  let t13;
  let t22;
  let br;
  let current;
  let if_block = (
    /*cost_num*/
    ctx2[25] && /*num*/
    ctx2[24] - /*cost_num*/
    ctx2[25] && create_if_block_118(get_if_ctx2(ctx2))
  );
  return {
    c() {
      span = element("span");
      t03 = text(t0_value);
      t13 = space();
      if (if_block)
        if_block.c();
      t22 = space();
      br = element("br");
      attr(span, "title", span_title_value = /*$currency_name*/
      ctx2[10](
        /*currency*/
        ctx2[23]
      ));
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t03);
      insert(target, t13, anchor);
      if (if_block)
        if_block.m(target, anchor);
      insert(target, t22, anchor);
      insert(target, br, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      if ((!current || dirty & /*$ctx, invert, shown_balance_other*/
      578) && t0_value !== (t0_value = /*$ctx*/
      ctx3[9].amount(
        /*invert*/
        ctx3[1] * /*num*/
        ctx3[24],
        /*currency*/
        ctx3[23]
      ) + ""))
        set_data(t03, t0_value);
      if (!current || dirty & /*$currency_name, shown_balance_other*/
      1088 && span_title_value !== (span_title_value = /*$currency_name*/
      ctx3[10](
        /*currency*/
        ctx3[23]
      ))) {
        attr(span, "title", span_title_value);
      }
      if (
        /*cost_num*/
        ctx3[25] && /*num*/
        ctx3[24] - /*cost_num*/
        ctx3[25]
      ) {
        if (if_block) {
          if_block.p(get_if_ctx2(ctx3), dirty);
          if (dirty & /*shown_cost, shown_balance_other*/
          192) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_118(get_if_ctx2(ctx3));
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(t22.parentNode, t22);
        }
      } 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 (detaching) {
        detach(span);
        detach(t13);
        detach(t22);
        detach(br);
      }
      if (if_block)
        if_block.d(detaching);
    }
  };
}
function create_if_block28(ctx2) {
  let ol;
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let current;
  let each_value = ensure_array_like(
    /*children*/
    ctx2[8].filter(
      /*func_1*/
      ctx2[19]
    )
  );
  const get_key = (ctx3) => (
    /*child*/
    ctx3[20].account
  );
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context28(ctx2, each_value, i);
    let key2 = get_key(child_ctx);
    each_1_lookup.set(key2, each_blocks[i] = create_each_block28(key2, child_ctx));
  }
  return {
    c() {
      ol = element("ol");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
    },
    m(target, anchor) {
      insert(target, ol, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(ol, null);
        }
      }
      current = true;
    },
    p(ctx3, dirty) {
      if (dirty & /*children, $not_shown, invert*/
      2306) {
        each_value = ensure_array_like(
          /*children*/
          ctx3[8].filter(
            /*func_1*/
            ctx3[19]
          )
        );
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx3, each_value, each_1_lookup, ol, outro_and_destroy_block, create_each_block28, null, get_each_context28);
        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) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(ol);
      }
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
function create_each_block28(key_1, ctx2) {
  let first;
  let treetablenode;
  let current;
  treetablenode = new TreeTableNode({
    props: {
      node: (
        /*child*/
        ctx2[20]
      ),
      invert: (
        /*invert*/
        ctx2[1]
      )
    }
  });
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(treetablenode.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(treetablenode, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      const treetablenode_changes = {};
      if (dirty & /*children, $not_shown*/
      2304)
        treetablenode_changes.node = /*child*/
        ctx2[20];
      if (dirty & /*invert*/
      2)
        treetablenode_changes.invert = /*invert*/
        ctx2[1];
      treetablenode.$set(treetablenode_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(treetablenode.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(treetablenode.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(first);
      }
      destroy_component(treetablenode, detaching);
    }
  };
}
function create_fragment58(ctx2) {
  let li;
  let p;
  let accountcell;
  let t03;
  let t13;
  let span;
  let t22;
  let show_if = !/*is_toggled*/
  ctx2[2] && /*children*/
  ctx2[8].some(
    /*func*/
    ctx2[18]
  );
  let current;
  accountcell = new AccountCell_default({ props: { node: (
    /*node*/
    ctx2[0]
  ) } });
  let each_value_2 = ensure_array_like(
    /*$operating_currency*/
    ctx2[4]
  );
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_2.length; i += 1) {
    each_blocks_1[i] = create_each_block_24(get_each_context_24(ctx2, each_value_2, i));
  }
  const out2 = (i) => transition_out(each_blocks_1[i], 1, 1, () => {
    each_blocks_1[i] = null;
  });
  let each_value_1 = ensure_array_like(
    /*shown_balance_other*/
    ctx2[6]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks[i] = create_each_block_110(get_each_context_110(ctx2, each_value_1, i));
  }
  const out_1 = (i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  });
  let if_block = show_if && create_if_block28(ctx2);
  return {
    c() {
      li = element("li");
      p = element("p");
      create_component(accountcell.$$.fragment);
      t03 = space();
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t13 = space();
      span = element("span");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t22 = space();
      if (if_block)
        if_block.c();
      attr(span, "class", "num other");
      toggle_class(
        span,
        "dimmed",
        /*dimmed*/
        ctx2[5]
      );
    },
    m(target, anchor) {
      insert(target, li, anchor);
      append(li, p);
      mount_component(accountcell, p, null);
      append(p, t03);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(p, null);
        }
      }
      append(p, t13);
      append(p, span);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(span, null);
        }
      }
      append(li, t22);
      if (if_block)
        if_block.m(li, null);
      current = true;
    },
    p(ctx3, [dirty]) {
      const accountcell_changes = {};
      if (dirty & /*node*/
      1)
        accountcell_changes.node = /*node*/
        ctx3[0];
      accountcell.$set(accountcell_changes);
      if (dirty & /*dimmed, invert, shown_balance, $operating_currency, shown_cost, $ctx*/
      698) {
        each_value_2 = ensure_array_like(
          /*$operating_currency*/
          ctx3[4]
        );
        let i;
        for (i = 0; i < each_value_2.length; i += 1) {
          const child_ctx = get_each_context_24(ctx3, each_value_2, i);
          if (each_blocks_1[i]) {
            each_blocks_1[i].p(child_ctx, dirty);
            transition_in(each_blocks_1[i], 1);
          } else {
            each_blocks_1[i] = create_each_block_24(child_ctx);
            each_blocks_1[i].c();
            transition_in(each_blocks_1[i], 1);
            each_blocks_1[i].m(p, t13);
          }
        }
        group_outros();
        for (i = each_value_2.length; i < each_blocks_1.length; i += 1) {
          out2(i);
        }
        check_outros();
      }
      if (dirty & /*invert, shown_balance_other, shown_cost, $currency_name, $ctx*/
      1730) {
        each_value_1 = ensure_array_like(
          /*shown_balance_other*/
          ctx3[6]
        );
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_110(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_110(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(span, null);
          }
        }
        group_outros();
        for (i = each_value_1.length; i < each_blocks.length; i += 1) {
          out_1(i);
        }
        check_outros();
      }
      if (!current || dirty & /*dimmed*/
      32) {
        toggle_class(
          span,
          "dimmed",
          /*dimmed*/
          ctx3[5]
        );
      }
      if (dirty & /*is_toggled, children, $not_shown*/
      2308)
        show_if = !/*is_toggled*/
        ctx3[2] && /*children*/
        ctx3[8].some(
          /*func*/
          ctx3[18]
        );
      if (show_if) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & /*is_toggled, children, $not_shown*/
          2308) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block28(ctx3);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(li, null);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(accountcell.$$.fragment, local);
      for (let i = 0; i < each_value_2.length; i += 1) {
        transition_in(each_blocks_1[i]);
      }
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(accountcell.$$.fragment, local);
      each_blocks_1 = each_blocks_1.filter(Boolean);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        transition_out(each_blocks_1[i]);
      }
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(li);
      }
      destroy_component(accountcell);
      destroy_each(each_blocks_1, detaching);
      destroy_each(each_blocks, detaching);
      if (if_block)
        if_block.d();
    }
  };
}
function instance59($$self, $$props, $$invalidate) {
  let account2;
  let children3;
  let is_toggled;
  let has_balance;
  let show_balance;
  let shown_balance;
  let shown_cost;
  let shown_balance_other;
  let dimmed;
  let $operating_currency;
  let $toggled;
  let $ctx;
  let $currency_name;
  let $not_shown;
  component_subscribe($$self, operating_currency, ($$value) => $$invalidate(4, $operating_currency = $$value));
  component_subscribe($$self, ctx, ($$value) => $$invalidate(9, $ctx = $$value));
  component_subscribe($$self, currency_name, ($$value) => $$invalidate(10, $currency_name = $$value));
  let { node } = $$props;
  let { invert } = $$props;
  const { toggled, not_shown } = getTreeTableContext();
  component_subscribe($$self, toggled, (value) => $$invalidate(17, $toggled = value));
  component_subscribe($$self, not_shown, (value) => $$invalidate(11, $not_shown = value));
  const func3 = (n) => !$not_shown.has(n.account);
  const func_1 = (n) => !$not_shown.has(n.account);
  $$self.$$set = ($$props2) => {
    if ("node" in $$props2)
      $$invalidate(0, node = $$props2.node);
    if ("invert" in $$props2)
      $$invalidate(1, invert = $$props2.invert);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*node*/
    1) {
      $:
        $$invalidate(16, { account: account2, children: children3 } = node, account2, ($$invalidate(8, children3), $$invalidate(0, node)));
    }
    if ($$self.$$.dirty & /*$toggled, account*/
    196608) {
      $:
        $$invalidate(2, is_toggled = $toggled.has(account2));
    }
    if ($$self.$$.dirty & /*node*/
    1) {
      $:
        $$invalidate(14, has_balance = !is_empty2(node.balance));
    }
    if ($$self.$$.dirty & /*is_toggled, has_balance*/
    16388) {
      $:
        $$invalidate(15, show_balance = !is_toggled && has_balance);
    }
    if ($$self.$$.dirty & /*show_balance, node*/
    32769) {
      $:
        $$invalidate(3, shown_balance = show_balance ? node.balance : node.balance_children);
    }
    if ($$self.$$.dirty & /*show_balance, node*/
    32769) {
      $:
        $$invalidate(7, shown_cost = show_balance ? node.cost : node.cost_children);
    }
    if ($$self.$$.dirty & /*shown_balance, $operating_currency*/
    24) {
      $:
        $$invalidate(6, shown_balance_other = Object.entries(shown_balance).sort().filter(([c]) => !$operating_currency.includes(c)));
    }
    if ($$self.$$.dirty & /*is_toggled, has_balance*/
    16388) {
      $:
        $$invalidate(5, dimmed = !is_toggled && !has_balance);
    }
  };
  return [
    node,
    invert,
    is_toggled,
    shown_balance,
    $operating_currency,
    dimmed,
    shown_balance_other,
    shown_cost,
    children3,
    $ctx,
    $currency_name,
    $not_shown,
    toggled,
    not_shown,
    has_balance,
    show_balance,
    account2,
    $toggled,
    func3,
    func_1
  ];
}
var TreeTableNode = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance59, create_fragment58, safe_not_equal, { node: 0, invert: 1 });
  }
};
var TreeTableNode_default = TreeTableNode;

// src/tree-table/TreeTable.svelte
function get_each_context29(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[10] = list[i];
  return child_ctx;
}
function get_each_context_111(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[13] = list[i];
  return child_ctx;
}
function create_each_block_111(ctx2) {
  let span;
  let t_value = (
    /*currency*/
    ctx2[13] + ""
  );
  let t4;
  let span_title_value;
  return {
    c() {
      span = element("span");
      t4 = text(t_value);
      attr(span, "class", "num");
      attr(span, "title", span_title_value = /*$currency_name*/
      ctx2[2](
        /*currency*/
        ctx2[13]
      ));
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t4);
    },
    p(ctx3, dirty) {
      if (dirty & /*$operating_currency*/
      2 && t_value !== (t_value = /*currency*/
      ctx3[13] + ""))
        set_data(t4, t_value);
      if (dirty & /*$currency_name, $operating_currency*/
      6 && span_title_value !== (span_title_value = /*$currency_name*/
      ctx3[2](
        /*currency*/
        ctx3[13]
      ))) {
        attr(span, "title", span_title_value);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
    }
  };
}
function create_each_block29(ctx2) {
  let treetablenode;
  let current;
  treetablenode = new TreeTableNode_default({
    props: {
      node: (
        /*n*/
        ctx2[10]
      ),
      invert: (
        /*$invert_account*/
        ctx2[3](
          /*n*/
          ctx2[10].account
        ) ? -1 : 1
      )
    }
  });
  return {
    c() {
      create_component(treetablenode.$$.fragment);
    },
    m(target, anchor) {
      mount_component(treetablenode, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const treetablenode_changes = {};
      if (dirty & /*tree*/
      1)
        treetablenode_changes.node = /*n*/
        ctx3[10];
      if (dirty & /*$invert_account, tree*/
      9)
        treetablenode_changes.invert = /*$invert_account*/
        ctx3[3](
          /*n*/
          ctx3[10].account
        ) ? -1 : 1;
      treetablenode.$set(treetablenode_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(treetablenode.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(treetablenode.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(treetablenode, detaching);
    }
  };
}
function create_fragment59(ctx2) {
  let ol;
  let li;
  let p;
  let accountcellheader;
  let t03;
  let t13;
  let span;
  let t32;
  let current;
  accountcellheader = new AccountCellHeader_default({});
  let each_value_1 = ensure_array_like(
    /*$operating_currency*/
    ctx2[1]
  );
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks_1[i] = create_each_block_111(get_each_context_111(ctx2, each_value_1, i));
  }
  let each_value = ensure_array_like(
    /*tree*/
    ctx2[0].account === "" ? (
      /*tree*/
      ctx2[0].children
    ) : [
      /*tree*/
      ctx2[0]
    ]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block29(get_each_context29(ctx2, each_value, i));
  }
  const out2 = (i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  });
  return {
    c() {
      ol = element("ol");
      li = element("li");
      p = element("p");
      create_component(accountcellheader.$$.fragment);
      t03 = space();
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t13 = space();
      span = element("span");
      span.textContent = `${_("Other")}`;
      t32 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(span, "class", "num other");
      attr(li, "class", "head");
      attr(ol, "class", "flex-table tree-table-new svelte-12upc2c");
      toggle_class(
        ol,
        "wider",
        /*$operating_currency*/
        ctx2[1].length > 1
      );
    },
    m(target, anchor) {
      insert(target, ol, anchor);
      append(ol, li);
      append(li, p);
      mount_component(accountcellheader, p, null);
      append(p, t03);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(p, null);
        }
      }
      append(p, t13);
      append(p, span);
      append(ol, t32);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(ol, null);
        }
      }
      current = true;
    },
    p(ctx3, [dirty]) {
      if (dirty & /*$currency_name, $operating_currency*/
      6) {
        each_value_1 = ensure_array_like(
          /*$operating_currency*/
          ctx3[1]
        );
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_111(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_111(child_ctx);
            each_blocks_1[i].c();
            each_blocks_1[i].m(p, t13);
          }
        }
        for (; i < each_blocks_1.length; i += 1) {
          each_blocks_1[i].d(1);
        }
        each_blocks_1.length = each_value_1.length;
      }
      if (dirty & /*tree, $invert_account*/
      9) {
        each_value = ensure_array_like(
          /*tree*/
          ctx3[0].account === "" ? (
            /*tree*/
            ctx3[0].children
          ) : [
            /*tree*/
            ctx3[0]
          ]
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context29(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_block29(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(ol, null);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out2(i);
        }
        check_outros();
      }
      if (!current || dirty & /*$operating_currency*/
      2) {
        toggle_class(
          ol,
          "wider",
          /*$operating_currency*/
          ctx3[1].length > 1
        );
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(accountcellheader.$$.fragment, local);
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      transition_out(accountcellheader.$$.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(ol);
      }
      destroy_component(accountcellheader);
      destroy_each(each_blocks_1, detaching);
      destroy_each(each_blocks, detaching);
    }
  };
}
function instance60($$self, $$props, $$invalidate) {
  let $get_not_shown;
  let $not_shown;
  let $collapse_account;
  let $operating_currency;
  let $currency_name;
  let $invert_account;
  component_subscribe($$self, get_not_shown, ($$value) => $$invalidate(6, $get_not_shown = $$value));
  component_subscribe($$self, collapse_account, ($$value) => $$invalidate(8, $collapse_account = $$value));
  component_subscribe($$self, operating_currency, ($$value) => $$invalidate(1, $operating_currency = $$value));
  component_subscribe($$self, currency_name, ($$value) => $$invalidate(2, $currency_name = $$value));
  component_subscribe($$self, invert_account, ($$value) => $$invalidate(3, $invert_account = $$value));
  let { tree } = $$props;
  let { end } = $$props;
  const toggled = writable(get_collapsed(tree, $collapse_account));
  const not_shown = writable(/* @__PURE__ */ new Set());
  component_subscribe($$self, not_shown, (value) => $$invalidate(7, $not_shown = value));
  setTreeTableContext({ toggled, not_shown });
  $$self.$$set = ($$props2) => {
    if ("tree" in $$props2)
      $$invalidate(0, tree = $$props2.tree);
    if ("end" in $$props2)
      $$invalidate(5, end = $$props2.end);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$get_not_shown, tree, end*/
    97) {
      $:
        set_store_value(not_shown, $not_shown = $get_not_shown(tree, end), $not_shown);
    }
  };
  return [
    tree,
    $operating_currency,
    $currency_name,
    $invert_account,
    not_shown,
    end,
    $get_not_shown
  ];
}
var TreeTable = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance60, create_fragment59, safe_not_equal, { tree: 0, end: 5 });
  }
};
var TreeTable_default = TreeTable;

// src/reports/tree_reports/BalanceSheet.svelte
function get_each_context30(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[5] = list[i];
  return child_ctx;
}
function get_each_context_112(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[5] = list[i];
  return child_ctx;
}
function create_if_block29(ctx2) {
  let chartswitcher;
  let current;
  chartswitcher = new ChartSwitcher_default({ props: { charts: (
    /*chartData*/
    ctx2[2]
  ) } });
  return {
    c() {
      create_component(chartswitcher.$$.fragment);
    },
    m(target, anchor) {
      mount_component(chartswitcher, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const chartswitcher_changes = {};
      if (dirty & /*chartData*/
      4)
        chartswitcher_changes.charts = /*chartData*/
        ctx3[2];
      chartswitcher.$set(chartswitcher_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(chartswitcher.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(chartswitcher.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(chartswitcher, detaching);
    }
  };
}
function create_each_block_112(ctx2) {
  let treetable;
  let current;
  treetable = new TreeTable_default({
    props: {
      tree: (
        /*tree*/
        ctx2[5]
      ),
      end: (
        /*date_range*/
        ctx2[1]?.end ?? null
      )
    }
  });
  return {
    c() {
      create_component(treetable.$$.fragment);
    },
    m(target, anchor) {
      mount_component(treetable, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const treetable_changes = {};
      if (dirty & /*trees*/
      1)
        treetable_changes.tree = /*tree*/
        ctx3[5];
      if (dirty & /*date_range*/
      2)
        treetable_changes.end = /*date_range*/
        ctx3[1]?.end ?? null;
      treetable.$set(treetable_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(treetable.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(treetable.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(treetable, detaching);
    }
  };
}
function create_each_block30(ctx2) {
  let treetable;
  let current;
  treetable = new TreeTable_default({
    props: {
      tree: (
        /*tree*/
        ctx2[5]
      ),
      end: (
        /*date_range*/
        ctx2[1]?.end ?? null
      )
    }
  });
  return {
    c() {
      create_component(treetable.$$.fragment);
    },
    m(target, anchor) {
      mount_component(treetable, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const treetable_changes = {};
      if (dirty & /*trees*/
      1)
        treetable_changes.tree = /*tree*/
        ctx3[5];
      if (dirty & /*date_range*/
      2)
        treetable_changes.end = /*date_range*/
        ctx3[1]?.end ?? null;
      treetable.$set(treetable_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(treetable.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(treetable.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(treetable, detaching);
    }
  };
}
function create_fragment60(ctx2) {
  let t03;
  let div2;
  let div0;
  let t13;
  let div1;
  let current;
  let if_block = (
    /*chartData*/
    ctx2[2] && create_if_block29(ctx2)
  );
  let each_value_1 = ensure_array_like(
    /*trees*/
    ctx2[0].slice(0, 1)
  );
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks_1[i] = create_each_block_112(get_each_context_112(ctx2, each_value_1, i));
  }
  const out2 = (i) => transition_out(each_blocks_1[i], 1, 1, () => {
    each_blocks_1[i] = null;
  });
  let each_value = ensure_array_like(
    /*trees*/
    ctx2[0].slice(1)
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block30(get_each_context30(ctx2, each_value, i));
  }
  const out_1 = (i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  });
  return {
    c() {
      if (if_block)
        if_block.c();
      t03 = space();
      div2 = element("div");
      div0 = element("div");
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t13 = space();
      div1 = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(div0, "class", "column");
      attr(div1, "class", "column");
      attr(div2, "class", "row");
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, t03, anchor);
      insert(target, div2, anchor);
      append(div2, div0);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(div0, null);
        }
      }
      append(div2, t13);
      append(div2, div1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div1, null);
        }
      }
      current = true;
    },
    p(ctx3, [dirty]) {
      if (
        /*chartData*/
        ctx3[2]
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & /*chartData*/
          4) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block29(ctx3);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(t03.parentNode, t03);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
      if (dirty & /*trees, date_range*/
      3) {
        each_value_1 = ensure_array_like(
          /*trees*/
          ctx3[0].slice(0, 1)
        );
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_112(ctx3, each_value_1, i);
          if (each_blocks_1[i]) {
            each_blocks_1[i].p(child_ctx, dirty);
            transition_in(each_blocks_1[i], 1);
          } else {
            each_blocks_1[i] = create_each_block_112(child_ctx);
            each_blocks_1[i].c();
            transition_in(each_blocks_1[i], 1);
            each_blocks_1[i].m(div0, null);
          }
        }
        group_outros();
        for (i = each_value_1.length; i < each_blocks_1.length; i += 1) {
          out2(i);
        }
        check_outros();
      }
      if (dirty & /*trees, date_range*/
      3) {
        each_value = ensure_array_like(
          /*trees*/
          ctx3[0].slice(1)
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context30(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_block30(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(div1, null);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out_1(i);
        }
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks_1[i]);
      }
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      transition_out(if_block);
      each_blocks_1 = each_blocks_1.filter(Boolean);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        transition_out(each_blocks_1[i]);
      }
      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(t03);
        detach(div2);
      }
      if (if_block)
        if_block.d(detaching);
      destroy_each(each_blocks_1, detaching);
      destroy_each(each_blocks, detaching);
    }
  };
}
function instance61($$self, $$props, $$invalidate) {
  let chartData;
  let $chartContext;
  component_subscribe($$self, chartContext, ($$value) => $$invalidate(4, $chartContext = $$value));
  let { charts } = $$props;
  let { trees } = $$props;
  let { date_range: date_range2 } = $$props;
  $$self.$$set = ($$props2) => {
    if ("charts" in $$props2)
      $$invalidate(3, charts = $$props2.charts);
    if ("trees" in $$props2)
      $$invalidate(0, trees = $$props2.trees);
    if ("date_range" in $$props2)
      $$invalidate(1, date_range2 = $$props2.date_range);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*charts, $chartContext*/
    24) {
      $:
        $$invalidate(2, chartData = parseChartData(charts, $chartContext).unwrap_or(null));
    }
  };
  return [trees, date_range2, chartData, charts, $chartContext];
}
var BalanceSheet = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance61, create_fragment60, safe_not_equal, { charts: 3, trees: 0, date_range: 1 });
  }
};
var BalanceSheet_default = BalanceSheet;

// src/reports/tree_reports/IncomeStatement.svelte
function get_each_context31(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[5] = list[i];
  return child_ctx;
}
function get_each_context_113(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[5] = list[i];
  return child_ctx;
}
function create_if_block30(ctx2) {
  let chartswitcher;
  let current;
  chartswitcher = new ChartSwitcher_default({ props: { charts: (
    /*chartData*/
    ctx2[2]
  ) } });
  return {
    c() {
      create_component(chartswitcher.$$.fragment);
    },
    m(target, anchor) {
      mount_component(chartswitcher, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const chartswitcher_changes = {};
      if (dirty & /*chartData*/
      4)
        chartswitcher_changes.charts = /*chartData*/
        ctx3[2];
      chartswitcher.$set(chartswitcher_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(chartswitcher.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(chartswitcher.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(chartswitcher, detaching);
    }
  };
}
function create_each_block_113(ctx2) {
  let treetable;
  let current;
  treetable = new TreeTable_default({
    props: {
      tree: (
        /*tree*/
        ctx2[5]
      ),
      end: (
        /*date_range*/
        ctx2[1]?.end ?? null
      )
    }
  });
  return {
    c() {
      create_component(treetable.$$.fragment);
    },
    m(target, anchor) {
      mount_component(treetable, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const treetable_changes = {};
      if (dirty & /*trees*/
      1)
        treetable_changes.tree = /*tree*/
        ctx3[5];
      if (dirty & /*date_range*/
      2)
        treetable_changes.end = /*date_range*/
        ctx3[1]?.end ?? null;
      treetable.$set(treetable_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(treetable.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(treetable.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(treetable, detaching);
    }
  };
}
function create_each_block31(ctx2) {
  let treetable;
  let current;
  treetable = new TreeTable_default({
    props: {
      tree: (
        /*tree*/
        ctx2[5]
      ),
      end: (
        /*date_range*/
        ctx2[1]?.end ?? null
      )
    }
  });
  return {
    c() {
      create_component(treetable.$$.fragment);
    },
    m(target, anchor) {
      mount_component(treetable, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const treetable_changes = {};
      if (dirty & /*trees*/
      1)
        treetable_changes.tree = /*tree*/
        ctx3[5];
      if (dirty & /*date_range*/
      2)
        treetable_changes.end = /*date_range*/
        ctx3[1]?.end ?? null;
      treetable.$set(treetable_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(treetable.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(treetable.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(treetable, detaching);
    }
  };
}
function create_fragment61(ctx2) {
  let t03;
  let div2;
  let div0;
  let t13;
  let div1;
  let current;
  let if_block = (
    /*chartData*/
    ctx2[2] && create_if_block30(ctx2)
  );
  let each_value_1 = ensure_array_like(
    /*trees*/
    ctx2[0].slice(0, 2)
  );
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks_1[i] = create_each_block_113(get_each_context_113(ctx2, each_value_1, i));
  }
  const out2 = (i) => transition_out(each_blocks_1[i], 1, 1, () => {
    each_blocks_1[i] = null;
  });
  let each_value = ensure_array_like(
    /*trees*/
    ctx2[0].slice(2)
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block31(get_each_context31(ctx2, each_value, i));
  }
  const out_1 = (i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  });
  return {
    c() {
      if (if_block)
        if_block.c();
      t03 = space();
      div2 = element("div");
      div0 = element("div");
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t13 = space();
      div1 = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(div0, "class", "column");
      attr(div1, "class", "column");
      attr(div2, "class", "row");
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, t03, anchor);
      insert(target, div2, anchor);
      append(div2, div0);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(div0, null);
        }
      }
      append(div2, t13);
      append(div2, div1);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div1, null);
        }
      }
      current = true;
    },
    p(ctx3, [dirty]) {
      if (
        /*chartData*/
        ctx3[2]
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & /*chartData*/
          4) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block30(ctx3);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(t03.parentNode, t03);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
      if (dirty & /*trees, date_range*/
      3) {
        each_value_1 = ensure_array_like(
          /*trees*/
          ctx3[0].slice(0, 2)
        );
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_113(ctx3, each_value_1, i);
          if (each_blocks_1[i]) {
            each_blocks_1[i].p(child_ctx, dirty);
            transition_in(each_blocks_1[i], 1);
          } else {
            each_blocks_1[i] = create_each_block_113(child_ctx);
            each_blocks_1[i].c();
            transition_in(each_blocks_1[i], 1);
            each_blocks_1[i].m(div0, null);
          }
        }
        group_outros();
        for (i = each_value_1.length; i < each_blocks_1.length; i += 1) {
          out2(i);
        }
        check_outros();
      }
      if (dirty & /*trees, date_range*/
      3) {
        each_value = ensure_array_like(
          /*trees*/
          ctx3[0].slice(2)
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context31(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_block31(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(div1, null);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out_1(i);
        }
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks_1[i]);
      }
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      transition_out(if_block);
      each_blocks_1 = each_blocks_1.filter(Boolean);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        transition_out(each_blocks_1[i]);
      }
      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(t03);
        detach(div2);
      }
      if (if_block)
        if_block.d(detaching);
      destroy_each(each_blocks_1, detaching);
      destroy_each(each_blocks, detaching);
    }
  };
}
function instance62($$self, $$props, $$invalidate) {
  let chartData;
  let $chartContext;
  component_subscribe($$self, chartContext, ($$value) => $$invalidate(4, $chartContext = $$value));
  let { charts } = $$props;
  let { trees } = $$props;
  let { date_range: date_range2 } = $$props;
  $$self.$$set = ($$props2) => {
    if ("charts" in $$props2)
      $$invalidate(3, charts = $$props2.charts);
    if ("trees" in $$props2)
      $$invalidate(0, trees = $$props2.trees);
    if ("date_range" in $$props2)
      $$invalidate(1, date_range2 = $$props2.date_range);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*charts, $chartContext*/
    24) {
      $:
        $$invalidate(2, chartData = parseChartData(charts, $chartContext).unwrap_or(null));
    }
  };
  return [trees, date_range2, chartData, charts, $chartContext];
}
var IncomeStatement = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance62, create_fragment61, safe_not_equal, { charts: 3, trees: 0, date_range: 1 });
  }
};
var IncomeStatement_default = IncomeStatement;

// src/reports/tree_reports/TrialBalance.svelte
function get_each_context32(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[5] = list[i];
  return child_ctx;
}
function create_if_block31(ctx2) {
  let chartswitcher;
  let current;
  chartswitcher = new ChartSwitcher_default({ props: { charts: (
    /*chartData*/
    ctx2[2]
  ) } });
  return {
    c() {
      create_component(chartswitcher.$$.fragment);
    },
    m(target, anchor) {
      mount_component(chartswitcher, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const chartswitcher_changes = {};
      if (dirty & /*chartData*/
      4)
        chartswitcher_changes.charts = /*chartData*/
        ctx3[2];
      chartswitcher.$set(chartswitcher_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(chartswitcher.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(chartswitcher.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(chartswitcher, detaching);
    }
  };
}
function create_each_block32(ctx2) {
  let treetable;
  let current;
  treetable = new TreeTable_default({
    props: {
      tree: (
        /*tree*/
        ctx2[5]
      ),
      end: (
        /*date_range*/
        ctx2[1]?.end ?? null
      )
    }
  });
  return {
    c() {
      create_component(treetable.$$.fragment);
    },
    m(target, anchor) {
      mount_component(treetable, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const treetable_changes = {};
      if (dirty & /*trees*/
      1)
        treetable_changes.tree = /*tree*/
        ctx3[5];
      if (dirty & /*date_range*/
      2)
        treetable_changes.end = /*date_range*/
        ctx3[1]?.end ?? null;
      treetable.$set(treetable_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(treetable.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(treetable.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(treetable, detaching);
    }
  };
}
function create_fragment62(ctx2) {
  let t4;
  let div;
  let current;
  let if_block = (
    /*chartData*/
    ctx2[2] && create_if_block31(ctx2)
  );
  let each_value = ensure_array_like(
    /*trees*/
    ctx2[0]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block32(get_each_context32(ctx2, each_value, i));
  }
  const out2 = (i) => transition_out(each_blocks[i], 1, 1, () => {
    each_blocks[i] = null;
  });
  return {
    c() {
      if (if_block)
        if_block.c();
      t4 = space();
      div = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(div, "class", "row");
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, t4, anchor);
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div, null);
        }
      }
      current = true;
    },
    p(ctx3, [dirty]) {
      if (
        /*chartData*/
        ctx3[2]
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & /*chartData*/
          4) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block31(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 (dirty & /*trees, date_range*/
      3) {
        each_value = ensure_array_like(
          /*trees*/
          ctx3[0]
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context32(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_block32(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(div, null);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) {
          out2(i);
        }
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      transition_out(if_block);
      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(t4);
        detach(div);
      }
      if (if_block)
        if_block.d(detaching);
      destroy_each(each_blocks, detaching);
    }
  };
}
function instance63($$self, $$props, $$invalidate) {
  let chartData;
  let $chartContext;
  component_subscribe($$self, chartContext, ($$value) => $$invalidate(4, $chartContext = $$value));
  let { charts } = $$props;
  let { trees } = $$props;
  let { date_range: date_range2 } = $$props;
  $$self.$$set = ($$props2) => {
    if ("charts" in $$props2)
      $$invalidate(3, charts = $$props2.charts);
    if ("trees" in $$props2)
      $$invalidate(0, trees = $$props2.trees);
    if ("date_range" in $$props2)
      $$invalidate(1, date_range2 = $$props2.date_range);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*charts, $chartContext*/
    24) {
      $:
        $$invalidate(2, chartData = parseChartData(charts, $chartContext).unwrap_or(null));
    }
  };
  return [trees, date_range2, chartData, charts, $chartContext];
}
var TrialBalance = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance63, create_fragment62, safe_not_equal, { charts: 3, trees: 0, date_range: 1 });
  }
};
var TrialBalance_default = TrialBalance;

// src/reports/tree_reports/index.ts
var income_statement = new Route(
  "income_statement",
  IncomeStatement_default,
  (url) => get("income_statement", getURLFilters(url)),
  () => _("Income Statement")
);
var balance_sheet = new Route(
  "balance_sheet",
  BalanceSheet_default,
  (url) => get("balance_sheet", getURLFilters(url)),
  () => _("Balance Sheet")
);
var trial_balance = new Route(
  "trial_balance",
  TrialBalance_default,
  (url) => get("trial_balance", getURLFilters(url)),
  () => _("Trial Balance")
);

// src/reports/routes.ts
var frontend_routes = [
  account_report,
  balance_sheet,
  commodities2,
  documents,
  editor,
  new Route("errors", Errors_default, noload, () => _("Errors")),
  events,
  import_report,
  income_statement,
  new Route("query", Query_default, noload, () => _("Query")),
  trial_balance
];

// src/stores/editor.ts
var reloadAfterSavingEntrySlice = localStorageSyncedStore(
  "reload-after-saving-entry-slice",
  boolean,
  () => true
);
var addEntryContinue = localStorageSyncedStore(
  "add-entry-continue",
  boolean,
  () => false
);

// src/modals/AddEntry.svelte
function get_each_context33(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[9] = list[i][0];
  child_ctx[10] = list[i][1];
  return child_ctx;
}
function create_each_block33(ctx2) {
  let button;
  let t13;
  let t2_value = " ";
  let t22;
  let mounted;
  let dispose;
  function click_handler() {
    return (
      /*click_handler*/
      ctx2[6](
        /*Cls*/
        ctx2[9]
      )
    );
  }
  return {
    c() {
      button = element("button");
      button.textContent = `${/*displayName*/
      ctx2[10]}`;
      t13 = space();
      t22 = text(t2_value);
      attr(button, "type", "button");
      toggle_class(button, "muted", !/*entry*/
      (ctx2[0] instanceof /*Cls*/
      ctx2[9]));
    },
    m(target, anchor) {
      insert(target, button, anchor);
      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 & /*entry, entryTypes*/
      9) {
        toggle_class(button, "muted", !/*entry*/
        (ctx2[0] instanceof /*Cls*/
        ctx2[9]));
      }
    },
    d(detaching) {
      if (detaching) {
        detach(button);
        detach(t13);
        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 span0;
  let t4;
  let label;
  let input;
  let t5;
  let span1;
  let t7;
  let button;
  let current;
  let mounted;
  let dispose;
  let each_value = ensure_array_like(
    /*entryTypes*/
    ctx2[3]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block33(get_each_context33(ctx2, each_value, i));
  }
  function entry_1_entry_binding(value) {
    ctx2[7](value);
  }
  let entry_1_props = {};
  if (
    /*entry*/
    ctx2[0] !== void 0
  ) {
    entry_1_props.entry = /*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");
      span0 = element("span");
      t4 = space();
      label = element("label");
      input = element("input");
      t5 = space();
      span1 = element("span");
      span1.textContent = `${_("continue")}`;
      t7 = space();
      button = element("button");
      button.textContent = `${_("Save")}`;
      attr(span0, "class", "spacer");
      attr(input, "type", "checkbox");
      attr(span1, "class", "svelte-1c9vhis");
      attr(label, "class", "svelte-1c9vhis");
      attr(button, "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) {
        if (each_blocks[i]) {
          each_blocks[i].m(h3, null);
        }
      }
      append(form, t22);
      mount_component(entry_1, form, null);
      append(form, t32);
      append(form, div);
      append(div, span0);
      append(div, t4);
      append(div, label);
      append(label, input);
      input.checked = /*$addEntryContinue*/
      ctx2[2];
      append(label, t5);
      append(label, span1);
      append(div, t7);
      append(div, button);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            input,
            "change",
            /*input_change_handler*/
            ctx2[8]
          ),
          listen(form, "submit", prevent_default(
            /*submit*/
            ctx2[4]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if (dirty & /*entry, entryTypes*/
      9) {
        each_value = ensure_array_like(
          /*entryTypes*/
          ctx3[3]
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context33(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block33(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 & /*entry*/
      1) {
        updating_entry = true;
        entry_1_changes.entry = /*entry*/
        ctx3[0];
        add_flush_callback(() => updating_entry = false);
      }
      entry_1.$set(entry_1_changes);
      if (dirty & /*$addEntryContinue*/
      4) {
        input.checked = /*$addEntryContinue*/
        ctx3[2];
      }
    },
    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_fragment63(ctx2) {
  let modalbase;
  let current;
  modalbase = new ModalBase_default({
    props: {
      shown: (
        /*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 & /*shown*/
      2)
        modalbase_changes.shown = /*shown*/
        ctx3[1];
      if (dirty & /*$$scope, $addEntryContinue, entry*/
      8197) {
        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 instance64($$self, $$props, $$invalidate) {
  let shown;
  let $urlHash;
  let $addEntryContinue;
  component_subscribe($$self, urlHash, ($$value) => $$invalidate(5, $urlHash = $$value));
  component_subscribe($$self, addEntryContinue, ($$value) => $$invalidate(2, $addEntryContinue = $$value));
  const entryTypes = [[Transaction, _("Transaction")], [Balance, _("Balance")], [Note, _("Note")]];
  let entry = new Transaction(todayAsString());
  async function submit() {
    await saveEntries([entry]);
    const added_entry_date = entry.date;
    $$invalidate(0, entry = new entry.constructor(added_entry_date));
    if (!$addEntryContinue) {
      closeOverlay();
    }
  }
  const click_handler = (Cls) => {
    $$invalidate(0, entry = new Cls(entry.date));
  };
  function entry_1_entry_binding(value) {
    entry = value;
    $$invalidate(0, entry);
  }
  function input_change_handler() {
    $addEntryContinue = this.checked;
    addEntryContinue.set($addEntryContinue);
  }
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$urlHash*/
    32) {
      $:
        $$invalidate(1, shown = $urlHash === "add-transaction");
    }
  };
  return [
    entry,
    shown,
    $addEntryContinue,
    entryTypes,
    submit,
    $urlHash,
    click_handler,
    entry_1_entry_binding,
    input_change_handler
  ];
}
var AddEntry = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance64, create_fragment63, safe_not_equal, {});
  }
};
var AddEntry_default = AddEntry;

// src/editor/DeleteButton.svelte
function create_fragment64(ctx2) {
  let button;
  let t4;
  let button_title_value;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      t4 = text(
        /*buttonContent*/
        ctx2[1]
      );
      attr(button, "type", "button");
      attr(button, "class", "muted");
      attr(button, "title", button_title_value = _("Delete"));
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, t4);
      if (!mounted) {
        dispose = listen(button, "click", function() {
          if (is_function(
            /*onDelete*/
            ctx2[0]
          ))
            ctx2[0].apply(this, arguments);
        });
        mounted = true;
      }
    },
    p(new_ctx, [dirty]) {
      ctx2 = new_ctx;
      if (dirty & /*buttonContent*/
      2)
        set_data(
          t4,
          /*buttonContent*/
          ctx2[1]
        );
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      mounted = false;
      dispose();
    }
  };
}
function instance65($$self, $$props, $$invalidate) {
  let buttonContent;
  let { deleting } = $$props;
  let { onDelete } = $$props;
  $$self.$$set = ($$props2) => {
    if ("deleting" in $$props2)
      $$invalidate(2, deleting = $$props2.deleting);
    if ("onDelete" in $$props2)
      $$invalidate(0, onDelete = $$props2.onDelete);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*deleting*/
    4) {
      $:
        $$invalidate(1, buttonContent = deleting ? _("Deleting...") : _("Delete"));
    }
  };
  return [onDelete, buttonContent, deleting];
}
var DeleteButton = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance65, create_fragment64, safe_not_equal, { deleting: 2, onDelete: 0 });
  }
};
var DeleteButton_default = DeleteButton;

// src/editor/SliceEditor.svelte
function create_fragment65(ctx2) {
  let form;
  let div0;
  let renderEditor_action;
  let t03;
  let div1;
  let span0;
  let t13;
  let label;
  let input;
  let t22;
  let span1;
  let t4;
  let deletebutton;
  let t5;
  let savebutton;
  let current;
  let mounted;
  let dispose;
  deletebutton = new DeleteButton_default({
    props: {
      deleting: (
        /*deleting*/
        ctx2[1]
      ),
      onDelete: (
        /*deleteSlice*/
        ctx2[5]
      )
    }
  });
  savebutton = new SaveButton_default({
    props: {
      changed: (
        /*changed*/
        ctx2[2]
      ),
      saving: (
        /*saving*/
        ctx2[0]
      )
    }
  });
  return {
    c() {
      form = element("form");
      div0 = element("div");
      t03 = space();
      div1 = element("div");
      span0 = element("span");
      t13 = space();
      label = element("label");
      input = element("input");
      t22 = space();
      span1 = element("span");
      span1.textContent = `${_("reload")}`;
      t4 = space();
      create_component(deletebutton.$$.fragment);
      t5 = space();
      create_component(savebutton.$$.fragment);
      attr(div0, "class", "editor svelte-qiyosp");
      attr(span0, "class", "spacer");
      attr(input, "type", "checkbox");
      attr(span1, "class", "svelte-qiyosp");
      attr(label, "class", "svelte-qiyosp");
      attr(div1, "class", "flex-row");
    },
    m(target, anchor) {
      insert(target, form, anchor);
      append(form, div0);
      append(form, t03);
      append(form, div1);
      append(div1, span0);
      append(div1, t13);
      append(div1, label);
      append(label, input);
      input.checked = /*$reloadAfterSavingEntrySlice*/
      ctx2[3];
      append(label, t22);
      append(label, span1);
      append(div1, t4);
      mount_component(deletebutton, div1, null);
      append(div1, t5);
      mount_component(savebutton, div1, null);
      current = true;
      if (!mounted) {
        dispose = [
          action_destroyer(renderEditor_action = /*renderEditor*/
          ctx2[6].call(null, div0)),
          listen(
            input,
            "change",
            /*input_change_handler*/
            ctx2[12]
          ),
          listen(form, "submit", prevent_default(
            /*save*/
            ctx2[4]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (dirty & /*$reloadAfterSavingEntrySlice*/
      8) {
        input.checked = /*$reloadAfterSavingEntrySlice*/
        ctx3[3];
      }
      const deletebutton_changes = {};
      if (dirty & /*deleting*/
      2)
        deletebutton_changes.deleting = /*deleting*/
        ctx3[1];
      deletebutton.$set(deletebutton_changes);
      const savebutton_changes = {};
      if (dirty & /*changed*/
      4)
        savebutton_changes.changed = /*changed*/
        ctx3[2];
      if (dirty & /*saving*/
      1)
        savebutton_changes.saving = /*saving*/
        ctx3[0];
      savebutton.$set(savebutton_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(deletebutton.$$.fragment, local);
      transition_in(savebutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(deletebutton.$$.fragment, local);
      transition_out(savebutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(form);
      }
      destroy_component(deletebutton);
      destroy_component(savebutton);
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance66($$self, $$props, $$invalidate) {
  let changed;
  let $reloadAfterSavingEntrySlice;
  component_subscribe($$self, reloadAfterSavingEntrySlice, ($$value) => $$invalidate(3, $reloadAfterSavingEntrySlice = $$value));
  let { beancount_language_support } = $$props;
  let { slice: slice2 } = $$props;
  let { entry_hash } = $$props;
  let { sha256sum } = $$props;
  let currentSlice = slice2;
  let saving = false;
  let deleting = false;
  async function save() {
    $$invalidate(0, saving = true);
    try {
      $$invalidate(8, sha256sum = await put("source_slice", {
        entry_hash,
        source: currentSlice,
        sha256sum
      }));
      if ($reloadAfterSavingEntrySlice) {
        router_default.reload();
      }
      closeOverlay();
    } catch (error2) {
      notify_err(error2, (err3) => `Saving failed: ${err3.message}`);
    } finally {
      $$invalidate(0, saving = false);
    }
  }
  async function deleteSlice() {
    $$invalidate(1, deleting = true);
    try {
      await doDelete("source_slice", { entry_hash, sha256sum });
      $$invalidate(7, entry_hash = "");
      if ($reloadAfterSavingEntrySlice) {
        router_default.reload();
      }
      closeOverlay();
    } catch (error2) {
      notify_err(error2, (err3) => `Deleting failed: ${err3.message}`);
    } finally {
      $$invalidate(1, deleting = false);
    }
  }
  const { renderEditor } = initBeancountEditor(
    slice2,
    (state) => {
      $$invalidate(11, currentSlice = state.sliceDoc());
    },
    [
      {
        key: "Control-s",
        mac: "Meta-s",
        run: () => {
          save().catch(() => {
          });
          return true;
        }
      }
    ],
    beancount_language_support
  );
  function input_change_handler() {
    $reloadAfterSavingEntrySlice = this.checked;
    reloadAfterSavingEntrySlice.set($reloadAfterSavingEntrySlice);
  }
  $$self.$$set = ($$props2) => {
    if ("beancount_language_support" in $$props2)
      $$invalidate(9, beancount_language_support = $$props2.beancount_language_support);
    if ("slice" in $$props2)
      $$invalidate(10, slice2 = $$props2.slice);
    if ("entry_hash" in $$props2)
      $$invalidate(7, entry_hash = $$props2.entry_hash);
    if ("sha256sum" in $$props2)
      $$invalidate(8, sha256sum = $$props2.sha256sum);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*currentSlice, slice*/
    3072) {
      $:
        $$invalidate(2, changed = currentSlice !== slice2);
    }
  };
  return [
    saving,
    deleting,
    changed,
    $reloadAfterSavingEntrySlice,
    save,
    deleteSlice,
    renderEditor,
    entry_hash,
    sha256sum,
    beancount_language_support,
    slice2,
    currentSlice,
    input_change_handler
  ];
}
var SliceEditor = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance66, create_fragment65, safe_not_equal, {
      beancount_language_support: 9,
      slice: 10,
      entry_hash: 7,
      sha256sum: 8
    });
  }
};
var SliceEditor_default = SliceEditor;

// src/modals/EntryContext.svelte
function get_each_context34(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[4] = list[i][0];
  child_ctx[5] = list[i][1];
  return child_ctx;
}
function get_each_context_114(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[8] = list[i];
  return child_ctx;
}
function get_each_context_25(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[4] = list[i][0];
  child_ctx[5] = list[i][1];
  return child_ctx;
}
function get_each_context_34(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[8] = list[i];
  return child_ctx;
}
function create_if_block32(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 = ensure_array_like(Object.entries(
    /*balances_before*/
    ctx2[1]
  ));
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_2.length; i += 1) {
    each_blocks_1[i] = create_each_block_25(get_each_context_25(ctx2, each_value_2, i));
  }
  let each_value = ensure_array_like(Object.entries(
    /*balances_after*/
    ctx2[2]
  ));
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block34(get_each_context34(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) {
        if (each_blocks_1[i]) {
          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) {
        if (each_blocks[i]) {
          each_blocks[i].m(tbody1, null);
        }
      }
    },
    p(ctx3, dirty) {
      if (dirty & /*Object, balances_before, $urlForAccount*/
      10) {
        each_value_2 = ensure_array_like(Object.entries(
          /*balances_before*/
          ctx3[1]
        ));
        let i;
        for (i = 0; i < each_value_2.length; i += 1) {
          const child_ctx = get_each_context_25(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_25(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 & /*Object, balances_after, $urlForAccount*/
      12) {
        each_value = ensure_array_like(Object.entries(
          /*balances_after*/
          ctx3[2]
        ));
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context34(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block34(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_34(ctx2) {
  let t0_value = (
    /*amount*/
    ctx2[8] + ""
  );
  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 & /*balances_before*/
      2 && t0_value !== (t0_value = /*amount*/
      ctx3[8] + ""))
        set_data(t03, t0_value);
    },
    d(detaching) {
      if (detaching) {
        detach(t03);
        detach(t13);
        detach(br);
      }
    }
  };
}
function create_each_block_25(ctx2) {
  let tr;
  let td0;
  let a;
  let t0_value = (
    /*account*/
    ctx2[4] + ""
  );
  let t03;
  let a_href_value;
  let t13;
  let td1;
  let t22;
  let each_value_3 = ensure_array_like(
    /*inventory*/
    ctx2[5]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value_3.length; i += 1) {
    each_blocks[i] = create_each_block_34(get_each_context_34(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](
        /*account*/
        ctx2[4]
      ));
    },
    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) {
        if (each_blocks[i]) {
          each_blocks[i].m(td1, null);
        }
      }
      append(tr, t22);
    },
    p(ctx3, dirty) {
      if (dirty & /*balances_before*/
      2 && t0_value !== (t0_value = /*account*/
      ctx3[4] + ""))
        set_data(t03, t0_value);
      if (dirty & /*$urlForAccount, balances_before*/
      10 && a_href_value !== (a_href_value = /*$urlForAccount*/
      ctx3[3](
        /*account*/
        ctx3[4]
      ))) {
        attr(a, "href", a_href_value);
      }
      if (dirty & /*Object, balances_before*/
      2) {
        each_value_3 = ensure_array_like(
          /*inventory*/
          ctx3[5]
        );
        let i;
        for (i = 0; i < each_value_3.length; i += 1) {
          const child_ctx = get_each_context_34(ctx3, each_value_3, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_34(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_114(ctx2) {
  let t0_value = (
    /*amount*/
    ctx2[8] + ""
  );
  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 & /*balances_after*/
      4 && t0_value !== (t0_value = /*amount*/
      ctx3[8] + ""))
        set_data(t03, t0_value);
    },
    d(detaching) {
      if (detaching) {
        detach(t03);
        detach(t13);
        detach(br);
      }
    }
  };
}
function create_each_block34(ctx2) {
  let tr;
  let td0;
  let a;
  let t0_value = (
    /*account*/
    ctx2[4] + ""
  );
  let t03;
  let a_href_value;
  let t13;
  let td1;
  let t22;
  let each_value_1 = ensure_array_like(
    /*inventory*/
    ctx2[5]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks[i] = create_each_block_114(get_each_context_114(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](
        /*account*/
        ctx2[4]
      ));
    },
    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) {
        if (each_blocks[i]) {
          each_blocks[i].m(td1, null);
        }
      }
      append(tr, t22);
    },
    p(ctx3, dirty) {
      if (dirty & /*balances_after*/
      4 && t0_value !== (t0_value = /*account*/
      ctx3[4] + ""))
        set_data(t03, t0_value);
      if (dirty & /*$urlForAccount, balances_after*/
      12 && a_href_value !== (a_href_value = /*$urlForAccount*/
      ctx3[3](
        /*account*/
        ctx3[4]
      ))) {
        attr(a, "href", a_href_value);
      }
      if (dirty & /*Object, balances_after*/
      4) {
        each_value_1 = ensure_array_like(
          /*inventory*/
          ctx3[5]
        );
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_114(ctx3, each_value_1, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_114(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_fragment66(ctx2) {
  let p;
  let t0_value = _("Location") + "";
  let t03;
  let t13;
  let code;
  let a;
  let t2_value = (
    /*entry*/
    ctx2[0].meta.filename + ""
  );
  let t22;
  let t32;
  let t4_value = (
    /*entry*/
    ctx2[0].meta.lineno + ""
  );
  let t4;
  let a_href_value;
  let t5;
  let if_block_anchor;
  let if_block = (
    /*balances_before*/
    ctx2[1] && /*balances_after*/
    ctx2[2] && create_if_block32(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(
        /*entry*/
        ctx2[0].meta.filename?.toString() ?? "",
        /*entry*/
        ctx2[0].meta.lineno?.toString() ?? ""
      ));
    },
    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 & /*entry*/
      1 && t2_value !== (t2_value = /*entry*/
      ctx3[0].meta.filename + ""))
        set_data(t22, t2_value);
      if (dirty & /*entry*/
      1 && t4_value !== (t4_value = /*entry*/
      ctx3[0].meta.lineno + ""))
        set_data(t4, t4_value);
      if (dirty & /*entry*/
      1 && a_href_value !== (a_href_value = urlForSource(
        /*entry*/
        ctx3[0].meta.filename?.toString() ?? "",
        /*entry*/
        ctx3[0].meta.lineno?.toString() ?? ""
      ))) {
        attr(a, "href", a_href_value);
      }
      if (
        /*balances_before*/
        ctx3[1] && /*balances_after*/
        ctx3[2]
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block32(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);
        detach(t5);
        detach(if_block_anchor);
      }
      if (if_block)
        if_block.d(detaching);
    }
  };
}
function instance67($$self, $$props, $$invalidate) {
  let $urlForAccount;
  component_subscribe($$self, urlForAccount, ($$value) => $$invalidate(3, $urlForAccount = $$value));
  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, $urlForAccount];
}
var EntryContext = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance67, create_fragment66, safe_not_equal, {
      entry: 0,
      balances_before: 1,
      balances_after: 2
    });
  }
};
var EntryContext_default = EntryContext;

// src/modals/Context.svelte
function create_catch_block_1(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 = (
    /*response*/
    ctx2[4] && create_if_block33(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 (
        /*response*/
        ctx3[4]
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
          if (dirty & /*content*/
          4) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block33(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 (detaching) {
        detach(if_block_anchor);
      }
      if (if_block)
        if_block.d(detaching);
    }
  };
}
function create_if_block33(ctx2) {
  let entrycontext;
  let t4;
  let await_block_anchor;
  let promise;
  let current;
  entrycontext = new EntryContext_default({
    props: {
      entry: (
        /*response*/
        ctx2[4].entry
      ),
      balances_before: (
        /*response*/
        ctx2[4].balances_before
      ),
      balances_after: (
        /*response*/
        ctx2[4].balances_after
      )
    }
  });
  let info2 = {
    ctx: ctx2,
    current: null,
    token: null,
    hasCatch: true,
    pending: create_pending_block_1,
    then: create_then_block_1,
    catch: create_catch_block,
    value: 5,
    blocks: [, , ,]
  };
  handle_promise(promise = getBeancountLanguageSupport(), info2);
  return {
    c() {
      create_component(entrycontext.$$.fragment);
      t4 = space();
      await_block_anchor = empty();
      info2.block.c();
    },
    m(target, anchor) {
      mount_component(entrycontext, target, anchor);
      insert(target, t4, anchor);
      insert(target, await_block_anchor, anchor);
      info2.block.m(target, info2.anchor = anchor);
      info2.mount = () => await_block_anchor.parentNode;
      info2.anchor = await_block_anchor;
      current = true;
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      const entrycontext_changes = {};
      if (dirty & /*content*/
      4)
        entrycontext_changes.entry = /*response*/
        ctx2[4].entry;
      if (dirty & /*content*/
      4)
        entrycontext_changes.balances_before = /*response*/
        ctx2[4].balances_before;
      if (dirty & /*content*/
      4)
        entrycontext_changes.balances_after = /*response*/
        ctx2[4].balances_after;
      entrycontext.$set(entrycontext_changes);
      update_await_block_branch(info2, ctx2, dirty);
    },
    i(local) {
      if (current)
        return;
      transition_in(entrycontext.$$.fragment, local);
      transition_in(info2.block);
      current = true;
    },
    o(local) {
      transition_out(entrycontext.$$.fragment, local);
      for (let i = 0; i < 3; i += 1) {
        const block = info2.blocks[i];
        transition_out(block);
      }
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t4);
        detach(await_block_anchor);
      }
      destroy_component(entrycontext, detaching);
      info2.block.d(detaching);
      info2.token = null;
      info2 = null;
    }
  };
}
function create_catch_block(ctx2) {
  let t4;
  return {
    c() {
      t4 = text("Loading tree-sitter language failed...");
    },
    m(target, anchor) {
      insert(target, t4, anchor);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(t4);
      }
    }
  };
}
function create_then_block_1(ctx2) {
  let sliceeditor;
  let current;
  sliceeditor = new SliceEditor_default({
    props: {
      entry_hash: (
        /*entry_hash*/
        ctx2[0]
      ),
      slice: (
        /*response*/
        ctx2[4].slice
      ),
      sha256sum: (
        /*response*/
        ctx2[4].sha256sum
      ),
      beancount_language_support: (
        /*beancount_language_support*/
        ctx2[5]
      )
    }
  });
  return {
    c() {
      create_component(sliceeditor.$$.fragment);
    },
    m(target, anchor) {
      mount_component(sliceeditor, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const sliceeditor_changes = {};
      if (dirty & /*entry_hash*/
      1)
        sliceeditor_changes.entry_hash = /*entry_hash*/
        ctx3[0];
      if (dirty & /*content*/
      4)
        sliceeditor_changes.slice = /*response*/
        ctx3[4].slice;
      if (dirty & /*content*/
      4)
        sliceeditor_changes.sha256sum = /*response*/
        ctx3[4].sha256sum;
      sliceeditor.$set(sliceeditor_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(sliceeditor.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(sliceeditor.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(sliceeditor, detaching);
    }
  };
}
function create_pending_block_1(ctx2) {
  return {
    c: noop,
    m: noop,
    p: noop,
    i: noop,
    o: noop,
    d: noop
  };
}
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 info2 = {
    ctx: ctx2,
    current: null,
    token: null,
    hasCatch: true,
    pending: create_pending_block,
    then: create_then_block,
    catch: create_catch_block_1,
    value: 4,
    blocks: [, , ,]
  };
  handle_promise(promise = /*content*/
  ctx2[2], info2);
  return {
    c() {
      div = element("div");
      info2.block.c();
      attr(div, "class", "content");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      info2.block.m(div, info2.anchor = null);
      info2.mount = () => div;
      info2.anchor = null;
      current = true;
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      info2.ctx = ctx2;
      if (dirty & /*content*/
      4 && promise !== (promise = /*content*/
      ctx2[2]) && handle_promise(promise, info2)) {
      } else {
        update_await_block_branch(info2, ctx2, dirty);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(info2.block);
      current = true;
    },
    o(local) {
      for (let i = 0; i < 3; i += 1) {
        const block = info2.blocks[i];
        transition_out(block);
      }
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      info2.block.d();
      info2.token = null;
      info2 = null;
    }
  };
}
function create_fragment67(ctx2) {
  let modalbase;
  let current;
  modalbase = new ModalBase_default({
    props: {
      shown: (
        /*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 & /*shown*/
      2)
        modalbase_changes.shown = /*shown*/
        ctx3[1];
      if (dirty & /*$$scope, content, entry_hash*/
      69) {
        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 instance68($$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 & /*$urlHash*/
    8) {
      $:
        $$invalidate(1, shown = $urlHash.startsWith("context"));
    }
    if ($$self.$$.dirty & /*shown, $urlHash*/
    10) {
      $:
        $$invalidate(0, entry_hash = shown ? $urlHash.slice(8) : "");
    }
    if ($$self.$$.dirty & /*shown, entry_hash*/
    3) {
      $:
        $$invalidate(2, content2 = shown ? get("context", { entry_hash }) : null);
    }
  };
  return [entry_hash, shown, content2, $urlHash];
}
var Context = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance68, create_fragment67, safe_not_equal, {});
  }
};
var Context_default = Context;

// src/document-upload.ts
function dragover(event, closestTarget) {
  if (event.dataTransfer?.types.includes("Files") ?? event.dataTransfer?.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) {
  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 date4 = target.getAttribute("data-entry-date") ?? todayAsString();
    const uploadedFiles = [];
    for (const dataTransferFile of event.dataTransfer.files) {
      let { name: name2 } = dataTransferFile;
      if (!/^\d{4}-\d{2}-\d{2}/.test(name2)) {
        name2 = `${date4} ${name2}`;
      }
      uploadedFiles.push({ dataTransferFile, name: name2 });
    }
    account.set(targetAccount ?? "");
    hash.set(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,
        (error2) => {
          notify_err(
            error2,
            (e3) => `Adding document metadata failed: ${e3.message}`
          );
        }
      );
    }
  }
}
delegate(document, "drop", ".droptarget", drop);

// src/modals/DocumentUpload.svelte
function get_each_context35(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[12] = list[i];
  return child_ctx;
}
function get_each_context_115(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_115(ctx2) {
  let div;
  let input;
  let mounted;
  let dispose;
  function input_input_handler() {
    ctx2[8].call(
      input,
      /*each_value_1*/
      ctx2[16],
      /*file_index*/
      ctx2[17]
    );
  }
  return {
    c() {
      div = element("div");
      input = element("input");
      attr(input, "class", "file svelte-v4rmq1");
      attr(div, "class", "fieldset svelte-v4rmq1");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, input);
      set_input_value(
        input,
        /*file*/
        ctx2[15].name
      );
      if (!mounted) {
        dispose = listen(input, "input", input_input_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx2 = new_ctx;
      if (dirty & /*$files*/
      1 && input.value !== /*file*/
      ctx2[15].name) {
        set_input_value(
          input,
          /*file*/
          ctx2[15].name
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_each_block35(ctx2) {
  let option;
  let t_value = (
    /*folder*/
    ctx2[12] + ""
  );
  let t4;
  let option_value_value;
  return {
    c() {
      option = element("option");
      t4 = text(t_value);
      option.__value = option_value_value = /*folder*/
      ctx2[12];
      set_input_value(option, option.__value);
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t4);
    },
    p(ctx3, dirty) {
      if (dirty & /*documents*/
      4 && t_value !== (t_value = /*folder*/
      ctx3[12] + ""))
        set_data(t4, t_value);
      if (dirty & /*documents*/
      4 && option_value_value !== (option_value_value = /*folder*/
      ctx3[12])) {
        option.__value = option_value_value;
        set_input_value(option, 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 = ensure_array_like(
    /*$files*/
    ctx2[0]
  );
  let each_blocks_1 = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks_1[i] = create_each_block_115(get_each_context_115(ctx2, each_value_1, i));
  }
  let each_value = ensure_array_like(
    /*documents*/
    ctx2[2]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block35(get_each_context35(ctx2, each_value, i));
  }
  function accountinput_value_binding(value) {
    ctx2[10](value);
  }
  let accountinput_props = {};
  if (
    /*$account*/
    ctx2[4] !== void 0
  ) {
    accountinput_props.value = /*$account*/
    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 (
        /*documents_folder*/
        ctx2[1] === void 0
      )
        add_render_callback(() => (
          /*select_change_handler*/
          ctx2[9].call(select)
        ));
      attr(div0, "class", "fieldset svelte-v4rmq1");
      attr(div1, "class", "fieldset account svelte-v4rmq1");
      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) {
        if (each_blocks_1[i]) {
          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) {
        if (each_blocks[i]) {
          each_blocks[i].m(select, null);
        }
      }
      select_option(
        select,
        /*documents_folder*/
        ctx2[1],
        true
      );
      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",
            /*select_change_handler*/
            ctx2[9]
          ),
          listen(form, "submit", prevent_default(
            /*submit*/
            ctx2[6]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx3, dirty) {
      if (dirty & /*$files*/
      1) {
        each_value_1 = ensure_array_like(
          /*$files*/
          ctx3[0]
        );
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_115(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_115(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 & /*documents*/
      4) {
        each_value = ensure_array_like(
          /*documents*/
          ctx3[2]
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context35(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block35(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 & /*documents_folder, documents*/
      6) {
        select_option(
          select,
          /*documents_folder*/
          ctx3[1]
        );
      }
      const accountinput_changes = {};
      if (!updating_value && dirty & /*$account*/
      16) {
        updating_value = true;
        accountinput_changes.value = /*$account*/
        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_fragment68(ctx2) {
  let modalbase;
  let current;
  modalbase = new ModalBase_default({
    props: {
      shown: (
        /*shown*/
        ctx2[3]
      ),
      closeHandler: (
        /*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 & /*shown*/
      8)
        modalbase_changes.shown = /*shown*/
        ctx3[3];
      if (dirty & /*$$scope, $account, documents_folder, documents, $files*/
      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 instance69($$self, $$props, $$invalidate) {
  let shown;
  let documents2;
  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, (error2) => {
        notify_err(error2, (err3) => `Upload error: ${err3.message}`);
      });
    }));
    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, documents2), $$invalidate(7, $options);
  }
  function accountinput_value_binding(value) {
    $account = value;
    account.set($account);
  }
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$files*/
    1) {
      $:
        $$invalidate(3, shown = !!$files.length);
    }
    if ($$self.$$.dirty & /*$options*/
    128) {
      $:
        $$invalidate(2, documents2 = $options.documents);
    }
  };
  return [
    $files,
    documents_folder,
    documents2,
    shown,
    $account,
    closeHandler,
    submit,
    $options,
    input_input_handler,
    select_change_handler,
    accountinput_value_binding
  ];
}
var DocumentUpload = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance69, create_fragment68, safe_not_equal, {});
  }
};
var DocumentUpload_default = DocumentUpload;

// src/modals/Export.svelte
function create_if_block34(ctx2) {
  let div;
  let h3;
  let t22;
  let a;
  let a_href_value;
  return {
    c() {
      div = element("div");
      h3 = element("h3");
      h3.textContent = `${_("Export")}:`;
      t22 = space();
      a = element("a");
      a.textContent = `${_("Download currently filtered entries as a Beancount file")}`;
      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);
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
    }
  };
}
function create_default_slot9(ctx2) {
  let if_block_anchor;
  let if_block = (
    /*shown*/
    ctx2[0] && create_if_block34(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 (
        /*shown*/
        ctx3[0]
      ) {
        if (if_block) {
        } else {
          if_block = create_if_block34(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 (detaching) {
        detach(if_block_anchor);
      }
      if (if_block)
        if_block.d(detaching);
    }
  };
}
function create_fragment69(ctx2) {
  let modalbase;
  let current;
  modalbase = new ModalBase_default({
    props: {
      shown: (
        /*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 & /*shown*/
      1)
        modalbase_changes.shown = /*shown*/
        ctx3[0];
      if (dirty & /*$$scope, shown*/
      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 instance70($$self, $$props, $$invalidate) {
  let shown;
  let $urlHash;
  component_subscribe($$self, urlHash, ($$value) => $$invalidate(1, $urlHash = $$value));
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$urlHash*/
    2) {
      $:
        $$invalidate(0, shown = $urlHash === "export");
    }
  };
  return [shown, $urlHash];
}
var Export = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance70, create_fragment69, safe_not_equal, {});
  }
};
var Export_default = Export;

// src/modals/Modals.svelte
function create_fragment70(ctx2) {
  let addentry;
  let t03;
  let context2;
  let t13;
  let documentupload;
  let t22;
  let export_1;
  let current;
  addentry = new AddEntry_default({});
  context2 = new Context_default({});
  documentupload = new DocumentUpload_default({});
  export_1 = new Export_default({});
  return {
    c() {
      create_component(addentry.$$.fragment);
      t03 = space();
      create_component(context2.$$.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(context2, 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(context2.$$.fragment, local);
      transition_in(documentupload.$$.fragment, local);
      transition_in(export_1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(addentry.$$.fragment, local);
      transition_out(context2.$$.fragment, local);
      transition_out(documentupload.$$.fragment, local);
      transition_out(export_1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t03);
        detach(t13);
        detach(t22);
      }
      destroy_component(addentry, detaching);
      destroy_component(context2, detaching);
      destroy_component(documentupload, detaching);
      destroy_component(export_1, detaching);
    }
  };
}
var Modals = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, null, create_fragment70, safe_not_equal, {});
  }
};
var Modals_default = Modals;

// src/sidebar/AccountSelector.svelte
function create_fragment71(ctx2) {
  let li;
  let autocompleteinput;
  let updating_value;
  let current;
  function autocompleteinput_value_binding(value) {
    ctx2[3](value);
  }
  let autocompleteinput_props = {
    placeholder: _("Go to account"),
    suggestions: (
      /*$accounts*/
      ctx2[1]
    ),
    className: "account-selector",
    key: "g a"
  };
  if (
    /*value*/
    ctx2[0] !== void 0
  ) {
    autocompleteinput_props.value = /*value*/
    ctx2[0];
  }
  autocompleteinput = new AutocompleteInput_default({ props: autocompleteinput_props });
  binding_callbacks.push(() => bind(autocompleteinput, "value", autocompleteinput_value_binding));
  autocompleteinput.$on(
    "select",
    /*select*/
    ctx2[2]
  );
  autocompleteinput.$on(
    "enter",
    /*select*/
    ctx2[2]
  );
  return {
    c() {
      li = element("li");
      create_component(autocompleteinput.$$.fragment);
    },
    m(target, anchor) {
      insert(target, li, anchor);
      mount_component(autocompleteinput, li, null);
      current = true;
    },
    p(ctx3, [dirty]) {
      const autocompleteinput_changes = {};
      if (dirty & /*$accounts*/
      2)
        autocompleteinput_changes.suggestions = /*$accounts*/
        ctx3[1];
      if (!updating_value && dirty & /*value*/
      1) {
        updating_value = true;
        autocompleteinput_changes.value = /*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) {
      if (detaching) {
        detach(li);
      }
      destroy_component(autocompleteinput);
    }
  };
}
function instance71($$self, $$props, $$invalidate) {
  let $urlForAccount;
  let $accounts;
  component_subscribe($$self, urlForAccount, ($$value) => $$invalidate(4, $urlForAccount = $$value));
  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(options3) {
    super();
    init2(this, options3, instance71, create_fragment71, safe_not_equal, {});
  }
};
var AccountSelector_default = AccountSelector;

// src/sidebar/SidebarLink.svelte
function create_if_block35(ctx2) {
  let span;
  let t_value = (
    /*bubble*/
    ctx2[3][0] + ""
  );
  let t4;
  return {
    c() {
      span = element("span");
      t4 = text(t_value);
      attr(span, "class", "bubble svelte-unghjo");
      toggle_class(
        span,
        "error",
        /*bubble*/
        ctx2[3][1] === "error"
      );
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t4);
    },
    p(ctx3, dirty) {
      if (dirty & /*bubble*/
      8 && t_value !== (t_value = /*bubble*/
      ctx3[3][0] + ""))
        set_data(t4, t_value);
      if (dirty & /*bubble*/
      8) {
        toggle_class(
          span,
          "error",
          /*bubble*/
          ctx3[3][1] === "error"
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
    }
  };
}
function create_fragment72(ctx2) {
  let li;
  let a;
  let t03;
  let t13;
  let keyboardShortcut_action;
  let t22;
  let current;
  let mounted;
  let dispose;
  let if_block = (
    /*bubble*/
    ctx2[3] && /*bubble*/
    ctx2[3][0] > 0 && create_if_block35(ctx2)
  );
  const default_slot_template = (
    /*#slots*/
    ctx2[11].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx2,
    /*$$scope*/
    ctx2[10],
    null
  );
  return {
    c() {
      li = element("li");
      a = element("a");
      t03 = text(
        /*name*/
        ctx2[0]
      );
      t13 = space();
      if (if_block)
        if_block.c();
      t22 = space();
      if (default_slot)
        default_slot.c();
      attr(
        a,
        "href",
        /*href*/
        ctx2[4]
      );
      attr(
        a,
        "data-remote",
        /*remote*/
        ctx2[2]
      );
      attr(a, "class", "svelte-unghjo");
      toggle_class(
        a,
        "selected",
        /*selected*/
        ctx2[5]
      );
      attr(li, "class", "svelte-unghjo");
    },
    m(target, anchor) {
      insert(target, li, anchor);
      append(li, a);
      append(a, t03);
      append(a, t13);
      if (if_block)
        if_block.m(a, null);
      append(li, t22);
      if (default_slot) {
        default_slot.m(li, null);
      }
      current = true;
      if (!mounted) {
        dispose = action_destroyer(keyboardShortcut_action = keyboardShortcut.call(
          null,
          a,
          /*key*/
          ctx2[1]
        ));
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (!current || dirty & /*name*/
      1)
        set_data(
          t03,
          /*name*/
          ctx3[0]
        );
      if (
        /*bubble*/
        ctx3[3] && /*bubble*/
        ctx3[3][0] > 0
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block35(ctx3);
          if_block.c();
          if_block.m(a, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (!current || dirty & /*href*/
      16) {
        attr(
          a,
          "href",
          /*href*/
          ctx3[4]
        );
      }
      if (!current || dirty & /*remote*/
      4) {
        attr(
          a,
          "data-remote",
          /*remote*/
          ctx3[2]
        );
      }
      if (keyboardShortcut_action && is_function(keyboardShortcut_action.update) && dirty & /*key*/
      2)
        keyboardShortcut_action.update.call(
          null,
          /*key*/
          ctx3[1]
        );
      if (!current || dirty & /*selected*/
      32) {
        toggle_class(
          a,
          "selected",
          /*selected*/
          ctx3[5]
        );
      }
      if (default_slot) {
        if (default_slot.p && (!current || dirty & /*$$scope*/
        1024)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx3,
            /*$$scope*/
            ctx3[10],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx3[10]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx3[10],
              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(li);
      }
      if (if_block)
        if_block.d();
      if (default_slot)
        default_slot.d(detaching);
      mounted = false;
      dispose();
    }
  };
}
function instance72($$self, $$props, $$invalidate) {
  let href;
  let selected;
  let $pathname;
  let $synced_query_string;
  let $base_url;
  component_subscribe($$self, pathname, ($$value) => $$invalidate(7, $pathname = $$value));
  component_subscribe($$self, synced_query_string, ($$value) => $$invalidate(8, $synced_query_string = $$value));
  component_subscribe($$self, base_url, ($$value) => $$invalidate(9, $base_url = $$value));
  let { $$slots: slots = {}, $$scope } = $$props;
  let { report } = $$props;
  let { name: name2 } = $$props;
  let { key: key2 = void 0 } = $$props;
  let { remote = void 0 } = $$props;
  let { bubble = void 0 } = $$props;
  $$self.$$set = ($$props2) => {
    if ("report" in $$props2)
      $$invalidate(6, report = $$props2.report);
    if ("name" in $$props2)
      $$invalidate(0, name2 = $$props2.name);
    if ("key" in $$props2)
      $$invalidate(1, key2 = $$props2.key);
    if ("remote" in $$props2)
      $$invalidate(2, remote = $$props2.remote);
    if ("bubble" in $$props2)
      $$invalidate(3, bubble = $$props2.bubble);
    if ("$$scope" in $$props2)
      $$invalidate(10, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*remote, report, $base_url, $synced_query_string*/
    836) {
      $:
        $$invalidate(4, href = remote ? report : `${$base_url}${report}/${$synced_query_string}`);
    }
    if ($$self.$$.dirty & /*remote, href, $pathname*/
    148) {
      $:
        $$invalidate(5, selected = remote ? false : href.includes($pathname));
    }
  };
  return [
    name2,
    key2,
    remote,
    bubble,
    href,
    selected,
    report,
    $pathname,
    $synced_query_string,
    $base_url,
    $$scope,
    slots
  ];
}
var SidebarLink = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance72, create_fragment72, safe_not_equal, {
      report: 6,
      name: 0,
      key: 1,
      remote: 2,
      bubble: 3
    });
  }
};
var SidebarLink_default = SidebarLink;

// src/sidebar/AsideContents.svelte
function get_each_context36(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[8] = list[i];
  return child_ctx;
}
function get_each_context_116(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[11] = list[i].query_string;
  child_ctx[12] = list[i].name;
  return child_ctx;
}
function get_each_context_26(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[15] = list[i][0];
  child_ctx[16] = list[i][1];
  return child_ctx;
}
function create_if_block_310(ctx2) {
  let ul;
  let current;
  let each_value_2 = ensure_array_like(
    /*sidebar_links*/
    ctx2[1]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value_2.length; i += 1) {
    each_blocks[i] = create_each_block_26(get_each_context_26(ctx2, each_value_2, i));
  }
  const out2 = (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", "navigation svelte-mmgz8u");
    },
    m(target, anchor) {
      insert(target, ul, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(ul, null);
        }
      }
      current = true;
    },
    p(ctx3, dirty) {
      if (dirty & /*sidebar_links*/
      2) {
        each_value_2 = ensure_array_like(
          /*sidebar_links*/
          ctx3[1]
        );
        let i;
        for (i = 0; i < each_value_2.length; i += 1) {
          const child_ctx = get_each_context_26(ctx3, each_value_2, 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_26(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(ul, null);
          }
        }
        group_outros();
        for (i = each_value_2.length; i < each_blocks.length; i += 1) {
          out2(i);
        }
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      for (let i = 0; i < each_value_2.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_block_26(ctx2) {
  let link_1;
  let current;
  link_1 = new SidebarLink_default({
    props: {
      report: (
        /*link*/
        ctx2[16]
      ),
      name: (
        /*label*/
        ctx2[15]
      ),
      remote: true
    }
  });
  return {
    c() {
      create_component(link_1.$$.fragment);
    },
    m(target, anchor) {
      mount_component(link_1, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const link_1_changes = {};
      if (dirty & /*sidebar_links*/
      2)
        link_1_changes.report = /*link*/
        ctx3[16];
      if (dirty & /*sidebar_links*/
      2)
        link_1_changes.name = /*label*/
        ctx3[15];
      link_1.$set(link_1_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(link_1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(link_1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(link_1, detaching);
    }
  };
}
function create_if_block_213(ctx2) {
  let ul;
  let each_value_1 = ensure_array_like(
    /*user_queries*/
    ctx2[3]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks[i] = create_each_block_116(get_each_context_116(ctx2, each_value_1, i));
  }
  return {
    c() {
      ul = element("ul");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(ul, "class", "submenu svelte-mmgz8u");
    },
    m(target, anchor) {
      insert(target, ul, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(ul, null);
        }
      }
    },
    p(ctx3, dirty) {
      if (dirty & /*user_queries, truncate*/
      40) {
        each_value_1 = ensure_array_like(
          /*user_queries*/
          ctx3[3]
        );
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_116(ctx3, each_value_1, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_116(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_1.length;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(ul);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_each_block_116(ctx2) {
  let li;
  let a;
  let t0_value = (
    /*truncate*/
    ctx2[5](
      /*name*/
      ctx2[12]
    ) + ""
  );
  let t03;
  let a_href_value;
  let t13;
  return {
    c() {
      li = element("li");
      a = element("a");
      t03 = text(t0_value);
      t13 = space();
      attr(a, "href", a_href_value = urlFor("query/", { query_string: (
        /*query_string*/
        ctx2[11]
      ) }));
      attr(a, "class", "svelte-mmgz8u");
      attr(li, "class", "svelte-mmgz8u");
    },
    m(target, anchor) {
      insert(target, li, anchor);
      append(li, a);
      append(a, t03);
      append(li, t13);
    },
    p(ctx3, dirty) {
      if (dirty & /*user_queries*/
      8 && t0_value !== (t0_value = /*truncate*/
      ctx3[5](
        /*name*/
        ctx3[12]
      ) + ""))
        set_data(t03, t0_value);
      if (dirty & /*user_queries*/
      8 && a_href_value !== (a_href_value = urlFor("query/", { query_string: (
        /*query_string*/
        ctx3[11]
      ) }))) {
        attr(a, "href", a_href_value);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(li);
      }
    }
  };
}
function create_default_slot_22(ctx2) {
  let if_block_anchor;
  let if_block = (
    /*user_queries*/
    ctx2[3].length && create_if_block_213(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 (
        /*user_queries*/
        ctx3[3].length
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block_213(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 (detaching) {
        detach(if_block_anchor);
      }
      if (if_block)
        if_block.d(detaching);
    }
  };
}
function create_default_slot_12(ctx2) {
  let a;
  let keyboardShortcut_action;
  let mounted;
  let dispose;
  return {
    c() {
      a = element("a");
      a.textContent = "+";
      attr(a, "href", "#add-transaction");
      attr(a, "class", "secondary add-transaction svelte-mmgz8u");
    },
    m(target, anchor) {
      insert(target, a, anchor);
      if (!mounted) {
        dispose = action_destroyer(keyboardShortcut_action = keyboardShortcut.call(null, a, "n"));
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching) {
        detach(a);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_119(ctx2) {
  let link_1;
  let current;
  link_1 = new SidebarLink_default({
    props: {
      report: "errors",
      name: _("Errors"),
      bubble: [
        /*$errors*/
        ctx2[4].length,
        "error"
      ]
    }
  });
  return {
    c() {
      create_component(link_1.$$.fragment);
    },
    m(target, anchor) {
      mount_component(link_1, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const link_1_changes = {};
      if (dirty & /*$errors*/
      16)
        link_1_changes.bubble = [
          /*$errors*/
          ctx3[4].length,
          "error"
        ];
      link_1.$set(link_1_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(link_1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(link_1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(link_1, detaching);
    }
  };
}
function create_default_slot10(ctx2) {
  let a;
  let a_title_value;
  return {
    c() {
      a = element("a");
      a.textContent = "\u2B07";
      attr(a, "href", "#export");
      attr(a, "class", "secondary svelte-mmgz8u");
      attr(a, "title", a_title_value = _("Export"));
    },
    m(target, anchor) {
      insert(target, a, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching) {
        detach(a);
      }
    }
  };
}
function create_if_block36(ctx2) {
  let ul;
  let current;
  let each_value = ensure_array_like(
    /*extension_reports*/
    ctx2[0]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block36(get_each_context36(ctx2, each_value, i));
  }
  const out2 = (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", "navigation svelte-mmgz8u");
    },
    m(target, anchor) {
      insert(target, ul, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(ul, null);
        }
      }
      current = true;
    },
    p(ctx3, dirty) {
      if (dirty & /*extension_reports*/
      1) {
        each_value = ensure_array_like(
          /*extension_reports*/
          ctx3[0]
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context36(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_block36(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) {
          out2(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) {
      if (detaching) {
        detach(ul);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_each_block36(ctx2) {
  let link_1;
  let current;
  link_1 = new SidebarLink_default({
    props: {
      report: `extension/${/*ext*/
      ctx2[8].name}`,
      name: (
        /*ext*/
        ctx2[8].report_title ?? ""
      )
    }
  });
  return {
    c() {
      create_component(link_1.$$.fragment);
    },
    m(target, anchor) {
      mount_component(link_1, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const link_1_changes = {};
      if (dirty & /*extension_reports*/
      1)
        link_1_changes.report = `extension/${/*ext*/
        ctx3[8].name}`;
      if (dirty & /*extension_reports*/
      1)
        link_1_changes.name = /*ext*/
        ctx3[8].report_title ?? "";
      link_1.$set(link_1_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(link_1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(link_1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(link_1, detaching);
    }
  };
}
function create_fragment73(ctx2) {
  let t03;
  let ul0;
  let link0;
  let t13;
  let link1;
  let t22;
  let link2;
  let t32;
  let link3;
  let t4;
  let link4;
  let t5;
  let accountselector;
  let t6;
  let ul1;
  let link5;
  let t7;
  let link6;
  let t8;
  let link7;
  let t9;
  let link8;
  let t10;
  let link9;
  let t11;
  let ul2;
  let link10;
  let t122;
  let t132;
  let link11;
  let t14;
  let link12;
  let t15;
  let link13;
  let t16;
  let if_block2_anchor;
  let current;
  let if_block0 = (
    /*sidebar_links*/
    ctx2[1].length && create_if_block_310(ctx2)
  );
  link0 = new SidebarLink_default({
    props: {
      report: "income_statement",
      name: _("Income Statement"),
      key: "g i"
    }
  });
  link1 = new SidebarLink_default({
    props: {
      report: "balance_sheet",
      name: _("Balance Sheet"),
      key: "g b"
    }
  });
  link2 = new SidebarLink_default({
    props: {
      report: "trial_balance",
      name: _("Trial Balance"),
      key: "g t"
    }
  });
  link3 = new SidebarLink_default({
    props: {
      report: "journal",
      name: _("Journal"),
      key: "g j"
    }
  });
  link4 = new SidebarLink_default({
    props: {
      report: "query",
      name: _("Query"),
      key: "g q",
      $$slots: { default: [create_default_slot_22] },
      $$scope: { ctx: ctx2 }
    }
  });
  accountselector = new AccountSelector_default({});
  link5 = new SidebarLink_default({
    props: {
      report: "holdings",
      name: _("Holdings"),
      key: "g h"
    }
  });
  link6 = new SidebarLink_default({
    props: {
      report: "commodities",
      name: _("Commodities"),
      key: "g c"
    }
  });
  link7 = new SidebarLink_default({
    props: {
      report: "documents",
      name: _("Documents"),
      key: "g d"
    }
  });
  link8 = new SidebarLink_default({
    props: {
      report: "events",
      name: _("Events"),
      key: "g E",
      bubble: [
        /*upcoming_events_count*/
        ctx2[2],
        "info"
      ]
    }
  });
  link9 = new SidebarLink_default({
    props: {
      report: "statistics",
      name: _("Statistics"),
      key: "g s"
    }
  });
  link10 = new SidebarLink_default({
    props: {
      report: "editor",
      name: _("Editor"),
      key: "g e",
      $$slots: { default: [create_default_slot_12] },
      $$scope: { ctx: ctx2 }
    }
  });
  let if_block1 = (
    /*$errors*/
    ctx2[4].length > 0 && create_if_block_119(ctx2)
  );
  link11 = new SidebarLink_default({
    props: {
      report: "import",
      name: _("Import"),
      key: "g n",
      $$slots: { default: [create_default_slot10] },
      $$scope: { ctx: ctx2 }
    }
  });
  link12 = new SidebarLink_default({
    props: {
      report: "options",
      name: _("Options"),
      key: "g o"
    }
  });
  link13 = new SidebarLink_default({
    props: {
      report: "help",
      name: _("Help"),
      key: "g H"
    }
  });
  let if_block2 = (
    /*extension_reports*/
    ctx2[0].length && create_if_block36(ctx2)
  );
  return {
    c() {
      if (if_block0)
        if_block0.c();
      t03 = space();
      ul0 = element("ul");
      create_component(link0.$$.fragment);
      t13 = space();
      create_component(link1.$$.fragment);
      t22 = space();
      create_component(link2.$$.fragment);
      t32 = space();
      create_component(link3.$$.fragment);
      t4 = space();
      create_component(link4.$$.fragment);
      t5 = space();
      create_component(accountselector.$$.fragment);
      t6 = space();
      ul1 = element("ul");
      create_component(link5.$$.fragment);
      t7 = space();
      create_component(link6.$$.fragment);
      t8 = space();
      create_component(link7.$$.fragment);
      t9 = space();
      create_component(link8.$$.fragment);
      t10 = space();
      create_component(link9.$$.fragment);
      t11 = space();
      ul2 = element("ul");
      create_component(link10.$$.fragment);
      t122 = space();
      if (if_block1)
        if_block1.c();
      t132 = space();
      create_component(link11.$$.fragment);
      t14 = space();
      create_component(link12.$$.fragment);
      t15 = space();
      create_component(link13.$$.fragment);
      t16 = space();
      if (if_block2)
        if_block2.c();
      if_block2_anchor = empty();
      attr(ul0, "class", "navigation svelte-mmgz8u");
      attr(ul1, "class", "navigation svelte-mmgz8u");
      attr(ul2, "class", "navigation svelte-mmgz8u");
    },
    m(target, anchor) {
      if (if_block0)
        if_block0.m(target, anchor);
      insert(target, t03, anchor);
      insert(target, ul0, anchor);
      mount_component(link0, ul0, null);
      append(ul0, t13);
      mount_component(link1, ul0, null);
      append(ul0, t22);
      mount_component(link2, ul0, null);
      append(ul0, t32);
      mount_component(link3, ul0, null);
      append(ul0, t4);
      mount_component(link4, ul0, null);
      append(ul0, t5);
      mount_component(accountselector, ul0, null);
      insert(target, t6, anchor);
      insert(target, ul1, anchor);
      mount_component(link5, ul1, null);
      append(ul1, t7);
      mount_component(link6, ul1, null);
      append(ul1, t8);
      mount_component(link7, ul1, null);
      append(ul1, t9);
      mount_component(link8, ul1, null);
      append(ul1, t10);
      mount_component(link9, ul1, null);
      insert(target, t11, anchor);
      insert(target, ul2, anchor);
      mount_component(link10, ul2, null);
      append(ul2, t122);
      if (if_block1)
        if_block1.m(ul2, null);
      append(ul2, t132);
      mount_component(link11, ul2, null);
      append(ul2, t14);
      mount_component(link12, ul2, null);
      append(ul2, t15);
      mount_component(link13, ul2, null);
      insert(target, t16, anchor);
      if (if_block2)
        if_block2.m(target, anchor);
      insert(target, if_block2_anchor, anchor);
      current = true;
    },
    p(ctx3, [dirty]) {
      if (
        /*sidebar_links*/
        ctx3[1].length
      ) {
        if (if_block0) {
          if_block0.p(ctx3, dirty);
          if (dirty & /*sidebar_links*/
          2) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_310(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 link4_changes = {};
      if (dirty & /*$$scope, user_queries*/
      524296) {
        link4_changes.$$scope = { dirty, ctx: ctx3 };
      }
      link4.$set(link4_changes);
      const link8_changes = {};
      if (dirty & /*upcoming_events_count*/
      4)
        link8_changes.bubble = [
          /*upcoming_events_count*/
          ctx3[2],
          "info"
        ];
      link8.$set(link8_changes);
      const link10_changes = {};
      if (dirty & /*$$scope*/
      524288) {
        link10_changes.$$scope = { dirty, ctx: ctx3 };
      }
      link10.$set(link10_changes);
      if (
        /*$errors*/
        ctx3[4].length > 0
      ) {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
          if (dirty & /*$errors*/
          16) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_119(ctx3);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(ul2, t132);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      const link11_changes = {};
      if (dirty & /*$$scope*/
      524288) {
        link11_changes.$$scope = { dirty, ctx: ctx3 };
      }
      link11.$set(link11_changes);
      if (
        /*extension_reports*/
        ctx3[0].length
      ) {
        if (if_block2) {
          if_block2.p(ctx3, dirty);
          if (dirty & /*extension_reports*/
          1) {
            transition_in(if_block2, 1);
          }
        } else {
          if_block2 = create_if_block36(ctx3);
          if_block2.c();
          transition_in(if_block2, 1);
          if_block2.m(if_block2_anchor.parentNode, if_block2_anchor);
        }
      } else if (if_block2) {
        group_outros();
        transition_out(if_block2, 1, 1, () => {
          if_block2 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block0);
      transition_in(link0.$$.fragment, local);
      transition_in(link1.$$.fragment, local);
      transition_in(link2.$$.fragment, local);
      transition_in(link3.$$.fragment, local);
      transition_in(link4.$$.fragment, local);
      transition_in(accountselector.$$.fragment, local);
      transition_in(link5.$$.fragment, local);
      transition_in(link6.$$.fragment, local);
      transition_in(link7.$$.fragment, local);
      transition_in(link8.$$.fragment, local);
      transition_in(link9.$$.fragment, local);
      transition_in(link10.$$.fragment, local);
      transition_in(if_block1);
      transition_in(link11.$$.fragment, local);
      transition_in(link12.$$.fragment, local);
      transition_in(link13.$$.fragment, local);
      transition_in(if_block2);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(link0.$$.fragment, local);
      transition_out(link1.$$.fragment, local);
      transition_out(link2.$$.fragment, local);
      transition_out(link3.$$.fragment, local);
      transition_out(link4.$$.fragment, local);
      transition_out(accountselector.$$.fragment, local);
      transition_out(link5.$$.fragment, local);
      transition_out(link6.$$.fragment, local);
      transition_out(link7.$$.fragment, local);
      transition_out(link8.$$.fragment, local);
      transition_out(link9.$$.fragment, local);
      transition_out(link10.$$.fragment, local);
      transition_out(if_block1);
      transition_out(link11.$$.fragment, local);
      transition_out(link12.$$.fragment, local);
      transition_out(link13.$$.fragment, local);
      transition_out(if_block2);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t03);
        detach(ul0);
        detach(t6);
        detach(ul1);
        detach(t11);
        detach(ul2);
        detach(t16);
        detach(if_block2_anchor);
      }
      if (if_block0)
        if_block0.d(detaching);
      destroy_component(link0);
      destroy_component(link1);
      destroy_component(link2);
      destroy_component(link3);
      destroy_component(link4);
      destroy_component(accountselector);
      destroy_component(link5);
      destroy_component(link6);
      destroy_component(link7);
      destroy_component(link8);
      destroy_component(link9);
      destroy_component(link10);
      if (if_block1)
        if_block1.d();
      destroy_component(link11);
      destroy_component(link12);
      destroy_component(link13);
      if (if_block2)
        if_block2.d(detaching);
    }
  };
}
function instance73($$self, $$props, $$invalidate) {
  let user_queries;
  let upcoming_events_count;
  let sidebar_links;
  let extension_reports;
  let $extensions;
  let $ledgerData;
  let $errors;
  component_subscribe($$self, extensions, ($$value) => $$invalidate(6, $extensions = $$value));
  component_subscribe($$self, ledgerData, ($$value) => $$invalidate(7, $ledgerData = $$value));
  component_subscribe($$self, errors, ($$value) => $$invalidate(4, $errors = $$value));
  const truncate = (s) => s.length < 25 ? s : `${s.slice(25)}\u2026`;
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$ledgerData*/
    128) {
      $:
        $$invalidate(3, user_queries = $ledgerData.user_queries);
    }
    if ($$self.$$.dirty & /*$ledgerData*/
    128) {
      $:
        $$invalidate(2, upcoming_events_count = $ledgerData.upcoming_events_count);
    }
    if ($$self.$$.dirty & /*$ledgerData*/
    128) {
      $:
        $$invalidate(1, sidebar_links = $ledgerData.sidebar_links);
    }
    if ($$self.$$.dirty & /*$extensions*/
    64) {
      $:
        $$invalidate(0, extension_reports = $extensions.filter((e3) => e3.report_title));
    }
  };
  return [
    extension_reports,
    sidebar_links,
    upcoming_events_count,
    user_queries,
    $errors,
    truncate,
    $extensions,
    $ledgerData
  ];
}
var AsideContents = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance73, create_fragment73, safe_not_equal, {});
  }
};
var AsideContents_default = AsideContents;

// src/sidebar/AsideWithButton.svelte
function create_if_block37(ctx2) {
  let div;
  let mounted;
  let dispose;
  return {
    c() {
      div = element("div");
      attr(div, "class", "overlay svelte-18c6e75");
      attr(div, "aria-hidden", "true");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (!mounted) {
        dispose = listen(
          div,
          "click",
          /*toggle*/
          ctx2[1]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_fragment74(ctx2) {
  let t03;
  let div;
  let button;
  let t22;
  let a;
  let t4;
  let aside;
  let asidecontents;
  let current;
  let mounted;
  let dispose;
  let if_block = (
    /*active*/
    ctx2[0] && create_if_block37(ctx2)
  );
  asidecontents = new AsideContents_default({});
  return {
    c() {
      if (if_block)
        if_block.c();
      t03 = space();
      div = element("div");
      button = element("button");
      button.textContent = "\u2630";
      t22 = space();
      a = element("a");
      a.textContent = "+";
      t4 = space();
      aside = element("aside");
      create_component(asidecontents.$$.fragment);
      attr(button, "type", "button");
      attr(button, "class", "svelte-18c6e75");
      attr(a, "class", "button svelte-18c6e75");
      attr(a, "href", "#add-transaction");
      attr(div, "class", "aside-buttons svelte-18c6e75");
      toggle_class(
        div,
        "active",
        /*active*/
        ctx2[0]
      );
      attr(aside, "class", "svelte-18c6e75");
      toggle_class(
        aside,
        "active",
        /*active*/
        ctx2[0]
      );
    },
    m(target, anchor) {
      if (if_block)
        if_block.m(target, anchor);
      insert(target, t03, anchor);
      insert(target, div, anchor);
      append(div, button);
      append(div, t22);
      append(div, a);
      insert(target, t4, anchor);
      insert(target, aside, anchor);
      mount_component(asidecontents, aside, null);
      current = true;
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*toggle*/
          ctx2[1]
        );
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (
        /*active*/
        ctx3[0]
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block37(ctx3);
          if_block.c();
          if_block.m(t03.parentNode, t03);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (!current || dirty & /*active*/
      1) {
        toggle_class(
          div,
          "active",
          /*active*/
          ctx3[0]
        );
      }
      if (!current || dirty & /*active*/
      1) {
        toggle_class(
          aside,
          "active",
          /*active*/
          ctx3[0]
        );
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(asidecontents.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(asidecontents.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t03);
        detach(div);
        detach(t4);
        detach(aside);
      }
      if (if_block)
        if_block.d(detaching);
      destroy_component(asidecontents);
      mounted = false;
      dispose();
    }
  };
}
function instance74($$self, $$props, $$invalidate) {
  let active = false;
  const toggle2 = () => {
    $$invalidate(0, active = !active);
  };
  return [active, toggle2];
}
var AsideWithButton = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance74, create_fragment74, safe_not_equal, {});
  }
};
var AsideWithButton_default = AsideWithButton;

// src/sidebar/FilterForm.svelte
function create_fragment75(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: (
      /*$years*/
      ctx2[4]
    ),
    key: "f t",
    clearButton: true,
    setSize: true
  };
  if (
    /*time_filter_value*/
    ctx2[2] !== void 0
  ) {
    autocompleteinput0_props.value = /*time_filter_value*/
    ctx2[2];
  }
  autocompleteinput0 = new AutocompleteInput_default({ props: autocompleteinput0_props });
  binding_callbacks.push(() => bind(autocompleteinput0, "value", autocompleteinput0_value_binding));
  autocompleteinput0.$on(
    "blur",
    /*submit*/
    ctx2[6]
  );
  autocompleteinput0.$on(
    "select",
    /*submit*/
    ctx2[6]
  );
  autocompleteinput0.$on(
    "enter",
    /*submit*/
    ctx2[6]
  );
  function autocompleteinput1_value_binding(value) {
    ctx2[11](value);
  }
  let autocompleteinput1_props = {
    placeholder: _("Account"),
    suggestions: (
      /*$accounts*/
      ctx2[5]
    ),
    key: "f a",
    clearButton: true,
    setSize: true
  };
  if (
    /*account_filter_value*/
    ctx2[0] !== void 0
  ) {
    autocompleteinput1_props.value = /*account_filter_value*/
    ctx2[0];
  }
  autocompleteinput1 = new AutocompleteInput_default({ props: autocompleteinput1_props });
  binding_callbacks.push(() => bind(autocompleteinput1, "value", autocompleteinput1_value_binding));
  autocompleteinput1.$on(
    "blur",
    /*submit*/
    ctx2[6]
  );
  autocompleteinput1.$on(
    "select",
    /*submit*/
    ctx2[6]
  );
  autocompleteinput1.$on(
    "enter",
    /*submit*/
    ctx2[6]
  );
  function autocompleteinput2_value_binding(value) {
    ctx2[12](value);
  }
  let autocompleteinput2_props = {
    placeholder: _("Filter by tag, payee, ..."),
    suggestions: (
      /*fql_filter_suggestions*/
      ctx2[3]
    ),
    key: "f f",
    clearButton: true,
    setSize: true,
    valueExtractor,
    valueSelector
  };
  if (
    /*fql_filter_value*/
    ctx2[1] !== void 0
  ) {
    autocompleteinput2_props.value = /*fql_filter_value*/
    ctx2[1];
  }
  autocompleteinput2 = new AutocompleteInput_default({ props: autocompleteinput2_props });
  binding_callbacks.push(() => bind(autocompleteinput2, "value", autocompleteinput2_value_binding));
  autocompleteinput2.$on(
    "blur",
    /*submit*/
    ctx2[6]
  );
  autocompleteinput2.$on(
    "select",
    /*submit*/
    ctx2[6]
  );
  autocompleteinput2.$on(
    "enter",
    /*submit*/
    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-lw8mrp");
      attr(form, "class", "svelte-lw8mrp");
    },
    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(
          /*submit*/
          ctx2[6]
        ));
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      const autocompleteinput0_changes = {};
      if (dirty & /*$years*/
      16)
        autocompleteinput0_changes.suggestions = /*$years*/
        ctx3[4];
      if (!updating_value && dirty & /*time_filter_value*/
      4) {
        updating_value = true;
        autocompleteinput0_changes.value = /*time_filter_value*/
        ctx3[2];
        add_flush_callback(() => updating_value = false);
      }
      autocompleteinput0.$set(autocompleteinput0_changes);
      const autocompleteinput1_changes = {};
      if (dirty & /*$accounts*/
      32)
        autocompleteinput1_changes.suggestions = /*$accounts*/
        ctx3[5];
      if (!updating_value_1 && dirty & /*account_filter_value*/
      1) {
        updating_value_1 = true;
        autocompleteinput1_changes.value = /*account_filter_value*/
        ctx3[0];
        add_flush_callback(() => updating_value_1 = false);
      }
      autocompleteinput1.$set(autocompleteinput1_changes);
      const autocompleteinput2_changes = {};
      if (dirty & /*fql_filter_suggestions*/
      8)
        autocompleteinput2_changes.suggestions = /*fql_filter_suggestions*/
        ctx3[3];
      if (!updating_value_2 && dirty & /*fql_filter_value*/
      2) {
        updating_value_2 = true;
        autocompleteinput2_changes.value = /*fql_filter_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?.[0] ?? value;
}
function valueSelector(value, input) {
  const selectionStart = input.selectionStart ?? 0;
  const match = input.value.slice(0, selectionStart).match(/\S*$/);
  const matchLength = match?.[0]?.length;
  return matchLength !== void 0 ? `${input.value.slice(0, selectionStart - matchLength)}${value}${input.value.slice(selectionStart)}` : value;
}
function instance75($$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, years, ($$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 & /*$tags, $links, $payees*/
    896) {
      $:
        $$invalidate(3, fql_filter_suggestions = [
          ...$tags.map((tag) => `#${tag}`),
          ...$links.map((link) => `^${link}`),
          ...$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(options3) {
    super();
    init2(this, options3, instance75, create_fragment75, safe_not_equal, {});
  }
};
var FilterForm_default = FilterForm;

// src/sidebar/HeaderIcon.svelte
function create_fragment76(ctx2) {
  let svg2;
  let path0;
  let path1;
  return {
    c() {
      svg2 = svg_element("svg");
      path0 = svg_element("path");
      path1 = svg_element("path");
      attr(path0, "fill", "#FFF");
      attr(path0, "d", "M14 17.854c0 1.537-.498 2.86-1.493 3.97-.995 1.11-2.288 1.796-3.88 2.057v2.64c0 .14-.044.26-.134.35-.09.09-.205.14-.345.14H6.122c-.13 0-.242-.04-.337-.14-.095-.09-.143-.21-.143-.34v-2.64c-.66-.09-1.298-.24-1.913-.46-.62-.22-1.13-.44-1.53-.67-.4-.22-.77-.46-1.11-.72-.34-.26-.58-.45-.7-.57-.13-.12-.21-.21-.26-.27-.17-.21-.18-.42-.03-.62l1.54-2.03c.07-.1.18-.16.34-.18.15-.02.27.03.36.14l.03.03c1.13 1 2.34 1.63 3.64 1.89.37.08.74.12 1.11.12.81 0 1.52-.21 2.14-.64.61-.43.92-1.04.92-1.83 0-.28-.08-.55-.23-.8-.15-.25-.32-.46-.51-.63-.19-.17-.48-.36-.88-.56-.4-.21-.73-.37-.99-.48-.26-.12-.66-.28-1.2-.49l-.93-.38c-.23-.09-.54-.22-.93-.4-.39-.17-.7-.33-.94-.46s-.52-.31-.85-.53c-.33-.22-.6-.43-.8-.64-.21-.202-.42-.45-.65-.74-.23-.28-.41-.572-.53-.87-.13-.295-.23-.63-.32-1-.06-.4-.1-.79-.1-1.2 0-1.39.49-2.6 1.47-3.65S4.07 3.5 5.64 3.2V.48c0-.13.05-.243.143-.34.097-.09.21-.14.34-.14H8.15c.14 0 .254.045.344.136.09.09.135.206.135.346v2.652c.57.06 1.12.176 1.65.346.53.17.97.34 1.3.505.33.166.65.354.95.565.3.21.49.357.58.437.09.08.16.15.22.21.17.182.19.373.07.574l-1.21 2.2c-.08.15-.2.23-.35.24-.14.04-.28 0-.41-.1-.03-.03-.1-.09-.22-.18s-.31-.22-.59-.4c-.28-.17-.57-.33-.88-.48-.31-.14-.69-.27-1.12-.39-.44-.11-.86-.17-1.28-.17-.95 0-1.73.22-2.33.65-.6.44-.9.99-.9 1.68 0 .26.04.5.13.72.08.22.23.43.44.63s.41.36.59.5.464.29.84.47c.374.18.677.31.907.41.23.09.58.23 1.05.41.53.2.94.36 1.22.48s.66.29 1.14.53c.48.24.86.45 1.13.64.28.19.59.44.93.76.35.31.61.63.8.95.19.33.345.71.475 1.16.13.44.192.92.192 1.42z");
      attr(path0, "class", "svelte-16giu83");
      attr(path1, "fill", "#A6C4DA");
      attr(path1, "d", "M10 17.854c0 1.537.498 2.86 1.493 3.97.995 1.11 2.288 1.796 3.88 2.057v2.64c0 .14.044.26.134.35.09.09.205.14.345.14h2.026c.13 0 .242-.04.337-.14.095-.09.143-.21.143-.34v-2.64c.66-.09 1.298-.24 1.913-.46.62-.22 1.13-.44 1.53-.67.4-.22.77-.46 1.11-.72.34-.26.58-.45.7-.57.13-.12.21-.21.26-.27.17-.21.18-.42.03-.62l-1.54-2.03c-.07-.1-.18-.16-.34-.18-.15-.02-.27.03-.36.14l-.03.03c-1.13 1-2.34 1.63-3.64 1.89-.37.08-.74.12-1.11.12-.81 0-1.52-.21-2.14-.64-.61-.43-.92-1.04-.92-1.83 0-.28.08-.55.23-.8.15-.25.32-.46.51-.63.19-.17.48-.36.88-.56.4-.21.73-.37.99-.48.26-.12.66-.28 1.2-.49l.93-.38c.23-.09.54-.22.93-.4.39-.17.7-.33.94-.46s.52-.31.85-.53c.33-.22.6-.43.8-.64.21-.202.42-.45.65-.74.23-.28.41-.572.53-.87.13-.295.23-.63.32-1s.13-.762.13-1.174c0-1.382-.49-2.6-1.47-3.642s-2.27-1.74-3.84-2.04V.49c0-.13-.05-.245-.14-.34-.14-.1-.25-.15-.38-.15h-2.03c-.14 0-.254.045-.344.136-.09.09-.135.206-.135.346v2.652c-.57.06-1.122.176-1.657.346-.535.17-.97.34-1.306.505-.335.166-.652.354-.953.565-.3.21-.495.357-.585.437-.09.08-.166.15-.226.21-.17.182-.195.373-.075.574l1.215 2.2c.08.15.195.23.345.24.14.04.28 0 .41-.1.03-.03.1-.09.22-.18s.31-.22.59-.4c.27-.17.56-.33.87-.48.31-.14.68-.27 1.12-.39.43-.11.86-.17 1.28-.17.95 0 1.72.22 2.32.65.6.44.9.99.9 1.68 0 .26-.04.5-.13.72-.09.22-.24.43-.45.63-.21.2-.41.36-.6.5s-.47.29-.84.47c-.38.18-.68.31-.91.41-.23.09-.58.23-1.05.41-.53.2-.94.36-1.22.48s-.66.29-1.14.53c-.48.24-.86.45-1.14.64s-.58.44-.93.76c-.34.31-.61.63-.79.95-.19.33-.35.71-.48 1.16-.13.44-.2.92-.2 1.42z");
      attr(path1, "class", "svelte-16giu83");
      attr(svg2, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg2, "width", "24");
      attr(svg2, "height", "25");
      attr(svg2, "viewBox", "0 0 24 27");
      attr(svg2, "class", "svelte-16giu83");
      toggle_class(
        svg2,
        "loading",
        /*$is_loading*/
        ctx2[0]
      );
    },
    m(target, anchor) {
      insert(target, svg2, anchor);
      append(svg2, path0);
      append(svg2, path1);
    },
    p(ctx3, [dirty]) {
      if (dirty & /*$is_loading*/
      1) {
        toggle_class(
          svg2,
          "loading",
          /*$is_loading*/
          ctx3[0]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg2);
      }
    }
  };
}
function instance76($$self, $$props, $$invalidate) {
  let $is_loading;
  component_subscribe($$self, is_loading, ($$value) => $$invalidate(0, $is_loading = $$value));
  return [$is_loading];
}
var HeaderIcon = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance76, create_fragment76, safe_not_equal, {});
  }
};
var HeaderIcon_default = HeaderIcon;

// src/sidebar/AccountPageTitle.svelte
function get_each_context37(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[6] = list[i];
  child_ctx[9] = i;
  const constants_0 = (
    /*parts*/
    child_ctx[2].slice(
      0,
      /*index*/
      child_ctx[9] + 1
    ).join(":")
  );
  child_ctx[7] = constants_0;
  return child_ctx;
}
function create_if_block_120(ctx2) {
  let t4;
  return {
    c() {
      t4 = text(":");
    },
    m(target, anchor) {
      insert(target, t4, anchor);
    },
    d(detaching) {
      if (detaching) {
        detach(t4);
      }
    }
  };
}
function create_each_block37(ctx2) {
  let a;
  let t_value = (
    /*part*/
    ctx2[6] + ""
  );
  let t4;
  let a_href_value;
  let a_title_value;
  let if_block_anchor;
  let if_block = (
    /*index*/
    ctx2[9] < /*parts*/
    ctx2[2].length - 1 && create_if_block_120(ctx2)
  );
  return {
    c() {
      a = element("a");
      t4 = text(t_value);
      if (if_block)
        if_block.c();
      if_block_anchor = empty();
      attr(a, "href", a_href_value = /*$urlForAccount*/
      ctx2[3](
        /*name*/
        ctx2[7]
      ));
      attr(a, "title", a_title_value = /*name*/
      ctx2[7]);
      attr(a, "class", "svelte-lqe8fq");
    },
    m(target, anchor) {
      insert(target, a, anchor);
      append(a, t4);
      if (if_block)
        if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & /*parts*/
      4 && t_value !== (t_value = /*part*/
      ctx3[6] + ""))
        set_data(t4, t_value);
      if (dirty & /*$urlForAccount, parts*/
      12 && a_href_value !== (a_href_value = /*$urlForAccount*/
      ctx3[3](
        /*name*/
        ctx3[7]
      ))) {
        attr(a, "href", a_href_value);
      }
      if (dirty & /*parts*/
      4 && a_title_value !== (a_title_value = /*name*/
      ctx3[7])) {
        attr(a, "title", a_title_value);
      }
      if (
        /*index*/
        ctx3[9] < /*parts*/
        ctx3[2].length - 1
      ) {
        if (if_block) {
        } else {
          if_block = create_if_block_120(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 (detaching) {
        detach(a);
        detach(if_block_anchor);
      }
      if (if_block)
        if_block.d(detaching);
    }
  };
}
function create_if_block38(ctx2) {
  let span;
  let t03;
  let a;
  let t1_value = day(
    /*last*/
    ctx2[1].date
  ) + "";
  let t13;
  let a_href_value;
  let t22;
  return {
    c() {
      span = element("span");
      t03 = text("(Last entry: ");
      a = element("a");
      t13 = text(t1_value);
      t22 = text(")");
      attr(a, "href", a_href_value = "#context-" + /*last*/
      ctx2[1].entry_hash);
      attr(a, "class", "svelte-lqe8fq");
      attr(span, "class", "last-activity svelte-lqe8fq");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t03);
      append(span, a);
      append(a, t13);
      append(span, t22);
    },
    p(ctx3, dirty) {
      if (dirty & /*last*/
      2 && t1_value !== (t1_value = day(
        /*last*/
        ctx3[1].date
      ) + ""))
        set_data(t13, t1_value);
      if (dirty & /*last*/
      2 && a_href_value !== (a_href_value = "#context-" + /*last*/
      ctx3[1].entry_hash)) {
        attr(a, "href", a_href_value);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
    }
  };
}
function create_fragment77(ctx2) {
  let span;
  let t03;
  let accountindicator;
  let t13;
  let current;
  let each_value = ensure_array_like(
    /*parts*/
    ctx2[2]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block37(get_each_context37(ctx2, each_value, i));
  }
  accountindicator = new AccountIndicator_default({ props: { account: (
    /*account*/
    ctx2[0]
  ) } });
  let if_block = (
    /*last*/
    ctx2[1] && create_if_block38(ctx2)
  );
  return {
    c() {
      span = element("span");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t03 = space();
      create_component(accountindicator.$$.fragment);
      t13 = space();
      if (if_block)
        if_block.c();
      attr(span, "class", "droptarget svelte-lqe8fq");
      attr(
        span,
        "data-account-name",
        /*account*/
        ctx2[0]
      );
    },
    m(target, anchor) {
      insert(target, span, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(span, null);
        }
      }
      append(span, t03);
      mount_component(accountindicator, span, null);
      append(span, t13);
      if (if_block)
        if_block.m(span, null);
      current = true;
    },
    p(ctx3, [dirty]) {
      if (dirty & /*parts, $urlForAccount*/
      12) {
        each_value = ensure_array_like(
          /*parts*/
          ctx3[2]
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context37(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block37(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(span, t03);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
      const accountindicator_changes = {};
      if (dirty & /*account*/
      1)
        accountindicator_changes.account = /*account*/
        ctx3[0];
      accountindicator.$set(accountindicator_changes);
      if (
        /*last*/
        ctx3[1]
      ) {
        if (if_block) {
          if_block.p(ctx3, dirty);
        } else {
          if_block = create_if_block38(ctx3);
          if_block.c();
          if_block.m(span, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (!current || dirty & /*account*/
      1) {
        attr(
          span,
          "data-account-name",
          /*account*/
          ctx3[0]
        );
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(accountindicator.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(accountindicator.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
      destroy_each(each_blocks, detaching);
      destroy_component(accountindicator);
      if (if_block)
        if_block.d();
    }
  };
}
function instance77($$self, $$props, $$invalidate) {
  let parts;
  let details;
  let last;
  let $account_details;
  let $urlForAccount;
  component_subscribe($$self, account_details, ($$value) => $$invalidate(5, $account_details = $$value));
  component_subscribe($$self, urlForAccount, ($$value) => $$invalidate(3, $urlForAccount = $$value));
  let { account: account2 } = $$props;
  $$self.$$set = ($$props2) => {
    if ("account" in $$props2)
      $$invalidate(0, account2 = $$props2.account);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*account*/
    1) {
      $:
        $$invalidate(2, parts = account2.split(":"));
    }
    if ($$self.$$.dirty & /*$account_details, account*/
    33) {
      $:
        $$invalidate(4, details = $account_details[account2]);
    }
    if ($$self.$$.dirty & /*details*/
    16) {
      $:
        $$invalidate(1, last = details?.last_entry);
    }
  };
  return [account2, last, parts, $urlForAccount, details, $account_details];
}
var AccountPageTitle = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance77, create_fragment77, safe_not_equal, { account: 0 });
  }
};
var AccountPageTitle_default = AccountPageTitle;

// src/sidebar/PageTitle.svelte
function create_else_block10(ctx2) {
  let accountpagetitle;
  let current;
  accountpagetitle = new AccountPageTitle_default({ props: { account: (
    /*title*/
    ctx2[1]
  ) } });
  return {
    c() {
      create_component(accountpagetitle.$$.fragment);
    },
    m(target, anchor) {
      mount_component(accountpagetitle, target, anchor);
      current = true;
    },
    p(ctx3, dirty) {
      const accountpagetitle_changes = {};
      if (dirty & /*title*/
      2)
        accountpagetitle_changes.account = /*title*/
        ctx3[1];
      accountpagetitle.$set(accountpagetitle_changes);
    },
    i(local) {
      if (current)
        return;
      transition_in(accountpagetitle.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(accountpagetitle.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(accountpagetitle, detaching);
    }
  };
}
function create_if_block39(ctx2) {
  let t4;
  return {
    c() {
      t4 = text(
        /*title*/
        ctx2[1]
      );
    },
    m(target, anchor) {
      insert(target, t4, anchor);
    },
    p(ctx3, dirty) {
      if (dirty & /*title*/
      2)
        set_data(
          t4,
          /*title*/
          ctx3[1]
        );
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(t4);
      }
    }
  };
}
function create_fragment78(ctx2) {
  let strong;
  let current_block_type_index;
  let if_block;
  let current;
  const if_block_creators = [create_if_block39, create_else_block10];
  const if_blocks = [];
  function select_block_type(ctx3, dirty) {
    if (!/*is_account*/
    ctx3[0])
      return 0;
    return 1;
  }
  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() {
      strong = element("strong");
      if_block.c();
      attr(strong, "class", "svelte-1mx7cyo");
    },
    m(target, anchor) {
      insert(target, strong, anchor);
      if_blocks[current_block_type_index].m(strong, null);
      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(strong, null);
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(strong);
      }
      if_blocks[current_block_type_index].d();
    }
  };
}
function instance78($$self, $$props, $$invalidate) {
  let title;
  let type;
  let is_account;
  let $page_title;
  component_subscribe($$self, page_title, ($$value) => $$invalidate(3, $page_title = $$value));
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$page_title*/
    8) {
      $:
        $$invalidate(1, { title, type } = $page_title, title, ($$invalidate(2, type), $$invalidate(3, $page_title)));
    }
    if ($$self.$$.dirty & /*type*/
    4) {
      $:
        $$invalidate(0, is_account = type === "account");
    }
  };
  return [is_account, title, type, $page_title];
}
var PageTitle = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance78, create_fragment78, safe_not_equal, {});
  }
};
var PageTitle_default = PageTitle;

// src/sidebar/Header.svelte
function get_each_context38(ctx2, list, i) {
  const child_ctx = ctx2.slice();
  child_ctx[5] = list[i][0];
  child_ctx[6] = list[i][1];
  return child_ctx;
}
function create_if_block_121(ctx2) {
  let t4;
  return {
    c() {
      t4 = text("\xA0\u25BE");
    },
    m(target, anchor) {
      insert(target, t4, anchor);
    },
    d(detaching) {
      if (detaching) {
        detach(t4);
      }
    }
  };
}
function create_if_block40(ctx2) {
  let div;
  let ul;
  let each_value = ensure_array_like(
    /*other_ledgers*/
    ctx2[0]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block38(get_each_context38(ctx2, each_value, i));
  }
  return {
    c() {
      div = element("div");
      ul = element("ul");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(ul, "class", "svelte-ol2rwm");
      attr(div, "class", "beancount-files svelte-ol2rwm");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, ul);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(ul, null);
        }
      }
    },
    p(ctx3, dirty) {
      if (dirty & /*other_ledgers*/
      1) {
        each_value = ensure_array_like(
          /*other_ledgers*/
          ctx3[0]
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context38(ctx3, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block38(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;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_each_block38(ctx2) {
  let li;
  let a;
  let t0_value = (
    /*name*/
    ctx2[5] + ""
  );
  let t03;
  let a_href_value;
  let t13;
  return {
    c() {
      li = element("li");
      a = element("a");
      t03 = text(t0_value);
      t13 = space();
      attr(a, "href", a_href_value = /*url*/
      ctx2[6]);
      attr(a, "data-remote", "");
      attr(a, "class", "svelte-ol2rwm");
    },
    m(target, anchor) {
      insert(target, li, anchor);
      append(li, a);
      append(a, t03);
      append(li, t13);
    },
    p(ctx3, dirty) {
      if (dirty & /*other_ledgers*/
      1 && t0_value !== (t0_value = /*name*/
      ctx3[5] + ""))
        set_data(t03, t0_value);
      if (dirty & /*other_ledgers*/
      1 && a_href_value !== (a_href_value = /*url*/
      ctx3[6])) {
        attr(a, "href", a_href_value);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(li);
      }
    }
  };
}
function create_fragment79(ctx2) {
  let header;
  let headericon;
  let t03;
  let h1;
  let t13;
  let if_block0_anchor;
  let pagetitle;
  let t22;
  let t32;
  let button;
  let t4;
  let button_hidden_value;
  let keyboardShortcut_action;
  let t5;
  let span;
  let t6;
  let filterform;
  let current;
  let mounted;
  let dispose;
  headericon = new HeaderIcon_default({});
  let if_block0 = (
    /*has_dropdown*/
    ctx2[1] && create_if_block_121(ctx2)
  );
  pagetitle = new PageTitle_default({});
  let if_block1 = (
    /*has_dropdown*/
    ctx2[1] && create_if_block40(ctx2)
  );
  filterform = new FilterForm_default({});
  return {
    c() {
      header = element("header");
      create_component(headericon.$$.fragment);
      t03 = space();
      h1 = element("h1");
      t13 = text(
        /*$ledger_title*/
        ctx2[2]
      );
      if (if_block0)
        if_block0.c();
      if_block0_anchor = empty();
      create_component(pagetitle.$$.fragment);
      t22 = space();
      if (if_block1)
        if_block1.c();
      t32 = space();
      button = element("button");
      t4 = text("\u21BB");
      t5 = space();
      span = element("span");
      t6 = space();
      create_component(filterform.$$.fragment);
      attr(h1, "class", "svelte-ol2rwm");
      attr(button, "type", "button");
      button.hidden = button_hidden_value = !/*$has_changes*/
      ctx2[3];
      attr(button, "class", "reload-page svelte-ol2rwm");
      attr(span, "class", "spacer");
      attr(header, "class", "svelte-ol2rwm");
    },
    m(target, anchor) {
      insert(target, header, anchor);
      mount_component(headericon, header, null);
      append(header, t03);
      append(header, h1);
      append(h1, t13);
      if (if_block0)
        if_block0.m(h1, null);
      append(h1, if_block0_anchor);
      mount_component(pagetitle, h1, null);
      append(h1, t22);
      if (if_block1)
        if_block1.m(h1, null);
      append(header, t32);
      append(header, button);
      append(button, t4);
      append(header, t5);
      append(header, span);
      append(header, t6);
      mount_component(filterform, header, null);
      current = true;
      if (!mounted) {
        dispose = [
          action_destroyer(keyboardShortcut_action = keyboardShortcut.call(null, button, "r")),
          listen(button, "click", router_default.reload.bind(router_default))
        ];
        mounted = true;
      }
    },
    p(ctx3, [dirty]) {
      if (!current || dirty & /*$ledger_title*/
      4)
        set_data(
          t13,
          /*$ledger_title*/
          ctx3[2]
        );
      if (
        /*has_dropdown*/
        ctx3[1]
      ) {
        if (if_block0) {
        } else {
          if_block0 = create_if_block_121(ctx3);
          if_block0.c();
          if_block0.m(h1, if_block0_anchor);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*has_dropdown*/
        ctx3[1]
      ) {
        if (if_block1) {
          if_block1.p(ctx3, dirty);
        } else {
          if_block1 = create_if_block40(ctx3);
          if_block1.c();
          if_block1.m(h1, null);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (!current || dirty & /*$has_changes*/
      8 && button_hidden_value !== (button_hidden_value = !/*$has_changes*/
      ctx3[3])) {
        button.hidden = button_hidden_value;
      }
    },
    i(local) {
      if (current)
        return;
      transition_in(headericon.$$.fragment, local);
      transition_in(pagetitle.$$.fragment, local);
      transition_in(filterform.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(headericon.$$.fragment, local);
      transition_out(pagetitle.$$.fragment, local);
      transition_out(filterform.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(header);
      }
      destroy_component(headericon);
      if (if_block0)
        if_block0.d();
      destroy_component(pagetitle);
      if (if_block1)
        if_block1.d();
      destroy_component(filterform);
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance79($$self, $$props, $$invalidate) {
  let other_ledgers;
  let has_dropdown;
  let $ledgerData;
  let $ledger_title;
  let $has_changes;
  component_subscribe($$self, ledgerData, ($$value) => $$invalidate(4, $ledgerData = $$value));
  component_subscribe($$self, ledger_title, ($$value) => $$invalidate(2, $ledger_title = $$value));
  component_subscribe($$self, has_changes, ($$value) => $$invalidate(3, $has_changes = $$value));
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*$ledgerData*/
    16) {
      $:
        $$invalidate(0, other_ledgers = $ledgerData.other_ledgers);
    }
    if ($$self.$$.dirty & /*other_ledgers*/
    1) {
      $:
        $$invalidate(1, has_dropdown = other_ledgers.length);
    }
  };
  return [other_ledgers, has_dropdown, $ledger_title, $has_changes, $ledgerData];
}
var Header = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, instance79, create_fragment79, safe_not_equal, {});
  }
};
var Header_default = Header;

// src/sidebar/HeaderAndAside.svelte
function create_fragment80(ctx2) {
  let header;
  let t4;
  let asidewithbutton;
  let current;
  header = new Header_default({});
  asidewithbutton = new AsideWithButton_default({});
  return {
    c() {
      create_component(header.$$.fragment);
      t4 = space();
      create_component(asidewithbutton.$$.fragment);
    },
    m(target, anchor) {
      mount_component(header, target, anchor);
      insert(target, t4, anchor);
      mount_component(asidewithbutton, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current)
        return;
      transition_in(header.$$.fragment, local);
      transition_in(asidewithbutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(header.$$.fragment, local);
      transition_out(asidewithbutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t4);
      }
      destroy_component(header, detaching);
      destroy_component(asidewithbutton, detaching);
    }
  };
}
var HeaderAndAside = class extends SvelteComponent {
  constructor(options3) {
    super();
    init2(this, options3, null, create_fragment80, safe_not_equal, {});
  }
};
var HeaderAndAside_default = HeaderAndAside;

// src/sidebar/index.ts
function initSidebar() {
  page_title.subscribe(({ title }) => {
    document.title = `${title} - ${get_store_value(ledger_title)}`;
  });
  new HeaderAndAside_default({
    target: document.body,
    anchor: document.querySelector("article") ?? void 0
  });
  new Modals_default({
    target: document.body
  });
}

// src/svelte-custom-elements.ts
var SvelteCustomElementComponent = class {
  constructor(Component, validate) {
    this.Component = Component;
    this.validate = validate;
  }
  /** Load data and render the component for this route to the given target. */
  render(target, data) {
    const res2 = this.validate(data);
    if (res2.is_err) {
      const type = target.getAttribute("type");
      target.classList.add("error");
      target.replaceChildren(
        domHelpers.t(
          `Rendering component '${type}' failed due to invalid JSON data:`
        ),
        domHelpers.br(),
        domHelpers.pre(res2.error)
      );
      log_error("Invalid JSON for component:", data);
      return void 0;
    }
    const instance80 = new this.Component({ target, props: res2.value });
    return () => {
      instance80.$destroy();
    };
  }
};
var components = /* @__PURE__ */ new Map([
  [
    "charts",
    new SvelteCustomElementComponent(
      ChartSwitcher_default,
      (data) => parseChartData(data, get_store_value(chartContext)).map((charts) => ({
        charts
      }))
    )
  ]
]);
var SvelteCustomElement = class extends HTMLElement {
  destroy;
  connectedCallback() {
    if (this.destroy) {
      return;
    }
    const type = this.getAttribute("type");
    if (!type) {
      throw new Error("Component is missing type");
    }
    const comp = components.get(type);
    if (!comp) {
      throw new Error("Invalid component");
    }
    const script = this.querySelector("script");
    this.destroy = comp.render(
      this,
      script && script.type === "application/json" ? JSON.parse(script.innerHTML) : null
    );
  }
  disconnectedCallback() {
    try {
      this.destroy?.();
      this.destroy = void 0;
    } catch (e3) {
    }
  }
};

// src/tree-table/tree-table-custom-element.ts
var TreeTableCustomElement = class extends HTMLElement {
  constructor() {
    super();
    const expandAllLink = this.querySelector(".expand-all");
    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?.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("svelte-component", SvelteCustomElement);
  customElements.define("tree-table", TreeTableCustomElement);
}
router_default.on("page-loaded", () => {
  read_mtime();
  updatePageTitle();
  has_changes.set(false);
  handleExtensionPageLoad();
});
function pollForChanges() {
  get("changed").then((changed) => {
    if (changed) {
      has_changes.set(true);
      if (get_store_value(fava_options).auto_reload) {
        router_default.reload();
      } else {
        get("errors").then((v) => {
          errors.set(v);
        }, log_error);
        notify(_("File change detected. Click to reload."), "warning", () => {
          router_default.reload();
        });
      }
    }
  }, log_error);
}
function init3() {
  const initial = getScriptTagValue("#ledger-data", ledgerDataValidator);
  if (initial.is_ok) {
    ledgerData.set(initial.value);
  } else {
    log_error(initial.error);
  }
  read_mtime();
  let initial_mtime = true;
  ledger_mtime.subscribe(() => {
    if (initial_mtime) {
      initial_mtime = false;
      return;
    }
    get("ledger_data").then((v) => {
      ledgerData.set(v);
    }).catch((e3) => {
      notify_err(e3, (err3) => `Error fetching ledger data: ${err3.message}`);
    });
  });
  router_default.init(frontend_routes);
  setStoreValuesFromURL();
  syncStoreValuesToURL();
  initSidebar();
  initGlobalKeyboardShortcuts();
  defineCustomElements();
  setInterval(pollForChanges, 5e3);
  ledgerData.subscribe((val) => {
    errors.set(val.errors);
  });
  router_default.trigger("page-loaded");
}
init3();
/*! Bundled license information:

@ungap/custom-elements/index.js:
  (*! (c) Andrea Giammarchi @webreflection ISC *)
  (*! (c) Andrea Giammarchi - ISC *)
*/
