/* Datacore: Autogenerated ESBuild file. See https://github.com/blacksmithgu/datacore for source. */
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 __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// node_modules/parsimmon/build/parsimmon.umd.min.js
var require_parsimmon_umd_min = __commonJS({
  "node_modules/parsimmon/build/parsimmon.umd.min.js"(exports, module2) {
    !function(n3, t4) {
      "object" == typeof exports && "object" == typeof module2 ? module2.exports = t4() : "function" == typeof define && define.amd ? define([], t4) : "object" == typeof exports ? exports.Parsimmon = t4() : n3.Parsimmon = t4();
    }("undefined" != typeof self ? self : exports, function() {
      return function(n3) {
        var t4 = {};
        function r3(e3) {
          if (t4[e3])
            return t4[e3].exports;
          var u4 = t4[e3] = { i: e3, l: false, exports: {} };
          return n3[e3].call(u4.exports, u4, u4.exports, r3), u4.l = true, u4.exports;
        }
        return r3.m = n3, r3.c = t4, r3.d = function(n4, t5, e3) {
          r3.o(n4, t5) || Object.defineProperty(n4, t5, { configurable: false, enumerable: true, get: e3 });
        }, r3.r = function(n4) {
          Object.defineProperty(n4, "__esModule", { value: true });
        }, r3.n = function(n4) {
          var t5 = n4 && n4.__esModule ? function() {
            return n4.default;
          } : function() {
            return n4;
          };
          return r3.d(t5, "a", t5), t5;
        }, r3.o = function(n4, t5) {
          return Object.prototype.hasOwnProperty.call(n4, t5);
        }, r3.p = "", r3(r3.s = 0);
      }([function(n3, t4, r3) {
        "use strict";
        function e3(n4) {
          if (!(this instanceof e3))
            return new e3(n4);
          this._ = n4;
        }
        var u4 = e3.prototype;
        function o3(n4, t5) {
          for (var r4 = 0; r4 < n4; r4++)
            t5(r4);
        }
        function i4(n4, t5, r4) {
          return function(n5, t6) {
            o3(t6.length, function(r5) {
              n5(t6[r5], r5, t6);
            });
          }(function(r5, e4, u5) {
            t5 = n4(t5, r5, e4, u5);
          }, r4), t5;
        }
        function a3(n4, t5) {
          return i4(function(t6, r4, e4, u5) {
            return t6.concat([n4(r4, e4, u5)]);
          }, [], t5);
        }
        function f4(n4, t5) {
          var r4 = { v: 0, buf: t5 };
          return o3(n4, function() {
            var n5;
            r4 = { v: r4.v << 1 | (n5 = r4.buf, n5[0] >> 7), buf: function(n6) {
              var t6 = i4(function(n7, t7, r5, e4) {
                return n7.concat(r5 === e4.length - 1 ? Buffer.from([t7, 0]).readUInt16BE(0) : e4.readUInt16BE(r5));
              }, [], n6);
              return Buffer.from(a3(function(n7) {
                return (n7 << 1 & 65535) >> 8;
              }, t6));
            }(r4.buf) };
          }), r4;
        }
        function c3() {
          return "undefined" != typeof Buffer;
        }
        function s4() {
          if (!c3())
            throw new Error("Buffer global does not exist; please use webpack if you need to parse Buffers in the browser.");
        }
        function l4(n4) {
          s4();
          var t5 = i4(function(n5, t6) {
            return n5 + t6;
          }, 0, n4);
          if (t5 % 8 != 0)
            throw new Error("The bits [" + n4.join(", ") + "] add up to " + t5 + " which is not an even number of bytes; the total should be divisible by 8");
          var r4, u5 = t5 / 8, o4 = (r4 = function(n5) {
            return n5 > 48;
          }, i4(function(n5, t6) {
            return n5 || (r4(t6) ? t6 : n5);
          }, null, n4));
          if (o4)
            throw new Error(o4 + " bit range requested exceeds 48 bit (6 byte) Number max.");
          return new e3(function(t6, r5) {
            var e4 = u5 + r5;
            return e4 > t6.length ? x4(r5, u5.toString() + " bytes") : b3(e4, i4(function(n5, t7) {
              var r6 = f4(t7, n5.buf);
              return { coll: n5.coll.concat(r6.v), buf: r6.buf };
            }, { coll: [], buf: t6.slice(r5, e4) }, n4).coll);
          });
        }
        function h3(n4, t5) {
          return new e3(function(r4, e4) {
            return s4(), e4 + t5 > r4.length ? x4(e4, t5 + " bytes for " + n4) : b3(e4 + t5, r4.slice(e4, e4 + t5));
          });
        }
        function p3(n4, t5) {
          if ("number" != typeof (r4 = t5) || Math.floor(r4) !== r4 || t5 < 0 || t5 > 6)
            throw new Error(n4 + " requires integer length in range [0, 6].");
          var r4;
        }
        function d3(n4) {
          return p3("uintBE", n4), h3("uintBE(" + n4 + ")", n4).map(function(t5) {
            return t5.readUIntBE(0, n4);
          });
        }
        function v3(n4) {
          return p3("uintLE", n4), h3("uintLE(" + n4 + ")", n4).map(function(t5) {
            return t5.readUIntLE(0, n4);
          });
        }
        function g4(n4) {
          return p3("intBE", n4), h3("intBE(" + n4 + ")", n4).map(function(t5) {
            return t5.readIntBE(0, n4);
          });
        }
        function m3(n4) {
          return p3("intLE", n4), h3("intLE(" + n4 + ")", n4).map(function(t5) {
            return t5.readIntLE(0, n4);
          });
        }
        function y3(n4) {
          return n4 instanceof e3;
        }
        function E3(n4) {
          return "[object Array]" === {}.toString.call(n4);
        }
        function w4(n4) {
          return c3() && Buffer.isBuffer(n4);
        }
        function b3(n4, t5) {
          return { status: true, index: n4, value: t5, furthest: -1, expected: [] };
        }
        function x4(n4, t5) {
          return E3(t5) || (t5 = [t5]), { status: false, index: -1, value: null, furthest: n4, expected: t5 };
        }
        function B4(n4, t5) {
          if (!t5)
            return n4;
          if (n4.furthest > t5.furthest)
            return n4;
          var r4 = n4.furthest === t5.furthest ? function(n5, t6) {
            if (function() {
              if (void 0 !== e3._supportsSet)
                return e3._supportsSet;
              var n6 = "undefined" != typeof Set;
              return e3._supportsSet = n6, n6;
            }() && Array.from) {
              for (var r5 = new Set(n5), u5 = 0; u5 < t6.length; u5++)
                r5.add(t6[u5]);
              var o4 = Array.from(r5);
              return o4.sort(), o4;
            }
            for (var i5 = {}, a4 = 0; a4 < n5.length; a4++)
              i5[n5[a4]] = true;
            for (var f5 = 0; f5 < t6.length; f5++)
              i5[t6[f5]] = true;
            var c4 = [];
            for (var s5 in i5)
              ({}).hasOwnProperty.call(i5, s5) && c4.push(s5);
            return c4.sort(), c4;
          }(n4.expected, t5.expected) : t5.expected;
          return { status: n4.status, index: n4.index, value: n4.value, furthest: t5.furthest, expected: r4 };
        }
        var j4 = {};
        function S2(n4, t5) {
          if (w4(n4))
            return { offset: t5, line: -1, column: -1 };
          n4 in j4 || (j4[n4] = {});
          for (var r4 = j4[n4], e4 = 0, u5 = 0, o4 = 0, i5 = t5; i5 >= 0; ) {
            if (i5 in r4) {
              e4 = r4[i5].line, 0 === o4 && (o4 = r4[i5].lineStart);
              break;
            }
            ("\n" === n4.charAt(i5) || "\r" === n4.charAt(i5) && "\n" !== n4.charAt(i5 + 1)) && (u5++, 0 === o4 && (o4 = i5 + 1)), i5--;
          }
          var a4 = e4 + u5, f5 = t5 - o4;
          return r4[t5] = { line: a4, lineStart: o4 }, { offset: t5, line: a4 + 1, column: f5 + 1 };
        }
        function _3(n4) {
          if (!y3(n4))
            throw new Error("not a parser: " + n4);
        }
        function L3(n4, t5) {
          return "string" == typeof n4 ? n4.charAt(t5) : n4[t5];
        }
        function O3(n4) {
          if ("number" != typeof n4)
            throw new Error("not a number: " + n4);
        }
        function k4(n4) {
          if ("function" != typeof n4)
            throw new Error("not a function: " + n4);
        }
        function P7(n4) {
          if ("string" != typeof n4)
            throw new Error("not a string: " + n4);
        }
        var q4 = 2, A4 = 3, I3 = 8, F4 = 5 * I3, M3 = 4 * I3, z4 = "  ";
        function R2(n4, t5) {
          return new Array(t5 + 1).join(n4);
        }
        function U2(n4, t5, r4) {
          var e4 = t5 - n4.length;
          return e4 <= 0 ? n4 : R2(r4, e4) + n4;
        }
        function W2(n4, t5, r4, e4) {
          return { from: n4 - t5 > 0 ? n4 - t5 : 0, to: n4 + r4 > e4 ? e4 : n4 + r4 };
        }
        function D4(n4, t5) {
          var r4, e4, u5, o4, f5, c4 = t5.index, s5 = c4.offset, l5 = 1;
          if (s5 === n4.length)
            return "Got the end of the input";
          if (w4(n4)) {
            var h4 = s5 - s5 % I3, p4 = s5 - h4, d4 = W2(h4, F4, M3 + I3, n4.length), v4 = a3(function(n5) {
              return a3(function(n6) {
                return U2(n6.toString(16), 2, "0");
              }, n5);
            }, function(n5, t6) {
              var r5 = n5.length, e5 = [], u6 = 0;
              if (r5 <= t6)
                return [n5.slice()];
              for (var o5 = 0; o5 < r5; o5++)
                e5[u6] || e5.push([]), e5[u6].push(n5[o5]), (o5 + 1) % t6 == 0 && u6++;
              return e5;
            }(n4.slice(d4.from, d4.to).toJSON().data, I3));
            o4 = function(n5) {
              return 0 === n5.from && 1 === n5.to ? { from: n5.from, to: n5.to } : { from: n5.from / I3, to: Math.floor(n5.to / I3) };
            }(d4), e4 = h4 / I3, r4 = 3 * p4, p4 >= 4 && (r4 += 1), l5 = 2, u5 = a3(function(n5) {
              return n5.length <= 4 ? n5.join(" ") : n5.slice(0, 4).join(" ") + "  " + n5.slice(4).join(" ");
            }, v4), (f5 = (8 * (o4.to > 0 ? o4.to - 1 : o4.to)).toString(16).length) < 2 && (f5 = 2);
          } else {
            var g5 = n4.split(/\r\n|[\n\r\u2028\u2029]/);
            r4 = c4.column - 1, e4 = c4.line - 1, o4 = W2(e4, q4, A4, g5.length), u5 = g5.slice(o4.from, o4.to), f5 = o4.to.toString().length;
          }
          var m4 = e4 - o4.from;
          return w4(n4) && (f5 = (8 * (o4.to > 0 ? o4.to - 1 : o4.to)).toString(16).length) < 2 && (f5 = 2), i4(function(t6, e5, u6) {
            var i5, a4 = u6 === m4, c5 = a4 ? "> " : z4;
            return i5 = w4(n4) ? U2((8 * (o4.from + u6)).toString(16), f5, "0") : U2((o4.from + u6 + 1).toString(), f5, " "), [].concat(t6, [c5 + i5 + " | " + e5], a4 ? [z4 + R2(" ", f5) + " | " + U2("", r4, " ") + R2("^", l5)] : []);
          }, [], u5).join("\n");
        }
        function N3(n4, t5) {
          return ["\n", "-- PARSING FAILED " + R2("-", 50), "\n\n", D4(n4, t5), "\n\n", (r4 = t5.expected, 1 === r4.length ? "Expected:\n\n" + r4[0] : "Expected one of the following: \n\n" + r4.join(", ")), "\n"].join("");
          var r4;
        }
        function G3(n4) {
          return void 0 !== n4.flags ? n4.flags : [n4.global ? "g" : "", n4.ignoreCase ? "i" : "", n4.multiline ? "m" : "", n4.unicode ? "u" : "", n4.sticky ? "y" : ""].join("");
        }
        function C4() {
          for (var n4 = [].slice.call(arguments), t5 = n4.length, r4 = 0; r4 < t5; r4 += 1)
            _3(n4[r4]);
          return e3(function(r5, e4) {
            for (var u5, o4 = new Array(t5), i5 = 0; i5 < t5; i5 += 1) {
              if (!(u5 = B4(n4[i5]._(r5, e4), u5)).status)
                return u5;
              o4[i5] = u5.value, e4 = u5.index;
            }
            return B4(b3(e4, o4), u5);
          });
        }
        function J3() {
          var n4 = [].slice.call(arguments);
          if (0 === n4.length)
            throw new Error("seqMap needs at least one argument");
          var t5 = n4.pop();
          return k4(t5), C4.apply(null, n4).map(function(n5) {
            return t5.apply(null, n5);
          });
        }
        function T4() {
          var n4 = [].slice.call(arguments), t5 = n4.length;
          if (0 === t5)
            return Y2("zero alternates");
          for (var r4 = 0; r4 < t5; r4 += 1)
            _3(n4[r4]);
          return e3(function(t6, r5) {
            for (var e4, u5 = 0; u5 < n4.length; u5 += 1)
              if ((e4 = B4(n4[u5]._(t6, r5), e4)).status)
                return e4;
            return e4;
          });
        }
        function V3(n4, t5) {
          return H3(n4, t5).or(X2([]));
        }
        function H3(n4, t5) {
          return _3(n4), _3(t5), J3(n4, t5.then(n4).many(), function(n5, t6) {
            return [n5].concat(t6);
          });
        }
        function K3(n4) {
          P7(n4);
          var t5 = "'" + n4 + "'";
          return e3(function(r4, e4) {
            var u5 = e4 + n4.length, o4 = r4.slice(e4, u5);
            return o4 === n4 ? b3(u5, o4) : x4(e4, t5);
          });
        }
        function Q2(n4, t5) {
          !function(n5) {
            if (!(n5 instanceof RegExp))
              throw new Error("not a regexp: " + n5);
            for (var t6 = G3(n5), r5 = 0; r5 < t6.length; r5++) {
              var e4 = t6.charAt(r5);
              if ("i" !== e4 && "m" !== e4 && "u" !== e4 && "s" !== e4)
                throw new Error('unsupported regexp flag "' + e4 + '": ' + n5);
            }
          }(n4), arguments.length >= 2 ? O3(t5) : t5 = 0;
          var r4 = function(n5) {
            return RegExp("^(?:" + n5.source + ")", G3(n5));
          }(n4), u5 = "" + n4;
          return e3(function(n5, e4) {
            var o4 = r4.exec(n5.slice(e4));
            if (o4) {
              if (0 <= t5 && t5 <= o4.length) {
                var i5 = o4[0], a4 = o4[t5];
                return b3(e4 + i5.length, a4);
              }
              return x4(e4, "valid match group (0 to " + o4.length + ") in " + u5);
            }
            return x4(e4, u5);
          });
        }
        function X2(n4) {
          return e3(function(t5, r4) {
            return b3(r4, n4);
          });
        }
        function Y2(n4) {
          return e3(function(t5, r4) {
            return x4(r4, n4);
          });
        }
        function Z2(n4) {
          if (y3(n4))
            return e3(function(t5, r4) {
              var e4 = n4._(t5, r4);
              return e4.index = r4, e4.value = "", e4;
            });
          if ("string" == typeof n4)
            return Z2(K3(n4));
          if (n4 instanceof RegExp)
            return Z2(Q2(n4));
          throw new Error("not a string, regexp, or parser: " + n4);
        }
        function $3(n4) {
          return _3(n4), e3(function(t5, r4) {
            var e4 = n4._(t5, r4), u5 = t5.slice(r4, e4.index);
            return e4.status ? x4(r4, 'not "' + u5 + '"') : b3(r4, null);
          });
        }
        function nn2(n4) {
          return k4(n4), e3(function(t5, r4) {
            var e4 = L3(t5, r4);
            return r4 < t5.length && n4(e4) ? b3(r4 + 1, e4) : x4(r4, "a character/byte matching " + n4);
          });
        }
        function tn2(n4, t5) {
          arguments.length < 2 && (t5 = n4, n4 = void 0);
          var r4 = e3(function(n5, e4) {
            return r4._ = t5()._, r4._(n5, e4);
          });
          return n4 ? r4.desc(n4) : r4;
        }
        function rn2() {
          return Y2("fantasy-land/empty");
        }
        u4.parse = function(n4) {
          if ("string" != typeof n4 && !w4(n4))
            throw new Error(".parse must be called with a string or Buffer as its argument");
          var t5, r4 = this.skip(an2)._(n4, 0);
          return t5 = r4.status ? { status: true, value: r4.value } : { status: false, index: S2(n4, r4.furthest), expected: r4.expected }, delete j4[n4], t5;
        }, u4.tryParse = function(n4) {
          var t5 = this.parse(n4);
          if (t5.status)
            return t5.value;
          var r4 = N3(n4, t5), e4 = new Error(r4);
          throw e4.type = "ParsimmonError", e4.result = t5, e4;
        }, u4.assert = function(n4, t5) {
          return this.chain(function(r4) {
            return n4(r4) ? X2(r4) : Y2(t5);
          });
        }, u4.or = function(n4) {
          return T4(this, n4);
        }, u4.trim = function(n4) {
          return this.wrap(n4, n4);
        }, u4.wrap = function(n4, t5) {
          return J3(n4, this, t5, function(n5, t6) {
            return t6;
          });
        }, u4.thru = function(n4) {
          return n4(this);
        }, u4.then = function(n4) {
          return _3(n4), C4(this, n4).map(function(n5) {
            return n5[1];
          });
        }, u4.many = function() {
          var n4 = this;
          return e3(function(t5, r4) {
            for (var e4 = [], u5 = void 0; ; ) {
              if (!(u5 = B4(n4._(t5, r4), u5)).status)
                return B4(b3(r4, e4), u5);
              if (r4 === u5.index)
                throw new Error("infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause");
              r4 = u5.index, e4.push(u5.value);
            }
          });
        }, u4.tieWith = function(n4) {
          return P7(n4), this.map(function(t5) {
            if (function(n5) {
              if (!E3(n5))
                throw new Error("not an array: " + n5);
            }(t5), t5.length) {
              P7(t5[0]);
              for (var r4 = t5[0], e4 = 1; e4 < t5.length; e4++)
                P7(t5[e4]), r4 += n4 + t5[e4];
              return r4;
            }
            return "";
          });
        }, u4.tie = function() {
          return this.tieWith("");
        }, u4.times = function(n4, t5) {
          var r4 = this;
          return arguments.length < 2 && (t5 = n4), O3(n4), O3(t5), e3(function(e4, u5) {
            for (var o4 = [], i5 = void 0, a4 = void 0, f5 = 0; f5 < n4; f5 += 1) {
              if (a4 = B4(i5 = r4._(e4, u5), a4), !i5.status)
                return a4;
              u5 = i5.index, o4.push(i5.value);
            }
            for (; f5 < t5 && (a4 = B4(i5 = r4._(e4, u5), a4), i5.status); f5 += 1)
              u5 = i5.index, o4.push(i5.value);
            return B4(b3(u5, o4), a4);
          });
        }, u4.result = function(n4) {
          return this.map(function() {
            return n4;
          });
        }, u4.atMost = function(n4) {
          return this.times(0, n4);
        }, u4.atLeast = function(n4) {
          return J3(this.times(n4), this.many(), function(n5, t5) {
            return n5.concat(t5);
          });
        }, u4.map = function(n4) {
          k4(n4);
          var t5 = this;
          return e3(function(r4, e4) {
            var u5 = t5._(r4, e4);
            return u5.status ? B4(b3(u5.index, n4(u5.value)), u5) : u5;
          });
        }, u4.contramap = function(n4) {
          k4(n4);
          var t5 = this;
          return e3(function(r4, e4) {
            var u5 = t5.parse(n4(r4.slice(e4)));
            return u5.status ? b3(e4 + r4.length, u5.value) : u5;
          });
        }, u4.promap = function(n4, t5) {
          return k4(n4), k4(t5), this.contramap(n4).map(t5);
        }, u4.skip = function(n4) {
          return C4(this, n4).map(function(n5) {
            return n5[0];
          });
        }, u4.mark = function() {
          return J3(en2, this, en2, function(n4, t5, r4) {
            return { start: n4, value: t5, end: r4 };
          });
        }, u4.node = function(n4) {
          return J3(en2, this, en2, function(t5, r4, e4) {
            return { name: n4, value: r4, start: t5, end: e4 };
          });
        }, u4.sepBy = function(n4) {
          return V3(this, n4);
        }, u4.sepBy1 = function(n4) {
          return H3(this, n4);
        }, u4.lookahead = function(n4) {
          return this.skip(Z2(n4));
        }, u4.notFollowedBy = function(n4) {
          return this.skip($3(n4));
        }, u4.desc = function(n4) {
          E3(n4) || (n4 = [n4]);
          var t5 = this;
          return e3(function(r4, e4) {
            var u5 = t5._(r4, e4);
            return u5.status || (u5.expected = n4), u5;
          });
        }, u4.fallback = function(n4) {
          return this.or(X2(n4));
        }, u4.ap = function(n4) {
          return J3(n4, this, function(n5, t5) {
            return n5(t5);
          });
        }, u4.chain = function(n4) {
          var t5 = this;
          return e3(function(r4, e4) {
            var u5 = t5._(r4, e4);
            return u5.status ? B4(n4(u5.value)._(r4, u5.index), u5) : u5;
          });
        }, u4.concat = u4.or, u4.empty = rn2, u4.of = X2, u4["fantasy-land/ap"] = u4.ap, u4["fantasy-land/chain"] = u4.chain, u4["fantasy-land/concat"] = u4.concat, u4["fantasy-land/empty"] = u4.empty, u4["fantasy-land/of"] = u4.of, u4["fantasy-land/map"] = u4.map;
        var en2 = e3(function(n4, t5) {
          return b3(t5, S2(n4, t5));
        }), un2 = e3(function(n4, t5) {
          return t5 >= n4.length ? x4(t5, "any character/byte") : b3(t5 + 1, L3(n4, t5));
        }), on2 = e3(function(n4, t5) {
          return b3(n4.length, n4.slice(t5));
        }), an2 = e3(function(n4, t5) {
          return t5 < n4.length ? x4(t5, "EOF") : b3(t5, null);
        }), fn2 = Q2(/[0-9]/).desc("a digit"), cn2 = Q2(/[0-9]*/).desc("optional digits"), sn2 = Q2(/[a-z]/i).desc("a letter"), ln2 = Q2(/[a-z]*/i).desc("optional letters"), hn2 = Q2(/\s*/).desc("optional whitespace"), pn2 = Q2(/\s+/).desc("whitespace"), dn2 = K3("\r"), vn = K3("\n"), gn2 = K3("\r\n"), mn2 = T4(gn2, vn, dn2).desc("newline"), yn2 = T4(mn2, an2);
        e3.all = on2, e3.alt = T4, e3.any = un2, e3.cr = dn2, e3.createLanguage = function(n4) {
          var t5 = {};
          for (var r4 in n4)
            ({}).hasOwnProperty.call(n4, r4) && function(r5) {
              t5[r5] = tn2(function() {
                return n4[r5](t5);
              });
            }(r4);
          return t5;
        }, e3.crlf = gn2, e3.custom = function(n4) {
          return e3(n4(b3, x4));
        }, e3.digit = fn2, e3.digits = cn2, e3.empty = rn2, e3.end = yn2, e3.eof = an2, e3.fail = Y2, e3.formatError = N3, e3.index = en2, e3.isParser = y3, e3.lazy = tn2, e3.letter = sn2, e3.letters = ln2, e3.lf = vn, e3.lookahead = Z2, e3.makeFailure = x4, e3.makeSuccess = b3, e3.newline = mn2, e3.noneOf = function(n4) {
          return nn2(function(t5) {
            return n4.indexOf(t5) < 0;
          }).desc("none of '" + n4 + "'");
        }, e3.notFollowedBy = $3, e3.of = X2, e3.oneOf = function(n4) {
          for (var t5 = n4.split(""), r4 = 0; r4 < t5.length; r4++)
            t5[r4] = "'" + t5[r4] + "'";
          return nn2(function(t6) {
            return n4.indexOf(t6) >= 0;
          }).desc(t5);
        }, e3.optWhitespace = hn2, e3.Parser = e3, e3.range = function(n4, t5) {
          return nn2(function(r4) {
            return n4 <= r4 && r4 <= t5;
          }).desc(n4 + "-" + t5);
        }, e3.regex = Q2, e3.regexp = Q2, e3.sepBy = V3, e3.sepBy1 = H3, e3.seq = C4, e3.seqMap = J3, e3.seqObj = function() {
          for (var n4, t5 = {}, r4 = 0, u5 = (n4 = arguments, Array.prototype.slice.call(n4)), o4 = u5.length, i5 = 0; i5 < o4; i5 += 1) {
            var a4 = u5[i5];
            if (!y3(a4)) {
              if (E3(a4) && 2 === a4.length && "string" == typeof a4[0] && y3(a4[1])) {
                var f5 = a4[0];
                if (Object.prototype.hasOwnProperty.call(t5, f5))
                  throw new Error("seqObj: duplicate key " + f5);
                t5[f5] = true, r4++;
                continue;
              }
              throw new Error("seqObj arguments must be parsers or [string, parser] array pairs.");
            }
          }
          if (0 === r4)
            throw new Error("seqObj expects at least one named parser, found zero");
          return e3(function(n5, t6) {
            for (var r5, e4 = {}, i6 = 0; i6 < o4; i6 += 1) {
              var a5, f6;
              if (E3(u5[i6]) ? (a5 = u5[i6][0], f6 = u5[i6][1]) : (a5 = null, f6 = u5[i6]), !(r5 = B4(f6._(n5, t6), r5)).status)
                return r5;
              a5 && (e4[a5] = r5.value), t6 = r5.index;
            }
            return B4(b3(t6, e4), r5);
          });
        }, e3.string = K3, e3.succeed = X2, e3.takeWhile = function(n4) {
          return k4(n4), e3(function(t5, r4) {
            for (var e4 = r4; e4 < t5.length && n4(L3(t5, e4)); )
              e4++;
            return b3(e4, t5.slice(r4, e4));
          });
        }, e3.test = nn2, e3.whitespace = pn2, e3["fantasy-land/empty"] = rn2, e3["fantasy-land/of"] = X2, e3.Binary = { bitSeq: l4, bitSeqObj: function(n4) {
          s4();
          var t5 = {}, r4 = 0, e4 = a3(function(n5) {
            if (E3(n5)) {
              var e5 = n5;
              if (2 !== e5.length)
                throw new Error("[" + e5.join(", ") + "] should be length 2, got length " + e5.length);
              if (P7(e5[0]), O3(e5[1]), Object.prototype.hasOwnProperty.call(t5, e5[0]))
                throw new Error("duplicate key in bitSeqObj: " + e5[0]);
              return t5[e5[0]] = true, r4++, e5;
            }
            return O3(n5), [null, n5];
          }, n4);
          if (r4 < 1)
            throw new Error("bitSeqObj expects at least one named pair, got [" + n4.join(", ") + "]");
          var u5 = a3(function(n5) {
            return n5[0];
          }, e4);
          return l4(a3(function(n5) {
            return n5[1];
          }, e4)).map(function(n5) {
            return i4(function(n6, t6) {
              return null !== t6[0] && (n6[t6[0]] = t6[1]), n6;
            }, {}, a3(function(t6, r5) {
              return [t6, n5[r5]];
            }, u5));
          });
        }, byte: function(n4) {
          if (s4(), O3(n4), n4 > 255)
            throw new Error("Value specified to byte constructor (" + n4 + "=0x" + n4.toString(16) + ") is larger in value than a single byte.");
          var t5 = (n4 > 15 ? "0x" : "0x0") + n4.toString(16);
          return e3(function(r4, e4) {
            var u5 = L3(r4, e4);
            return u5 === n4 ? b3(e4 + 1, u5) : x4(e4, t5);
          });
        }, buffer: function(n4) {
          return h3("buffer", n4).map(function(n5) {
            return Buffer.from(n5);
          });
        }, encodedString: function(n4, t5) {
          return h3("string", t5).map(function(t6) {
            return t6.toString(n4);
          });
        }, uintBE: d3, uint8BE: d3(1), uint16BE: d3(2), uint32BE: d3(4), uintLE: v3, uint8LE: v3(1), uint16LE: v3(2), uint32LE: v3(4), intBE: g4, int8BE: g4(1), int16BE: g4(2), int32BE: g4(4), intLE: m3, int8LE: m3(1), int16LE: m3(2), int32LE: m3(4), floatBE: h3("floatBE", 4).map(function(n4) {
          return n4.readFloatBE(0);
        }), floatLE: h3("floatLE", 4).map(function(n4) {
          return n4.readFloatLE(0);
        }), doubleBE: h3("doubleBE", 8).map(function(n4) {
          return n4.readDoubleBE(0);
        }), doubleLE: h3("doubleLE", 8).map(function(n4) {
          return n4.readDoubleLE(0);
        }) }, n3.exports = e3;
      }]);
    });
  }
});

// node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js
var require_resolve_uri_umd = __commonJS({
  "node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js"(exports, module2) {
    (function(global2, factory) {
      typeof exports === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.resolveURI = factory());
    })(exports, function() {
      "use strict";
      const schemeRegex = /^[\w+.-]+:\/\//;
      const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
      const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
      function isAbsoluteUrl(input2) {
        return schemeRegex.test(input2);
      }
      function isSchemeRelativeUrl(input2) {
        return input2.startsWith("//");
      }
      function isAbsolutePath(input2) {
        return input2.startsWith("/");
      }
      function isFileUrl(input2) {
        return input2.startsWith("file:");
      }
      function isRelative(input2) {
        return /^[.?#]/.test(input2);
      }
      function parseAbsoluteUrl(input2) {
        const match3 = urlRegex.exec(input2);
        return makeUrl(match3[1], match3[2] || "", match3[3], match3[4] || "", match3[5] || "/", match3[6] || "", match3[7] || "");
      }
      function parseFileUrl(input2) {
        const match3 = fileRegex.exec(input2);
        const path = match3[2];
        return makeUrl("file:", "", match3[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match3[3] || "", match3[4] || "");
      }
      function makeUrl(scheme, user, host, port, path, query, hash) {
        return {
          scheme,
          user,
          host,
          port,
          path,
          query,
          hash,
          type: 7
        };
      }
      function parseUrl(input2) {
        if (isSchemeRelativeUrl(input2)) {
          const url2 = parseAbsoluteUrl("http:" + input2);
          url2.scheme = "";
          url2.type = 6;
          return url2;
        }
        if (isAbsolutePath(input2)) {
          const url2 = parseAbsoluteUrl("http://foo.com" + input2);
          url2.scheme = "";
          url2.host = "";
          url2.type = 5;
          return url2;
        }
        if (isFileUrl(input2))
          return parseFileUrl(input2);
        if (isAbsoluteUrl(input2))
          return parseAbsoluteUrl(input2);
        const url = parseAbsoluteUrl("http://foo.com/" + input2);
        url.scheme = "";
        url.host = "";
        url.type = input2 ? input2.startsWith("?") ? 3 : input2.startsWith("#") ? 2 : 4 : 1;
        return url;
      }
      function stripPathFilename(path) {
        if (path.endsWith("/.."))
          return path;
        const index = path.lastIndexOf("/");
        return path.slice(0, index + 1);
      }
      function mergePaths(url, base) {
        normalizePath(base, base.type);
        if (url.path === "/") {
          url.path = base.path;
        } else {
          url.path = stripPathFilename(base.path) + url.path;
        }
      }
      function normalizePath(url, type) {
        const rel = type <= 4;
        const pieces = url.path.split("/");
        let pointer = 1;
        let positive = 0;
        let addTrailingSlash = false;
        for (let i4 = 1; i4 < pieces.length; i4++) {
          const piece = pieces[i4];
          if (!piece) {
            addTrailingSlash = true;
            continue;
          }
          addTrailingSlash = false;
          if (piece === ".")
            continue;
          if (piece === "..") {
            if (positive) {
              addTrailingSlash = true;
              positive--;
              pointer--;
            } else if (rel) {
              pieces[pointer++] = piece;
            }
            continue;
          }
          pieces[pointer++] = piece;
          positive++;
        }
        let path = "";
        for (let i4 = 1; i4 < pointer; i4++) {
          path += "/" + pieces[i4];
        }
        if (!path || addTrailingSlash && !path.endsWith("/..")) {
          path += "/";
        }
        url.path = path;
      }
      function resolve(input2, base) {
        if (!input2 && !base)
          return "";
        const url = parseUrl(input2);
        let inputType = url.type;
        if (base && inputType !== 7) {
          const baseUrl = parseUrl(base);
          const baseType = baseUrl.type;
          switch (inputType) {
            case 1:
              url.hash = baseUrl.hash;
            case 2:
              url.query = baseUrl.query;
            case 3:
            case 4:
              mergePaths(url, baseUrl);
            case 5:
              url.user = baseUrl.user;
              url.host = baseUrl.host;
              url.port = baseUrl.port;
            case 6:
              url.scheme = baseUrl.scheme;
          }
          if (baseType > inputType)
            inputType = baseType;
        }
        normalizePath(url, inputType);
        const queryHash = url.query + url.hash;
        switch (inputType) {
          case 2:
          case 3:
            return queryHash;
          case 4: {
            const path = url.path.slice(1);
            if (!path)
              return queryHash || ".";
            if (isRelative(base || input2) && !isRelative(path)) {
              return "./" + path + queryHash;
            }
            return path + queryHash;
          }
          case 5:
            return url.path + queryHash;
          default:
            return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash;
        }
      }
      return resolve;
    });
  }
});

// node_modules/ts-interface-checker/dist/util.js
var require_util = __commonJS({
  "node_modules/ts-interface-checker/dist/util.js"(exports) {
    "use strict";
    var __extends = exports && exports.__extends || function() {
      var extendStatics = function(d3, b3) {
        extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b4) {
          d4.__proto__ = b4;
        } || function(d4, b4) {
          for (var p3 in b4)
            if (b4.hasOwnProperty(p3))
              d4[p3] = b4[p3];
        };
        return extendStatics(d3, b3);
      };
      return function(d3, b3) {
        extendStatics(d3, b3);
        function __() {
          this.constructor = d3;
        }
        d3.prototype = b3 === null ? Object.create(b3) : (__.prototype = b3.prototype, new __());
      };
    }();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DetailContext = exports.NoopContext = exports.VError = void 0;
    var VError = (
      /** @class */
      function(_super) {
        __extends(VError2, _super);
        function VError2(path, message) {
          var _this = _super.call(this, message) || this;
          _this.path = path;
          Object.setPrototypeOf(_this, VError2.prototype);
          return _this;
        }
        return VError2;
      }(Error)
    );
    exports.VError = VError;
    var NoopContext = (
      /** @class */
      function() {
        function NoopContext2() {
        }
        NoopContext2.prototype.fail = function(relPath, message, score) {
          return false;
        };
        NoopContext2.prototype.unionResolver = function() {
          return this;
        };
        NoopContext2.prototype.createContext = function() {
          return this;
        };
        NoopContext2.prototype.resolveUnion = function(ur) {
        };
        return NoopContext2;
      }()
    );
    exports.NoopContext = NoopContext;
    var DetailContext = (
      /** @class */
      function() {
        function DetailContext2() {
          this._propNames = [""];
          this._messages = [null];
          this._score = 0;
        }
        DetailContext2.prototype.fail = function(relPath, message, score) {
          this._propNames.push(relPath);
          this._messages.push(message);
          this._score += score;
          return false;
        };
        DetailContext2.prototype.unionResolver = function() {
          return new DetailUnionResolver();
        };
        DetailContext2.prototype.resolveUnion = function(unionResolver) {
          var _a, _b;
          var u4 = unionResolver;
          var best = null;
          for (var _i = 0, _c = u4.contexts; _i < _c.length; _i++) {
            var ctx = _c[_i];
            if (!best || ctx._score >= best._score) {
              best = ctx;
            }
          }
          if (best && best._score > 0) {
            (_a = this._propNames).push.apply(_a, best._propNames);
            (_b = this._messages).push.apply(_b, best._messages);
          }
        };
        DetailContext2.prototype.getError = function(path) {
          var msgParts = [];
          for (var i4 = this._propNames.length - 1; i4 >= 0; i4--) {
            var p3 = this._propNames[i4];
            path += typeof p3 === "number" ? "[" + p3 + "]" : p3 ? "." + p3 : "";
            var m3 = this._messages[i4];
            if (m3) {
              msgParts.push(path + " " + m3);
            }
          }
          return new VError(path, msgParts.join("; "));
        };
        DetailContext2.prototype.getErrorDetail = function(path) {
          var details = [];
          for (var i4 = this._propNames.length - 1; i4 >= 0; i4--) {
            var p3 = this._propNames[i4];
            path += typeof p3 === "number" ? "[" + p3 + "]" : p3 ? "." + p3 : "";
            var message = this._messages[i4];
            if (message) {
              details.push({ path, message });
            }
          }
          var detail = null;
          for (var i4 = details.length - 1; i4 >= 0; i4--) {
            if (detail) {
              details[i4].nested = [detail];
            }
            detail = details[i4];
          }
          return detail;
        };
        return DetailContext2;
      }()
    );
    exports.DetailContext = DetailContext;
    var DetailUnionResolver = (
      /** @class */
      function() {
        function DetailUnionResolver2() {
          this.contexts = [];
        }
        DetailUnionResolver2.prototype.createContext = function() {
          var ctx = new DetailContext();
          this.contexts.push(ctx);
          return ctx;
        };
        return DetailUnionResolver2;
      }()
    );
  }
});

// node_modules/ts-interface-checker/dist/types.js
var require_types = __commonJS({
  "node_modules/ts-interface-checker/dist/types.js"(exports) {
    "use strict";
    var __extends = exports && exports.__extends || function() {
      var extendStatics = function(d3, b3) {
        extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b4) {
          d4.__proto__ = b4;
        } || function(d4, b4) {
          for (var p3 in b4)
            if (b4.hasOwnProperty(p3))
              d4[p3] = b4[p3];
        };
        return extendStatics(d3, b3);
      };
      return function(d3, b3) {
        extendStatics(d3, b3);
        function __() {
          this.constructor = d3;
        }
        d3.prototype = b3 === null ? Object.create(b3) : (__.prototype = b3.prototype, new __());
      };
    }();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.basicTypes = exports.BasicType = exports.TParamList = exports.TParam = exports.param = exports.TFunc = exports.func = exports.TProp = exports.TOptional = exports.opt = exports.TIface = exports.iface = exports.TEnumLiteral = exports.enumlit = exports.TEnumType = exports.enumtype = exports.TIntersection = exports.intersection = exports.TUnion = exports.union = exports.TTuple = exports.tuple = exports.TArray = exports.array = exports.TLiteral = exports.lit = exports.TName = exports.name = exports.TType = void 0;
    var util_1 = require_util();
    var TType = (
      /** @class */
      function() {
        function TType2() {
        }
        return TType2;
      }()
    );
    exports.TType = TType;
    function parseSpec(typeSpec) {
      return typeof typeSpec === "string" ? name(typeSpec) : typeSpec;
    }
    function getNamedType(suite, name2) {
      var ttype = suite[name2];
      if (!ttype) {
        throw new Error("Unknown type " + name2);
      }
      return ttype;
    }
    function name(value) {
      return new TName(value);
    }
    exports.name = name;
    var TName = (
      /** @class */
      function(_super) {
        __extends(TName2, _super);
        function TName2(name2) {
          var _this = _super.call(this) || this;
          _this.name = name2;
          _this._failMsg = "is not a " + name2;
          return _this;
        }
        TName2.prototype.getChecker = function(suite, strict, allowedProps) {
          var _this = this;
          var ttype = getNamedType(suite, this.name);
          var checker = ttype.getChecker(suite, strict, allowedProps);
          if (ttype instanceof BasicType || ttype instanceof TName2) {
            return checker;
          }
          return function(value, ctx) {
            return checker(value, ctx) ? true : ctx.fail(null, _this._failMsg, 0);
          };
        };
        return TName2;
      }(TType)
    );
    exports.TName = TName;
    function lit2(value) {
      return new TLiteral(value);
    }
    exports.lit = lit2;
    var TLiteral = (
      /** @class */
      function(_super) {
        __extends(TLiteral2, _super);
        function TLiteral2(value) {
          var _this = _super.call(this) || this;
          _this.value = value;
          _this.name = JSON.stringify(value);
          _this._failMsg = "is not " + _this.name;
          return _this;
        }
        TLiteral2.prototype.getChecker = function(suite, strict) {
          var _this = this;
          return function(value, ctx) {
            return value === _this.value ? true : ctx.fail(null, _this._failMsg, -1);
          };
        };
        return TLiteral2;
      }(TType)
    );
    exports.TLiteral = TLiteral;
    function array2(typeSpec) {
      return new TArray(parseSpec(typeSpec));
    }
    exports.array = array2;
    var TArray = (
      /** @class */
      function(_super) {
        __extends(TArray2, _super);
        function TArray2(ttype) {
          var _this = _super.call(this) || this;
          _this.ttype = ttype;
          return _this;
        }
        TArray2.prototype.getChecker = function(suite, strict) {
          var itemChecker = this.ttype.getChecker(suite, strict);
          return function(value, ctx) {
            if (!Array.isArray(value)) {
              return ctx.fail(null, "is not an array", 0);
            }
            for (var i4 = 0; i4 < value.length; i4++) {
              var ok = itemChecker(value[i4], ctx);
              if (!ok) {
                return ctx.fail(i4, null, 1);
              }
            }
            return true;
          };
        };
        return TArray2;
      }(TType)
    );
    exports.TArray = TArray;
    function tuple() {
      var typeSpec = [];
      for (var _i2 = 0; _i2 < arguments.length; _i2++) {
        typeSpec[_i2] = arguments[_i2];
      }
      return new TTuple(typeSpec.map(function(t4) {
        return parseSpec(t4);
      }));
    }
    exports.tuple = tuple;
    var TTuple = (
      /** @class */
      function(_super) {
        __extends(TTuple2, _super);
        function TTuple2(ttypes) {
          var _this = _super.call(this) || this;
          _this.ttypes = ttypes;
          return _this;
        }
        TTuple2.prototype.getChecker = function(suite, strict) {
          var itemCheckers = this.ttypes.map(function(t4) {
            return t4.getChecker(suite, strict);
          });
          var checker = function(value, ctx) {
            if (!Array.isArray(value)) {
              return ctx.fail(null, "is not an array", 0);
            }
            for (var i4 = 0; i4 < itemCheckers.length; i4++) {
              var ok = itemCheckers[i4](value[i4], ctx);
              if (!ok) {
                return ctx.fail(i4, null, 1);
              }
            }
            return true;
          };
          if (!strict) {
            return checker;
          }
          return function(value, ctx) {
            if (!checker(value, ctx)) {
              return false;
            }
            return value.length <= itemCheckers.length ? true : ctx.fail(itemCheckers.length, "is extraneous", 2);
          };
        };
        return TTuple2;
      }(TType)
    );
    exports.TTuple = TTuple;
    function union2() {
      var typeSpec = [];
      for (var _i2 = 0; _i2 < arguments.length; _i2++) {
        typeSpec[_i2] = arguments[_i2];
      }
      return new TUnion(typeSpec.map(function(t4) {
        return parseSpec(t4);
      }));
    }
    exports.union = union2;
    var TUnion = (
      /** @class */
      function(_super) {
        __extends(TUnion2, _super);
        function TUnion2(ttypes) {
          var _this = _super.call(this) || this;
          _this.ttypes = ttypes;
          var names = ttypes.map(function(t4) {
            return t4 instanceof TName || t4 instanceof TLiteral ? t4.name : null;
          }).filter(function(n3) {
            return n3;
          });
          var otherTypes = ttypes.length - names.length;
          if (names.length) {
            if (otherTypes > 0) {
              names.push(otherTypes + " more");
            }
            _this._failMsg = "is none of " + names.join(", ");
          } else {
            _this._failMsg = "is none of " + otherTypes + " types";
          }
          return _this;
        }
        TUnion2.prototype.getChecker = function(suite, strict) {
          var _this = this;
          var itemCheckers = this.ttypes.map(function(t4) {
            return t4.getChecker(suite, strict);
          });
          return function(value, ctx) {
            var ur = ctx.unionResolver();
            for (var i4 = 0; i4 < itemCheckers.length; i4++) {
              var ok = itemCheckers[i4](value, ur.createContext());
              if (ok) {
                return true;
              }
            }
            ctx.resolveUnion(ur);
            return ctx.fail(null, _this._failMsg, 0);
          };
        };
        return TUnion2;
      }(TType)
    );
    exports.TUnion = TUnion;
    function intersection() {
      var typeSpec = [];
      for (var _i2 = 0; _i2 < arguments.length; _i2++) {
        typeSpec[_i2] = arguments[_i2];
      }
      return new TIntersection(typeSpec.map(function(t4) {
        return parseSpec(t4);
      }));
    }
    exports.intersection = intersection;
    var TIntersection = (
      /** @class */
      function(_super) {
        __extends(TIntersection2, _super);
        function TIntersection2(ttypes) {
          var _this = _super.call(this) || this;
          _this.ttypes = ttypes;
          return _this;
        }
        TIntersection2.prototype.getChecker = function(suite, strict) {
          var allowedProps = /* @__PURE__ */ new Set();
          var itemCheckers = this.ttypes.map(function(t4) {
            return t4.getChecker(suite, strict, allowedProps);
          });
          return function(value, ctx) {
            var ok = itemCheckers.every(function(checker) {
              return checker(value, ctx);
            });
            if (ok) {
              return true;
            }
            return ctx.fail(null, null, 0);
          };
        };
        return TIntersection2;
      }(TType)
    );
    exports.TIntersection = TIntersection;
    function enumtype(values) {
      return new TEnumType(values);
    }
    exports.enumtype = enumtype;
    var TEnumType = (
      /** @class */
      function(_super) {
        __extends(TEnumType2, _super);
        function TEnumType2(members) {
          var _this = _super.call(this) || this;
          _this.members = members;
          _this.validValues = /* @__PURE__ */ new Set();
          _this._failMsg = "is not a valid enum value";
          _this.validValues = new Set(Object.keys(members).map(function(name2) {
            return members[name2];
          }));
          return _this;
        }
        TEnumType2.prototype.getChecker = function(suite, strict) {
          var _this = this;
          return function(value, ctx) {
            return _this.validValues.has(value) ? true : ctx.fail(null, _this._failMsg, 0);
          };
        };
        return TEnumType2;
      }(TType)
    );
    exports.TEnumType = TEnumType;
    function enumlit(name2, prop) {
      return new TEnumLiteral(name2, prop);
    }
    exports.enumlit = enumlit;
    var TEnumLiteral = (
      /** @class */
      function(_super) {
        __extends(TEnumLiteral2, _super);
        function TEnumLiteral2(enumName, prop) {
          var _this = _super.call(this) || this;
          _this.enumName = enumName;
          _this.prop = prop;
          _this._failMsg = "is not " + enumName + "." + prop;
          return _this;
        }
        TEnumLiteral2.prototype.getChecker = function(suite, strict) {
          var _this = this;
          var ttype = getNamedType(suite, this.enumName);
          if (!(ttype instanceof TEnumType)) {
            throw new Error("Type " + this.enumName + " used in enumlit is not an enum type");
          }
          var val = ttype.members[this.prop];
          if (!ttype.members.hasOwnProperty(this.prop)) {
            throw new Error("Unknown value " + this.enumName + "." + this.prop + " used in enumlit");
          }
          return function(value, ctx) {
            return value === val ? true : ctx.fail(null, _this._failMsg, -1);
          };
        };
        return TEnumLiteral2;
      }(TType)
    );
    exports.TEnumLiteral = TEnumLiteral;
    function makeIfaceProps(props) {
      return Object.keys(props).map(function(name2) {
        return makeIfaceProp(name2, props[name2]);
      });
    }
    function makeIfaceProp(name2, prop) {
      return prop instanceof TOptional ? new TProp(name2, prop.ttype, true) : new TProp(name2, parseSpec(prop), false);
    }
    function iface2(bases, props) {
      return new TIface(bases, makeIfaceProps(props));
    }
    exports.iface = iface2;
    var TIface = (
      /** @class */
      function(_super) {
        __extends(TIface2, _super);
        function TIface2(bases, props) {
          var _this = _super.call(this) || this;
          _this.bases = bases;
          _this.props = props;
          _this.propSet = new Set(props.map(function(p3) {
            return p3.name;
          }));
          return _this;
        }
        TIface2.prototype.getChecker = function(suite, strict, allowedProps) {
          var _this = this;
          var baseCheckers = this.bases.map(function(b3) {
            return getNamedType(suite, b3).getChecker(suite, strict);
          });
          var propCheckers = this.props.map(function(prop) {
            return prop.ttype.getChecker(suite, strict);
          });
          var testCtx = new util_1.NoopContext();
          var isPropRequired = this.props.map(function(prop, i4) {
            return !prop.isOpt && !propCheckers[i4](void 0, testCtx);
          });
          var checker = function(value, ctx) {
            if (typeof value !== "object" || value === null) {
              return ctx.fail(null, "is not an object", 0);
            }
            for (var i4 = 0; i4 < baseCheckers.length; i4++) {
              if (!baseCheckers[i4](value, ctx)) {
                return false;
              }
            }
            for (var i4 = 0; i4 < propCheckers.length; i4++) {
              var name_1 = _this.props[i4].name;
              var v3 = value[name_1];
              if (v3 === void 0) {
                if (isPropRequired[i4]) {
                  return ctx.fail(name_1, "is missing", 1);
                }
              } else {
                var ok = propCheckers[i4](v3, ctx);
                if (!ok) {
                  return ctx.fail(name_1, null, 1);
                }
              }
            }
            return true;
          };
          if (!strict) {
            return checker;
          }
          var propSet = this.propSet;
          if (allowedProps) {
            this.propSet.forEach(function(prop) {
              return allowedProps.add(prop);
            });
            propSet = allowedProps;
          }
          return function(value, ctx) {
            if (!checker(value, ctx)) {
              return false;
            }
            for (var prop in value) {
              if (!propSet.has(prop)) {
                return ctx.fail(prop, "is extraneous", 2);
              }
            }
            return true;
          };
        };
        return TIface2;
      }(TType)
    );
    exports.TIface = TIface;
    function opt2(typeSpec) {
      return new TOptional(parseSpec(typeSpec));
    }
    exports.opt = opt2;
    var TOptional = (
      /** @class */
      function(_super) {
        __extends(TOptional2, _super);
        function TOptional2(ttype) {
          var _this = _super.call(this) || this;
          _this.ttype = ttype;
          return _this;
        }
        TOptional2.prototype.getChecker = function(suite, strict) {
          var itemChecker = this.ttype.getChecker(suite, strict);
          return function(value, ctx) {
            return value === void 0 || itemChecker(value, ctx);
          };
        };
        return TOptional2;
      }(TType)
    );
    exports.TOptional = TOptional;
    var TProp = (
      /** @class */
      function() {
        function TProp2(name2, ttype, isOpt) {
          this.name = name2;
          this.ttype = ttype;
          this.isOpt = isOpt;
        }
        return TProp2;
      }()
    );
    exports.TProp = TProp;
    function func(resultSpec) {
      var params = [];
      for (var _i2 = 1; _i2 < arguments.length; _i2++) {
        params[_i2 - 1] = arguments[_i2];
      }
      return new TFunc(new TParamList(params), parseSpec(resultSpec));
    }
    exports.func = func;
    var TFunc = (
      /** @class */
      function(_super) {
        __extends(TFunc2, _super);
        function TFunc2(paramList, result) {
          var _this = _super.call(this) || this;
          _this.paramList = paramList;
          _this.result = result;
          return _this;
        }
        TFunc2.prototype.getChecker = function(suite, strict) {
          return function(value, ctx) {
            return typeof value === "function" ? true : ctx.fail(null, "is not a function", 0);
          };
        };
        return TFunc2;
      }(TType)
    );
    exports.TFunc = TFunc;
    function param(name2, typeSpec, isOpt) {
      return new TParam(name2, parseSpec(typeSpec), Boolean(isOpt));
    }
    exports.param = param;
    var TParam = (
      /** @class */
      function() {
        function TParam2(name2, ttype, isOpt) {
          this.name = name2;
          this.ttype = ttype;
          this.isOpt = isOpt;
        }
        return TParam2;
      }()
    );
    exports.TParam = TParam;
    var TParamList = (
      /** @class */
      function(_super) {
        __extends(TParamList2, _super);
        function TParamList2(params) {
          var _this = _super.call(this) || this;
          _this.params = params;
          return _this;
        }
        TParamList2.prototype.getChecker = function(suite, strict) {
          var _this = this;
          var itemCheckers = this.params.map(function(t4) {
            return t4.ttype.getChecker(suite, strict);
          });
          var testCtx = new util_1.NoopContext();
          var isParamRequired = this.params.map(function(param2, i4) {
            return !param2.isOpt && !itemCheckers[i4](void 0, testCtx);
          });
          var checker = function(value, ctx) {
            if (!Array.isArray(value)) {
              return ctx.fail(null, "is not an array", 0);
            }
            for (var i4 = 0; i4 < itemCheckers.length; i4++) {
              var p3 = _this.params[i4];
              if (value[i4] === void 0) {
                if (isParamRequired[i4]) {
                  return ctx.fail(p3.name, "is missing", 1);
                }
              } else {
                var ok = itemCheckers[i4](value[i4], ctx);
                if (!ok) {
                  return ctx.fail(p3.name, null, 1);
                }
              }
            }
            return true;
          };
          if (!strict) {
            return checker;
          }
          return function(value, ctx) {
            if (!checker(value, ctx)) {
              return false;
            }
            return value.length <= itemCheckers.length ? true : ctx.fail(itemCheckers.length, "is extraneous", 2);
          };
        };
        return TParamList2;
      }(TType)
    );
    exports.TParamList = TParamList;
    var BasicType = (
      /** @class */
      function(_super) {
        __extends(BasicType2, _super);
        function BasicType2(validator, message) {
          var _this = _super.call(this) || this;
          _this.validator = validator;
          _this.message = message;
          return _this;
        }
        BasicType2.prototype.getChecker = function(suite, strict) {
          var _this = this;
          return function(value, ctx) {
            return _this.validator(value) ? true : ctx.fail(null, _this.message, 0);
          };
        };
        return BasicType2;
      }(TType)
    );
    exports.BasicType = BasicType;
    exports.basicTypes = {
      any: new BasicType(function(v3) {
        return true;
      }, "is invalid"),
      number: new BasicType(function(v3) {
        return typeof v3 === "number";
      }, "is not a number"),
      object: new BasicType(function(v3) {
        return typeof v3 === "object" && v3;
      }, "is not an object"),
      boolean: new BasicType(function(v3) {
        return typeof v3 === "boolean";
      }, "is not a boolean"),
      string: new BasicType(function(v3) {
        return typeof v3 === "string";
      }, "is not a string"),
      symbol: new BasicType(function(v3) {
        return typeof v3 === "symbol";
      }, "is not a symbol"),
      void: new BasicType(function(v3) {
        return v3 == null;
      }, "is not void"),
      undefined: new BasicType(function(v3) {
        return v3 === void 0;
      }, "is not undefined"),
      null: new BasicType(function(v3) {
        return v3 === null;
      }, "is not null"),
      never: new BasicType(function(v3) {
        return false;
      }, "is unexpected"),
      Date: new BasicType(getIsNativeChecker("[object Date]"), "is not a Date"),
      RegExp: new BasicType(getIsNativeChecker("[object RegExp]"), "is not a RegExp")
    };
    var nativeToString = Object.prototype.toString;
    function getIsNativeChecker(tag) {
      return function(v3) {
        return typeof v3 === "object" && v3 && nativeToString.call(v3) === tag;
      };
    }
    if (typeof Buffer !== "undefined") {
      exports.basicTypes.Buffer = new BasicType(function(v3) {
        return Buffer.isBuffer(v3);
      }, "is not a Buffer");
    }
    var _loop_1 = function(array_12) {
      exports.basicTypes[array_12.name] = new BasicType(function(v3) {
        return v3 instanceof array_12;
      }, "is not a " + array_12.name);
    };
    for (_i = 0, _a = [
      Int8Array,
      Uint8Array,
      Uint8ClampedArray,
      Int16Array,
      Uint16Array,
      Int32Array,
      Uint32Array,
      Float32Array,
      Float64Array,
      ArrayBuffer
    ]; _i < _a.length; _i++) {
      array_1 = _a[_i];
      _loop_1(array_1);
    }
    var array_1;
    var _i;
    var _a;
  }
});

// node_modules/ts-interface-checker/dist/index.js
var require_dist = __commonJS({
  "node_modules/ts-interface-checker/dist/index.js"(exports) {
    "use strict";
    var __spreadArrays = exports && exports.__spreadArrays || function() {
      for (var s4 = 0, i4 = 0, il = arguments.length; i4 < il; i4++)
        s4 += arguments[i4].length;
      for (var r3 = Array(s4), k4 = 0, i4 = 0; i4 < il; i4++)
        for (var a3 = arguments[i4], j4 = 0, jl = a3.length; j4 < jl; j4++, k4++)
          r3[k4] = a3[j4];
      return r3;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Checker = exports.createCheckers = void 0;
    var types_1 = require_types();
    var util_1 = require_util();
    var types_2 = require_types();
    Object.defineProperty(exports, "TArray", { enumerable: true, get: function() {
      return types_2.TArray;
    } });
    Object.defineProperty(exports, "TEnumType", { enumerable: true, get: function() {
      return types_2.TEnumType;
    } });
    Object.defineProperty(exports, "TEnumLiteral", { enumerable: true, get: function() {
      return types_2.TEnumLiteral;
    } });
    Object.defineProperty(exports, "TFunc", { enumerable: true, get: function() {
      return types_2.TFunc;
    } });
    Object.defineProperty(exports, "TIface", { enumerable: true, get: function() {
      return types_2.TIface;
    } });
    Object.defineProperty(exports, "TLiteral", { enumerable: true, get: function() {
      return types_2.TLiteral;
    } });
    Object.defineProperty(exports, "TName", { enumerable: true, get: function() {
      return types_2.TName;
    } });
    Object.defineProperty(exports, "TOptional", { enumerable: true, get: function() {
      return types_2.TOptional;
    } });
    Object.defineProperty(exports, "TParam", { enumerable: true, get: function() {
      return types_2.TParam;
    } });
    Object.defineProperty(exports, "TParamList", { enumerable: true, get: function() {
      return types_2.TParamList;
    } });
    Object.defineProperty(exports, "TProp", { enumerable: true, get: function() {
      return types_2.TProp;
    } });
    Object.defineProperty(exports, "TTuple", { enumerable: true, get: function() {
      return types_2.TTuple;
    } });
    Object.defineProperty(exports, "TType", { enumerable: true, get: function() {
      return types_2.TType;
    } });
    Object.defineProperty(exports, "TUnion", { enumerable: true, get: function() {
      return types_2.TUnion;
    } });
    Object.defineProperty(exports, "TIntersection", { enumerable: true, get: function() {
      return types_2.TIntersection;
    } });
    Object.defineProperty(exports, "array", { enumerable: true, get: function() {
      return types_2.array;
    } });
    Object.defineProperty(exports, "enumlit", { enumerable: true, get: function() {
      return types_2.enumlit;
    } });
    Object.defineProperty(exports, "enumtype", { enumerable: true, get: function() {
      return types_2.enumtype;
    } });
    Object.defineProperty(exports, "func", { enumerable: true, get: function() {
      return types_2.func;
    } });
    Object.defineProperty(exports, "iface", { enumerable: true, get: function() {
      return types_2.iface;
    } });
    Object.defineProperty(exports, "lit", { enumerable: true, get: function() {
      return types_2.lit;
    } });
    Object.defineProperty(exports, "name", { enumerable: true, get: function() {
      return types_2.name;
    } });
    Object.defineProperty(exports, "opt", { enumerable: true, get: function() {
      return types_2.opt;
    } });
    Object.defineProperty(exports, "param", { enumerable: true, get: function() {
      return types_2.param;
    } });
    Object.defineProperty(exports, "tuple", { enumerable: true, get: function() {
      return types_2.tuple;
    } });
    Object.defineProperty(exports, "union", { enumerable: true, get: function() {
      return types_2.union;
    } });
    Object.defineProperty(exports, "intersection", { enumerable: true, get: function() {
      return types_2.intersection;
    } });
    Object.defineProperty(exports, "BasicType", { enumerable: true, get: function() {
      return types_2.BasicType;
    } });
    var util_2 = require_util();
    Object.defineProperty(exports, "VError", { enumerable: true, get: function() {
      return util_2.VError;
    } });
    function createCheckers2() {
      var typeSuite = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        typeSuite[_i] = arguments[_i];
      }
      var fullSuite = Object.assign.apply(Object, __spreadArrays([{}, types_1.basicTypes], typeSuite));
      var checkers = {};
      for (var _a = 0, typeSuite_1 = typeSuite; _a < typeSuite_1.length; _a++) {
        var suite_1 = typeSuite_1[_a];
        for (var _b = 0, _c = Object.keys(suite_1); _b < _c.length; _b++) {
          var name = _c[_b];
          checkers[name] = new Checker(fullSuite, suite_1[name]);
        }
      }
      return checkers;
    }
    exports.createCheckers = createCheckers2;
    var Checker = (
      /** @class */
      function() {
        function Checker2(suite, ttype, _path) {
          if (_path === void 0) {
            _path = "value";
          }
          this.suite = suite;
          this.ttype = ttype;
          this._path = _path;
          this.props = /* @__PURE__ */ new Map();
          if (ttype instanceof types_1.TIface) {
            for (var _i = 0, _a = ttype.props; _i < _a.length; _i++) {
              var p3 = _a[_i];
              this.props.set(p3.name, p3.ttype);
            }
          }
          this.checkerPlain = this.ttype.getChecker(suite, false);
          this.checkerStrict = this.ttype.getChecker(suite, true);
        }
        Checker2.prototype.setReportedPath = function(path) {
          this._path = path;
        };
        Checker2.prototype.check = function(value) {
          return this._doCheck(this.checkerPlain, value);
        };
        Checker2.prototype.test = function(value) {
          return this.checkerPlain(value, new util_1.NoopContext());
        };
        Checker2.prototype.validate = function(value) {
          return this._doValidate(this.checkerPlain, value);
        };
        Checker2.prototype.strictCheck = function(value) {
          return this._doCheck(this.checkerStrict, value);
        };
        Checker2.prototype.strictTest = function(value) {
          return this.checkerStrict(value, new util_1.NoopContext());
        };
        Checker2.prototype.strictValidate = function(value) {
          return this._doValidate(this.checkerStrict, value);
        };
        Checker2.prototype.getProp = function(prop) {
          var ttype = this.props.get(prop);
          if (!ttype) {
            throw new Error("Type has no property " + prop);
          }
          return new Checker2(this.suite, ttype, this._path + "." + prop);
        };
        Checker2.prototype.methodArgs = function(methodName) {
          var tfunc = this._getMethod(methodName);
          return new Checker2(this.suite, tfunc.paramList);
        };
        Checker2.prototype.methodResult = function(methodName) {
          var tfunc = this._getMethod(methodName);
          return new Checker2(this.suite, tfunc.result);
        };
        Checker2.prototype.getArgs = function() {
          if (!(this.ttype instanceof types_1.TFunc)) {
            throw new Error("getArgs() applied to non-function");
          }
          return new Checker2(this.suite, this.ttype.paramList);
        };
        Checker2.prototype.getResult = function() {
          if (!(this.ttype instanceof types_1.TFunc)) {
            throw new Error("getResult() applied to non-function");
          }
          return new Checker2(this.suite, this.ttype.result);
        };
        Checker2.prototype.getType = function() {
          return this.ttype;
        };
        Checker2.prototype._doCheck = function(checkerFunc, value) {
          var noopCtx = new util_1.NoopContext();
          if (!checkerFunc(value, noopCtx)) {
            var detailCtx = new util_1.DetailContext();
            checkerFunc(value, detailCtx);
            throw detailCtx.getError(this._path);
          }
        };
        Checker2.prototype._doValidate = function(checkerFunc, value) {
          var noopCtx = new util_1.NoopContext();
          if (checkerFunc(value, noopCtx)) {
            return null;
          }
          var detailCtx = new util_1.DetailContext();
          checkerFunc(value, detailCtx);
          return detailCtx.getErrorDetail(this._path);
        };
        Checker2.prototype._getMethod = function(methodName) {
          var ttype = this.props.get(methodName);
          if (!ttype) {
            throw new Error("Type has no property " + methodName);
          }
          if (!(ttype instanceof types_1.TFunc)) {
            throw new Error("Property " + methodName + " is not a method");
          }
          return ttype;
        };
        return Checker2;
      }()
    );
    exports.Checker = Checker;
  }
});

// node_modules/lines-and-columns/build/index.js
var require_build = __commonJS({
  "node_modules/lines-and-columns/build/index.js"(exports) {
    "use strict";
    exports.__esModule = true;
    exports.LinesAndColumns = void 0;
    var LF = "\n";
    var CR = "\r";
    var LinesAndColumns2 = (
      /** @class */
      function() {
        function LinesAndColumns3(string2) {
          this.string = string2;
          var offsets = [0];
          for (var offset2 = 0; offset2 < string2.length; ) {
            switch (string2[offset2]) {
              case LF:
                offset2 += LF.length;
                offsets.push(offset2);
                break;
              case CR:
                offset2 += CR.length;
                if (string2[offset2] === LF) {
                  offset2 += LF.length;
                }
                offsets.push(offset2);
                break;
              default:
                offset2++;
                break;
            }
          }
          this.offsets = offsets;
        }
        LinesAndColumns3.prototype.locationForIndex = function(index) {
          if (index < 0 || index > this.string.length) {
            return null;
          }
          var line = 0;
          var offsets = this.offsets;
          while (offsets[line + 1] <= index) {
            line++;
          }
          var column = index - offsets[line];
          return { line, column };
        };
        LinesAndColumns3.prototype.indexForLocation = function(location) {
          var line = location.line, column = location.column;
          if (line < 0 || line >= this.offsets.length) {
            return null;
          }
          if (column < 0 || column > this.lengthOfLine(line)) {
            return null;
          }
          return this.offsets[line] + column;
        };
        LinesAndColumns3.prototype.lengthOfLine = function(line) {
          var offset2 = this.offsets[line];
          var nextOffset = line === this.offsets.length - 1 ? this.string.length : this.offsets[line + 1];
          return nextOffset - offset2;
        };
        return LinesAndColumns3;
      }()
    );
    exports.LinesAndColumns = LinesAndColumns2;
    exports["default"] = LinesAndColumns2;
  }
});

// node_modules/sorted-btree/b+tree.js
var require_b_tree = __commonJS({
  "node_modules/sorted-btree/b+tree.js"(exports) {
    "use strict";
    var __extends = exports && exports.__extends || function() {
      var extendStatics = function(d3, b3) {
        extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b4) {
          d4.__proto__ = b4;
        } || function(d4, b4) {
          for (var p3 in b4)
            if (Object.prototype.hasOwnProperty.call(b4, p3))
              d4[p3] = b4[p3];
        };
        return extendStatics(d3, b3);
      };
      return function(d3, b3) {
        if (typeof b3 !== "function" && b3 !== null)
          throw new TypeError("Class extends value " + String(b3) + " is not a constructor or null");
        extendStatics(d3, b3);
        function __() {
          this.constructor = d3;
        }
        d3.prototype = b3 === null ? Object.create(b3) : (__.prototype = b3.prototype, new __());
      };
    }();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmptyBTree = exports.asSet = exports.simpleComparator = exports.defaultComparator = void 0;
    function defaultComparator(a3, b3) {
      if (Number.isFinite(a3) && Number.isFinite(b3)) {
        return a3 - b3;
      }
      var ta = typeof a3;
      var tb = typeof b3;
      if (ta !== tb) {
        return ta < tb ? -1 : 1;
      }
      if (ta === "object") {
        if (a3 === null)
          return b3 === null ? 0 : -1;
        else if (b3 === null)
          return 1;
        a3 = a3.valueOf();
        b3 = b3.valueOf();
        ta = typeof a3;
        tb = typeof b3;
        if (ta !== tb) {
          return ta < tb ? -1 : 1;
        }
      }
      if (a3 < b3)
        return -1;
      if (a3 > b3)
        return 1;
      if (a3 === b3)
        return 0;
      if (Number.isNaN(a3))
        return Number.isNaN(b3) ? 0 : -1;
      else if (Number.isNaN(b3))
        return 1;
      return Array.isArray(a3) ? 0 : Number.NaN;
    }
    exports.defaultComparator = defaultComparator;
    function simpleComparator(a3, b3) {
      return a3 > b3 ? 1 : a3 < b3 ? -1 : 0;
    }
    exports.simpleComparator = simpleComparator;
    var BTree2 = (
      /** @class */
      function() {
        function BTree3(entries, compare, maxNodeSize) {
          this._root = EmptyLeaf;
          this._size = 0;
          this._maxNodeSize = maxNodeSize >= 4 ? Math.min(maxNodeSize, 256) : 32;
          this._compare = compare || defaultComparator;
          if (entries)
            this.setPairs(entries);
        }
        Object.defineProperty(BTree3.prototype, "size", {
          /////////////////////////////////////////////////////////////////////////////
          // ES6 Map<K,V> methods /////////////////////////////////////////////////////
          /** Gets the number of key-value pairs in the tree. */
          get: function() {
            return this._size;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(BTree3.prototype, "length", {
          /** Gets the number of key-value pairs in the tree. */
          get: function() {
            return this._size;
          },
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(BTree3.prototype, "isEmpty", {
          /** Returns true iff the tree contains no key-value pairs. */
          get: function() {
            return this._size === 0;
          },
          enumerable: false,
          configurable: true
        });
        BTree3.prototype.clear = function() {
          this._root = EmptyLeaf;
          this._size = 0;
        };
        BTree3.prototype.forEach = function(callback, thisArg) {
          var _this = this;
          if (thisArg !== void 0)
            callback = callback.bind(thisArg);
          return this.forEachPair(function(k4, v3) {
            return callback(v3, k4, _this);
          });
        };
        BTree3.prototype.forEachPair = function(callback, initialCounter) {
          var low = this.minKey(), high = this.maxKey();
          return this.forRange(low, high, true, callback, initialCounter);
        };
        BTree3.prototype.get = function(key, defaultValue) {
          return this._root.get(key, defaultValue, this);
        };
        BTree3.prototype.set = function(key, value, overwrite) {
          if (this._root.isShared)
            this._root = this._root.clone();
          var result = this._root.set(key, value, overwrite, this);
          if (result === true || result === false)
            return result;
          this._root = new BNodeInternal([this._root, result]);
          return true;
        };
        BTree3.prototype.has = function(key) {
          return this.forRange(key, key, true, void 0) !== 0;
        };
        BTree3.prototype.delete = function(key) {
          return this.editRange(key, key, true, DeleteRange) !== 0;
        };
        BTree3.prototype.with = function(key, value, overwrite) {
          var nu = this.clone();
          return nu.set(key, value, overwrite) || overwrite ? nu : this;
        };
        BTree3.prototype.withPairs = function(pairs, overwrite) {
          var nu = this.clone();
          return nu.setPairs(pairs, overwrite) !== 0 || overwrite ? nu : this;
        };
        BTree3.prototype.withKeys = function(keys, returnThisIfUnchanged) {
          var nu = this.clone(), changed = false;
          for (var i4 = 0; i4 < keys.length; i4++)
            changed = nu.set(keys[i4], void 0, false) || changed;
          return returnThisIfUnchanged && !changed ? this : nu;
        };
        BTree3.prototype.without = function(key, returnThisIfUnchanged) {
          return this.withoutRange(key, key, true, returnThisIfUnchanged);
        };
        BTree3.prototype.withoutKeys = function(keys, returnThisIfUnchanged) {
          var nu = this.clone();
          return nu.deleteKeys(keys) || !returnThisIfUnchanged ? nu : this;
        };
        BTree3.prototype.withoutRange = function(low, high, includeHigh, returnThisIfUnchanged) {
          var nu = this.clone();
          if (nu.deleteRange(low, high, includeHigh) === 0 && returnThisIfUnchanged)
            return this;
          return nu;
        };
        BTree3.prototype.filter = function(callback, returnThisIfUnchanged) {
          var nu = this.greedyClone();
          var del;
          nu.editAll(function(k4, v3, i4) {
            if (!callback(k4, v3, i4))
              return del = Delete;
          });
          if (!del && returnThisIfUnchanged)
            return this;
          return nu;
        };
        BTree3.prototype.mapValues = function(callback) {
          var tmp = {};
          var nu = this.greedyClone();
          nu.editAll(function(k4, v3, i4) {
            return tmp.value = callback(v3, k4, i4), tmp;
          });
          return nu;
        };
        BTree3.prototype.reduce = function(callback, initialValue) {
          var i4 = 0, p3 = initialValue;
          var it = this.entries(this.minKey(), ReusedArray), next2;
          while (!(next2 = it.next()).done)
            p3 = callback(p3, next2.value, i4++, this);
          return p3;
        };
        BTree3.prototype.entries = function(lowestKey, reusedArray) {
          var info = this.findPath(lowestKey);
          if (info === void 0)
            return iterator();
          var nodequeue = info.nodequeue, nodeindex = info.nodeindex, leaf = info.leaf;
          var state2 = reusedArray !== void 0 ? 1 : 0;
          var i4 = lowestKey === void 0 ? -1 : leaf.indexOf(lowestKey, 0, this._compare) - 1;
          return iterator(function() {
            jump:
              for (; ; ) {
                switch (state2) {
                  case 0:
                    if (++i4 < leaf.keys.length)
                      return { done: false, value: [leaf.keys[i4], leaf.values[i4]] };
                    state2 = 2;
                    continue;
                  case 1:
                    if (++i4 < leaf.keys.length) {
                      reusedArray[0] = leaf.keys[i4], reusedArray[1] = leaf.values[i4];
                      return { done: false, value: reusedArray };
                    }
                    state2 = 2;
                  case 2:
                    for (var level = -1; ; ) {
                      if (++level >= nodequeue.length) {
                        state2 = 3;
                        continue jump;
                      }
                      if (++nodeindex[level] < nodequeue[level].length)
                        break;
                    }
                    for (; level > 0; level--) {
                      nodequeue[level - 1] = nodequeue[level][nodeindex[level]].children;
                      nodeindex[level - 1] = 0;
                    }
                    leaf = nodequeue[0][nodeindex[0]];
                    i4 = -1;
                    state2 = reusedArray !== void 0 ? 1 : 0;
                    continue;
                  case 3:
                    return { done: true, value: void 0 };
                }
              }
          });
        };
        BTree3.prototype.entriesReversed = function(highestKey, reusedArray, skipHighest) {
          if (highestKey === void 0) {
            highestKey = this.maxKey();
            skipHighest = void 0;
            if (highestKey === void 0)
              return iterator();
          }
          var _a = this.findPath(highestKey) || this.findPath(this.maxKey()), nodequeue = _a.nodequeue, nodeindex = _a.nodeindex, leaf = _a.leaf;
          check(!nodequeue[0] || leaf === nodequeue[0][nodeindex[0]], "wat!");
          var i4 = leaf.indexOf(highestKey, 0, this._compare);
          if (!skipHighest && i4 < leaf.keys.length && this._compare(leaf.keys[i4], highestKey) <= 0)
            i4++;
          var state2 = reusedArray !== void 0 ? 1 : 0;
          return iterator(function() {
            jump:
              for (; ; ) {
                switch (state2) {
                  case 0:
                    if (--i4 >= 0)
                      return { done: false, value: [leaf.keys[i4], leaf.values[i4]] };
                    state2 = 2;
                    continue;
                  case 1:
                    if (--i4 >= 0) {
                      reusedArray[0] = leaf.keys[i4], reusedArray[1] = leaf.values[i4];
                      return { done: false, value: reusedArray };
                    }
                    state2 = 2;
                  case 2:
                    for (var level = -1; ; ) {
                      if (++level >= nodequeue.length) {
                        state2 = 3;
                        continue jump;
                      }
                      if (--nodeindex[level] >= 0)
                        break;
                    }
                    for (; level > 0; level--) {
                      nodequeue[level - 1] = nodequeue[level][nodeindex[level]].children;
                      nodeindex[level - 1] = nodequeue[level - 1].length - 1;
                    }
                    leaf = nodequeue[0][nodeindex[0]];
                    i4 = leaf.keys.length;
                    state2 = reusedArray !== void 0 ? 1 : 0;
                    continue;
                  case 3:
                    return { done: true, value: void 0 };
                }
              }
          });
        };
        BTree3.prototype.findPath = function(key) {
          var nextnode = this._root;
          var nodequeue, nodeindex;
          if (nextnode.isLeaf) {
            nodequeue = EmptyArray, nodeindex = EmptyArray;
          } else {
            nodequeue = [], nodeindex = [];
            for (var d3 = 0; !nextnode.isLeaf; d3++) {
              nodequeue[d3] = nextnode.children;
              nodeindex[d3] = key === void 0 ? 0 : nextnode.indexOf(key, 0, this._compare);
              if (nodeindex[d3] >= nodequeue[d3].length)
                return;
              nextnode = nodequeue[d3][nodeindex[d3]];
            }
            nodequeue.reverse();
            nodeindex.reverse();
          }
          return { nodequeue, nodeindex, leaf: nextnode };
        };
        BTree3.prototype.diffAgainst = function(other, onlyThis, onlyOther, different) {
          if (other._compare !== this._compare) {
            throw new Error("Tree comparators are not the same.");
          }
          if (this.isEmpty || other.isEmpty) {
            if (this.isEmpty && other.isEmpty)
              return void 0;
            if (this.isEmpty)
              return onlyOther === void 0 ? void 0 : BTree3.stepToEnd(BTree3.makeDiffCursor(other), onlyOther);
            return onlyThis === void 0 ? void 0 : BTree3.stepToEnd(BTree3.makeDiffCursor(this), onlyThis);
          }
          var _compare = this._compare;
          var thisCursor = BTree3.makeDiffCursor(this);
          var otherCursor = BTree3.makeDiffCursor(other);
          var thisSuccess = true, otherSuccess = true, prevCursorOrder = BTree3.compare(thisCursor, otherCursor, _compare);
          while (thisSuccess && otherSuccess) {
            var cursorOrder = BTree3.compare(thisCursor, otherCursor, _compare);
            var thisLeaf = thisCursor.leaf, thisInternalSpine = thisCursor.internalSpine, thisLevelIndices = thisCursor.levelIndices;
            var otherLeaf = otherCursor.leaf, otherInternalSpine = otherCursor.internalSpine, otherLevelIndices = otherCursor.levelIndices;
            if (thisLeaf || otherLeaf) {
              if (prevCursorOrder !== 0) {
                if (cursorOrder === 0) {
                  if (thisLeaf && otherLeaf && different) {
                    var valThis = thisLeaf.values[thisLevelIndices[thisLevelIndices.length - 1]];
                    var valOther = otherLeaf.values[otherLevelIndices[otherLevelIndices.length - 1]];
                    if (!Object.is(valThis, valOther)) {
                      var result = different(thisCursor.currentKey, valThis, valOther);
                      if (result && result.break)
                        return result.break;
                    }
                  }
                } else if (cursorOrder > 0) {
                  if (otherLeaf && onlyOther) {
                    var otherVal = otherLeaf.values[otherLevelIndices[otherLevelIndices.length - 1]];
                    var result = onlyOther(otherCursor.currentKey, otherVal);
                    if (result && result.break)
                      return result.break;
                  }
                } else if (onlyThis) {
                  if (thisLeaf && prevCursorOrder !== 0) {
                    var valThis = thisLeaf.values[thisLevelIndices[thisLevelIndices.length - 1]];
                    var result = onlyThis(thisCursor.currentKey, valThis);
                    if (result && result.break)
                      return result.break;
                  }
                }
              }
            } else if (!thisLeaf && !otherLeaf && cursorOrder === 0) {
              var lastThis = thisInternalSpine.length - 1;
              var lastOther = otherInternalSpine.length - 1;
              var nodeThis = thisInternalSpine[lastThis][thisLevelIndices[lastThis]];
              var nodeOther = otherInternalSpine[lastOther][otherLevelIndices[lastOther]];
              if (nodeOther === nodeThis) {
                prevCursorOrder = 0;
                thisSuccess = BTree3.step(thisCursor, true);
                otherSuccess = BTree3.step(otherCursor, true);
                continue;
              }
            }
            prevCursorOrder = cursorOrder;
            if (cursorOrder < 0) {
              thisSuccess = BTree3.step(thisCursor);
            } else {
              otherSuccess = BTree3.step(otherCursor);
            }
          }
          if (thisSuccess && onlyThis)
            return BTree3.finishCursorWalk(thisCursor, otherCursor, _compare, onlyThis);
          if (otherSuccess && onlyOther)
            return BTree3.finishCursorWalk(otherCursor, thisCursor, _compare, onlyOther);
        };
        BTree3.finishCursorWalk = function(cursor, cursorFinished, compareKeys, callback) {
          var compared = BTree3.compare(cursor, cursorFinished, compareKeys);
          if (compared === 0) {
            if (!BTree3.step(cursor))
              return void 0;
          } else if (compared < 0) {
            check(false, "cursor walk terminated early");
          }
          return BTree3.stepToEnd(cursor, callback);
        };
        BTree3.stepToEnd = function(cursor, callback) {
          var canStep = true;
          while (canStep) {
            var leaf = cursor.leaf, levelIndices = cursor.levelIndices, currentKey = cursor.currentKey;
            if (leaf) {
              var value = leaf.values[levelIndices[levelIndices.length - 1]];
              var result = callback(currentKey, value);
              if (result && result.break)
                return result.break;
            }
            canStep = BTree3.step(cursor);
          }
          return void 0;
        };
        BTree3.makeDiffCursor = function(tree) {
          var _root = tree._root, height = tree.height;
          return { height, internalSpine: [[_root]], levelIndices: [0], leaf: void 0, currentKey: _root.maxKey() };
        };
        BTree3.step = function(cursor, stepToNode) {
          var internalSpine = cursor.internalSpine, levelIndices = cursor.levelIndices, leaf = cursor.leaf;
          if (stepToNode === true || leaf) {
            var levelsLength = levelIndices.length;
            if (stepToNode === true || levelIndices[levelsLength - 1] === 0) {
              var spineLength = internalSpine.length;
              if (spineLength === 0)
                return false;
              var nodeLevelIndex = spineLength - 1;
              var levelIndexWalkBack = nodeLevelIndex;
              while (levelIndexWalkBack >= 0) {
                if (levelIndices[levelIndexWalkBack] > 0) {
                  if (levelIndexWalkBack < levelsLength - 1) {
                    cursor.leaf = void 0;
                    levelIndices.pop();
                  }
                  if (levelIndexWalkBack < nodeLevelIndex)
                    cursor.internalSpine = internalSpine.slice(0, levelIndexWalkBack + 1);
                  cursor.currentKey = internalSpine[levelIndexWalkBack][--levelIndices[levelIndexWalkBack]].maxKey();
                  return true;
                }
                levelIndexWalkBack--;
              }
              return false;
            } else {
              var valueIndex = --levelIndices[levelsLength - 1];
              cursor.currentKey = leaf.keys[valueIndex];
              return true;
            }
          } else {
            var nextLevel = internalSpine.length;
            var currentLevel = nextLevel - 1;
            var node = internalSpine[currentLevel][levelIndices[currentLevel]];
            if (node.isLeaf) {
              cursor.leaf = node;
              var valueIndex = levelIndices[nextLevel] = node.values.length - 1;
              cursor.currentKey = node.keys[valueIndex];
            } else {
              var children = node.children;
              internalSpine[nextLevel] = children;
              var childIndex = children.length - 1;
              levelIndices[nextLevel] = childIndex;
              cursor.currentKey = children[childIndex].maxKey();
            }
            return true;
          }
        };
        BTree3.compare = function(cursorA, cursorB, compareKeys) {
          var heightA = cursorA.height, currentKeyA = cursorA.currentKey, levelIndicesA = cursorA.levelIndices;
          var heightB = cursorB.height, currentKeyB = cursorB.currentKey, levelIndicesB = cursorB.levelIndices;
          var keyComparison = compareKeys(currentKeyB, currentKeyA);
          if (keyComparison !== 0) {
            return keyComparison;
          }
          var heightMin = heightA < heightB ? heightA : heightB;
          var depthANormalized = levelIndicesA.length - (heightA - heightMin);
          var depthBNormalized = levelIndicesB.length - (heightB - heightMin);
          return depthANormalized - depthBNormalized;
        };
        BTree3.prototype.keys = function(firstKey) {
          var it = this.entries(firstKey, ReusedArray);
          return iterator(function() {
            var n3 = it.next();
            if (n3.value)
              n3.value = n3.value[0];
            return n3;
          });
        };
        BTree3.prototype.values = function(firstKey) {
          var it = this.entries(firstKey, ReusedArray);
          return iterator(function() {
            var n3 = it.next();
            if (n3.value)
              n3.value = n3.value[1];
            return n3;
          });
        };
        Object.defineProperty(BTree3.prototype, "maxNodeSize", {
          /////////////////////////////////////////////////////////////////////////////
          // Additional methods ///////////////////////////////////////////////////////
          /** Returns the maximum number of children/values before nodes will split. */
          get: function() {
            return this._maxNodeSize;
          },
          enumerable: false,
          configurable: true
        });
        BTree3.prototype.minKey = function() {
          return this._root.minKey();
        };
        BTree3.prototype.maxKey = function() {
          return this._root.maxKey();
        };
        BTree3.prototype.clone = function() {
          this._root.isShared = true;
          var result = new BTree3(void 0, this._compare, this._maxNodeSize);
          result._root = this._root;
          result._size = this._size;
          return result;
        };
        BTree3.prototype.greedyClone = function(force) {
          var result = new BTree3(void 0, this._compare, this._maxNodeSize);
          result._root = this._root.greedyClone(force);
          result._size = this._size;
          return result;
        };
        BTree3.prototype.toArray = function(maxLength) {
          if (maxLength === void 0) {
            maxLength = 2147483647;
          }
          var min = this.minKey(), max = this.maxKey();
          if (min !== void 0)
            return this.getRange(min, max, true, maxLength);
          return [];
        };
        BTree3.prototype.keysArray = function() {
          var results = [];
          this._root.forRange(this.minKey(), this.maxKey(), true, false, this, 0, function(k4, v3) {
            results.push(k4);
          });
          return results;
        };
        BTree3.prototype.valuesArray = function() {
          var results = [];
          this._root.forRange(this.minKey(), this.maxKey(), true, false, this, 0, function(k4, v3) {
            results.push(v3);
          });
          return results;
        };
        BTree3.prototype.toString = function() {
          return this.toArray().toString();
        };
        BTree3.prototype.setIfNotPresent = function(key, value) {
          return this.set(key, value, false);
        };
        BTree3.prototype.nextHigherPair = function(key, reusedArray) {
          reusedArray = reusedArray || [];
          if (key === void 0) {
            return this._root.minPair(reusedArray);
          }
          return this._root.getPairOrNextHigher(key, this._compare, false, reusedArray);
        };
        BTree3.prototype.nextHigherKey = function(key) {
          var p3 = this.nextHigherPair(key, ReusedArray);
          return p3 && p3[0];
        };
        BTree3.prototype.nextLowerPair = function(key, reusedArray) {
          reusedArray = reusedArray || [];
          if (key === void 0) {
            return this._root.maxPair(reusedArray);
          }
          return this._root.getPairOrNextLower(key, this._compare, false, reusedArray);
        };
        BTree3.prototype.nextLowerKey = function(key) {
          var p3 = this.nextLowerPair(key, ReusedArray);
          return p3 && p3[0];
        };
        BTree3.prototype.getPairOrNextLower = function(key, reusedArray) {
          return this._root.getPairOrNextLower(key, this._compare, true, reusedArray || []);
        };
        BTree3.prototype.getPairOrNextHigher = function(key, reusedArray) {
          return this._root.getPairOrNextHigher(key, this._compare, true, reusedArray || []);
        };
        BTree3.prototype.changeIfPresent = function(key, value) {
          return this.editRange(key, key, true, function(k4, v3) {
            return { value };
          }) !== 0;
        };
        BTree3.prototype.getRange = function(low, high, includeHigh, maxLength) {
          if (maxLength === void 0) {
            maxLength = 67108863;
          }
          var results = [];
          this._root.forRange(low, high, includeHigh, false, this, 0, function(k4, v3) {
            results.push([k4, v3]);
            return results.length > maxLength ? Break : void 0;
          });
          return results;
        };
        BTree3.prototype.setPairs = function(pairs, overwrite) {
          var added = 0;
          for (var i4 = 0; i4 < pairs.length; i4++)
            if (this.set(pairs[i4][0], pairs[i4][1], overwrite))
              added++;
          return added;
        };
        BTree3.prototype.forRange = function(low, high, includeHigh, onFound, initialCounter) {
          var r3 = this._root.forRange(low, high, includeHigh, false, this, initialCounter || 0, onFound);
          return typeof r3 === "number" ? r3 : r3.break;
        };
        BTree3.prototype.editRange = function(low, high, includeHigh, onFound, initialCounter) {
          var root = this._root;
          if (root.isShared)
            this._root = root = root.clone();
          try {
            var r3 = root.forRange(low, high, includeHigh, true, this, initialCounter || 0, onFound);
            return typeof r3 === "number" ? r3 : r3.break;
          } finally {
            var isShared = void 0;
            while (root.keys.length <= 1 && !root.isLeaf) {
              isShared || (isShared = root.isShared);
              this._root = root = root.keys.length === 0 ? EmptyLeaf : root.children[0];
            }
            if (isShared) {
              root.isShared = true;
            }
          }
        };
        BTree3.prototype.editAll = function(onFound, initialCounter) {
          return this.editRange(this.minKey(), this.maxKey(), true, onFound, initialCounter);
        };
        BTree3.prototype.deleteRange = function(low, high, includeHigh) {
          return this.editRange(low, high, includeHigh, DeleteRange);
        };
        BTree3.prototype.deleteKeys = function(keys) {
          for (var i4 = 0, r3 = 0; i4 < keys.length; i4++)
            if (this.delete(keys[i4]))
              r3++;
          return r3;
        };
        Object.defineProperty(BTree3.prototype, "height", {
          /** Gets the height of the tree: the number of internal nodes between the
           *  BTree object and its leaf nodes (zero if there are no internal nodes). */
          get: function() {
            var node = this._root;
            var height = -1;
            while (node) {
              height++;
              node = node.isLeaf ? void 0 : node.children[0];
            }
            return height;
          },
          enumerable: false,
          configurable: true
        });
        BTree3.prototype.freeze = function() {
          var t4 = this;
          t4.clear = t4.set = t4.editRange = function() {
            throw new Error("Attempted to modify a frozen BTree");
          };
        };
        BTree3.prototype.unfreeze = function() {
          delete this.clear;
          delete this.set;
          delete this.editRange;
        };
        Object.defineProperty(BTree3.prototype, "isFrozen", {
          /** Returns true if the tree appears to be frozen. */
          get: function() {
            return this.hasOwnProperty("editRange");
          },
          enumerable: false,
          configurable: true
        });
        BTree3.prototype.checkValid = function() {
          var size = this._root.checkValid(0, this, 0);
          check(size === this.size, "size mismatch: counted ", size, "but stored", this.size);
        };
        return BTree3;
      }()
    );
    exports.default = BTree2;
    function asSet(btree) {
      return btree;
    }
    exports.asSet = asSet;
    if (Symbol && Symbol.iterator)
      BTree2.prototype[Symbol.iterator] = BTree2.prototype.entries;
    BTree2.prototype.where = BTree2.prototype.filter;
    BTree2.prototype.setRange = BTree2.prototype.setPairs;
    BTree2.prototype.add = BTree2.prototype.set;
    function iterator(next2) {
      if (next2 === void 0) {
        next2 = function() {
          return { done: true, value: void 0 };
        };
      }
      var result = { next: next2 };
      if (Symbol && Symbol.iterator)
        result[Symbol.iterator] = function() {
          return this;
        };
      return result;
    }
    var BNode = (
      /** @class */
      function() {
        function BNode2(keys, values) {
          if (keys === void 0) {
            keys = [];
          }
          this.keys = keys;
          this.values = values || undefVals;
          this.isShared = void 0;
        }
        Object.defineProperty(BNode2.prototype, "isLeaf", {
          get: function() {
            return this.children === void 0;
          },
          enumerable: false,
          configurable: true
        });
        BNode2.prototype.maxKey = function() {
          return this.keys[this.keys.length - 1];
        };
        BNode2.prototype.indexOf = function(key, failXor, cmp) {
          var keys = this.keys;
          var lo = 0, hi = keys.length, mid = hi >> 1;
          while (lo < hi) {
            var c3 = cmp(keys[mid], key);
            if (c3 < 0)
              lo = mid + 1;
            else if (c3 > 0)
              hi = mid;
            else if (c3 === 0)
              return mid;
            else {
              if (key === key)
                return keys.length;
              else
                throw new Error("BTree: NaN was used as a key");
            }
            mid = lo + hi >> 1;
          }
          return mid ^ failXor;
        };
        BNode2.prototype.minKey = function() {
          return this.keys[0];
        };
        BNode2.prototype.minPair = function(reusedArray) {
          if (this.keys.length === 0)
            return void 0;
          reusedArray[0] = this.keys[0];
          reusedArray[1] = this.values[0];
          return reusedArray;
        };
        BNode2.prototype.maxPair = function(reusedArray) {
          if (this.keys.length === 0)
            return void 0;
          var lastIndex = this.keys.length - 1;
          reusedArray[0] = this.keys[lastIndex];
          reusedArray[1] = this.values[lastIndex];
          return reusedArray;
        };
        BNode2.prototype.clone = function() {
          var v3 = this.values;
          return new BNode2(this.keys.slice(0), v3 === undefVals ? v3 : v3.slice(0));
        };
        BNode2.prototype.greedyClone = function(force) {
          return this.isShared && !force ? this : this.clone();
        };
        BNode2.prototype.get = function(key, defaultValue, tree) {
          var i4 = this.indexOf(key, -1, tree._compare);
          return i4 < 0 ? defaultValue : this.values[i4];
        };
        BNode2.prototype.getPairOrNextLower = function(key, compare, inclusive, reusedArray) {
          var i4 = this.indexOf(key, -1, compare);
          var indexOrLower = i4 < 0 ? ~i4 - 1 : inclusive ? i4 : i4 - 1;
          if (indexOrLower >= 0) {
            reusedArray[0] = this.keys[indexOrLower];
            reusedArray[1] = this.values[indexOrLower];
            return reusedArray;
          }
          return void 0;
        };
        BNode2.prototype.getPairOrNextHigher = function(key, compare, inclusive, reusedArray) {
          var i4 = this.indexOf(key, -1, compare);
          var indexOrLower = i4 < 0 ? ~i4 : inclusive ? i4 : i4 + 1;
          var keys = this.keys;
          if (indexOrLower < keys.length) {
            reusedArray[0] = keys[indexOrLower];
            reusedArray[1] = this.values[indexOrLower];
            return reusedArray;
          }
          return void 0;
        };
        BNode2.prototype.checkValid = function(depth, tree, baseIndex) {
          var kL = this.keys.length, vL = this.values.length;
          check(this.values === undefVals ? kL <= vL : kL === vL, "keys/values length mismatch: depth", depth, "with lengths", kL, vL, "and baseIndex", baseIndex);
          check(depth == 0 || kL > 0, "empty leaf at depth", depth, "and baseIndex", baseIndex);
          return kL;
        };
        BNode2.prototype.set = function(key, value, overwrite, tree) {
          var i4 = this.indexOf(key, -1, tree._compare);
          if (i4 < 0) {
            i4 = ~i4;
            tree._size++;
            if (this.keys.length < tree._maxNodeSize) {
              return this.insertInLeaf(i4, key, value, tree);
            } else {
              var newRightSibling = this.splitOffRightSide(), target = this;
              if (i4 > this.keys.length) {
                i4 -= this.keys.length;
                target = newRightSibling;
              }
              target.insertInLeaf(i4, key, value, tree);
              return newRightSibling;
            }
          } else {
            if (overwrite !== false) {
              if (value !== void 0)
                this.reifyValues();
              this.keys[i4] = key;
              this.values[i4] = value;
            }
            return false;
          }
        };
        BNode2.prototype.reifyValues = function() {
          if (this.values === undefVals)
            return this.values = this.values.slice(0, this.keys.length);
          return this.values;
        };
        BNode2.prototype.insertInLeaf = function(i4, key, value, tree) {
          this.keys.splice(i4, 0, key);
          if (this.values === undefVals) {
            while (undefVals.length < tree._maxNodeSize)
              undefVals.push(void 0);
            if (value === void 0) {
              return true;
            } else {
              this.values = undefVals.slice(0, this.keys.length - 1);
            }
          }
          this.values.splice(i4, 0, value);
          return true;
        };
        BNode2.prototype.takeFromRight = function(rhs) {
          var v3 = this.values;
          if (rhs.values === undefVals) {
            if (v3 !== undefVals)
              v3.push(void 0);
          } else {
            v3 = this.reifyValues();
            v3.push(rhs.values.shift());
          }
          this.keys.push(rhs.keys.shift());
        };
        BNode2.prototype.takeFromLeft = function(lhs) {
          var v3 = this.values;
          if (lhs.values === undefVals) {
            if (v3 !== undefVals)
              v3.unshift(void 0);
          } else {
            v3 = this.reifyValues();
            v3.unshift(lhs.values.pop());
          }
          this.keys.unshift(lhs.keys.pop());
        };
        BNode2.prototype.splitOffRightSide = function() {
          var half = this.keys.length >> 1, keys = this.keys.splice(half);
          var values = this.values === undefVals ? undefVals : this.values.splice(half);
          return new BNode2(keys, values);
        };
        BNode2.prototype.forRange = function(low, high, includeHigh, editMode, tree, count, onFound) {
          var cmp = tree._compare;
          var iLow, iHigh;
          if (high === low) {
            if (!includeHigh)
              return count;
            iHigh = (iLow = this.indexOf(low, -1, cmp)) + 1;
            if (iLow < 0)
              return count;
          } else {
            iLow = this.indexOf(low, 0, cmp);
            iHigh = this.indexOf(high, -1, cmp);
            if (iHigh < 0)
              iHigh = ~iHigh;
            else if (includeHigh === true)
              iHigh++;
          }
          var keys = this.keys, values = this.values;
          if (onFound !== void 0) {
            for (var i4 = iLow; i4 < iHigh; i4++) {
              var key = keys[i4];
              var result = onFound(key, values[i4], count++);
              if (result !== void 0) {
                if (editMode === true) {
                  if (key !== keys[i4] || this.isShared === true)
                    throw new Error("BTree illegally changed or cloned in editRange");
                  if (result.delete) {
                    this.keys.splice(i4, 1);
                    if (this.values !== undefVals)
                      this.values.splice(i4, 1);
                    tree._size--;
                    i4--;
                    iHigh--;
                  } else if (result.hasOwnProperty("value")) {
                    values[i4] = result.value;
                  }
                }
                if (result.break !== void 0)
                  return result;
              }
            }
          } else
            count += iHigh - iLow;
          return count;
        };
        BNode2.prototype.mergeSibling = function(rhs, _3) {
          this.keys.push.apply(this.keys, rhs.keys);
          if (this.values === undefVals) {
            if (rhs.values === undefVals)
              return;
            this.values = this.values.slice(0, this.keys.length);
          }
          this.values.push.apply(this.values, rhs.reifyValues());
        };
        return BNode2;
      }()
    );
    var BNodeInternal = (
      /** @class */
      function(_super) {
        __extends(BNodeInternal2, _super);
        function BNodeInternal2(children, keys) {
          var _this = this;
          if (!keys) {
            keys = [];
            for (var i4 = 0; i4 < children.length; i4++)
              keys[i4] = children[i4].maxKey();
          }
          _this = _super.call(this, keys) || this;
          _this.children = children;
          return _this;
        }
        BNodeInternal2.prototype.clone = function() {
          var children = this.children.slice(0);
          for (var i4 = 0; i4 < children.length; i4++)
            children[i4].isShared = true;
          return new BNodeInternal2(children, this.keys.slice(0));
        };
        BNodeInternal2.prototype.greedyClone = function(force) {
          if (this.isShared && !force)
            return this;
          var nu = new BNodeInternal2(this.children.slice(0), this.keys.slice(0));
          for (var i4 = 0; i4 < nu.children.length; i4++)
            nu.children[i4] = nu.children[i4].greedyClone(force);
          return nu;
        };
        BNodeInternal2.prototype.minKey = function() {
          return this.children[0].minKey();
        };
        BNodeInternal2.prototype.minPair = function(reusedArray) {
          return this.children[0].minPair(reusedArray);
        };
        BNodeInternal2.prototype.maxPair = function(reusedArray) {
          return this.children[this.children.length - 1].maxPair(reusedArray);
        };
        BNodeInternal2.prototype.get = function(key, defaultValue, tree) {
          var i4 = this.indexOf(key, 0, tree._compare), children = this.children;
          return i4 < children.length ? children[i4].get(key, defaultValue, tree) : void 0;
        };
        BNodeInternal2.prototype.getPairOrNextLower = function(key, compare, inclusive, reusedArray) {
          var i4 = this.indexOf(key, 0, compare), children = this.children;
          if (i4 >= children.length)
            return this.maxPair(reusedArray);
          var result = children[i4].getPairOrNextLower(key, compare, inclusive, reusedArray);
          if (result === void 0 && i4 > 0) {
            return children[i4 - 1].maxPair(reusedArray);
          }
          return result;
        };
        BNodeInternal2.prototype.getPairOrNextHigher = function(key, compare, inclusive, reusedArray) {
          var i4 = this.indexOf(key, 0, compare), children = this.children, length = children.length;
          if (i4 >= length)
            return void 0;
          var result = children[i4].getPairOrNextHigher(key, compare, inclusive, reusedArray);
          if (result === void 0 && i4 < length - 1) {
            return children[i4 + 1].minPair(reusedArray);
          }
          return result;
        };
        BNodeInternal2.prototype.checkValid = function(depth, tree, baseIndex) {
          var kL = this.keys.length, cL = this.children.length;
          check(kL === cL, "keys/children length mismatch: depth", depth, "lengths", kL, cL, "baseIndex", baseIndex);
          check(kL > 1 || depth > 0, "internal node has length", kL, "at depth", depth, "baseIndex", baseIndex);
          var size = 0, c3 = this.children, k4 = this.keys, childSize = 0;
          for (var i4 = 0; i4 < cL; i4++) {
            size += c3[i4].checkValid(depth + 1, tree, baseIndex + size);
            childSize += c3[i4].keys.length;
            check(size >= childSize, "wtf", baseIndex);
            check(i4 === 0 || c3[i4 - 1].constructor === c3[i4].constructor, "type mismatch, baseIndex:", baseIndex);
            if (c3[i4].maxKey() != k4[i4])
              check(false, "keys[", i4, "] =", k4[i4], "is wrong, should be ", c3[i4].maxKey(), "at depth", depth, "baseIndex", baseIndex);
            if (!(i4 === 0 || tree._compare(k4[i4 - 1], k4[i4]) < 0))
              check(false, "sort violation at depth", depth, "index", i4, "keys", k4[i4 - 1], k4[i4]);
          }
          var toofew = childSize === 0;
          if (toofew || childSize > tree.maxNodeSize * cL)
            check(false, toofew ? "too few" : "too many", "children (", childSize, size, ") at depth", depth, "maxNodeSize:", tree.maxNodeSize, "children.length:", cL, "baseIndex:", baseIndex);
          return size;
        };
        BNodeInternal2.prototype.set = function(key, value, overwrite, tree) {
          var c3 = this.children, max = tree._maxNodeSize, cmp = tree._compare;
          var i4 = Math.min(this.indexOf(key, 0, cmp), c3.length - 1), child = c3[i4];
          if (child.isShared)
            c3[i4] = child = child.clone();
          if (child.keys.length >= max) {
            var other;
            if (i4 > 0 && (other = c3[i4 - 1]).keys.length < max && cmp(child.keys[0], key) < 0) {
              if (other.isShared)
                c3[i4 - 1] = other = other.clone();
              other.takeFromRight(child);
              this.keys[i4 - 1] = other.maxKey();
            } else if ((other = c3[i4 + 1]) !== void 0 && other.keys.length < max && cmp(child.maxKey(), key) < 0) {
              if (other.isShared)
                c3[i4 + 1] = other = other.clone();
              other.takeFromLeft(child);
              this.keys[i4] = c3[i4].maxKey();
            }
          }
          var result = child.set(key, value, overwrite, tree);
          if (result === false)
            return false;
          this.keys[i4] = child.maxKey();
          if (result === true)
            return true;
          if (this.keys.length < max) {
            this.insert(i4 + 1, result);
            return true;
          } else {
            var newRightSibling = this.splitOffRightSide(), target = this;
            if (cmp(result.maxKey(), this.maxKey()) > 0) {
              target = newRightSibling;
              i4 -= this.keys.length;
            }
            target.insert(i4 + 1, result);
            return newRightSibling;
          }
        };
        BNodeInternal2.prototype.insert = function(i4, child) {
          this.children.splice(i4, 0, child);
          this.keys.splice(i4, 0, child.maxKey());
        };
        BNodeInternal2.prototype.splitOffRightSide = function() {
          var half = this.children.length >> 1;
          return new BNodeInternal2(this.children.splice(half), this.keys.splice(half));
        };
        BNodeInternal2.prototype.takeFromRight = function(rhs) {
          this.keys.push(rhs.keys.shift());
          this.children.push(rhs.children.shift());
        };
        BNodeInternal2.prototype.takeFromLeft = function(lhs) {
          this.keys.unshift(lhs.keys.pop());
          this.children.unshift(lhs.children.pop());
        };
        BNodeInternal2.prototype.forRange = function(low, high, includeHigh, editMode, tree, count, onFound) {
          var cmp = tree._compare;
          var keys = this.keys, children = this.children;
          var iLow = this.indexOf(low, 0, cmp), i4 = iLow;
          var iHigh = Math.min(high === low ? iLow : this.indexOf(high, 0, cmp), keys.length - 1);
          if (!editMode) {
            for (; i4 <= iHigh; i4++) {
              var result = children[i4].forRange(low, high, includeHigh, editMode, tree, count, onFound);
              if (typeof result !== "number")
                return result;
              count = result;
            }
          } else if (i4 <= iHigh) {
            try {
              for (; i4 <= iHigh; i4++) {
                if (children[i4].isShared)
                  children[i4] = children[i4].clone();
                var result = children[i4].forRange(low, high, includeHigh, editMode, tree, count, onFound);
                keys[i4] = children[i4].maxKey();
                if (typeof result !== "number")
                  return result;
                count = result;
              }
            } finally {
              var half = tree._maxNodeSize >> 1;
              if (iLow > 0)
                iLow--;
              for (i4 = iHigh; i4 >= iLow; i4--) {
                if (children[i4].keys.length <= half) {
                  if (children[i4].keys.length !== 0) {
                    this.tryMerge(i4, tree._maxNodeSize);
                  } else {
                    keys.splice(i4, 1);
                    children.splice(i4, 1);
                  }
                }
              }
              if (children.length !== 0 && children[0].keys.length === 0)
                check(false, "emptiness bug");
            }
          }
          return count;
        };
        BNodeInternal2.prototype.tryMerge = function(i4, maxSize) {
          var children = this.children;
          if (i4 >= 0 && i4 + 1 < children.length) {
            if (children[i4].keys.length + children[i4 + 1].keys.length <= maxSize) {
              if (children[i4].isShared)
                children[i4] = children[i4].clone();
              children[i4].mergeSibling(children[i4 + 1], maxSize);
              children.splice(i4 + 1, 1);
              this.keys.splice(i4 + 1, 1);
              this.keys[i4] = children[i4].maxKey();
              return true;
            }
          }
          return false;
        };
        BNodeInternal2.prototype.mergeSibling = function(rhs, maxNodeSize) {
          var oldLength = this.keys.length;
          this.keys.push.apply(this.keys, rhs.keys);
          var rhsChildren = rhs.children;
          this.children.push.apply(this.children, rhsChildren);
          if (rhs.isShared && !this.isShared) {
            for (var i4 = 0; i4 < rhsChildren.length; i4++)
              rhsChildren[i4].isShared = true;
          }
          this.tryMerge(oldLength - 1, maxNodeSize);
        };
        return BNodeInternal2;
      }(BNode)
    );
    var undefVals = [];
    var Delete = { delete: true };
    var DeleteRange = function() {
      return Delete;
    };
    var Break = { break: true };
    var EmptyLeaf = function() {
      var n3 = new BNode();
      n3.isShared = true;
      return n3;
    }();
    var EmptyArray = [];
    var ReusedArray = [];
    function check(fact) {
      var args = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        args[_i - 1] = arguments[_i];
      }
      if (!fact) {
        args.unshift("B+ tree");
        throw new Error(args.join(" "));
      }
    }
    exports.EmptyBTree = function() {
      var t4 = new BTree2();
      t4.freeze();
      return t4;
    }();
  }
});

// node_modules/localforage/dist/localforage.js
var require_localforage = __commonJS({
  "node_modules/localforage/dist/localforage.js"(exports, module2) {
    (function(f4) {
      if (typeof exports === "object" && typeof module2 !== "undefined") {
        module2.exports = f4();
      } else if (typeof define === "function" && define.amd) {
        define([], f4);
      } else {
        var g4;
        if (typeof window !== "undefined") {
          g4 = window;
        } else if (typeof global !== "undefined") {
          g4 = global;
        } else if (typeof self !== "undefined") {
          g4 = self;
        } else {
          g4 = this;
        }
        g4.localforage = f4();
      }
    })(function() {
      var define2, module3, exports2;
      return function e3(t4, n3, r3) {
        function s4(o4, u4) {
          if (!n3[o4]) {
            if (!t4[o4]) {
              var a3 = typeof require == "function" && require;
              if (!u4 && a3)
                return a3(o4, true);
              if (i4)
                return i4(o4, true);
              var f4 = new Error("Cannot find module '" + o4 + "'");
              throw f4.code = "MODULE_NOT_FOUND", f4;
            }
            var l4 = n3[o4] = { exports: {} };
            t4[o4][0].call(l4.exports, function(e4) {
              var n4 = t4[o4][1][e4];
              return s4(n4 ? n4 : e4);
            }, l4, l4.exports, e3, t4, n3, r3);
          }
          return n3[o4].exports;
        }
        var i4 = typeof require == "function" && require;
        for (var o3 = 0; o3 < r3.length; o3++)
          s4(r3[o3]);
        return s4;
      }({ 1: [function(_dereq_, module4, exports3) {
        (function(global2) {
          "use strict";
          var Mutation = global2.MutationObserver || global2.WebKitMutationObserver;
          var scheduleDrain;
          {
            if (Mutation) {
              var called = 0;
              var observer = new Mutation(nextTick);
              var element = global2.document.createTextNode("");
              observer.observe(element, {
                characterData: true
              });
              scheduleDrain = function() {
                element.data = called = ++called % 2;
              };
            } else if (!global2.setImmediate && typeof global2.MessageChannel !== "undefined") {
              var channel = new global2.MessageChannel();
              channel.port1.onmessage = nextTick;
              scheduleDrain = function() {
                channel.port2.postMessage(0);
              };
            } else if ("document" in global2 && "onreadystatechange" in global2.document.createElement("script")) {
              scheduleDrain = function() {
                var scriptEl = global2.document.createElement("script");
                scriptEl.onreadystatechange = function() {
                  nextTick();
                  scriptEl.onreadystatechange = null;
                  scriptEl.parentNode.removeChild(scriptEl);
                  scriptEl = null;
                };
                global2.document.documentElement.appendChild(scriptEl);
              };
            } else {
              scheduleDrain = function() {
                setTimeout(nextTick, 0);
              };
            }
          }
          var draining;
          var queue = [];
          function nextTick() {
            draining = true;
            var i4, oldQueue;
            var len = queue.length;
            while (len) {
              oldQueue = queue;
              queue = [];
              i4 = -1;
              while (++i4 < len) {
                oldQueue[i4]();
              }
              len = queue.length;
            }
            draining = false;
          }
          module4.exports = immediate;
          function immediate(task) {
            if (queue.push(task) === 1 && !draining) {
              scheduleDrain();
            }
          }
        }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
      }, {}], 2: [function(_dereq_, module4, exports3) {
        "use strict";
        var immediate = _dereq_(1);
        function INTERNAL() {
        }
        var handlers = {};
        var REJECTED = ["REJECTED"];
        var FULFILLED = ["FULFILLED"];
        var PENDING = ["PENDING"];
        module4.exports = Promise2;
        function Promise2(resolver) {
          if (typeof resolver !== "function") {
            throw new TypeError("resolver must be a function");
          }
          this.state = PENDING;
          this.queue = [];
          this.outcome = void 0;
          if (resolver !== INTERNAL) {
            safelyResolveThenable(this, resolver);
          }
        }
        Promise2.prototype["catch"] = function(onRejected) {
          return this.then(null, onRejected);
        };
        Promise2.prototype.then = function(onFulfilled, onRejected) {
          if (typeof onFulfilled !== "function" && this.state === FULFILLED || typeof onRejected !== "function" && this.state === REJECTED) {
            return this;
          }
          var promise = new this.constructor(INTERNAL);
          if (this.state !== PENDING) {
            var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
            unwrap(promise, resolver, this.outcome);
          } else {
            this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
          }
          return promise;
        };
        function QueueItem(promise, onFulfilled, onRejected) {
          this.promise = promise;
          if (typeof onFulfilled === "function") {
            this.onFulfilled = onFulfilled;
            this.callFulfilled = this.otherCallFulfilled;
          }
          if (typeof onRejected === "function") {
            this.onRejected = onRejected;
            this.callRejected = this.otherCallRejected;
          }
        }
        QueueItem.prototype.callFulfilled = function(value) {
          handlers.resolve(this.promise, value);
        };
        QueueItem.prototype.otherCallFulfilled = function(value) {
          unwrap(this.promise, this.onFulfilled, value);
        };
        QueueItem.prototype.callRejected = function(value) {
          handlers.reject(this.promise, value);
        };
        QueueItem.prototype.otherCallRejected = function(value) {
          unwrap(this.promise, this.onRejected, value);
        };
        function unwrap(promise, func, value) {
          immediate(function() {
            var returnValue;
            try {
              returnValue = func(value);
            } catch (e3) {
              return handlers.reject(promise, e3);
            }
            if (returnValue === promise) {
              handlers.reject(promise, new TypeError("Cannot resolve promise with itself"));
            } else {
              handlers.resolve(promise, returnValue);
            }
          });
        }
        handlers.resolve = function(self2, value) {
          var result = tryCatch(getThen, value);
          if (result.status === "error") {
            return handlers.reject(self2, result.value);
          }
          var thenable = result.value;
          if (thenable) {
            safelyResolveThenable(self2, thenable);
          } else {
            self2.state = FULFILLED;
            self2.outcome = value;
            var i4 = -1;
            var len = self2.queue.length;
            while (++i4 < len) {
              self2.queue[i4].callFulfilled(value);
            }
          }
          return self2;
        };
        handlers.reject = function(self2, error) {
          self2.state = REJECTED;
          self2.outcome = error;
          var i4 = -1;
          var len = self2.queue.length;
          while (++i4 < len) {
            self2.queue[i4].callRejected(error);
          }
          return self2;
        };
        function getThen(obj) {
          var then = obj && obj.then;
          if (obj && (typeof obj === "object" || typeof obj === "function") && typeof then === "function") {
            return function appyThen() {
              then.apply(obj, arguments);
            };
          }
        }
        function safelyResolveThenable(self2, thenable) {
          var called = false;
          function onError(value) {
            if (called) {
              return;
            }
            called = true;
            handlers.reject(self2, value);
          }
          function onSuccess(value) {
            if (called) {
              return;
            }
            called = true;
            handlers.resolve(self2, value);
          }
          function tryToUnwrap() {
            thenable(onSuccess, onError);
          }
          var result = tryCatch(tryToUnwrap);
          if (result.status === "error") {
            onError(result.value);
          }
        }
        function tryCatch(func, value) {
          var out = {};
          try {
            out.value = func(value);
            out.status = "success";
          } catch (e3) {
            out.status = "error";
            out.value = e3;
          }
          return out;
        }
        Promise2.resolve = resolve;
        function resolve(value) {
          if (value instanceof this) {
            return value;
          }
          return handlers.resolve(new this(INTERNAL), value);
        }
        Promise2.reject = reject;
        function reject(reason) {
          var promise = new this(INTERNAL);
          return handlers.reject(promise, reason);
        }
        Promise2.all = all;
        function all(iterable) {
          var self2 = this;
          if (Object.prototype.toString.call(iterable) !== "[object Array]") {
            return this.reject(new TypeError("must be an array"));
          }
          var len = iterable.length;
          var called = false;
          if (!len) {
            return this.resolve([]);
          }
          var values = new Array(len);
          var resolved = 0;
          var i4 = -1;
          var promise = new this(INTERNAL);
          while (++i4 < len) {
            allResolver(iterable[i4], i4);
          }
          return promise;
          function allResolver(value, i5) {
            self2.resolve(value).then(resolveFromAll, function(error) {
              if (!called) {
                called = true;
                handlers.reject(promise, error);
              }
            });
            function resolveFromAll(outValue) {
              values[i5] = outValue;
              if (++resolved === len && !called) {
                called = true;
                handlers.resolve(promise, values);
              }
            }
          }
        }
        Promise2.race = race;
        function race(iterable) {
          var self2 = this;
          if (Object.prototype.toString.call(iterable) !== "[object Array]") {
            return this.reject(new TypeError("must be an array"));
          }
          var len = iterable.length;
          var called = false;
          if (!len) {
            return this.resolve([]);
          }
          var i4 = -1;
          var promise = new this(INTERNAL);
          while (++i4 < len) {
            resolver(iterable[i4]);
          }
          return promise;
          function resolver(value) {
            self2.resolve(value).then(function(response) {
              if (!called) {
                called = true;
                handlers.resolve(promise, response);
              }
            }, function(error) {
              if (!called) {
                called = true;
                handlers.reject(promise, error);
              }
            });
          }
        }
      }, { "1": 1 }], 3: [function(_dereq_, module4, exports3) {
        (function(global2) {
          "use strict";
          if (typeof global2.Promise !== "function") {
            global2.Promise = _dereq_(2);
          }
        }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
      }, { "2": 2 }], 4: [function(_dereq_, module4, exports3) {
        "use strict";
        var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
          return typeof obj;
        } : function(obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
        function _classCallCheck(instance, Constructor) {
          if (!(instance instanceof Constructor)) {
            throw new TypeError("Cannot call a class as a function");
          }
        }
        function getIDB() {
          try {
            if (typeof indexedDB !== "undefined") {
              return indexedDB;
            }
            if (typeof webkitIndexedDB !== "undefined") {
              return webkitIndexedDB;
            }
            if (typeof mozIndexedDB !== "undefined") {
              return mozIndexedDB;
            }
            if (typeof OIndexedDB !== "undefined") {
              return OIndexedDB;
            }
            if (typeof msIndexedDB !== "undefined") {
              return msIndexedDB;
            }
          } catch (e3) {
            return;
          }
        }
        var idb = getIDB();
        function isIndexedDBValid() {
          try {
            if (!idb || !idb.open) {
              return false;
            }
            var isSafari = typeof openDatabase !== "undefined" && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
            var hasFetch = typeof fetch === "function" && fetch.toString().indexOf("[native code") !== -1;
            return (!isSafari || hasFetch) && typeof indexedDB !== "undefined" && // some outdated implementations of IDB that appear on Samsung
            // and HTC Android devices <4.4 are missing IDBKeyRange
            // See: https://github.com/mozilla/localForage/issues/128
            // See: https://github.com/mozilla/localForage/issues/272
            typeof IDBKeyRange !== "undefined";
          } catch (e3) {
            return false;
          }
        }
        function createBlob(parts, properties) {
          parts = parts || [];
          properties = properties || {};
          try {
            return new Blob(parts, properties);
          } catch (e3) {
            if (e3.name !== "TypeError") {
              throw e3;
            }
            var Builder = typeof BlobBuilder !== "undefined" ? BlobBuilder : typeof MSBlobBuilder !== "undefined" ? MSBlobBuilder : typeof MozBlobBuilder !== "undefined" ? MozBlobBuilder : WebKitBlobBuilder;
            var builder = new Builder();
            for (var i4 = 0; i4 < parts.length; i4 += 1) {
              builder.append(parts[i4]);
            }
            return builder.getBlob(properties.type);
          }
        }
        if (typeof Promise === "undefined") {
          _dereq_(3);
        }
        var Promise$1 = Promise;
        function executeCallback(promise, callback) {
          if (callback) {
            promise.then(function(result) {
              callback(null, result);
            }, function(error) {
              callback(error);
            });
          }
        }
        function executeTwoCallbacks(promise, callback, errorCallback) {
          if (typeof callback === "function") {
            promise.then(callback);
          }
          if (typeof errorCallback === "function") {
            promise["catch"](errorCallback);
          }
        }
        function normalizeKey(key2) {
          if (typeof key2 !== "string") {
            console.warn(key2 + " used as a key, but it is not a string.");
            key2 = String(key2);
          }
          return key2;
        }
        function getCallback() {
          if (arguments.length && typeof arguments[arguments.length - 1] === "function") {
            return arguments[arguments.length - 1];
          }
        }
        var DETECT_BLOB_SUPPORT_STORE = "local-forage-detect-blob-support";
        var supportsBlobs = void 0;
        var dbContexts = {};
        var toString = Object.prototype.toString;
        var READ_ONLY = "readonly";
        var READ_WRITE = "readwrite";
        function _binStringToArrayBuffer(bin) {
          var length2 = bin.length;
          var buf = new ArrayBuffer(length2);
          var arr = new Uint8Array(buf);
          for (var i4 = 0; i4 < length2; i4++) {
            arr[i4] = bin.charCodeAt(i4);
          }
          return buf;
        }
        function _checkBlobSupportWithoutCaching(idb2) {
          return new Promise$1(function(resolve) {
            var txn = idb2.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
            var blob = createBlob([""]);
            txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, "key");
            txn.onabort = function(e3) {
              e3.preventDefault();
              e3.stopPropagation();
              resolve(false);
            };
            txn.oncomplete = function() {
              var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
              var matchedEdge = navigator.userAgent.match(/Edge\//);
              resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
            };
          })["catch"](function() {
            return false;
          });
        }
        function _checkBlobSupport(idb2) {
          if (typeof supportsBlobs === "boolean") {
            return Promise$1.resolve(supportsBlobs);
          }
          return _checkBlobSupportWithoutCaching(idb2).then(function(value) {
            supportsBlobs = value;
            return supportsBlobs;
          });
        }
        function _deferReadiness(dbInfo) {
          var dbContext = dbContexts[dbInfo.name];
          var deferredOperation = {};
          deferredOperation.promise = new Promise$1(function(resolve, reject) {
            deferredOperation.resolve = resolve;
            deferredOperation.reject = reject;
          });
          dbContext.deferredOperations.push(deferredOperation);
          if (!dbContext.dbReady) {
            dbContext.dbReady = deferredOperation.promise;
          } else {
            dbContext.dbReady = dbContext.dbReady.then(function() {
              return deferredOperation.promise;
            });
          }
        }
        function _advanceReadiness(dbInfo) {
          var dbContext = dbContexts[dbInfo.name];
          var deferredOperation = dbContext.deferredOperations.pop();
          if (deferredOperation) {
            deferredOperation.resolve();
            return deferredOperation.promise;
          }
        }
        function _rejectReadiness(dbInfo, err) {
          var dbContext = dbContexts[dbInfo.name];
          var deferredOperation = dbContext.deferredOperations.pop();
          if (deferredOperation) {
            deferredOperation.reject(err);
            return deferredOperation.promise;
          }
        }
        function _getConnection(dbInfo, upgradeNeeded) {
          return new Promise$1(function(resolve, reject) {
            dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
            if (dbInfo.db) {
              if (upgradeNeeded) {
                _deferReadiness(dbInfo);
                dbInfo.db.close();
              } else {
                return resolve(dbInfo.db);
              }
            }
            var dbArgs = [dbInfo.name];
            if (upgradeNeeded) {
              dbArgs.push(dbInfo.version);
            }
            var openreq = idb.open.apply(idb, dbArgs);
            if (upgradeNeeded) {
              openreq.onupgradeneeded = function(e3) {
                var db = openreq.result;
                try {
                  db.createObjectStore(dbInfo.storeName);
                  if (e3.oldVersion <= 1) {
                    db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
                  }
                } catch (ex) {
                  if (ex.name === "ConstraintError") {
                    console.warn('The database "' + dbInfo.name + '" has been upgraded from version ' + e3.oldVersion + " to version " + e3.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
                  } else {
                    throw ex;
                  }
                }
              };
            }
            openreq.onerror = function(e3) {
              e3.preventDefault();
              reject(openreq.error);
            };
            openreq.onsuccess = function() {
              var db = openreq.result;
              db.onversionchange = function(e3) {
                e3.target.close();
              };
              resolve(db);
              _advanceReadiness(dbInfo);
            };
          });
        }
        function _getOriginalConnection(dbInfo) {
          return _getConnection(dbInfo, false);
        }
        function _getUpgradedConnection(dbInfo) {
          return _getConnection(dbInfo, true);
        }
        function _isUpgradeNeeded(dbInfo, defaultVersion) {
          if (!dbInfo.db) {
            return true;
          }
          var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
          var isDowngrade = dbInfo.version < dbInfo.db.version;
          var isUpgrade = dbInfo.version > dbInfo.db.version;
          if (isDowngrade) {
            if (dbInfo.version !== defaultVersion) {
              console.warn('The database "' + dbInfo.name + `" can't be downgraded from version ` + dbInfo.db.version + " to version " + dbInfo.version + ".");
            }
            dbInfo.version = dbInfo.db.version;
          }
          if (isUpgrade || isNewStore) {
            if (isNewStore) {
              var incVersion = dbInfo.db.version + 1;
              if (incVersion > dbInfo.version) {
                dbInfo.version = incVersion;
              }
            }
            return true;
          }
          return false;
        }
        function _encodeBlob(blob) {
          return new Promise$1(function(resolve, reject) {
            var reader = new FileReader();
            reader.onerror = reject;
            reader.onloadend = function(e3) {
              var base64 = btoa(e3.target.result || "");
              resolve({
                __local_forage_encoded_blob: true,
                data: base64,
                type: blob.type
              });
            };
            reader.readAsBinaryString(blob);
          });
        }
        function _decodeBlob(encodedBlob) {
          var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
          return createBlob([arrayBuff], { type: encodedBlob.type });
        }
        function _isEncodedBlob(value) {
          return value && value.__local_forage_encoded_blob;
        }
        function _fullyReady(callback) {
          var self2 = this;
          var promise = self2._initReady().then(function() {
            var dbContext = dbContexts[self2._dbInfo.name];
            if (dbContext && dbContext.dbReady) {
              return dbContext.dbReady;
            }
          });
          executeTwoCallbacks(promise, callback, callback);
          return promise;
        }
        function _tryReconnect(dbInfo) {
          _deferReadiness(dbInfo);
          var dbContext = dbContexts[dbInfo.name];
          var forages = dbContext.forages;
          for (var i4 = 0; i4 < forages.length; i4++) {
            var forage = forages[i4];
            if (forage._dbInfo.db) {
              forage._dbInfo.db.close();
              forage._dbInfo.db = null;
            }
          }
          dbInfo.db = null;
          return _getOriginalConnection(dbInfo).then(function(db) {
            dbInfo.db = db;
            if (_isUpgradeNeeded(dbInfo)) {
              return _getUpgradedConnection(dbInfo);
            }
            return db;
          }).then(function(db) {
            dbInfo.db = dbContext.db = db;
            for (var i5 = 0; i5 < forages.length; i5++) {
              forages[i5]._dbInfo.db = db;
            }
          })["catch"](function(err) {
            _rejectReadiness(dbInfo, err);
            throw err;
          });
        }
        function createTransaction(dbInfo, mode, callback, retries) {
          if (retries === void 0) {
            retries = 1;
          }
          try {
            var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
            callback(null, tx);
          } catch (err) {
            if (retries > 0 && (!dbInfo.db || err.name === "InvalidStateError" || err.name === "NotFoundError")) {
              return Promise$1.resolve().then(function() {
                if (!dbInfo.db || err.name === "NotFoundError" && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
                  if (dbInfo.db) {
                    dbInfo.version = dbInfo.db.version + 1;
                  }
                  return _getUpgradedConnection(dbInfo);
                }
              }).then(function() {
                return _tryReconnect(dbInfo).then(function() {
                  createTransaction(dbInfo, mode, callback, retries - 1);
                });
              })["catch"](callback);
            }
            callback(err);
          }
        }
        function createDbContext() {
          return {
            // Running localForages sharing a database.
            forages: [],
            // Shared database.
            db: null,
            // Database readiness (promise).
            dbReady: null,
            // Deferred operations on the database.
            deferredOperations: []
          };
        }
        function _initStorage(options) {
          var self2 = this;
          var dbInfo = {
            db: null
          };
          if (options) {
            for (var i4 in options) {
              dbInfo[i4] = options[i4];
            }
          }
          var dbContext = dbContexts[dbInfo.name];
          if (!dbContext) {
            dbContext = createDbContext();
            dbContexts[dbInfo.name] = dbContext;
          }
          dbContext.forages.push(self2);
          if (!self2._initReady) {
            self2._initReady = self2.ready;
            self2.ready = _fullyReady;
          }
          var initPromises = [];
          function ignoreErrors() {
            return Promise$1.resolve();
          }
          for (var j4 = 0; j4 < dbContext.forages.length; j4++) {
            var forage = dbContext.forages[j4];
            if (forage !== self2) {
              initPromises.push(forage._initReady()["catch"](ignoreErrors));
            }
          }
          var forages = dbContext.forages.slice(0);
          return Promise$1.all(initPromises).then(function() {
            dbInfo.db = dbContext.db;
            return _getOriginalConnection(dbInfo);
          }).then(function(db) {
            dbInfo.db = db;
            if (_isUpgradeNeeded(dbInfo, self2._defaultConfig.version)) {
              return _getUpgradedConnection(dbInfo);
            }
            return db;
          }).then(function(db) {
            dbInfo.db = dbContext.db = db;
            self2._dbInfo = dbInfo;
            for (var k4 = 0; k4 < forages.length; k4++) {
              var forage2 = forages[k4];
              if (forage2 !== self2) {
                forage2._dbInfo.db = dbInfo.db;
                forage2._dbInfo.version = dbInfo.version;
              }
            }
          });
        }
        function getItem(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store.get(key2);
                  req.onsuccess = function() {
                    var value = req.result;
                    if (value === void 0) {
                      value = null;
                    }
                    if (_isEncodedBlob(value)) {
                      value = _decodeBlob(value);
                    }
                    resolve(value);
                  };
                  req.onerror = function() {
                    reject(req.error);
                  };
                } catch (e3) {
                  reject(e3);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function iterate(iterator, callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store.openCursor();
                  var iterationNumber = 1;
                  req.onsuccess = function() {
                    var cursor = req.result;
                    if (cursor) {
                      var value = cursor.value;
                      if (_isEncodedBlob(value)) {
                        value = _decodeBlob(value);
                      }
                      var result = iterator(value, cursor.key, iterationNumber++);
                      if (result !== void 0) {
                        resolve(result);
                      } else {
                        cursor["continue"]();
                      }
                    } else {
                      resolve();
                    }
                  };
                  req.onerror = function() {
                    reject(req.error);
                  };
                } catch (e3) {
                  reject(e3);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function setItem(key2, value, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve, reject) {
            var dbInfo;
            self2.ready().then(function() {
              dbInfo = self2._dbInfo;
              if (toString.call(value) === "[object Blob]") {
                return _checkBlobSupport(dbInfo.db).then(function(blobSupport) {
                  if (blobSupport) {
                    return value;
                  }
                  return _encodeBlob(value);
                });
              }
              return value;
            }).then(function(value2) {
              createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  if (value2 === null) {
                    value2 = void 0;
                  }
                  var req = store.put(value2, key2);
                  transaction.oncomplete = function() {
                    if (value2 === void 0) {
                      value2 = null;
                    }
                    resolve(value2);
                  };
                  transaction.onabort = transaction.onerror = function() {
                    var err2 = req.error ? req.error : req.transaction.error;
                    reject(err2);
                  };
                } catch (e3) {
                  reject(e3);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function removeItem(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store["delete"](key2);
                  transaction.oncomplete = function() {
                    resolve();
                  };
                  transaction.onerror = function() {
                    reject(req.error);
                  };
                  transaction.onabort = function() {
                    var err2 = req.error ? req.error : req.transaction.error;
                    reject(err2);
                  };
                } catch (e3) {
                  reject(e3);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function clear(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store.clear();
                  transaction.oncomplete = function() {
                    resolve();
                  };
                  transaction.onabort = transaction.onerror = function() {
                    var err2 = req.error ? req.error : req.transaction.error;
                    reject(err2);
                  };
                } catch (e3) {
                  reject(e3);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function length(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store.count();
                  req.onsuccess = function() {
                    resolve(req.result);
                  };
                  req.onerror = function() {
                    reject(req.error);
                  };
                } catch (e3) {
                  reject(e3);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function key(n3, callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            if (n3 < 0) {
              resolve(null);
              return;
            }
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var advanced = false;
                  var req = store.openKeyCursor();
                  req.onsuccess = function() {
                    var cursor = req.result;
                    if (!cursor) {
                      resolve(null);
                      return;
                    }
                    if (n3 === 0) {
                      resolve(cursor.key);
                    } else {
                      if (!advanced) {
                        advanced = true;
                        cursor.advance(n3);
                      } else {
                        resolve(cursor.key);
                      }
                    }
                  };
                  req.onerror = function() {
                    reject(req.error);
                  };
                } catch (e3) {
                  reject(e3);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function keys(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) {
                if (err) {
                  return reject(err);
                }
                try {
                  var store = transaction.objectStore(self2._dbInfo.storeName);
                  var req = store.openKeyCursor();
                  var keys2 = [];
                  req.onsuccess = function() {
                    var cursor = req.result;
                    if (!cursor) {
                      resolve(keys2);
                      return;
                    }
                    keys2.push(cursor.key);
                    cursor["continue"]();
                  };
                  req.onerror = function() {
                    reject(req.error);
                  };
                } catch (e3) {
                  reject(e3);
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function dropInstance(options, callback) {
          callback = getCallback.apply(this, arguments);
          var currentConfig = this.config();
          options = typeof options !== "function" && options || {};
          if (!options.name) {
            options.name = options.name || currentConfig.name;
            options.storeName = options.storeName || currentConfig.storeName;
          }
          var self2 = this;
          var promise;
          if (!options.name) {
            promise = Promise$1.reject("Invalid arguments");
          } else {
            var isCurrentDb = options.name === currentConfig.name && self2._dbInfo.db;
            var dbPromise = isCurrentDb ? Promise$1.resolve(self2._dbInfo.db) : _getOriginalConnection(options).then(function(db) {
              var dbContext = dbContexts[options.name];
              var forages = dbContext.forages;
              dbContext.db = db;
              for (var i4 = 0; i4 < forages.length; i4++) {
                forages[i4]._dbInfo.db = db;
              }
              return db;
            });
            if (!options.storeName) {
              promise = dbPromise.then(function(db) {
                _deferReadiness(options);
                var dbContext = dbContexts[options.name];
                var forages = dbContext.forages;
                db.close();
                for (var i4 = 0; i4 < forages.length; i4++) {
                  var forage = forages[i4];
                  forage._dbInfo.db = null;
                }
                var dropDBPromise = new Promise$1(function(resolve, reject) {
                  var req = idb.deleteDatabase(options.name);
                  req.onerror = function() {
                    var db2 = req.result;
                    if (db2) {
                      db2.close();
                    }
                    reject(req.error);
                  };
                  req.onblocked = function() {
                    console.warn('dropInstance blocked for database "' + options.name + '" until all open connections are closed');
                  };
                  req.onsuccess = function() {
                    var db2 = req.result;
                    if (db2) {
                      db2.close();
                    }
                    resolve(db2);
                  };
                });
                return dropDBPromise.then(function(db2) {
                  dbContext.db = db2;
                  for (var i5 = 0; i5 < forages.length; i5++) {
                    var _forage = forages[i5];
                    _advanceReadiness(_forage._dbInfo);
                  }
                })["catch"](function(err) {
                  (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function() {
                  });
                  throw err;
                });
              });
            } else {
              promise = dbPromise.then(function(db) {
                if (!db.objectStoreNames.contains(options.storeName)) {
                  return;
                }
                var newVersion = db.version + 1;
                _deferReadiness(options);
                var dbContext = dbContexts[options.name];
                var forages = dbContext.forages;
                db.close();
                for (var i4 = 0; i4 < forages.length; i4++) {
                  var forage = forages[i4];
                  forage._dbInfo.db = null;
                  forage._dbInfo.version = newVersion;
                }
                var dropObjectPromise = new Promise$1(function(resolve, reject) {
                  var req = idb.open(options.name, newVersion);
                  req.onerror = function(err) {
                    var db2 = req.result;
                    db2.close();
                    reject(err);
                  };
                  req.onupgradeneeded = function() {
                    var db2 = req.result;
                    db2.deleteObjectStore(options.storeName);
                  };
                  req.onsuccess = function() {
                    var db2 = req.result;
                    db2.close();
                    resolve(db2);
                  };
                });
                return dropObjectPromise.then(function(db2) {
                  dbContext.db = db2;
                  for (var j4 = 0; j4 < forages.length; j4++) {
                    var _forage2 = forages[j4];
                    _forage2._dbInfo.db = db2;
                    _advanceReadiness(_forage2._dbInfo);
                  }
                })["catch"](function(err) {
                  (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function() {
                  });
                  throw err;
                });
              });
            }
          }
          executeCallback(promise, callback);
          return promise;
        }
        var asyncStorage = {
          _driver: "asyncStorage",
          _initStorage,
          _support: isIndexedDBValid(),
          iterate,
          getItem,
          setItem,
          removeItem,
          clear,
          length,
          key,
          keys,
          dropInstance
        };
        function isWebSQLValid() {
          return typeof openDatabase === "function";
        }
        var BASE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var BLOB_TYPE_PREFIX = "~~local_forage_type~";
        var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
        var SERIALIZED_MARKER = "__lfsc__:";
        var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
        var TYPE_ARRAYBUFFER = "arbf";
        var TYPE_BLOB = "blob";
        var TYPE_INT8ARRAY = "si08";
        var TYPE_UINT8ARRAY = "ui08";
        var TYPE_UINT8CLAMPEDARRAY = "uic8";
        var TYPE_INT16ARRAY = "si16";
        var TYPE_INT32ARRAY = "si32";
        var TYPE_UINT16ARRAY = "ur16";
        var TYPE_UINT32ARRAY = "ui32";
        var TYPE_FLOAT32ARRAY = "fl32";
        var TYPE_FLOAT64ARRAY = "fl64";
        var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
        var toString$1 = Object.prototype.toString;
        function stringToBuffer(serializedString) {
          var bufferLength = serializedString.length * 0.75;
          var len = serializedString.length;
          var i4;
          var p3 = 0;
          var encoded1, encoded2, encoded3, encoded4;
          if (serializedString[serializedString.length - 1] === "=") {
            bufferLength--;
            if (serializedString[serializedString.length - 2] === "=") {
              bufferLength--;
            }
          }
          var buffer = new ArrayBuffer(bufferLength);
          var bytes = new Uint8Array(buffer);
          for (i4 = 0; i4 < len; i4 += 4) {
            encoded1 = BASE_CHARS.indexOf(serializedString[i4]);
            encoded2 = BASE_CHARS.indexOf(serializedString[i4 + 1]);
            encoded3 = BASE_CHARS.indexOf(serializedString[i4 + 2]);
            encoded4 = BASE_CHARS.indexOf(serializedString[i4 + 3]);
            bytes[p3++] = encoded1 << 2 | encoded2 >> 4;
            bytes[p3++] = (encoded2 & 15) << 4 | encoded3 >> 2;
            bytes[p3++] = (encoded3 & 3) << 6 | encoded4 & 63;
          }
          return buffer;
        }
        function bufferToString(buffer) {
          var bytes = new Uint8Array(buffer);
          var base64String = "";
          var i4;
          for (i4 = 0; i4 < bytes.length; i4 += 3) {
            base64String += BASE_CHARS[bytes[i4] >> 2];
            base64String += BASE_CHARS[(bytes[i4] & 3) << 4 | bytes[i4 + 1] >> 4];
            base64String += BASE_CHARS[(bytes[i4 + 1] & 15) << 2 | bytes[i4 + 2] >> 6];
            base64String += BASE_CHARS[bytes[i4 + 2] & 63];
          }
          if (bytes.length % 3 === 2) {
            base64String = base64String.substring(0, base64String.length - 1) + "=";
          } else if (bytes.length % 3 === 1) {
            base64String = base64String.substring(0, base64String.length - 2) + "==";
          }
          return base64String;
        }
        function serialize(value, callback) {
          var valueType = "";
          if (value) {
            valueType = toString$1.call(value);
          }
          if (value && (valueType === "[object ArrayBuffer]" || value.buffer && toString$1.call(value.buffer) === "[object ArrayBuffer]")) {
            var buffer;
            var marker = SERIALIZED_MARKER;
            if (value instanceof ArrayBuffer) {
              buffer = value;
              marker += TYPE_ARRAYBUFFER;
            } else {
              buffer = value.buffer;
              if (valueType === "[object Int8Array]") {
                marker += TYPE_INT8ARRAY;
              } else if (valueType === "[object Uint8Array]") {
                marker += TYPE_UINT8ARRAY;
              } else if (valueType === "[object Uint8ClampedArray]") {
                marker += TYPE_UINT8CLAMPEDARRAY;
              } else if (valueType === "[object Int16Array]") {
                marker += TYPE_INT16ARRAY;
              } else if (valueType === "[object Uint16Array]") {
                marker += TYPE_UINT16ARRAY;
              } else if (valueType === "[object Int32Array]") {
                marker += TYPE_INT32ARRAY;
              } else if (valueType === "[object Uint32Array]") {
                marker += TYPE_UINT32ARRAY;
              } else if (valueType === "[object Float32Array]") {
                marker += TYPE_FLOAT32ARRAY;
              } else if (valueType === "[object Float64Array]") {
                marker += TYPE_FLOAT64ARRAY;
              } else {
                callback(new Error("Failed to get type for BinaryArray"));
              }
            }
            callback(marker + bufferToString(buffer));
          } else if (valueType === "[object Blob]") {
            var fileReader = new FileReader();
            fileReader.onload = function() {
              var str = BLOB_TYPE_PREFIX + value.type + "~" + bufferToString(this.result);
              callback(SERIALIZED_MARKER + TYPE_BLOB + str);
            };
            fileReader.readAsArrayBuffer(value);
          } else {
            try {
              callback(JSON.stringify(value));
            } catch (e3) {
              console.error("Couldn't convert value into a JSON string: ", value);
              callback(null, e3);
            }
          }
        }
        function deserialize(value) {
          if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
            return JSON.parse(value);
          }
          var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
          var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
          var blobType;
          if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
            var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
            blobType = matcher[1];
            serializedString = serializedString.substring(matcher[0].length);
          }
          var buffer = stringToBuffer(serializedString);
          switch (type) {
            case TYPE_ARRAYBUFFER:
              return buffer;
            case TYPE_BLOB:
              return createBlob([buffer], { type: blobType });
            case TYPE_INT8ARRAY:
              return new Int8Array(buffer);
            case TYPE_UINT8ARRAY:
              return new Uint8Array(buffer);
            case TYPE_UINT8CLAMPEDARRAY:
              return new Uint8ClampedArray(buffer);
            case TYPE_INT16ARRAY:
              return new Int16Array(buffer);
            case TYPE_UINT16ARRAY:
              return new Uint16Array(buffer);
            case TYPE_INT32ARRAY:
              return new Int32Array(buffer);
            case TYPE_UINT32ARRAY:
              return new Uint32Array(buffer);
            case TYPE_FLOAT32ARRAY:
              return new Float32Array(buffer);
            case TYPE_FLOAT64ARRAY:
              return new Float64Array(buffer);
            default:
              throw new Error("Unkown type: " + type);
          }
        }
        var localforageSerializer = {
          serialize,
          deserialize,
          stringToBuffer,
          bufferToString
        };
        function createDbTable(t4, dbInfo, callback, errorCallback) {
          t4.executeSql("CREATE TABLE IF NOT EXISTS " + dbInfo.storeName + " (id INTEGER PRIMARY KEY, key unique, value)", [], callback, errorCallback);
        }
        function _initStorage$1(options) {
          var self2 = this;
          var dbInfo = {
            db: null
          };
          if (options) {
            for (var i4 in options) {
              dbInfo[i4] = typeof options[i4] !== "string" ? options[i4].toString() : options[i4];
            }
          }
          var dbInfoPromise = new Promise$1(function(resolve, reject) {
            try {
              dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
            } catch (e3) {
              return reject(e3);
            }
            dbInfo.db.transaction(function(t4) {
              createDbTable(t4, dbInfo, function() {
                self2._dbInfo = dbInfo;
                resolve();
              }, function(t5, error) {
                reject(error);
              });
            }, reject);
          });
          dbInfo.serializer = localforageSerializer;
          return dbInfoPromise;
        }
        function tryExecuteSql(t4, dbInfo, sqlStatement, args, callback, errorCallback) {
          t4.executeSql(sqlStatement, args, callback, function(t5, error) {
            if (error.code === error.SYNTAX_ERR) {
              t5.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?", [dbInfo.storeName], function(t6, results) {
                if (!results.rows.length) {
                  createDbTable(t6, dbInfo, function() {
                    t6.executeSql(sqlStatement, args, callback, errorCallback);
                  }, errorCallback);
                } else {
                  errorCallback(t6, error);
                }
              }, errorCallback);
            } else {
              errorCallback(t5, error);
            }
          }, errorCallback);
        }
        function getItem$1(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t4) {
                tryExecuteSql(t4, dbInfo, "SELECT * FROM " + dbInfo.storeName + " WHERE key = ? LIMIT 1", [key2], function(t5, results) {
                  var result = results.rows.length ? results.rows.item(0).value : null;
                  if (result) {
                    result = dbInfo.serializer.deserialize(result);
                  }
                  resolve(result);
                }, function(t5, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function iterate$1(iterator, callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t4) {
                tryExecuteSql(t4, dbInfo, "SELECT * FROM " + dbInfo.storeName, [], function(t5, results) {
                  var rows = results.rows;
                  var length2 = rows.length;
                  for (var i4 = 0; i4 < length2; i4++) {
                    var item = rows.item(i4);
                    var result = item.value;
                    if (result) {
                      result = dbInfo.serializer.deserialize(result);
                    }
                    result = iterator(result, item.key, i4 + 1);
                    if (result !== void 0) {
                      resolve(result);
                      return;
                    }
                  }
                  resolve();
                }, function(t5, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function _setItem(key2, value, callback, retriesLeft) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              if (value === void 0) {
                value = null;
              }
              var originalValue = value;
              var dbInfo = self2._dbInfo;
              dbInfo.serializer.serialize(value, function(value2, error) {
                if (error) {
                  reject(error);
                } else {
                  dbInfo.db.transaction(function(t4) {
                    tryExecuteSql(t4, dbInfo, "INSERT OR REPLACE INTO " + dbInfo.storeName + " (key, value) VALUES (?, ?)", [key2, value2], function() {
                      resolve(originalValue);
                    }, function(t5, error2) {
                      reject(error2);
                    });
                  }, function(sqlError) {
                    if (sqlError.code === sqlError.QUOTA_ERR) {
                      if (retriesLeft > 0) {
                        resolve(_setItem.apply(self2, [key2, originalValue, callback, retriesLeft - 1]));
                        return;
                      }
                      reject(sqlError);
                    }
                  });
                }
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function setItem$1(key2, value, callback) {
          return _setItem.apply(this, [key2, value, callback, 1]);
        }
        function removeItem$1(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t4) {
                tryExecuteSql(t4, dbInfo, "DELETE FROM " + dbInfo.storeName + " WHERE key = ?", [key2], function() {
                  resolve();
                }, function(t5, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function clear$1(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t4) {
                tryExecuteSql(t4, dbInfo, "DELETE FROM " + dbInfo.storeName, [], function() {
                  resolve();
                }, function(t5, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function length$1(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t4) {
                tryExecuteSql(t4, dbInfo, "SELECT COUNT(key) as c FROM " + dbInfo.storeName, [], function(t5, results) {
                  var result = results.rows.item(0).c;
                  resolve(result);
                }, function(t5, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function key$1(n3, callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t4) {
                tryExecuteSql(t4, dbInfo, "SELECT key FROM " + dbInfo.storeName + " WHERE id = ? LIMIT 1", [n3 + 1], function(t5, results) {
                  var result = results.rows.length ? results.rows.item(0).key : null;
                  resolve(result);
                }, function(t5, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function keys$1(callback) {
          var self2 = this;
          var promise = new Promise$1(function(resolve, reject) {
            self2.ready().then(function() {
              var dbInfo = self2._dbInfo;
              dbInfo.db.transaction(function(t4) {
                tryExecuteSql(t4, dbInfo, "SELECT key FROM " + dbInfo.storeName, [], function(t5, results) {
                  var keys2 = [];
                  for (var i4 = 0; i4 < results.rows.length; i4++) {
                    keys2.push(results.rows.item(i4).key);
                  }
                  resolve(keys2);
                }, function(t5, error) {
                  reject(error);
                });
              });
            })["catch"](reject);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function getAllStoreNames(db) {
          return new Promise$1(function(resolve, reject) {
            db.transaction(function(t4) {
              t4.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function(t5, results) {
                var storeNames = [];
                for (var i4 = 0; i4 < results.rows.length; i4++) {
                  storeNames.push(results.rows.item(i4).name);
                }
                resolve({
                  db,
                  storeNames
                });
              }, function(t5, error) {
                reject(error);
              });
            }, function(sqlError) {
              reject(sqlError);
            });
          });
        }
        function dropInstance$1(options, callback) {
          callback = getCallback.apply(this, arguments);
          var currentConfig = this.config();
          options = typeof options !== "function" && options || {};
          if (!options.name) {
            options.name = options.name || currentConfig.name;
            options.storeName = options.storeName || currentConfig.storeName;
          }
          var self2 = this;
          var promise;
          if (!options.name) {
            promise = Promise$1.reject("Invalid arguments");
          } else {
            promise = new Promise$1(function(resolve) {
              var db;
              if (options.name === currentConfig.name) {
                db = self2._dbInfo.db;
              } else {
                db = openDatabase(options.name, "", "", 0);
              }
              if (!options.storeName) {
                resolve(getAllStoreNames(db));
              } else {
                resolve({
                  db,
                  storeNames: [options.storeName]
                });
              }
            }).then(function(operationInfo) {
              return new Promise$1(function(resolve, reject) {
                operationInfo.db.transaction(function(t4) {
                  function dropTable(storeName) {
                    return new Promise$1(function(resolve2, reject2) {
                      t4.executeSql("DROP TABLE IF EXISTS " + storeName, [], function() {
                        resolve2();
                      }, function(t5, error) {
                        reject2(error);
                      });
                    });
                  }
                  var operations = [];
                  for (var i4 = 0, len = operationInfo.storeNames.length; i4 < len; i4++) {
                    operations.push(dropTable(operationInfo.storeNames[i4]));
                  }
                  Promise$1.all(operations).then(function() {
                    resolve();
                  })["catch"](function(e3) {
                    reject(e3);
                  });
                }, function(sqlError) {
                  reject(sqlError);
                });
              });
            });
          }
          executeCallback(promise, callback);
          return promise;
        }
        var webSQLStorage = {
          _driver: "webSQLStorage",
          _initStorage: _initStorage$1,
          _support: isWebSQLValid(),
          iterate: iterate$1,
          getItem: getItem$1,
          setItem: setItem$1,
          removeItem: removeItem$1,
          clear: clear$1,
          length: length$1,
          key: key$1,
          keys: keys$1,
          dropInstance: dropInstance$1
        };
        function isLocalStorageValid() {
          try {
            return typeof localStorage !== "undefined" && "setItem" in localStorage && // in IE8 typeof localStorage.setItem === 'object'
            !!localStorage.setItem;
          } catch (e3) {
            return false;
          }
        }
        function _getKeyPrefix(options, defaultConfig) {
          var keyPrefix = options.name + "/";
          if (options.storeName !== defaultConfig.storeName) {
            keyPrefix += options.storeName + "/";
          }
          return keyPrefix;
        }
        function checkIfLocalStorageThrows() {
          var localStorageTestKey = "_localforage_support_test";
          try {
            localStorage.setItem(localStorageTestKey, true);
            localStorage.removeItem(localStorageTestKey);
            return false;
          } catch (e3) {
            return true;
          }
        }
        function _isLocalStorageUsable() {
          return !checkIfLocalStorageThrows() || localStorage.length > 0;
        }
        function _initStorage$2(options) {
          var self2 = this;
          var dbInfo = {};
          if (options) {
            for (var i4 in options) {
              dbInfo[i4] = options[i4];
            }
          }
          dbInfo.keyPrefix = _getKeyPrefix(options, self2._defaultConfig);
          if (!_isLocalStorageUsable()) {
            return Promise$1.reject();
          }
          self2._dbInfo = dbInfo;
          dbInfo.serializer = localforageSerializer;
          return Promise$1.resolve();
        }
        function clear$2(callback) {
          var self2 = this;
          var promise = self2.ready().then(function() {
            var keyPrefix = self2._dbInfo.keyPrefix;
            for (var i4 = localStorage.length - 1; i4 >= 0; i4--) {
              var key2 = localStorage.key(i4);
              if (key2.indexOf(keyPrefix) === 0) {
                localStorage.removeItem(key2);
              }
            }
          });
          executeCallback(promise, callback);
          return promise;
        }
        function getItem$2(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = self2.ready().then(function() {
            var dbInfo = self2._dbInfo;
            var result = localStorage.getItem(dbInfo.keyPrefix + key2);
            if (result) {
              result = dbInfo.serializer.deserialize(result);
            }
            return result;
          });
          executeCallback(promise, callback);
          return promise;
        }
        function iterate$2(iterator, callback) {
          var self2 = this;
          var promise = self2.ready().then(function() {
            var dbInfo = self2._dbInfo;
            var keyPrefix = dbInfo.keyPrefix;
            var keyPrefixLength = keyPrefix.length;
            var length2 = localStorage.length;
            var iterationNumber = 1;
            for (var i4 = 0; i4 < length2; i4++) {
              var key2 = localStorage.key(i4);
              if (key2.indexOf(keyPrefix) !== 0) {
                continue;
              }
              var value = localStorage.getItem(key2);
              if (value) {
                value = dbInfo.serializer.deserialize(value);
              }
              value = iterator(value, key2.substring(keyPrefixLength), iterationNumber++);
              if (value !== void 0) {
                return value;
              }
            }
          });
          executeCallback(promise, callback);
          return promise;
        }
        function key$2(n3, callback) {
          var self2 = this;
          var promise = self2.ready().then(function() {
            var dbInfo = self2._dbInfo;
            var result;
            try {
              result = localStorage.key(n3);
            } catch (error) {
              result = null;
            }
            if (result) {
              result = result.substring(dbInfo.keyPrefix.length);
            }
            return result;
          });
          executeCallback(promise, callback);
          return promise;
        }
        function keys$2(callback) {
          var self2 = this;
          var promise = self2.ready().then(function() {
            var dbInfo = self2._dbInfo;
            var length2 = localStorage.length;
            var keys2 = [];
            for (var i4 = 0; i4 < length2; i4++) {
              var itemKey = localStorage.key(i4);
              if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
                keys2.push(itemKey.substring(dbInfo.keyPrefix.length));
              }
            }
            return keys2;
          });
          executeCallback(promise, callback);
          return promise;
        }
        function length$2(callback) {
          var self2 = this;
          var promise = self2.keys().then(function(keys2) {
            return keys2.length;
          });
          executeCallback(promise, callback);
          return promise;
        }
        function removeItem$2(key2, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = self2.ready().then(function() {
            var dbInfo = self2._dbInfo;
            localStorage.removeItem(dbInfo.keyPrefix + key2);
          });
          executeCallback(promise, callback);
          return promise;
        }
        function setItem$2(key2, value, callback) {
          var self2 = this;
          key2 = normalizeKey(key2);
          var promise = self2.ready().then(function() {
            if (value === void 0) {
              value = null;
            }
            var originalValue = value;
            return new Promise$1(function(resolve, reject) {
              var dbInfo = self2._dbInfo;
              dbInfo.serializer.serialize(value, function(value2, error) {
                if (error) {
                  reject(error);
                } else {
                  try {
                    localStorage.setItem(dbInfo.keyPrefix + key2, value2);
                    resolve(originalValue);
                  } catch (e3) {
                    if (e3.name === "QuotaExceededError" || e3.name === "NS_ERROR_DOM_QUOTA_REACHED") {
                      reject(e3);
                    }
                    reject(e3);
                  }
                }
              });
            });
          });
          executeCallback(promise, callback);
          return promise;
        }
        function dropInstance$2(options, callback) {
          callback = getCallback.apply(this, arguments);
          options = typeof options !== "function" && options || {};
          if (!options.name) {
            var currentConfig = this.config();
            options.name = options.name || currentConfig.name;
            options.storeName = options.storeName || currentConfig.storeName;
          }
          var self2 = this;
          var promise;
          if (!options.name) {
            promise = Promise$1.reject("Invalid arguments");
          } else {
            promise = new Promise$1(function(resolve) {
              if (!options.storeName) {
                resolve(options.name + "/");
              } else {
                resolve(_getKeyPrefix(options, self2._defaultConfig));
              }
            }).then(function(keyPrefix) {
              for (var i4 = localStorage.length - 1; i4 >= 0; i4--) {
                var key2 = localStorage.key(i4);
                if (key2.indexOf(keyPrefix) === 0) {
                  localStorage.removeItem(key2);
                }
              }
            });
          }
          executeCallback(promise, callback);
          return promise;
        }
        var localStorageWrapper = {
          _driver: "localStorageWrapper",
          _initStorage: _initStorage$2,
          _support: isLocalStorageValid(),
          iterate: iterate$2,
          getItem: getItem$2,
          setItem: setItem$2,
          removeItem: removeItem$2,
          clear: clear$2,
          length: length$2,
          key: key$2,
          keys: keys$2,
          dropInstance: dropInstance$2
        };
        var sameValue = function sameValue2(x4, y3) {
          return x4 === y3 || typeof x4 === "number" && typeof y3 === "number" && isNaN(x4) && isNaN(y3);
        };
        var includes = function includes2(array2, searchElement) {
          var len = array2.length;
          var i4 = 0;
          while (i4 < len) {
            if (sameValue(array2[i4], searchElement)) {
              return true;
            }
            i4++;
          }
          return false;
        };
        var isArray = Array.isArray || function(arg) {
          return Object.prototype.toString.call(arg) === "[object Array]";
        };
        var DefinedDrivers = {};
        var DriverSupport = {};
        var DefaultDrivers = {
          INDEXEDDB: asyncStorage,
          WEBSQL: webSQLStorage,
          LOCALSTORAGE: localStorageWrapper
        };
        var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];
        var OptionalDriverMethods = ["dropInstance"];
        var LibraryMethods = ["clear", "getItem", "iterate", "key", "keys", "length", "removeItem", "setItem"].concat(OptionalDriverMethods);
        var DefaultConfig = {
          description: "",
          driver: DefaultDriverOrder.slice(),
          name: "localforage",
          // Default DB size is _JUST UNDER_ 5MB, as it's the highest size
          // we can use without a prompt.
          size: 4980736,
          storeName: "keyvaluepairs",
          version: 1
        };
        function callWhenReady(localForageInstance, libraryMethod) {
          localForageInstance[libraryMethod] = function() {
            var _args = arguments;
            return localForageInstance.ready().then(function() {
              return localForageInstance[libraryMethod].apply(localForageInstance, _args);
            });
          };
        }
        function extend() {
          for (var i4 = 1; i4 < arguments.length; i4++) {
            var arg = arguments[i4];
            if (arg) {
              for (var _key in arg) {
                if (arg.hasOwnProperty(_key)) {
                  if (isArray(arg[_key])) {
                    arguments[0][_key] = arg[_key].slice();
                  } else {
                    arguments[0][_key] = arg[_key];
                  }
                }
              }
            }
          }
          return arguments[0];
        }
        var LocalForage = function() {
          function LocalForage2(options) {
            _classCallCheck(this, LocalForage2);
            for (var driverTypeKey in DefaultDrivers) {
              if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
                var driver = DefaultDrivers[driverTypeKey];
                var driverName = driver._driver;
                this[driverTypeKey] = driverName;
                if (!DefinedDrivers[driverName]) {
                  this.defineDriver(driver);
                }
              }
            }
            this._defaultConfig = extend({}, DefaultConfig);
            this._config = extend({}, this._defaultConfig, options);
            this._driverSet = null;
            this._initDriver = null;
            this._ready = false;
            this._dbInfo = null;
            this._wrapLibraryMethodsWithReady();
            this.setDriver(this._config.driver)["catch"](function() {
            });
          }
          LocalForage2.prototype.config = function config(options) {
            if ((typeof options === "undefined" ? "undefined" : _typeof(options)) === "object") {
              if (this._ready) {
                return new Error("Can't call config() after localforage has been used.");
              }
              for (var i4 in options) {
                if (i4 === "storeName") {
                  options[i4] = options[i4].replace(/\W/g, "_");
                }
                if (i4 === "version" && typeof options[i4] !== "number") {
                  return new Error("Database version must be a number.");
                }
                this._config[i4] = options[i4];
              }
              if ("driver" in options && options.driver) {
                return this.setDriver(this._config.driver);
              }
              return true;
            } else if (typeof options === "string") {
              return this._config[options];
            } else {
              return this._config;
            }
          };
          LocalForage2.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
            var promise = new Promise$1(function(resolve, reject) {
              try {
                var driverName = driverObject._driver;
                var complianceError = new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");
                if (!driverObject._driver) {
                  reject(complianceError);
                  return;
                }
                var driverMethods = LibraryMethods.concat("_initStorage");
                for (var i4 = 0, len = driverMethods.length; i4 < len; i4++) {
                  var driverMethodName = driverMethods[i4];
                  var isRequired = !includes(OptionalDriverMethods, driverMethodName);
                  if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== "function") {
                    reject(complianceError);
                    return;
                  }
                }
                var configureMissingMethods = function configureMissingMethods2() {
                  var methodNotImplementedFactory = function methodNotImplementedFactory2(methodName) {
                    return function() {
                      var error = new Error("Method " + methodName + " is not implemented by the current driver");
                      var promise2 = Promise$1.reject(error);
                      executeCallback(promise2, arguments[arguments.length - 1]);
                      return promise2;
                    };
                  };
                  for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {
                    var optionalDriverMethod = OptionalDriverMethods[_i];
                    if (!driverObject[optionalDriverMethod]) {
                      driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);
                    }
                  }
                };
                configureMissingMethods();
                var setDriverSupport = function setDriverSupport2(support) {
                  if (DefinedDrivers[driverName]) {
                    console.info("Redefining LocalForage driver: " + driverName);
                  }
                  DefinedDrivers[driverName] = driverObject;
                  DriverSupport[driverName] = support;
                  resolve();
                };
                if ("_support" in driverObject) {
                  if (driverObject._support && typeof driverObject._support === "function") {
                    driverObject._support().then(setDriverSupport, reject);
                  } else {
                    setDriverSupport(!!driverObject._support);
                  }
                } else {
                  setDriverSupport(true);
                }
              } catch (e3) {
                reject(e3);
              }
            });
            executeTwoCallbacks(promise, callback, errorCallback);
            return promise;
          };
          LocalForage2.prototype.driver = function driver() {
            return this._driver || null;
          };
          LocalForage2.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
            var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error("Driver not found."));
            executeTwoCallbacks(getDriverPromise, callback, errorCallback);
            return getDriverPromise;
          };
          LocalForage2.prototype.getSerializer = function getSerializer(callback) {
            var serializerPromise = Promise$1.resolve(localforageSerializer);
            executeTwoCallbacks(serializerPromise, callback);
            return serializerPromise;
          };
          LocalForage2.prototype.ready = function ready(callback) {
            var self2 = this;
            var promise = self2._driverSet.then(function() {
              if (self2._ready === null) {
                self2._ready = self2._initDriver();
              }
              return self2._ready;
            });
            executeTwoCallbacks(promise, callback, callback);
            return promise;
          };
          LocalForage2.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
            var self2 = this;
            if (!isArray(drivers)) {
              drivers = [drivers];
            }
            var supportedDrivers = this._getSupportedDrivers(drivers);
            function setDriverToConfig() {
              self2._config.driver = self2.driver();
            }
            function extendSelfWithDriver(driver) {
              self2._extend(driver);
              setDriverToConfig();
              self2._ready = self2._initStorage(self2._config);
              return self2._ready;
            }
            function initDriver(supportedDrivers2) {
              return function() {
                var currentDriverIndex = 0;
                function driverPromiseLoop() {
                  while (currentDriverIndex < supportedDrivers2.length) {
                    var driverName = supportedDrivers2[currentDriverIndex];
                    currentDriverIndex++;
                    self2._dbInfo = null;
                    self2._ready = null;
                    return self2.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop);
                  }
                  setDriverToConfig();
                  var error = new Error("No available storage method found.");
                  self2._driverSet = Promise$1.reject(error);
                  return self2._driverSet;
                }
                return driverPromiseLoop();
              };
            }
            var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function() {
              return Promise$1.resolve();
            }) : Promise$1.resolve();
            this._driverSet = oldDriverSetDone.then(function() {
              var driverName = supportedDrivers[0];
              self2._dbInfo = null;
              self2._ready = null;
              return self2.getDriver(driverName).then(function(driver) {
                self2._driver = driver._driver;
                setDriverToConfig();
                self2._wrapLibraryMethodsWithReady();
                self2._initDriver = initDriver(supportedDrivers);
              });
            })["catch"](function() {
              setDriverToConfig();
              var error = new Error("No available storage method found.");
              self2._driverSet = Promise$1.reject(error);
              return self2._driverSet;
            });
            executeTwoCallbacks(this._driverSet, callback, errorCallback);
            return this._driverSet;
          };
          LocalForage2.prototype.supports = function supports(driverName) {
            return !!DriverSupport[driverName];
          };
          LocalForage2.prototype._extend = function _extend(libraryMethodsAndProperties) {
            extend(this, libraryMethodsAndProperties);
          };
          LocalForage2.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
            var supportedDrivers = [];
            for (var i4 = 0, len = drivers.length; i4 < len; i4++) {
              var driverName = drivers[i4];
              if (this.supports(driverName)) {
                supportedDrivers.push(driverName);
              }
            }
            return supportedDrivers;
          };
          LocalForage2.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
            for (var i4 = 0, len = LibraryMethods.length; i4 < len; i4++) {
              callWhenReady(this, LibraryMethods[i4]);
            }
          };
          LocalForage2.prototype.createInstance = function createInstance(options) {
            return new LocalForage2(options);
          };
          return LocalForage2;
        }();
        var localforage_js = new LocalForage();
        module4.exports = localforage_js;
      }, { "3": 3 }] }, {}, [4])(4);
    });
  }
});

// node_modules/@datastructures-js/queue/src/queue.js
var require_queue = __commonJS({
  "node_modules/@datastructures-js/queue/src/queue.js"(exports) {
    var Queue3 = class {
      /**
       * Creates a queue.
       * @param {array} [elements]
       */
      constructor(elements) {
        this._elements = Array.isArray(elements) ? elements : [];
        this._offset = 0;
      }
      /**
       * Adds an element to the back of the queue.
       * @public
       * @param {number|string|object} element
       */
      enqueue(element) {
        this._elements.push(element);
        return this;
      }
      /**
       * Adds an element to the back of the queue.
       * @public
       * @param {number|string|object} element
       */
      push(element) {
        return this.enqueue(element);
      }
      /**
       * Dequeues the front element in the queue.
       * @public
       * @returns {number|string|object}
       */
      dequeue() {
        if (this.size() === 0)
          return null;
        const first = this.front();
        this._offset += 1;
        if (this._offset * 2 < this._elements.length)
          return first;
        this._elements = this._elements.slice(this._offset);
        this._offset = 0;
        return first;
      }
      /**
       * Dequeues the front element in the queue.
       * @public
       * @returns {number|string|object}
       */
      pop() {
        return this.dequeue();
      }
      /**
       * Returns the front element of the queue.
       * @public
       * @returns {number|string|object}
       */
      front() {
        return this.size() > 0 ? this._elements[this._offset] : null;
      }
      /**
       * Returns the back element of the queue.
       * @public
       * @returns {number|string|object}
       */
      back() {
        return this.size() > 0 ? this._elements[this._elements.length - 1] : null;
      }
      /**
       * Returns the number of elements in the queue.
       * @public
       * @returns {number}
       */
      size() {
        return this._elements.length - this._offset;
      }
      /**
       * Checks if the queue is empty.
       * @public
       * @returns {boolean}
       */
      isEmpty() {
        return this.size() === 0;
      }
      /**
       * Returns the remaining elements in the queue as an array.
       * @public
       * @returns {array}
       */
      toArray() {
        return this._elements.slice(this._offset);
      }
      /**
       * Clears the queue.
       * @public
       */
      clear() {
        this._elements = [];
        this._offset = 0;
      }
      /**
       * Creates a shallow copy of the queue.
       * @public
       * @return {Queue}
       */
      clone() {
        return new Queue3(this._elements.slice(this._offset));
      }
      /**
       * Creates a queue from an existing array.
       * @public
       * @static
       * @param {array} elements
       * @return {Queue}
       */
      static fromArray(elements) {
        return new Queue3(elements);
      }
    };
    exports.Queue = Queue3;
  }
});

// node_modules/@datastructures-js/queue/index.js
var require_queue2 = __commonJS({
  "node_modules/@datastructures-js/queue/index.js"(exports) {
    var { Queue: Queue3 } = require_queue();
    exports.Queue = Queue3;
  }
});

// src/main.ts
var main_exports = {};
__export(main_exports, {
  default: () => DatacorePlugin
});
module.exports = __toCommonJS(main_exports);

// node_modules/luxon/src/luxon.js
var luxon_exports = {};
__export(luxon_exports, {
  DateTime: () => DateTime,
  Duration: () => Duration,
  FixedOffsetZone: () => FixedOffsetZone,
  IANAZone: () => IANAZone,
  Info: () => Info,
  Interval: () => Interval,
  InvalidZone: () => InvalidZone,
  Settings: () => Settings,
  SystemZone: () => SystemZone,
  VERSION: () => VERSION,
  Zone: () => Zone
});

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

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

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

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

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

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

// node_modules/luxon/src/zone.js
var Zone = class {
  /**
   * The type of zone
   * @abstract
   * @type {string}
   */
  get type() {
    throw new ZoneIsAbstractError();
  }
  /**
   * The name of this zone.
   * @abstract
   * @type {string}
   */
  get name() {
    throw new ZoneIsAbstractError();
  }
  get ianaName() {
    return this.name;
  }
  /**
   * Returns whether the offset is known to be fixed for the whole year.
   * @abstract
   * @type {boolean}
   */
  get isUniversal() {
    throw new ZoneIsAbstractError();
  }
  /**
   * Returns the offset's common name (such as EST) at the specified timestamp
   * @abstract
   * @param {number} ts - Epoch milliseconds for which to get the name
   * @param {Object} opts - Options to affect the format
   * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.
   * @param {string} opts.locale - What locale to return the offset name in.
   * @return {string}
   */
  offsetName(ts, opts) {
    throw new ZoneIsAbstractError();
  }
  /**
   * Returns the offset's value as a string
   * @abstract
   * @param {number} ts - Epoch milliseconds for which to get the offset
   * @param {string} format - What style of offset to return.
   *                          Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
   * @return {string}
   */
  formatOffset(ts, format) {
    throw new ZoneIsAbstractError();
  }
  /**
   * Return the offset in minutes for this zone at the specified timestamp.
   * @abstract
   * @param {number} ts - Epoch milliseconds for which to compute the offset
   * @return {number}
   */
  offset(ts) {
    throw new ZoneIsAbstractError();
  }
  /**
   * Return whether this Zone is equal to another zone
   * @abstract
   * @param {Zone} otherZone - the zone to compare
   * @return {boolean}
   */
  equals(otherZone) {
    throw new ZoneIsAbstractError();
  }
  /**
   * Return whether this Zone is valid.
   * @abstract
   * @type {boolean}
   */
  get isValid() {
    throw new ZoneIsAbstractError();
  }
};

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

// node_modules/luxon/src/zones/IANAZone.js
var dtfCache = {};
function makeDTF(zone) {
  if (!dtfCache[zone]) {
    dtfCache[zone] = new Intl.DateTimeFormat("en-US", {
      hour12: false,
      timeZone: zone,
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      era: "short"
    });
  }
  return dtfCache[zone];
}
var typeToPos = {
  year: 0,
  month: 1,
  day: 2,
  era: 3,
  hour: 4,
  minute: 5,
  second: 6
};
function hackyOffset(dtf, date) {
  const formatted = dtf.format(date).replace(/\u200E/g, ""), parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed;
  return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond];
}
function partsOffset(dtf, date) {
  const formatted = dtf.formatToParts(date);
  const filled = [];
  for (let i4 = 0; i4 < formatted.length; i4++) {
    const { type, value } = formatted[i4];
    const pos = typeToPos[type];
    if (type === "era") {
      filled[pos] = value;
    } else if (!isUndefined(pos)) {
      filled[pos] = parseInt(value, 10);
    }
  }
  return filled;
}
var ianaZoneCache = {};
var IANAZone = class extends Zone {
  /**
   * @param {string} name - Zone name
   * @return {IANAZone}
   */
  static create(name) {
    if (!ianaZoneCache[name]) {
      ianaZoneCache[name] = new IANAZone(name);
    }
    return ianaZoneCache[name];
  }
  /**
   * Reset local caches. Should only be necessary in testing scenarios.
   * @return {void}
   */
  static resetCache() {
    ianaZoneCache = {};
    dtfCache = {};
  }
  /**
   * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that.
   * @param {string} s - The string to check validity on
   * @example IANAZone.isValidSpecifier("America/New_York") //=> true
   * @example IANAZone.isValidSpecifier("Sport~~blorp") //=> false
   * @deprecated This method returns false for some valid IANA names. Use isValidZone instead.
   * @return {boolean}
   */
  static isValidSpecifier(s4) {
    return this.isValidZone(s4);
  }
  /**
   * Returns whether the provided string identifies a real zone
   * @param {string} zone - The string to check
   * @example IANAZone.isValidZone("America/New_York") //=> true
   * @example IANAZone.isValidZone("Fantasia/Castle") //=> false
   * @example IANAZone.isValidZone("Sport~~blorp") //=> false
   * @return {boolean}
   */
  static isValidZone(zone) {
    if (!zone) {
      return false;
    }
    try {
      new Intl.DateTimeFormat("en-US", { timeZone: zone }).format();
      return true;
    } catch (e3) {
      return false;
    }
  }
  constructor(name) {
    super();
    this.zoneName = name;
    this.valid = IANAZone.isValidZone(name);
  }
  /** @override **/
  get type() {
    return "iana";
  }
  /** @override **/
  get name() {
    return this.zoneName;
  }
  /** @override **/
  get isUniversal() {
    return false;
  }
  /** @override **/
  offsetName(ts, { format, locale }) {
    return parseZoneInfo(ts, format, locale, this.name);
  }
  /** @override **/
  formatOffset(ts, format) {
    return formatOffset(this.offset(ts), format);
  }
  /** @override **/
  offset(ts) {
    const date = new Date(ts);
    if (isNaN(date))
      return NaN;
    const dtf = makeDTF(this.name);
    let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date);
    if (adOrBc === "BC") {
      year = -Math.abs(year) + 1;
    }
    const adjustedHour = hour === 24 ? 0 : hour;
    const asUTC = objToLocalTS({
      year,
      month,
      day,
      hour: adjustedHour,
      minute,
      second,
      millisecond: 0
    });
    let asTS = +date;
    const over = asTS % 1e3;
    asTS -= over >= 0 ? over : 1e3 + over;
    return (asUTC - asTS) / (60 * 1e3);
  }
  /** @override **/
  equals(otherZone) {
    return otherZone.type === "iana" && otherZone.name === this.name;
  }
  /** @override **/
  get isValid() {
    return this.valid;
  }
};

// node_modules/luxon/src/zones/fixedOffsetZone.js
var singleton2 = null;
var FixedOffsetZone = class extends Zone {
  /**
   * Get a singleton instance of UTC
   * @return {FixedOffsetZone}
   */
  static get utcInstance() {
    if (singleton2 === null) {
      singleton2 = new FixedOffsetZone(0);
    }
    return singleton2;
  }
  /**
   * Get an instance with a specified offset
   * @param {number} offset - The offset in minutes
   * @return {FixedOffsetZone}
   */
  static instance(offset2) {
    return offset2 === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset2);
  }
  /**
   * Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6"
   * @param {string} s - The offset string to parse
   * @example FixedOffsetZone.parseSpecifier("UTC+6")
   * @example FixedOffsetZone.parseSpecifier("UTC+06")
   * @example FixedOffsetZone.parseSpecifier("UTC-6:00")
   * @return {FixedOffsetZone}
   */
  static parseSpecifier(s4) {
    if (s4) {
      const r3 = s4.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);
      if (r3) {
        return new FixedOffsetZone(signedOffset(r3[1], r3[2]));
      }
    }
    return null;
  }
  constructor(offset2) {
    super();
    this.fixed = offset2;
  }
  /** @override **/
  get type() {
    return "fixed";
  }
  /** @override **/
  get name() {
    return this.fixed === 0 ? "UTC" : `UTC${formatOffset(this.fixed, "narrow")}`;
  }
  get ianaName() {
    if (this.fixed === 0) {
      return "Etc/UTC";
    } else {
      return `Etc/GMT${formatOffset(-this.fixed, "narrow")}`;
    }
  }
  /** @override **/
  offsetName() {
    return this.name;
  }
  /** @override **/
  formatOffset(ts, format) {
    return formatOffset(this.fixed, format);
  }
  /** @override **/
  get isUniversal() {
    return true;
  }
  /** @override **/
  offset() {
    return this.fixed;
  }
  /** @override **/
  equals(otherZone) {
    return otherZone.type === "fixed" && otherZone.fixed === this.fixed;
  }
  /** @override **/
  get isValid() {
    return true;
  }
};

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

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

// node_modules/luxon/src/settings.js
var now = () => Date.now();
var defaultZone = "system";
var defaultLocale = null;
var defaultNumberingSystem = null;
var defaultOutputCalendar = null;
var throwOnInvalid;
var Settings = class {
  /**
   * Get the callback for returning the current timestamp.
   * @type {function}
   */
  static get now() {
    return now;
  }
  /**
   * Set the callback for returning the current timestamp.
   * The function should return a number, which will be interpreted as an Epoch millisecond count
   * @type {function}
   * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future
   * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time
   */
  static set now(n3) {
    now = n3;
  }
  /**
   * Set the default time zone to create DateTimes in. Does not affect existing instances.
   * Use the value "system" to reset this value to the system's time zone.
   * @type {string}
   */
  static set defaultZone(zone) {
    defaultZone = zone;
  }
  /**
   * Get the default time zone object currently used to create DateTimes. Does not affect existing instances.
   * The default value is the system's time zone (the one set on the machine that runs this code).
   * @type {Zone}
   */
  static get defaultZone() {
    return normalizeZone(defaultZone, SystemZone.instance);
  }
  /**
   * Get the default locale to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static get defaultLocale() {
    return defaultLocale;
  }
  /**
   * Set the default locale to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static set defaultLocale(locale) {
    defaultLocale = locale;
  }
  /**
   * Get the default numbering system to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static get defaultNumberingSystem() {
    return defaultNumberingSystem;
  }
  /**
   * Set the default numbering system to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static set defaultNumberingSystem(numberingSystem) {
    defaultNumberingSystem = numberingSystem;
  }
  /**
   * Get the default output calendar to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static get defaultOutputCalendar() {
    return defaultOutputCalendar;
  }
  /**
   * Set the default output calendar to create DateTimes with. Does not affect existing instances.
   * @type {string}
   */
  static set defaultOutputCalendar(outputCalendar) {
    defaultOutputCalendar = outputCalendar;
  }
  /**
   * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
   * @type {boolean}
   */
  static get throwOnInvalid() {
    return throwOnInvalid;
  }
  /**
   * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
   * @type {boolean}
   */
  static set throwOnInvalid(t4) {
    throwOnInvalid = t4;
  }
  /**
   * Reset Luxon's global caches. Should only be necessary in testing scenarios.
   * @return {void}
   */
  static resetCaches() {
    Locale.resetCache();
    IANAZone.resetCache();
  }
};

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

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

// node_modules/luxon/src/duration.js
var INVALID = "Invalid Duration";
var lowOrderMatrix = {
  weeks: {
    days: 7,
    hours: 7 * 24,
    minutes: 7 * 24 * 60,
    seconds: 7 * 24 * 60 * 60,
    milliseconds: 7 * 24 * 60 * 60 * 1e3
  },
  days: {
    hours: 24,
    minutes: 24 * 60,
    seconds: 24 * 60 * 60,
    milliseconds: 24 * 60 * 60 * 1e3
  },
  hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1e3 },
  minutes: { seconds: 60, milliseconds: 60 * 1e3 },
  seconds: { milliseconds: 1e3 }
};
var casualMatrix = {
  years: {
    quarters: 4,
    months: 12,
    weeks: 52,
    days: 365,
    hours: 365 * 24,
    minutes: 365 * 24 * 60,
    seconds: 365 * 24 * 60 * 60,
    milliseconds: 365 * 24 * 60 * 60 * 1e3
  },
  quarters: {
    months: 3,
    weeks: 13,
    days: 91,
    hours: 91 * 24,
    minutes: 91 * 24 * 60,
    seconds: 91 * 24 * 60 * 60,
    milliseconds: 91 * 24 * 60 * 60 * 1e3
  },
  months: {
    weeks: 4,
    days: 30,
    hours: 30 * 24,
    minutes: 30 * 24 * 60,
    seconds: 30 * 24 * 60 * 60,
    milliseconds: 30 * 24 * 60 * 60 * 1e3
  },
  ...lowOrderMatrix
};
var daysInYearAccurate = 146097 / 400;
var daysInMonthAccurate = 146097 / 4800;
var accurateMatrix = {
  years: {
    quarters: 4,
    months: 12,
    weeks: daysInYearAccurate / 7,
    days: daysInYearAccurate,
    hours: daysInYearAccurate * 24,
    minutes: daysInYearAccurate * 24 * 60,
    seconds: daysInYearAccurate * 24 * 60 * 60,
    milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1e3
  },
  quarters: {
    months: 3,
    weeks: daysInYearAccurate / 28,
    days: daysInYearAccurate / 4,
    hours: daysInYearAccurate * 24 / 4,
    minutes: daysInYearAccurate * 24 * 60 / 4,
    seconds: daysInYearAccurate * 24 * 60 * 60 / 4,
    milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1e3 / 4
  },
  months: {
    weeks: daysInMonthAccurate / 7,
    days: daysInMonthAccurate,
    hours: daysInMonthAccurate * 24,
    minutes: daysInMonthAccurate * 24 * 60,
    seconds: daysInMonthAccurate * 24 * 60 * 60,
    milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1e3
  },
  ...lowOrderMatrix
};
var orderedUnits = [
  "years",
  "quarters",
  "months",
  "weeks",
  "days",
  "hours",
  "minutes",
  "seconds",
  "milliseconds"
];
var reverseUnits = orderedUnits.slice(0).reverse();
function clone(dur, alts, clear = false) {
  const conf = {
    values: clear ? alts.values : { ...dur.values, ...alts.values || {} },
    loc: dur.loc.clone(alts.loc),
    conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy
  };
  return new Duration(conf);
}
function antiTrunc(n3) {
  return n3 < 0 ? Math.floor(n3) : Math.ceil(n3);
}
function convert(matrix, fromMap, fromUnit, toMap, toUnit) {
  const conv = matrix[toUnit][fromUnit], raw = fromMap[fromUnit] / conv, sameSign = Math.sign(raw) === Math.sign(toMap[toUnit]), added = !sameSign && toMap[toUnit] !== 0 && Math.abs(raw) <= 1 ? antiTrunc(raw) : Math.trunc(raw);
  toMap[toUnit] += added;
  fromMap[fromUnit] -= added * conv;
}
function normalizeValues(matrix, vals) {
  reverseUnits.reduce((previous, current) => {
    if (!isUndefined(vals[current])) {
      if (previous) {
        convert(matrix, vals, previous, vals, current);
      }
      return current;
    } else {
      return previous;
    }
  }, null);
}
var Duration = class {
  /**
   * @private
   */
  constructor(config) {
    const accurate = config.conversionAccuracy === "longterm" || false;
    this.values = config.values;
    this.loc = config.loc || Locale.create();
    this.conversionAccuracy = accurate ? "longterm" : "casual";
    this.invalid = config.invalid || null;
    this.matrix = accurate ? accurateMatrix : casualMatrix;
    this.isLuxonDuration = true;
  }
  /**
   * Create Duration from a number of milliseconds.
   * @param {number} count of milliseconds
   * @param {Object} opts - options for parsing
   * @param {string} [opts.locale='en-US'] - the locale to use
   * @param {string} opts.numberingSystem - the numbering system to use
   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
   * @return {Duration}
   */
  static fromMillis(count, opts) {
    return Duration.fromObject({ milliseconds: count }, opts);
  }
  /**
   * Create a Duration from a JavaScript object with keys like 'years' and 'hours'.
   * If this object is empty then a zero milliseconds duration is returned.
   * @param {Object} obj - the object to create the DateTime from
   * @param {number} obj.years
   * @param {number} obj.quarters
   * @param {number} obj.months
   * @param {number} obj.weeks
   * @param {number} obj.days
   * @param {number} obj.hours
   * @param {number} obj.minutes
   * @param {number} obj.seconds
   * @param {number} obj.milliseconds
   * @param {Object} [opts=[]] - options for creating this Duration
   * @param {string} [opts.locale='en-US'] - the locale to use
   * @param {string} opts.numberingSystem - the numbering system to use
   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
   * @return {Duration}
   */
  static fromObject(obj, opts = {}) {
    if (obj == null || typeof obj !== "object") {
      throw new InvalidArgumentError(
        `Duration.fromObject: argument expected to be an object, got ${obj === null ? "null" : typeof obj}`
      );
    }
    return new Duration({
      values: normalizeObject(obj, Duration.normalizeUnit),
      loc: Locale.fromObject(opts),
      conversionAccuracy: opts.conversionAccuracy
    });
  }
  /**
   * Create a Duration from DurationLike.
   *
   * @param {Object | number | Duration} durationLike
   * One of:
   * - object with keys like 'years' and 'hours'.
   * - number representing milliseconds
   * - Duration instance
   * @return {Duration}
   */
  static fromDurationLike(durationLike) {
    if (isNumber(durationLike)) {
      return Duration.fromMillis(durationLike);
    } else if (Duration.isDuration(durationLike)) {
      return durationLike;
    } else if (typeof durationLike === "object") {
      return Duration.fromObject(durationLike);
    } else {
      throw new InvalidArgumentError(
        `Unknown duration argument ${durationLike} of type ${typeof durationLike}`
      );
    }
  }
  /**
   * Create a Duration from an ISO 8601 duration string.
   * @param {string} text - text to parse
   * @param {Object} opts - options for parsing
   * @param {string} [opts.locale='en-US'] - the locale to use
   * @param {string} opts.numberingSystem - the numbering system to use
   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
   * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
   * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }
   * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }
   * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }
   * @return {Duration}
   */
  static fromISO(text, opts) {
    const [parsed] = parseISODuration(text);
    if (parsed) {
      return Duration.fromObject(parsed, opts);
    } else {
      return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
    }
  }
  /**
   * Create a Duration from an ISO 8601 time string.
   * @param {string} text - text to parse
   * @param {Object} opts - options for parsing
   * @param {string} [opts.locale='en-US'] - the locale to use
   * @param {string} opts.numberingSystem - the numbering system to use
   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
   * @see https://en.wikipedia.org/wiki/ISO_8601#Times
   * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 }
   * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
   * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
   * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
   * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
   * @return {Duration}
   */
  static fromISOTime(text, opts) {
    const [parsed] = parseISOTimeOnly(text);
    if (parsed) {
      return Duration.fromObject(parsed, opts);
    } else {
      return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
    }
  }
  /**
   * Create an invalid Duration.
   * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent
   * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
   * @return {Duration}
   */
  static invalid(reason, explanation = null) {
    if (!reason) {
      throw new InvalidArgumentError("need to specify a reason the Duration is invalid");
    }
    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
    if (Settings.throwOnInvalid) {
      throw new InvalidDurationError(invalid);
    } else {
      return new Duration({ invalid });
    }
  }
  /**
   * @private
   */
  static normalizeUnit(unit) {
    const normalized = {
      year: "years",
      years: "years",
      quarter: "quarters",
      quarters: "quarters",
      month: "months",
      months: "months",
      week: "weeks",
      weeks: "weeks",
      day: "days",
      days: "days",
      hour: "hours",
      hours: "hours",
      minute: "minutes",
      minutes: "minutes",
      second: "seconds",
      seconds: "seconds",
      millisecond: "milliseconds",
      milliseconds: "milliseconds"
    }[unit ? unit.toLowerCase() : unit];
    if (!normalized)
      throw new InvalidUnitError(unit);
    return normalized;
  }
  /**
   * Check if an object is a Duration. Works across context boundaries
   * @param {object} o
   * @return {boolean}
   */
  static isDuration(o3) {
    return o3 && o3.isLuxonDuration || false;
  }
  /**
   * Get  the locale of a Duration, such 'en-GB'
   * @type {string}
   */
  get locale() {
    return this.isValid ? this.loc.locale : null;
  }
  /**
   * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration
   *
   * @type {string}
   */
  get numberingSystem() {
    return this.isValid ? this.loc.numberingSystem : null;
  }
  /**
   * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:
   * * `S` for milliseconds
   * * `s` for seconds
   * * `m` for minutes
   * * `h` for hours
   * * `d` for days
   * * `w` for weeks
   * * `M` for months
   * * `y` for years
   * Notes:
   * * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits
   * * Tokens can be escaped by wrapping with single quotes.
   * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting.
   * @param {string} fmt - the format string
   * @param {Object} opts - options
   * @param {boolean} [opts.floor=true] - floor numerical values
   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2"
   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002"
   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000"
   * @return {string}
   */
  toFormat(fmt, opts = {}) {
    const fmtOpts = {
      ...opts,
      floor: opts.round !== false && opts.floor !== false
    };
    return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID;
  }
  /**
   * Returns a string representation of a Duration with all units included.
   * To modify its behavior use the `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant.
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
   * @param opts - On option object to override the formatting. Accepts the same keys as the options parameter of the native `Int.NumberFormat` constructor, as well as `listStyle`.
   * @example
   * ```js
   * var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 })
   * dur.toHuman() //=> '1 day, 5 hours, 6 minutes'
   * dur.toHuman({ listStyle: "long" }) //=> '1 day, 5 hours, and 6 minutes'
   * dur.toHuman({ unitDisplay: "short" }) //=> '1 day, 5 hr, 6 min'
   * ```
   */
  toHuman(opts = {}) {
    const l4 = orderedUnits.map((unit) => {
      const val = this.values[unit];
      if (isUndefined(val)) {
        return null;
      }
      return this.loc.numberFormatter({ style: "unit", unitDisplay: "long", ...opts, unit: unit.slice(0, -1) }).format(val);
    }).filter((n3) => n3);
    return this.loc.listFormatter({ type: "conjunction", style: opts.listStyle || "narrow", ...opts }).format(l4);
  }
  /**
   * Returns a JavaScript object with this Duration's values.
   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }
   * @return {Object}
   */
  toObject() {
    if (!this.isValid)
      return {};
    return { ...this.values };
  }
  /**
   * Returns an ISO 8601-compliant string representation of this Duration.
   * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
   * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'
   * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'
   * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'
   * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'
   * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'
   * @return {string}
   */
  toISO() {
    if (!this.isValid)
      return null;
    let s4 = "P";
    if (this.years !== 0)
      s4 += this.years + "Y";
    if (this.months !== 0 || this.quarters !== 0)
      s4 += this.months + this.quarters * 3 + "M";
    if (this.weeks !== 0)
      s4 += this.weeks + "W";
    if (this.days !== 0)
      s4 += this.days + "D";
    if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0)
      s4 += "T";
    if (this.hours !== 0)
      s4 += this.hours + "H";
    if (this.minutes !== 0)
      s4 += this.minutes + "M";
    if (this.seconds !== 0 || this.milliseconds !== 0)
      s4 += roundTo(this.seconds + this.milliseconds / 1e3, 3) + "S";
    if (s4 === "P")
      s4 += "T0S";
    return s4;
  }
  /**
   * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day.
   * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours.
   * @see https://en.wikipedia.org/wiki/ISO_8601#Times
   * @param {Object} opts - options
   * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
   * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
   * @param {boolean} [opts.includePrefix=false] - include the `T` prefix
   * @param {string} [opts.format='extended'] - choose between the basic and extended format
   * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000'
   * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00'
   * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00'
   * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000'
   * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000'
   * @return {string}
   */
  toISOTime(opts = {}) {
    if (!this.isValid)
      return null;
    const millis = this.toMillis();
    if (millis < 0 || millis >= 864e5)
      return null;
    opts = {
      suppressMilliseconds: false,
      suppressSeconds: false,
      includePrefix: false,
      format: "extended",
      ...opts
    };
    const value = this.shiftTo("hours", "minutes", "seconds", "milliseconds");
    let fmt = opts.format === "basic" ? "hhmm" : "hh:mm";
    if (!opts.suppressSeconds || value.seconds !== 0 || value.milliseconds !== 0) {
      fmt += opts.format === "basic" ? "ss" : ":ss";
      if (!opts.suppressMilliseconds || value.milliseconds !== 0) {
        fmt += ".SSS";
      }
    }
    let str = value.toFormat(fmt);
    if (opts.includePrefix) {
      str = "T" + str;
    }
    return str;
  }
  /**
   * Returns an ISO 8601 representation of this Duration appropriate for use in JSON.
   * @return {string}
   */
  toJSON() {
    return this.toISO();
  }
  /**
   * Returns an ISO 8601 representation of this Duration appropriate for use in debugging.
   * @return {string}
   */
  toString() {
    return this.toISO();
  }
  /**
   * Returns an milliseconds value of this Duration.
   * @return {number}
   */
  toMillis() {
    return this.as("milliseconds");
  }
  /**
   * Returns an milliseconds value of this Duration. Alias of {@link toMillis}
   * @return {number}
   */
  valueOf() {
    return this.toMillis();
  }
  /**
   * Make this Duration longer by the specified amount. Return a newly-constructed Duration.
   * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
   * @return {Duration}
   */
  plus(duration) {
    if (!this.isValid)
      return this;
    const dur = Duration.fromDurationLike(duration), result = {};
    for (const k4 of orderedUnits) {
      if (hasOwnProperty(dur.values, k4) || hasOwnProperty(this.values, k4)) {
        result[k4] = dur.get(k4) + this.get(k4);
      }
    }
    return clone(this, { values: result }, true);
  }
  /**
   * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.
   * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
   * @return {Duration}
   */
  minus(duration) {
    if (!this.isValid)
      return this;
    const dur = Duration.fromDurationLike(duration);
    return this.plus(dur.negate());
  }
  /**
   * Scale this Duration by the specified amount. Return a newly-constructed Duration.
   * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.
   * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 }
   * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hour" ? x * 2 : x) //=> { hours: 2, minutes: 30 }
   * @return {Duration}
   */
  mapUnits(fn2) {
    if (!this.isValid)
      return this;
    const result = {};
    for (const k4 of Object.keys(this.values)) {
      result[k4] = asNumber(fn2(this.values[k4], k4));
    }
    return clone(this, { values: result }, true);
  }
  /**
   * Get the value of unit.
   * @param {string} unit - a unit such as 'minute' or 'day'
   * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2
   * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0
   * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3
   * @return {number}
   */
  get(unit) {
    return this[Duration.normalizeUnit(unit)];
  }
  /**
   * "Set" the values of specified units. Return a newly-constructed Duration.
   * @param {Object} values - a mapping of units to numbers
   * @example dur.set({ years: 2017 })
   * @example dur.set({ hours: 8, minutes: 30 })
   * @return {Duration}
   */
  set(values) {
    if (!this.isValid)
      return this;
    const mixed = { ...this.values, ...normalizeObject(values, Duration.normalizeUnit) };
    return clone(this, { values: mixed });
  }
  /**
   * "Set" the locale and/or numberingSystem.  Returns a newly-constructed Duration.
   * @example dur.reconfigure({ locale: 'en-GB' })
   * @return {Duration}
   */
  reconfigure({ locale, numberingSystem, conversionAccuracy } = {}) {
    const loc = this.loc.clone({ locale, numberingSystem }), opts = { loc };
    if (conversionAccuracy) {
      opts.conversionAccuracy = conversionAccuracy;
    }
    return clone(this, opts);
  }
  /**
   * Return the length of the duration in the specified unit.
   * @param {string} unit - a unit such as 'minutes' or 'days'
   * @example Duration.fromObject({years: 1}).as('days') //=> 365
   * @example Duration.fromObject({years: 1}).as('months') //=> 12
   * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5
   * @return {number}
   */
  as(unit) {
    return this.isValid ? this.shiftTo(unit).get(unit) : NaN;
  }
  /**
   * Reduce this Duration to its canonical representation in its current units.
   * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }
   * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }
   * @return {Duration}
   */
  normalize() {
    if (!this.isValid)
      return this;
    const vals = this.toObject();
    normalizeValues(this.matrix, vals);
    return clone(this, { values: vals }, true);
  }
  /**
   * Convert this Duration into its representation in a different set of units.
   * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }
   * @return {Duration}
   */
  shiftTo(...units) {
    if (!this.isValid)
      return this;
    if (units.length === 0) {
      return this;
    }
    units = units.map((u4) => Duration.normalizeUnit(u4));
    const built = {}, accumulated = {}, vals = this.toObject();
    let lastUnit;
    for (const k4 of orderedUnits) {
      if (units.indexOf(k4) >= 0) {
        lastUnit = k4;
        let own = 0;
        for (const ak in accumulated) {
          own += this.matrix[ak][k4] * accumulated[ak];
          accumulated[ak] = 0;
        }
        if (isNumber(vals[k4])) {
          own += vals[k4];
        }
        const i4 = Math.trunc(own);
        built[k4] = i4;
        accumulated[k4] = (own * 1e3 - i4 * 1e3) / 1e3;
        for (const down in vals) {
          if (orderedUnits.indexOf(down) > orderedUnits.indexOf(k4)) {
            convert(this.matrix, vals, down, built, k4);
          }
        }
      } else if (isNumber(vals[k4])) {
        accumulated[k4] = vals[k4];
      }
    }
    for (const key in accumulated) {
      if (accumulated[key] !== 0) {
        built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];
      }
    }
    return clone(this, { values: built }, true).normalize();
  }
  /**
   * Return the negative of this Duration.
   * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }
   * @return {Duration}
   */
  negate() {
    if (!this.isValid)
      return this;
    const negated = {};
    for (const k4 of Object.keys(this.values)) {
      negated[k4] = this.values[k4] === 0 ? 0 : -this.values[k4];
    }
    return clone(this, { values: negated }, true);
  }
  /**
   * Get the years.
   * @type {number}
   */
  get years() {
    return this.isValid ? this.values.years || 0 : NaN;
  }
  /**
   * Get the quarters.
   * @type {number}
   */
  get quarters() {
    return this.isValid ? this.values.quarters || 0 : NaN;
  }
  /**
   * Get the months.
   * @type {number}
   */
  get months() {
    return this.isValid ? this.values.months || 0 : NaN;
  }
  /**
   * Get the weeks
   * @type {number}
   */
  get weeks() {
    return this.isValid ? this.values.weeks || 0 : NaN;
  }
  /**
   * Get the days.
   * @type {number}
   */
  get days() {
    return this.isValid ? this.values.days || 0 : NaN;
  }
  /**
   * Get the hours.
   * @type {number}
   */
  get hours() {
    return this.isValid ? this.values.hours || 0 : NaN;
  }
  /**
   * Get the minutes.
   * @type {number}
   */
  get minutes() {
    return this.isValid ? this.values.minutes || 0 : NaN;
  }
  /**
   * Get the seconds.
   * @return {number}
   */
  get seconds() {
    return this.isValid ? this.values.seconds || 0 : NaN;
  }
  /**
   * Get the milliseconds.
   * @return {number}
   */
  get milliseconds() {
    return this.isValid ? this.values.milliseconds || 0 : NaN;
  }
  /**
   * Returns whether the Duration is invalid. Invalid durations are returned by diff operations
   * on invalid DateTimes or Intervals.
   * @return {boolean}
   */
  get isValid() {
    return this.invalid === null;
  }
  /**
   * Returns an error code if this Duration became invalid, or null if the Duration is valid
   * @return {string}
   */
  get invalidReason() {
    return this.invalid ? this.invalid.reason : null;
  }
  /**
   * Returns an explanation of why this Duration became invalid, or null if the Duration is valid
   * @type {string}
   */
  get invalidExplanation() {
    return this.invalid ? this.invalid.explanation : null;
  }
  /**
   * Equality check
   * Two Durations are equal iff they have the same units and the same values for each unit.
   * @param {Duration} other
   * @return {boolean}
   */
  equals(other) {
    if (!this.isValid || !other.isValid) {
      return false;
    }
    if (!this.loc.equals(other.loc)) {
      return false;
    }
    function eq(v1, v22) {
      if (v1 === void 0 || v1 === 0)
        return v22 === void 0 || v22 === 0;
      return v1 === v22;
    }
    for (const u4 of orderedUnits) {
      if (!eq(this.values[u4], other.values[u4])) {
        return false;
      }
    }
    return true;
  }
};

// node_modules/luxon/src/interval.js
var INVALID2 = "Invalid Interval";
function validateStartEnd(start, end) {
  if (!start || !start.isValid) {
    return Interval.invalid("missing or invalid start");
  } else if (!end || !end.isValid) {
    return Interval.invalid("missing or invalid end");
  } else if (end < start) {
    return Interval.invalid(
      "end before start",
      `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`
    );
  } else {
    return null;
  }
}
var Interval = class {
  /**
   * @private
   */
  constructor(config) {
    this.s = config.start;
    this.e = config.end;
    this.invalid = config.invalid || null;
    this.isLuxonInterval = true;
  }
  /**
   * Create an invalid Interval.
   * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent
   * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
   * @return {Interval}
   */
  static invalid(reason, explanation = null) {
    if (!reason) {
      throw new InvalidArgumentError("need to specify a reason the Interval is invalid");
    }
    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
    if (Settings.throwOnInvalid) {
      throw new InvalidIntervalError(invalid);
    } else {
      return new Interval({ invalid });
    }
  }
  /**
   * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end.
   * @param {DateTime|Date|Object} start
   * @param {DateTime|Date|Object} end
   * @return {Interval}
   */
  static fromDateTimes(start, end) {
    const builtStart = friendlyDateTime(start), builtEnd = friendlyDateTime(end);
    const validateError = validateStartEnd(builtStart, builtEnd);
    if (validateError == null) {
      return new Interval({
        start: builtStart,
        end: builtEnd
      });
    } else {
      return validateError;
    }
  }
  /**
   * Create an Interval from a start DateTime and a Duration to extend to.
   * @param {DateTime|Date|Object} start
   * @param {Duration|Object|number} duration - the length of the Interval.
   * @return {Interval}
   */
  static after(start, duration) {
    const dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(start);
    return Interval.fromDateTimes(dt, dt.plus(dur));
  }
  /**
   * Create an Interval from an end DateTime and a Duration to extend backwards to.
   * @param {DateTime|Date|Object} end
   * @param {Duration|Object|number} duration - the length of the Interval.
   * @return {Interval}
   */
  static before(end, duration) {
    const dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(end);
    return Interval.fromDateTimes(dt.minus(dur), dt);
  }
  /**
   * Create an Interval from an ISO 8601 string.
   * Accepts `<start>/<end>`, `<start>/<duration>`, and `<duration>/<end>` formats.
   * @param {string} text - the ISO string to parse
   * @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO}
   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
   * @return {Interval}
   */
  static fromISO(text, opts) {
    const [s4, e3] = (text || "").split("/", 2);
    if (s4 && e3) {
      let start, startIsValid;
      try {
        start = DateTime.fromISO(s4, opts);
        startIsValid = start.isValid;
      } catch (e4) {
        startIsValid = false;
      }
      let end, endIsValid;
      try {
        end = DateTime.fromISO(e3, opts);
        endIsValid = end.isValid;
      } catch (e4) {
        endIsValid = false;
      }
      if (startIsValid && endIsValid) {
        return Interval.fromDateTimes(start, end);
      }
      if (startIsValid) {
        const dur = Duration.fromISO(e3, opts);
        if (dur.isValid) {
          return Interval.after(start, dur);
        }
      } else if (endIsValid) {
        const dur = Duration.fromISO(s4, opts);
        if (dur.isValid) {
          return Interval.before(end, dur);
        }
      }
    }
    return Interval.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
  }
  /**
   * Check if an object is an Interval. Works across context boundaries
   * @param {object} o
   * @return {boolean}
   */
  static isInterval(o3) {
    return o3 && o3.isLuxonInterval || false;
  }
  /**
   * Returns the start of the Interval
   * @type {DateTime}
   */
  get start() {
    return this.isValid ? this.s : null;
  }
  /**
   * Returns the end of the Interval
   * @type {DateTime}
   */
  get end() {
    return this.isValid ? this.e : null;
  }
  /**
   * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'.
   * @type {boolean}
   */
  get isValid() {
    return this.invalidReason === null;
  }
  /**
   * Returns an error code if this Interval is invalid, or null if the Interval is valid
   * @type {string}
   */
  get invalidReason() {
    return this.invalid ? this.invalid.reason : null;
  }
  /**
   * Returns an explanation of why this Interval became invalid, or null if the Interval is valid
   * @type {string}
   */
  get invalidExplanation() {
    return this.invalid ? this.invalid.explanation : null;
  }
  /**
   * Returns the length of the Interval in the specified unit.
   * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in.
   * @return {number}
   */
  length(unit = "milliseconds") {
    return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN;
  }
  /**
   * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part.
   * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day'
   * asks 'what dates are included in this interval?', not 'how many days long is this interval?'
   * @param {string} [unit='milliseconds'] - the unit of time to count.
   * @return {number}
   */
  count(unit = "milliseconds") {
    if (!this.isValid)
      return NaN;
    const start = this.start.startOf(unit), end = this.end.startOf(unit);
    return Math.floor(end.diff(start, unit).get(unit)) + 1;
  }
  /**
   * Returns whether this Interval's start and end are both in the same unit of time
   * @param {string} unit - the unit of time to check sameness on
   * @return {boolean}
   */
  hasSame(unit) {
    return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false;
  }
  /**
   * Return whether this Interval has the same start and end DateTimes.
   * @return {boolean}
   */
  isEmpty() {
    return this.s.valueOf() === this.e.valueOf();
  }
  /**
   * Return whether this Interval's start is after the specified DateTime.
   * @param {DateTime} dateTime
   * @return {boolean}
   */
  isAfter(dateTime) {
    if (!this.isValid)
      return false;
    return this.s > dateTime;
  }
  /**
   * Return whether this Interval's end is before the specified DateTime.
   * @param {DateTime} dateTime
   * @return {boolean}
   */
  isBefore(dateTime) {
    if (!this.isValid)
      return false;
    return this.e <= dateTime;
  }
  /**
   * Return whether this Interval contains the specified DateTime.
   * @param {DateTime} dateTime
   * @return {boolean}
   */
  contains(dateTime) {
    if (!this.isValid)
      return false;
    return this.s <= dateTime && this.e > dateTime;
  }
  /**
   * "Sets" the start and/or end dates. Returns a newly-constructed Interval.
   * @param {Object} values - the values to set
   * @param {DateTime} values.start - the starting DateTime
   * @param {DateTime} values.end - the ending DateTime
   * @return {Interval}
   */
  set({ start, end } = {}) {
    if (!this.isValid)
      return this;
    return Interval.fromDateTimes(start || this.s, end || this.e);
  }
  /**
   * Split this Interval at each of the specified DateTimes
   * @param {...DateTime} dateTimes - the unit of time to count.
   * @return {Array}
   */
  splitAt(...dateTimes) {
    if (!this.isValid)
      return [];
    const sorted = dateTimes.map(friendlyDateTime).filter((d3) => this.contains(d3)).sort(), results = [];
    let { s: s4 } = this, i4 = 0;
    while (s4 < this.e) {
      const added = sorted[i4] || this.e, next2 = +added > +this.e ? this.e : added;
      results.push(Interval.fromDateTimes(s4, next2));
      s4 = next2;
      i4 += 1;
    }
    return results;
  }
  /**
   * Split this Interval into smaller Intervals, each of the specified length.
   * Left over time is grouped into a smaller interval
   * @param {Duration|Object|number} duration - The length of each resulting interval.
   * @return {Array}
   */
  splitBy(duration) {
    const dur = Duration.fromDurationLike(duration);
    if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) {
      return [];
    }
    let { s: s4 } = this, idx = 1, next2;
    const results = [];
    while (s4 < this.e) {
      const added = this.start.plus(dur.mapUnits((x4) => x4 * idx));
      next2 = +added > +this.e ? this.e : added;
      results.push(Interval.fromDateTimes(s4, next2));
      s4 = next2;
      idx += 1;
    }
    return results;
  }
  /**
   * Split this Interval into the specified number of smaller intervals.
   * @param {number} numberOfParts - The number of Intervals to divide the Interval into.
   * @return {Array}
   */
  divideEqually(numberOfParts) {
    if (!this.isValid)
      return [];
    return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts);
  }
  /**
   * Return whether this Interval overlaps with the specified Interval
   * @param {Interval} other
   * @return {boolean}
   */
  overlaps(other) {
    return this.e > other.s && this.s < other.e;
  }
  /**
   * Return whether this Interval's end is adjacent to the specified Interval's start.
   * @param {Interval} other
   * @return {boolean}
   */
  abutsStart(other) {
    if (!this.isValid)
      return false;
    return +this.e === +other.s;
  }
  /**
   * Return whether this Interval's start is adjacent to the specified Interval's end.
   * @param {Interval} other
   * @return {boolean}
   */
  abutsEnd(other) {
    if (!this.isValid)
      return false;
    return +other.e === +this.s;
  }
  /**
   * Return whether this Interval engulfs the start and end of the specified Interval.
   * @param {Interval} other
   * @return {boolean}
   */
  engulfs(other) {
    if (!this.isValid)
      return false;
    return this.s <= other.s && this.e >= other.e;
  }
  /**
   * Return whether this Interval has the same start and end as the specified Interval.
   * @param {Interval} other
   * @return {boolean}
   */
  equals(other) {
    if (!this.isValid || !other.isValid) {
      return false;
    }
    return this.s.equals(other.s) && this.e.equals(other.e);
  }
  /**
   * Return an Interval representing the intersection of this Interval and the specified Interval.
   * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals.
   * Returns null if the intersection is empty, meaning, the intervals don't intersect.
   * @param {Interval} other
   * @return {Interval}
   */
  intersection(other) {
    if (!this.isValid)
      return this;
    const s4 = this.s > other.s ? this.s : other.s, e3 = this.e < other.e ? this.e : other.e;
    if (s4 >= e3) {
      return null;
    } else {
      return Interval.fromDateTimes(s4, e3);
    }
  }
  /**
   * Return an Interval representing the union of this Interval and the specified Interval.
   * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals.
   * @param {Interval} other
   * @return {Interval}
   */
  union(other) {
    if (!this.isValid)
      return this;
    const s4 = this.s < other.s ? this.s : other.s, e3 = this.e > other.e ? this.e : other.e;
    return Interval.fromDateTimes(s4, e3);
  }
  /**
   * Merge an array of Intervals into a equivalent minimal set of Intervals.
   * Combines overlapping and adjacent Intervals.
   * @param {Array} intervals
   * @return {Array}
   */
  static merge(intervals) {
    const [found, final] = intervals.sort((a3, b3) => a3.s - b3.s).reduce(
      ([sofar, current], item) => {
        if (!current) {
          return [sofar, item];
        } else if (current.overlaps(item) || current.abutsStart(item)) {
          return [sofar, current.union(item)];
        } else {
          return [sofar.concat([current]), item];
        }
      },
      [[], null]
    );
    if (final) {
      found.push(final);
    }
    return found;
  }
  /**
   * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals.
   * @param {Array} intervals
   * @return {Array}
   */
  static xor(intervals) {
    let start = null, currentCount = 0;
    const results = [], ends = intervals.map((i4) => [
      { time: i4.s, type: "s" },
      { time: i4.e, type: "e" }
    ]), flattened = Array.prototype.concat(...ends), arr = flattened.sort((a3, b3) => a3.time - b3.time);
    for (const i4 of arr) {
      currentCount += i4.type === "s" ? 1 : -1;
      if (currentCount === 1) {
        start = i4.time;
      } else {
        if (start && +start !== +i4.time) {
          results.push(Interval.fromDateTimes(start, i4.time));
        }
        start = null;
      }
    }
    return Interval.merge(results);
  }
  /**
   * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals.
   * @param {...Interval} intervals
   * @return {Array}
   */
  difference(...intervals) {
    return Interval.xor([this].concat(intervals)).map((i4) => this.intersection(i4)).filter((i4) => i4 && !i4.isEmpty());
  }
  /**
   * Returns a string representation of this Interval appropriate for debugging.
   * @return {string}
   */
  toString() {
    if (!this.isValid)
      return INVALID2;
    return `[${this.s.toISO()} \u2013 ${this.e.toISO()})`;
  }
  /**
   * Returns an ISO 8601-compliant string representation of this Interval.
   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
   * @param {Object} opts - The same options as {@link DateTime#toISO}
   * @return {string}
   */
  toISO(opts) {
    if (!this.isValid)
      return INVALID2;
    return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`;
  }
  /**
   * Returns an ISO 8601-compliant string representation of date of this Interval.
   * The time components are ignored.
   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
   * @return {string}
   */
  toISODate() {
    if (!this.isValid)
      return INVALID2;
    return `${this.s.toISODate()}/${this.e.toISODate()}`;
  }
  /**
   * Returns an ISO 8601-compliant string representation of time of this Interval.
   * The date components are ignored.
   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
   * @param {Object} opts - The same options as {@link DateTime#toISO}
   * @return {string}
   */
  toISOTime(opts) {
    if (!this.isValid)
      return INVALID2;
    return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`;
  }
  /**
   * Returns a string representation of this Interval formatted according to the specified format string.
   * @param {string} dateFormat - the format string. This string formats the start and end time. See {@link DateTime#toFormat} for details.
   * @param {Object} opts - options
   * @param {string} [opts.separator =  ' – '] - a separator to place between the start and end representations
   * @return {string}
   */
  toFormat(dateFormat, { separator = " \u2013 " } = {}) {
    if (!this.isValid)
      return INVALID2;
    return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`;
  }
  /**
   * Return a Duration representing the time spanned by this interval.
   * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration.
   * @param {Object} opts - options that affect the creation of the Duration
   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
   * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 }
   * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 }
   * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 }
   * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 }
   * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 }
   * @return {Duration}
   */
  toDuration(unit, opts) {
    if (!this.isValid) {
      return Duration.invalid(this.invalidReason);
    }
    return this.e.diff(this.s, unit, opts);
  }
  /**
   * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes
   * @param {function} mapFn
   * @return {Interval}
   * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC())
   * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 }))
   */
  mapEndpoints(mapFn) {
    return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e));
  }
};

// node_modules/luxon/src/info.js
var Info = class {
  /**
   * Return whether the specified zone contains a DST.
   * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone.
   * @return {boolean}
   */
  static hasDST(zone = Settings.defaultZone) {
    const proto = DateTime.now().setZone(zone).set({ month: 12 });
    return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset;
  }
  /**
   * Return whether the specified zone is a valid IANA specifier.
   * @param {string} zone - Zone to check
   * @return {boolean}
   */
  static isValidIANAZone(zone) {
    return IANAZone.isValidZone(zone);
  }
  /**
   * Converts the input into a {@link Zone} instance.
   *
   * * If `input` is already a Zone instance, it is returned unchanged.
   * * If `input` is a string containing a valid time zone name, a Zone instance
   *   with that name is returned.
   * * If `input` is a string that doesn't refer to a known time zone, a Zone
   *   instance with {@link Zone#isValid} == false is returned.
   * * If `input is a number, a Zone instance with the specified fixed offset
   *   in minutes is returned.
   * * If `input` is `null` or `undefined`, the default zone is returned.
   * @param {string|Zone|number} [input] - the value to be converted
   * @return {Zone}
   */
  static normalizeZone(input2) {
    return normalizeZone(input2, Settings.defaultZone);
  }
  /**
   * Return an array of standalone month names.
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
   * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @param {string} [opts.numberingSystem=null] - the numbering system
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @param {string} [opts.outputCalendar='gregory'] - the calendar
   * @example Info.months()[0] //=> 'January'
   * @example Info.months('short')[0] //=> 'Jan'
   * @example Info.months('numeric')[0] //=> '1'
   * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.'
   * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١'
   * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I'
   * @return {Array}
   */
  static months(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) {
    return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length);
  }
  /**
   * Return an array of format month names.
   * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that
   * changes the string.
   * See {@link Info#months}
   * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @param {string} [opts.numberingSystem=null] - the numbering system
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @param {string} [opts.outputCalendar='gregory'] - the calendar
   * @return {Array}
   */
  static monthsFormat(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) {
    return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true);
  }
  /**
   * Return an array of standalone week names.
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
   * @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long".
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @param {string} [opts.numberingSystem=null] - the numbering system
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @example Info.weekdays()[0] //=> 'Monday'
   * @example Info.weekdays('short')[0] //=> 'Mon'
   * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.'
   * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين'
   * @return {Array}
   */
  static weekdays(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) {
    return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length);
  }
  /**
   * Return an array of format week names.
   * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that
   * changes the string.
   * See {@link Info#weekdays}
   * @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long".
   * @param {Object} opts - options
   * @param {string} [opts.locale=null] - the locale code
   * @param {string} [opts.numberingSystem=null] - the numbering system
   * @param {string} [opts.locObj=null] - an existing locale object to use
   * @return {Array}
   */
  static weekdaysFormat(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) {
    return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true);
  }
  /**
   * Return an array of meridiems.
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @example Info.meridiems() //=> [ 'AM', 'PM' ]
   * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ]
   * @return {Array}
   */
  static meridiems({ locale = null } = {}) {
    return Locale.create(locale).meridiems();
  }
  /**
   * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian.
   * @param {string} [length='short'] - the length of the era representation, such as "short" or "long".
   * @param {Object} opts - options
   * @param {string} [opts.locale] - the locale code
   * @example Info.eras() //=> [ 'BC', 'AD' ]
   * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ]
   * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ]
   * @return {Array}
   */
  static eras(length = "short", { locale = null } = {}) {
    return Locale.create(locale, null, "gregory").eras(length);
  }
  /**
   * Return the set of available features in this environment.
   * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case.
   * Keys:
   * * `relative`: whether this environment supports relative time formatting
   * @example Info.features() //=> { relative: false }
   * @return {Object}
   */
  static features() {
    return { relative: hasRelative() };
  }
};

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

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

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

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

// node_modules/luxon/src/datetime.js
var INVALID3 = "Invalid DateTime";
var MAX_DATE = 864e13;
function unsupportedZone(zone) {
  return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`);
}
function possiblyCachedWeekData(dt) {
  if (dt.weekData === null) {
    dt.weekData = gregorianToWeek(dt.c);
  }
  return dt.weekData;
}
function clone2(inst, alts) {
  const current = {
    ts: inst.ts,
    zone: inst.zone,
    c: inst.c,
    o: inst.o,
    loc: inst.loc,
    invalid: inst.invalid
  };
  return new DateTime({ ...current, ...alts, old: current });
}
function fixOffset(localTS, o3, tz) {
  let utcGuess = localTS - o3 * 60 * 1e3;
  const o22 = tz.offset(utcGuess);
  if (o3 === o22) {
    return [utcGuess, o3];
  }
  utcGuess -= (o22 - o3) * 60 * 1e3;
  const o32 = tz.offset(utcGuess);
  if (o22 === o32) {
    return [utcGuess, o22];
  }
  return [localTS - Math.min(o22, o32) * 60 * 1e3, Math.max(o22, o32)];
}
function tsToObj(ts, offset2) {
  ts += offset2 * 60 * 1e3;
  const d3 = new Date(ts);
  return {
    year: d3.getUTCFullYear(),
    month: d3.getUTCMonth() + 1,
    day: d3.getUTCDate(),
    hour: d3.getUTCHours(),
    minute: d3.getUTCMinutes(),
    second: d3.getUTCSeconds(),
    millisecond: d3.getUTCMilliseconds()
  };
}
function objToTS(obj, offset2, zone) {
  return fixOffset(objToLocalTS(obj), offset2, zone);
}
function adjustTime(inst, dur) {
  const oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c3 = {
    ...inst.c,
    year,
    month,
    day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7
  }, millisToAdd = Duration.fromObject({
    years: dur.years - Math.trunc(dur.years),
    quarters: dur.quarters - Math.trunc(dur.quarters),
    months: dur.months - Math.trunc(dur.months),
    weeks: dur.weeks - Math.trunc(dur.weeks),
    days: dur.days - Math.trunc(dur.days),
    hours: dur.hours,
    minutes: dur.minutes,
    seconds: dur.seconds,
    milliseconds: dur.milliseconds
  }).as("milliseconds"), localTS = objToLocalTS(c3);
  let [ts, o3] = fixOffset(localTS, oPre, inst.zone);
  if (millisToAdd !== 0) {
    ts += millisToAdd;
    o3 = inst.zone.offset(ts);
  }
  return { ts, o: o3 };
}
function parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) {
  const { setZone, zone } = opts;
  if (parsed && Object.keys(parsed).length !== 0) {
    const interpretationZone = parsedZone || zone, inst = DateTime.fromObject(parsed, {
      ...opts,
      zone: interpretationZone,
      specificOffset
    });
    return setZone ? inst : inst.setZone(zone);
  } else {
    return DateTime.invalid(
      new Invalid("unparsable", `the input "${text}" can't be parsed as ${format}`)
    );
  }
}
function toTechFormat(dt, format, allowZ = true) {
  return dt.isValid ? Formatter.create(Locale.create("en-US"), {
    allowZ,
    forceSimple: true
  }).formatDateTimeFromString(dt, format) : null;
}
function toISODate(o3, extended) {
  const longFormat = o3.c.year > 9999 || o3.c.year < 0;
  let c3 = "";
  if (longFormat && o3.c.year >= 0)
    c3 += "+";
  c3 += padStart(o3.c.year, longFormat ? 6 : 4);
  if (extended) {
    c3 += "-";
    c3 += padStart(o3.c.month);
    c3 += "-";
    c3 += padStart(o3.c.day);
  } else {
    c3 += padStart(o3.c.month);
    c3 += padStart(o3.c.day);
  }
  return c3;
}
function toISOTime(o3, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone) {
  let c3 = padStart(o3.c.hour);
  if (extended) {
    c3 += ":";
    c3 += padStart(o3.c.minute);
    if (o3.c.second !== 0 || !suppressSeconds) {
      c3 += ":";
    }
  } else {
    c3 += padStart(o3.c.minute);
  }
  if (o3.c.second !== 0 || !suppressSeconds) {
    c3 += padStart(o3.c.second);
    if (o3.c.millisecond !== 0 || !suppressMilliseconds) {
      c3 += ".";
      c3 += padStart(o3.c.millisecond, 3);
    }
  }
  if (includeOffset) {
    if (o3.isOffsetFixed && o3.offset === 0 && !extendedZone) {
      c3 += "Z";
    } else if (o3.o < 0) {
      c3 += "-";
      c3 += padStart(Math.trunc(-o3.o / 60));
      c3 += ":";
      c3 += padStart(Math.trunc(-o3.o % 60));
    } else {
      c3 += "+";
      c3 += padStart(Math.trunc(o3.o / 60));
      c3 += ":";
      c3 += padStart(Math.trunc(o3.o % 60));
    }
  }
  if (extendedZone) {
    c3 += "[" + o3.zone.ianaName + "]";
  }
  return c3;
}
var defaultUnitValues = {
  month: 1,
  day: 1,
  hour: 0,
  minute: 0,
  second: 0,
  millisecond: 0
};
var defaultWeekUnitValues = {
  weekNumber: 1,
  weekday: 1,
  hour: 0,
  minute: 0,
  second: 0,
  millisecond: 0
};
var defaultOrdinalUnitValues = {
  ordinal: 1,
  hour: 0,
  minute: 0,
  second: 0,
  millisecond: 0
};
var orderedUnits2 = ["year", "month", "day", "hour", "minute", "second", "millisecond"];
var orderedWeekUnits = [
  "weekYear",
  "weekNumber",
  "weekday",
  "hour",
  "minute",
  "second",
  "millisecond"
];
var orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"];
function normalizeUnit(unit) {
  const normalized = {
    year: "year",
    years: "year",
    month: "month",
    months: "month",
    day: "day",
    days: "day",
    hour: "hour",
    hours: "hour",
    minute: "minute",
    minutes: "minute",
    quarter: "quarter",
    quarters: "quarter",
    second: "second",
    seconds: "second",
    millisecond: "millisecond",
    milliseconds: "millisecond",
    weekday: "weekday",
    weekdays: "weekday",
    weeknumber: "weekNumber",
    weeksnumber: "weekNumber",
    weeknumbers: "weekNumber",
    weekyear: "weekYear",
    weekyears: "weekYear",
    ordinal: "ordinal"
  }[unit.toLowerCase()];
  if (!normalized)
    throw new InvalidUnitError(unit);
  return normalized;
}
function quickDT(obj, opts) {
  const zone = normalizeZone(opts.zone, Settings.defaultZone), loc = Locale.fromObject(opts), tsNow = Settings.now();
  let ts, o3;
  if (!isUndefined(obj.year)) {
    for (const u4 of orderedUnits2) {
      if (isUndefined(obj[u4])) {
        obj[u4] = defaultUnitValues[u4];
      }
    }
    const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
    if (invalid) {
      return DateTime.invalid(invalid);
    }
    const offsetProvis = zone.offset(tsNow);
    [ts, o3] = objToTS(obj, offsetProvis, zone);
  } else {
    ts = tsNow;
  }
  return new DateTime({ ts, zone, loc, o: o3 });
}
function diffRelative(start, end, opts) {
  const round = isUndefined(opts.round) ? true : opts.round, format = (c3, unit) => {
    c3 = roundTo(c3, round || opts.calendary ? 0 : 2, true);
    const formatter = end.loc.clone(opts).relFormatter(opts);
    return formatter.format(c3, unit);
  }, differ = (unit) => {
    if (opts.calendary) {
      if (!end.hasSame(start, unit)) {
        return end.startOf(unit).diff(start.startOf(unit), unit).get(unit);
      } else
        return 0;
    } else {
      return end.diff(start, unit).get(unit);
    }
  };
  if (opts.unit) {
    return format(differ(opts.unit), opts.unit);
  }
  for (const unit of opts.units) {
    const count = differ(unit);
    if (Math.abs(count) >= 1) {
      return format(count, unit);
    }
  }
  return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]);
}
function lastOpts(argList) {
  let opts = {}, args;
  if (argList.length > 0 && typeof argList[argList.length - 1] === "object") {
    opts = argList[argList.length - 1];
    args = Array.from(argList).slice(0, argList.length - 1);
  } else {
    args = Array.from(argList);
  }
  return [opts, args];
}
var DateTime = class {
  /**
   * @access private
   */
  constructor(config) {
    const zone = config.zone || Settings.defaultZone;
    let invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null);
    this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;
    let c3 = null, o3 = null;
    if (!invalid) {
      const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);
      if (unchanged) {
        [c3, o3] = [config.old.c, config.old.o];
      } else {
        const ot = zone.offset(this.ts);
        c3 = tsToObj(this.ts, ot);
        invalid = Number.isNaN(c3.year) ? new Invalid("invalid input") : null;
        c3 = invalid ? null : c3;
        o3 = invalid ? null : ot;
      }
    }
    this._zone = zone;
    this.loc = config.loc || Locale.create();
    this.invalid = invalid;
    this.weekData = null;
    this.c = c3;
    this.o = o3;
    this.isLuxonDateTime = true;
  }
  // CONSTRUCT
  /**
   * Create a DateTime for the current instant, in the system's time zone.
   *
   * Use Settings to override these default values if needed.
   * @example DateTime.now().toISO() //~> now in the ISO format
   * @return {DateTime}
   */
  static now() {
    return new DateTime({});
  }
  /**
   * Create a local DateTime
   * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used
   * @param {number} [month=1] - The month, 1-indexed
   * @param {number} [day=1] - The day of the month, 1-indexed
   * @param {number} [hour=0] - The hour of the day, in 24-hour time
   * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
   * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
   * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
   * @example DateTime.local()                                  //~> now
   * @example DateTime.local({ zone: "America/New_York" })      //~> now, in US east coast time
   * @example DateTime.local(2017)                              //~> 2017-01-01T00:00:00
   * @example DateTime.local(2017, 3)                           //~> 2017-03-01T00:00:00
   * @example DateTime.local(2017, 3, 12, { locale: "fr" })     //~> 2017-03-12T00:00:00, with a French locale
   * @example DateTime.local(2017, 3, 12, 5)                    //~> 2017-03-12T05:00:00
   * @example DateTime.local(2017, 3, 12, 5, { zone: "utc" })   //~> 2017-03-12T05:00:00, in UTC
   * @example DateTime.local(2017, 3, 12, 5, 45)                //~> 2017-03-12T05:45:00
   * @example DateTime.local(2017, 3, 12, 5, 45, 10)            //~> 2017-03-12T05:45:10
   * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765)       //~> 2017-03-12T05:45:10.765
   * @return {DateTime}
   */
  static local() {
    const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args;
    return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);
  }
  /**
   * Create a DateTime in UTC
   * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used
   * @param {number} [month=1] - The month, 1-indexed
   * @param {number} [day=1] - The day of the month
   * @param {number} [hour=0] - The hour of the day, in 24-hour time
   * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
   * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
   * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
   * @param {Object} options - configuration options for the DateTime
   * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
   * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance
   * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance
   * @example DateTime.utc()                                              //~> now
   * @example DateTime.utc(2017)                                          //~> 2017-01-01T00:00:00Z
   * @example DateTime.utc(2017, 3)                                       //~> 2017-03-01T00:00:00Z
   * @example DateTime.utc(2017, 3, 12)                                   //~> 2017-03-12T00:00:00Z
   * @example DateTime.utc(2017, 3, 12, 5)                                //~> 2017-03-12T05:00:00Z
   * @example DateTime.utc(2017, 3, 12, 5, 45)                            //~> 2017-03-12T05:45:00Z
   * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: "fr" })          //~> 2017-03-12T05:45:00Z with a French locale
   * @example DateTime.utc(2017, 3, 12, 5, 45, 10)                        //~> 2017-03-12T05:45:10Z
   * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: "fr" }) //~> 2017-03-12T05:45:10.765Z with a French locale
   * @return {DateTime}
   */
  static utc() {
    const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args;
    opts.zone = FixedOffsetZone.utcInstance;
    return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);
  }
  /**
   * Create a DateTime from a JavaScript Date object. Uses the default zone.
   * @param {Date} date - a JavaScript Date object
   * @param {Object} options - configuration options for the DateTime
   * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
   * @return {DateTime}
   */
  static fromJSDate(date, options = {}) {
    const ts = isDate(date) ? date.valueOf() : NaN;
    if (Number.isNaN(ts)) {
      return DateTime.invalid("invalid input");
    }
    const zoneToUse = normalizeZone(options.zone, Settings.defaultZone);
    if (!zoneToUse.isValid) {
      return DateTime.invalid(unsupportedZone(zoneToUse));
    }
    return new DateTime({
      ts,
      zone: zoneToUse,
      loc: Locale.fromObject(options)
    });
  }
  /**
   * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
   * @param {number} milliseconds - a number of milliseconds since 1970 UTC
   * @param {Object} options - configuration options for the DateTime
   * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
   * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
   * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
   * @return {DateTime}
   */
  static fromMillis(milliseconds, options = {}) {
    if (!isNumber(milliseconds)) {
      throw new InvalidArgumentError(
        `fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`
      );
    } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) {
      return DateTime.invalid("Timestamp out of range");
    } else {
      return new DateTime({
        ts: milliseconds,
        zone: normalizeZone(options.zone, Settings.defaultZone),
        loc: Locale.fromObject(options)
      });
    }
  }
  /**
   * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
   * @param {number} seconds - a number of seconds since 1970 UTC
   * @param {Object} options - configuration options for the DateTime
   * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
   * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
   * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
   * @return {DateTime}
   */
  static fromSeconds(seconds, options = {}) {
    if (!isNumber(seconds)) {
      throw new InvalidArgumentError("fromSeconds requires a numerical input");
    } else {
      return new DateTime({
        ts: seconds * 1e3,
        zone: normalizeZone(options.zone, Settings.defaultZone),
        loc: Locale.fromObject(options)
      });
    }
  }
  /**
   * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults.
   * @param {Object} obj - the object to create the DateTime from
   * @param {number} obj.year - a year, such as 1987
   * @param {number} obj.month - a month, 1-12
   * @param {number} obj.day - a day of the month, 1-31, depending on the month
   * @param {number} obj.ordinal - day of the year, 1-365 or 366
   * @param {number} obj.weekYear - an ISO week year
   * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year
   * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday
   * @param {number} obj.hour - hour of the day, 0-23
   * @param {number} obj.minute - minute of the hour, 0-59
   * @param {number} obj.second - second of the minute, 0-59
   * @param {number} obj.millisecond - millisecond of the second, 0-999
   * @param {Object} opts - options for creating this DateTime
   * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()
   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
   * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'
   * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'
   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06
   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }),
   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' })
   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' })
   * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'
   * @return {DateTime}
   */
  static fromObject(obj, opts = {}) {
    obj = obj || {};
    const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone);
    if (!zoneToUse.isValid) {
      return DateTime.invalid(unsupportedZone(zoneToUse));
    }
    const tsNow = Settings.now(), offsetProvis = !isUndefined(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow), normalized = normalizeObject(obj, normalizeUnit), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber, loc = Locale.fromObject(opts);
    if ((containsGregor || containsOrdinal) && definiteWeekDef) {
      throw new ConflictingSpecificationError(
        "Can't mix weekYear/weekNumber units with year/month/day or ordinals"
      );
    }
    if (containsGregorMD && containsOrdinal) {
      throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
    }
    const useWeekData = definiteWeekDef || normalized.weekday && !containsGregor;
    let units, defaultValues, objNow = tsToObj(tsNow, offsetProvis);
    if (useWeekData) {
      units = orderedWeekUnits;
      defaultValues = defaultWeekUnitValues;
      objNow = gregorianToWeek(objNow);
    } else if (containsOrdinal) {
      units = orderedOrdinalUnits;
      defaultValues = defaultOrdinalUnitValues;
      objNow = gregorianToOrdinal(objNow);
    } else {
      units = orderedUnits2;
      defaultValues = defaultUnitValues;
    }
    let foundFirst = false;
    for (const u4 of units) {
      const v3 = normalized[u4];
      if (!isUndefined(v3)) {
        foundFirst = true;
      } else if (foundFirst) {
        normalized[u4] = defaultValues[u4];
      } else {
        normalized[u4] = objNow[u4];
      }
    }
    const higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid = higherOrderInvalid || hasInvalidTimeData(normalized);
    if (invalid) {
      return DateTime.invalid(invalid);
    }
    const gregorian = useWeekData ? weekToGregorian(normalized) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse), inst = new DateTime({
      ts: tsFinal,
      zone: zoneToUse,
      o: offsetFinal,
      loc
    });
    if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {
      return DateTime.invalid(
        "mismatched weekday",
        `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`
      );
    }
    return inst;
  }
  /**
   * Create a DateTime from an ISO 8601 string
   * @param {string} text - the ISO string
   * @param {Object} opts - options to affect the creation
   * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone
   * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
   * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance
   * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance
   * @example DateTime.fromISO('2016-05-25T09:08:34.123')
   * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')
   * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})
   * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})
   * @example DateTime.fromISO('2016-W05-4')
   * @return {DateTime}
   */
  static fromISO(text, opts = {}) {
    const [vals, parsedZone] = parseISODate(text);
    return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text);
  }
  /**
   * Create a DateTime from an RFC 2822 string
   * @param {string} text - the RFC 2822 string
   * @param {Object} opts - options to affect the creation
   * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
   * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
   * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')
   * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')
   * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')
   * @return {DateTime}
   */
  static fromRFC2822(text, opts = {}) {
    const [vals, parsedZone] = parseRFC2822Date(text);
    return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text);
  }
  /**
   * Create a DateTime from an HTTP header date
   * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
   * @param {string} text - the HTTP header date
   * @param {Object} opts - options to affect the creation
   * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
   * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.
   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
   * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')
   * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')
   * @example DateTime.fromHTTP('Sun Nov  6 08:49:37 1994')
   * @return {DateTime}
   */
  static fromHTTP(text, opts = {}) {
    const [vals, parsedZone] = parseHTTPDate(text);
    return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts);
  }
  /**
   * Create a DateTime from an input string and format string.
   * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens).
   * @param {string} text - the string to parse
   * @param {string} fmt - the format the string is expected to be in (see the link below for the formats)
   * @param {Object} opts - options to affect the creation
   * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
   * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
   * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
   * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @return {DateTime}
   */
  static fromFormat(text, fmt, opts = {}) {
    if (isUndefined(text) || isUndefined(fmt)) {
      throw new InvalidArgumentError("fromFormat requires an input string and a format");
    }
    const { locale = null, numberingSystem = null } = opts, localeToUse = Locale.fromOpts({
      locale,
      numberingSystem,
      defaultToEN: true
    }), [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt);
    if (invalid) {
      return DateTime.invalid(invalid);
    } else {
      return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset);
    }
  }
  /**
   * @deprecated use fromFormat instead
   */
  static fromString(text, fmt, opts = {}) {
    return DateTime.fromFormat(text, fmt, opts);
  }
  /**
   * Create a DateTime from a SQL date, time, or datetime
   * Defaults to en-US if no locale has been specified, regardless of the system's locale
   * @param {string} text - the string to parse
   * @param {Object} opts - options to affect the creation
   * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
   * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
   * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
   * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
   * @example DateTime.fromSQL('2017-05-15')
   * @example DateTime.fromSQL('2017-05-15 09:12:34')
   * @example DateTime.fromSQL('2017-05-15 09:12:34.342')
   * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')
   * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')
   * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })
   * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })
   * @example DateTime.fromSQL('09:12:34.342')
   * @return {DateTime}
   */
  static fromSQL(text, opts = {}) {
    const [vals, parsedZone] = parseSQL(text);
    return parseDataToDateTime(vals, parsedZone, opts, "SQL", text);
  }
  /**
   * Create an invalid DateTime.
   * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent
   * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
   * @return {DateTime}
   */
  static invalid(reason, explanation = null) {
    if (!reason) {
      throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");
    }
    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
    if (Settings.throwOnInvalid) {
      throw new InvalidDateTimeError(invalid);
    } else {
      return new DateTime({ invalid });
    }
  }
  /**
   * Check if an object is an instance of DateTime. Works across context boundaries
   * @param {object} o
   * @return {boolean}
   */
  static isDateTime(o3) {
    return o3 && o3.isLuxonDateTime || false;
  }
  // INFO
  /**
   * Get the value of unit.
   * @param {string} unit - a unit such as 'minute' or 'day'
   * @example DateTime.local(2017, 7, 4).get('month'); //=> 7
   * @example DateTime.local(2017, 7, 4).get('day'); //=> 4
   * @return {number}
   */
  get(unit) {
    return this[unit];
  }
  /**
   * Returns whether the DateTime is valid. Invalid DateTimes occur when:
   * * The DateTime was created from invalid calendar information, such as the 13th month or February 30
   * * The DateTime was created by an operation on another invalid date
   * @type {boolean}
   */
  get isValid() {
    return this.invalid === null;
  }
  /**
   * Returns an error code if this DateTime is invalid, or null if the DateTime is valid
   * @type {string}
   */
  get invalidReason() {
    return this.invalid ? this.invalid.reason : null;
  }
  /**
   * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid
   * @type {string}
   */
  get invalidExplanation() {
    return this.invalid ? this.invalid.explanation : null;
  }
  /**
   * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime
   *
   * @type {string}
   */
  get locale() {
    return this.isValid ? this.loc.locale : null;
  }
  /**
   * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime
   *
   * @type {string}
   */
  get numberingSystem() {
    return this.isValid ? this.loc.numberingSystem : null;
  }
  /**
   * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime
   *
   * @type {string}
   */
  get outputCalendar() {
    return this.isValid ? this.loc.outputCalendar : null;
  }
  /**
   * Get the time zone associated with this DateTime.
   * @type {Zone}
   */
  get zone() {
    return this._zone;
  }
  /**
   * Get the name of the time zone.
   * @type {string}
   */
  get zoneName() {
    return this.isValid ? this.zone.name : null;
  }
  /**
   * Get the year
   * @example DateTime.local(2017, 5, 25).year //=> 2017
   * @type {number}
   */
  get year() {
    return this.isValid ? this.c.year : NaN;
  }
  /**
   * Get the quarter
   * @example DateTime.local(2017, 5, 25).quarter //=> 2
   * @type {number}
   */
  get quarter() {
    return this.isValid ? Math.ceil(this.c.month / 3) : NaN;
  }
  /**
   * Get the month (1-12).
   * @example DateTime.local(2017, 5, 25).month //=> 5
   * @type {number}
   */
  get month() {
    return this.isValid ? this.c.month : NaN;
  }
  /**
   * Get the day of the month (1-30ish).
   * @example DateTime.local(2017, 5, 25).day //=> 25
   * @type {number}
   */
  get day() {
    return this.isValid ? this.c.day : NaN;
  }
  /**
   * Get the hour of the day (0-23).
   * @example DateTime.local(2017, 5, 25, 9).hour //=> 9
   * @type {number}
   */
  get hour() {
    return this.isValid ? this.c.hour : NaN;
  }
  /**
   * Get the minute of the hour (0-59).
   * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30
   * @type {number}
   */
  get minute() {
    return this.isValid ? this.c.minute : NaN;
  }
  /**
   * Get the second of the minute (0-59).
   * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52
   * @type {number}
   */
  get second() {
    return this.isValid ? this.c.second : NaN;
  }
  /**
   * Get the millisecond of the second (0-999).
   * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654
   * @type {number}
   */
  get millisecond() {
    return this.isValid ? this.c.millisecond : NaN;
  }
  /**
   * Get the week year
   * @see https://en.wikipedia.org/wiki/ISO_week_date
   * @example DateTime.local(2014, 12, 31).weekYear //=> 2015
   * @type {number}
   */
  get weekYear() {
    return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;
  }
  /**
   * Get the week number of the week year (1-52ish).
   * @see https://en.wikipedia.org/wiki/ISO_week_date
   * @example DateTime.local(2017, 5, 25).weekNumber //=> 21
   * @type {number}
   */
  get weekNumber() {
    return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;
  }
  /**
   * Get the day of the week.
   * 1 is Monday and 7 is Sunday
   * @see https://en.wikipedia.org/wiki/ISO_week_date
   * @example DateTime.local(2014, 11, 31).weekday //=> 4
   * @type {number}
   */
  get weekday() {
    return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;
  }
  /**
   * Get the ordinal (meaning the day of the year)
   * @example DateTime.local(2017, 5, 25).ordinal //=> 145
   * @type {number|DateTime}
   */
  get ordinal() {
    return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;
  }
  /**
   * Get the human readable short month name, such as 'Oct'.
   * Defaults to the system's locale if no locale has been specified
   * @example DateTime.local(2017, 10, 30).monthShort //=> Oct
   * @type {string}
   */
  get monthShort() {
    return this.isValid ? Info.months("short", { locObj: this.loc })[this.month - 1] : null;
  }
  /**
   * Get the human readable long month name, such as 'October'.
   * Defaults to the system's locale if no locale has been specified
   * @example DateTime.local(2017, 10, 30).monthLong //=> October
   * @type {string}
   */
  get monthLong() {
    return this.isValid ? Info.months("long", { locObj: this.loc })[this.month - 1] : null;
  }
  /**
   * Get the human readable short weekday, such as 'Mon'.
   * Defaults to the system's locale if no locale has been specified
   * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon
   * @type {string}
   */
  get weekdayShort() {
    return this.isValid ? Info.weekdays("short", { locObj: this.loc })[this.weekday - 1] : null;
  }
  /**
   * Get the human readable long weekday, such as 'Monday'.
   * Defaults to the system's locale if no locale has been specified
   * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday
   * @type {string}
   */
  get weekdayLong() {
    return this.isValid ? Info.weekdays("long", { locObj: this.loc })[this.weekday - 1] : null;
  }
  /**
   * Get the UTC offset of this DateTime in minutes
   * @example DateTime.now().offset //=> -240
   * @example DateTime.utc().offset //=> 0
   * @type {number}
   */
  get offset() {
    return this.isValid ? +this.o : NaN;
  }
  /**
   * Get the short human name for the zone's current offset, for example "EST" or "EDT".
   * Defaults to the system's locale if no locale has been specified
   * @type {string}
   */
  get offsetNameShort() {
    if (this.isValid) {
      return this.zone.offsetName(this.ts, {
        format: "short",
        locale: this.locale
      });
    } else {
      return null;
    }
  }
  /**
   * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time".
   * Defaults to the system's locale if no locale has been specified
   * @type {string}
   */
  get offsetNameLong() {
    if (this.isValid) {
      return this.zone.offsetName(this.ts, {
        format: "long",
        locale: this.locale
      });
    } else {
      return null;
    }
  }
  /**
   * Get whether this zone's offset ever changes, as in a DST.
   * @type {boolean}
   */
  get isOffsetFixed() {
    return this.isValid ? this.zone.isUniversal : null;
  }
  /**
   * Get whether the DateTime is in a DST.
   * @type {boolean}
   */
  get isInDST() {
    if (this.isOffsetFixed) {
      return false;
    } else {
      return this.offset > this.set({ month: 1, day: 1 }).offset || this.offset > this.set({ month: 5 }).offset;
    }
  }
  /**
   * Returns true if this DateTime is in a leap year, false otherwise
   * @example DateTime.local(2016).isInLeapYear //=> true
   * @example DateTime.local(2013).isInLeapYear //=> false
   * @type {boolean}
   */
  get isInLeapYear() {
    return isLeapYear(this.year);
  }
  /**
   * Returns the number of days in this DateTime's month
   * @example DateTime.local(2016, 2).daysInMonth //=> 29
   * @example DateTime.local(2016, 3).daysInMonth //=> 31
   * @type {number}
   */
  get daysInMonth() {
    return daysInMonth(this.year, this.month);
  }
  /**
   * Returns the number of days in this DateTime's year
   * @example DateTime.local(2016).daysInYear //=> 366
   * @example DateTime.local(2013).daysInYear //=> 365
   * @type {number}
   */
  get daysInYear() {
    return this.isValid ? daysInYear(this.year) : NaN;
  }
  /**
   * Returns the number of weeks in this DateTime's year
   * @see https://en.wikipedia.org/wiki/ISO_week_date
   * @example DateTime.local(2004).weeksInWeekYear //=> 53
   * @example DateTime.local(2013).weeksInWeekYear //=> 52
   * @type {number}
   */
  get weeksInWeekYear() {
    return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;
  }
  /**
   * Returns the resolved Intl options for this DateTime.
   * This is useful in understanding the behavior of formatting methods
   * @param {Object} opts - the same options as toLocaleString
   * @return {Object}
   */
  resolvedLocaleOptions(opts = {}) {
    const { locale, numberingSystem, calendar } = Formatter.create(
      this.loc.clone(opts),
      opts
    ).resolvedOptions(this);
    return { locale, numberingSystem, outputCalendar: calendar };
  }
  // TRANSFORM
  /**
   * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime.
   *
   * Equivalent to {@link DateTime#setZone}('utc')
   * @param {number} [offset=0] - optionally, an offset from UTC in minutes
   * @param {Object} [opts={}] - options to pass to `setZone()`
   * @return {DateTime}
   */
  toUTC(offset2 = 0, opts = {}) {
    return this.setZone(FixedOffsetZone.instance(offset2), opts);
  }
  /**
   * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.
   *
   * Equivalent to `setZone('local')`
   * @return {DateTime}
   */
  toLocal() {
    return this.setZone(Settings.defaultZone);
  }
  /**
   * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.
   *
   * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones.
   * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class.
   * @param {Object} opts - options
   * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.
   * @return {DateTime}
   */
  setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) {
    zone = normalizeZone(zone, Settings.defaultZone);
    if (zone.equals(this.zone)) {
      return this;
    } else if (!zone.isValid) {
      return DateTime.invalid(unsupportedZone(zone));
    } else {
      let newTS = this.ts;
      if (keepLocalTime || keepCalendarTime) {
        const offsetGuess = zone.offset(this.ts);
        const asObj = this.toObject();
        [newTS] = objToTS(asObj, offsetGuess, zone);
      }
      return clone2(this, { ts: newTS, zone });
    }
  }
  /**
   * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.
   * @param {Object} properties - the properties to set
   * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })
   * @return {DateTime}
   */
  reconfigure({ locale, numberingSystem, outputCalendar } = {}) {
    const loc = this.loc.clone({ locale, numberingSystem, outputCalendar });
    return clone2(this, { loc });
  }
  /**
   * "Set" the locale. Returns a newly-constructed DateTime.
   * Just a convenient alias for reconfigure({ locale })
   * @example DateTime.local(2017, 5, 25).setLocale('en-GB')
   * @return {DateTime}
   */
  setLocale(locale) {
    return this.reconfigure({ locale });
  }
  /**
   * "Set" the values of specified units. Returns a newly-constructed DateTime.
   * You can only set units with this method; for "setting" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}.
   * @param {Object} values - a mapping of units to numbers
   * @example dt.set({ year: 2017 })
   * @example dt.set({ hour: 8, minute: 30 })
   * @example dt.set({ weekday: 5 })
   * @example dt.set({ year: 2005, ordinal: 234 })
   * @return {DateTime}
   */
  set(values) {
    if (!this.isValid)
      return this;
    const normalized = normalizeObject(values, normalizeUnit), settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber;
    if ((containsGregor || containsOrdinal) && definiteWeekDef) {
      throw new ConflictingSpecificationError(
        "Can't mix weekYear/weekNumber units with year/month/day or ordinals"
      );
    }
    if (containsGregorMD && containsOrdinal) {
      throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
    }
    let mixed;
    if (settingWeekStuff) {
      mixed = weekToGregorian({ ...gregorianToWeek(this.c), ...normalized });
    } else if (!isUndefined(normalized.ordinal)) {
      mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c), ...normalized });
    } else {
      mixed = { ...this.toObject(), ...normalized };
      if (isUndefined(normalized.day)) {
        mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);
      }
    }
    const [ts, o3] = objToTS(mixed, this.o, this.zone);
    return clone2(this, { ts, o: o3 });
  }
  /**
   * Add a period of time to this DateTime and return the resulting DateTime
   *
   * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.
   * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
   * @example DateTime.now().plus(123) //~> in 123 milliseconds
   * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes
   * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow
   * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday
   * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min
   * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min
   * @return {DateTime}
   */
  plus(duration) {
    if (!this.isValid)
      return this;
    const dur = Duration.fromDurationLike(duration);
    return clone2(this, adjustTime(this, dur));
  }
  /**
   * Subtract a period of time to this DateTime and return the resulting DateTime
   * See {@link DateTime#plus}
   * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
   @return {DateTime}
   */
  minus(duration) {
    if (!this.isValid)
      return this;
    const dur = Duration.fromDurationLike(duration).negate();
    return clone2(this, adjustTime(this, dur));
  }
  /**
   * "Set" this DateTime to the beginning of a unit of time.
   * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
   * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'
   * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'
   * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays
   * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'
   * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'
   * @return {DateTime}
   */
  startOf(unit) {
    if (!this.isValid)
      return this;
    const o3 = {}, normalizedUnit = Duration.normalizeUnit(unit);
    switch (normalizedUnit) {
      case "years":
        o3.month = 1;
      case "quarters":
      case "months":
        o3.day = 1;
      case "weeks":
      case "days":
        o3.hour = 0;
      case "hours":
        o3.minute = 0;
      case "minutes":
        o3.second = 0;
      case "seconds":
        o3.millisecond = 0;
        break;
      case "milliseconds":
        break;
    }
    if (normalizedUnit === "weeks") {
      o3.weekday = 1;
    }
    if (normalizedUnit === "quarters") {
      const q4 = Math.ceil(this.month / 3);
      o3.month = (q4 - 1) * 3 + 1;
    }
    return this.set(o3);
  }
  /**
   * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time
   * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
   * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'
   * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'
   * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays
   * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'
   * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'
   * @return {DateTime}
   */
  endOf(unit) {
    return this.isValid ? this.plus({ [unit]: 1 }).startOf(unit).minus(1) : this;
  }
  // OUTPUT
  /**
   * Returns a string representation of this DateTime formatted according to the specified format string.
   * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens).
   * Defaults to en-US if no locale has been specified, regardless of the system's locale.
   * @param {string} fmt - the format string
   * @param {Object} opts - opts to override the configuration options on this DateTime
   * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22'
   * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'
   * @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22'
   * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes'
   * @return {string}
   */
  toFormat(fmt, opts = {}) {
    return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID3;
  }
  /**
   * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.
   * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation
   * of the DateTime in the assigned locale.
   * Defaults to the system's locale if no locale has been specified
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
   * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options
   * @param {Object} opts - opts to override the configuration options on this DateTime
   * @example DateTime.now().toLocaleString(); //=> 4/20/2017
   * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'
   * @example DateTime.now().toLocaleString({ locale: 'en-gb' }); //=> '20/04/2017'
   * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'
   * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'
   * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'
   * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'
   * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'
   * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32'
   * @return {string}
   */
  toLocaleString(formatOpts = DATE_SHORT, opts = {}) {
    return this.isValid ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID3;
  }
  /**
   * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.
   * Defaults to the system's locale if no locale has been specified
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts
   * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.
   * @example DateTime.now().toLocaleParts(); //=> [
   *                                   //=>   { type: 'day', value: '25' },
   *                                   //=>   { type: 'literal', value: '/' },
   *                                   //=>   { type: 'month', value: '05' },
   *                                   //=>   { type: 'literal', value: '/' },
   *                                   //=>   { type: 'year', value: '1982' }
   *                                   //=> ]
   */
  toLocaleParts(opts = {}) {
    return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : [];
  }
  /**
   * Returns an ISO 8601-compliant string representation of this DateTime
   * @param {Object} opts - options
   * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
   * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
   * @param {boolean} [opts.extendedZone=true] - add the time zone format extension
   * @param {string} [opts.format='extended'] - choose between the basic and extended format
   * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'
   * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00'
   * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'
   * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'
   * @return {string}
   */
  toISO({
    format = "extended",
    suppressSeconds = false,
    suppressMilliseconds = false,
    includeOffset = true,
    extendedZone = false
  } = {}) {
    if (!this.isValid) {
      return null;
    }
    const ext = format === "extended";
    let c3 = toISODate(this, ext);
    c3 += "T";
    c3 += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone);
    return c3;
  }
  /**
   * Returns an ISO 8601-compliant string representation of this DateTime's date component
   * @param {Object} opts - options
   * @param {string} [opts.format='extended'] - choose between the basic and extended format
   * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'
   * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'
   * @return {string}
   */
  toISODate({ format = "extended" } = {}) {
    if (!this.isValid) {
      return null;
    }
    return toISODate(this, format === "extended");
  }
  /**
   * Returns an ISO 8601-compliant string representation of this DateTime's week date
   * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'
   * @return {string}
   */
  toISOWeekDate() {
    return toTechFormat(this, "kkkk-'W'WW-c");
  }
  /**
   * Returns an ISO 8601-compliant string representation of this DateTime's time component
   * @param {Object} opts - options
   * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
   * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
   * @param {boolean} [opts.extendedZone=true] - add the time zone format extension
   * @param {boolean} [opts.includePrefix=false] - include the `T` prefix
   * @param {string} [opts.format='extended'] - choose between the basic and extended format
   * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'
   * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'
   * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'
   * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z'
   * @return {string}
   */
  toISOTime({
    suppressMilliseconds = false,
    suppressSeconds = false,
    includeOffset = true,
    includePrefix = false,
    extendedZone = false,
    format = "extended"
  } = {}) {
    if (!this.isValid) {
      return null;
    }
    let c3 = includePrefix ? "T" : "";
    return c3 + toISOTime(
      this,
      format === "extended",
      suppressSeconds,
      suppressMilliseconds,
      includeOffset,
      extendedZone
    );
  }
  /**
   * Returns an RFC 2822-compatible string representation of this DateTime
   * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'
   * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'
   * @return {string}
   */
  toRFC2822() {
    return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false);
  }
  /**
   * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT.
   * Specifically, the string conforms to RFC 1123.
   * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
   * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'
   * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'
   * @return {string}
   */
  toHTTP() {
    return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'");
  }
  /**
   * Returns a string representation of this DateTime appropriate for use in SQL Date
   * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'
   * @return {string}
   */
  toSQLDate() {
    if (!this.isValid) {
      return null;
    }
    return toISODate(this, true);
  }
  /**
   * Returns a string representation of this DateTime appropriate for use in SQL Time
   * @param {Object} opts - options
   * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
   * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
   * @example DateTime.utc().toSQL() //=> '05:15:16.345'
   * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00'
   * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345'
   * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'
   * @return {string}
   */
  toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) {
    let fmt = "HH:mm:ss.SSS";
    if (includeZone || includeOffset) {
      if (includeOffsetSpace) {
        fmt += " ";
      }
      if (includeZone) {
        fmt += "z";
      } else if (includeOffset) {
        fmt += "ZZ";
      }
    }
    return toTechFormat(this, fmt, true);
  }
  /**
   * Returns a string representation of this DateTime appropriate for use in SQL DateTime
   * @param {Object} opts - options
   * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
   * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
   * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'
   * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'
   * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'
   * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'
   * @return {string}
   */
  toSQL(opts = {}) {
    if (!this.isValid) {
      return null;
    }
    return `${this.toSQLDate()} ${this.toSQLTime(opts)}`;
  }
  /**
   * Returns a string representation of this DateTime appropriate for debugging
   * @return {string}
   */
  toString() {
    return this.isValid ? this.toISO() : INVALID3;
  }
  /**
   * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis}
   * @return {number}
   */
  valueOf() {
    return this.toMillis();
  }
  /**
   * Returns the epoch milliseconds of this DateTime.
   * @return {number}
   */
  toMillis() {
    return this.isValid ? this.ts : NaN;
  }
  /**
   * Returns the epoch seconds of this DateTime.
   * @return {number}
   */
  toSeconds() {
    return this.isValid ? this.ts / 1e3 : NaN;
  }
  /**
   * Returns the epoch seconds (as a whole number) of this DateTime.
   * @return {number}
   */
  toUnixInteger() {
    return this.isValid ? Math.floor(this.ts / 1e3) : NaN;
  }
  /**
   * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.
   * @return {string}
   */
  toJSON() {
    return this.toISO();
  }
  /**
   * Returns a BSON serializable equivalent to this DateTime.
   * @return {Date}
   */
  toBSON() {
    return this.toJSDate();
  }
  /**
   * Returns a JavaScript object with this DateTime's year, month, day, and so on.
   * @param opts - options for generating the object
   * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output
   * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }
   * @return {Object}
   */
  toObject(opts = {}) {
    if (!this.isValid)
      return {};
    const base = { ...this.c };
    if (opts.includeConfig) {
      base.outputCalendar = this.outputCalendar;
      base.numberingSystem = this.loc.numberingSystem;
      base.locale = this.loc.locale;
    }
    return base;
  }
  /**
   * Returns a JavaScript Date equivalent to this DateTime.
   * @return {Date}
   */
  toJSDate() {
    return new Date(this.isValid ? this.ts : NaN);
  }
  // COMPARE
  /**
   * Return the difference between two DateTimes as a Duration.
   * @param {DateTime} otherDateTime - the DateTime to compare this one to
   * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.
   * @param {Object} opts - options that affect the creation of the Duration
   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
   * @example
   * var i1 = DateTime.fromISO('1982-05-25T09:45'),
   *     i2 = DateTime.fromISO('1983-10-14T10:30');
   * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }
   * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }
   * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }
   * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }
   * @return {Duration}
   */
  diff(otherDateTime, unit = "milliseconds", opts = {}) {
    if (!this.isValid || !otherDateTime.isValid) {
      return Duration.invalid("created by diffing an invalid DateTime");
    }
    const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts };
    const units = maybeArray(unit).map(Duration.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = diff_default(earlier, later, units, durOpts);
    return otherIsLater ? diffed.negate() : diffed;
  }
  /**
   * Return the difference between this DateTime and right now.
   * See {@link DateTime#diff}
   * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration
   * @param {Object} opts - options that affect the creation of the Duration
   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
   * @return {Duration}
   */
  diffNow(unit = "milliseconds", opts = {}) {
    return this.diff(DateTime.now(), unit, opts);
  }
  /**
   * Return an Interval spanning between this DateTime and another DateTime
   * @param {DateTime} otherDateTime - the other end point of the Interval
   * @return {Interval}
   */
  until(otherDateTime) {
    return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;
  }
  /**
   * Return whether this DateTime is in the same unit of time as another DateTime.
   * Higher-order units must also be identical for this function to return `true`.
   * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed.
   * @param {DateTime} otherDateTime - the other DateTime
   * @param {string} unit - the unit of time to check sameness on
   * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day
   * @return {boolean}
   */
  hasSame(otherDateTime, unit) {
    if (!this.isValid)
      return false;
    const inputMs = otherDateTime.valueOf();
    const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true });
    return adjustedToZone.startOf(unit) <= inputMs && inputMs <= adjustedToZone.endOf(unit);
  }
  /**
   * Equality check
   * Two DateTimes are equal iff they represent the same millisecond, have the same zone and location, and are both valid.
   * To compare just the millisecond values, use `+dt1 === +dt2`.
   * @param {DateTime} other - the other DateTime
   * @return {boolean}
   */
  equals(other) {
    return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc);
  }
  /**
   * Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your
   * platform supports Intl.RelativeTimeFormat. Rounds down by default.
   * @param {Object} options - options that affect the output
   * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
   * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow"
   * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds"
   * @param {boolean} [options.round=true] - whether to round the numbers in the output.
   * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.
   * @param {string} options.locale - override the locale of this DateTime
   * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
   * @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day"
   * @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día"
   * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures"
   * @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago"
   * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago"
   * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago"
   */
  toRelative(options = {}) {
    if (!this.isValid)
      return null;
    const base = options.base || DateTime.fromObject({}, { zone: this.zone }), padding = options.padding ? this < base ? -options.padding : options.padding : 0;
    let units = ["years", "months", "days", "hours", "minutes", "seconds"];
    let unit = options.unit;
    if (Array.isArray(options.unit)) {
      units = options.unit;
      unit = void 0;
    }
    return diffRelative(base, this.plus(padding), {
      ...options,
      numeric: "always",
      units,
      unit
    });
  }
  /**
   * Returns a string representation of this date relative to today, such as "yesterday" or "next month".
   * Only internationalizes on platforms that supports Intl.RelativeTimeFormat.
   * @param {Object} options - options that affect the output
   * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
   * @param {string} options.locale - override the locale of this DateTime
   * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days"
   * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
   * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow"
   * @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana"
   * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain"
   * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago"
   */
  toRelativeCalendar(options = {}) {
    if (!this.isValid)
      return null;
    return diffRelative(options.base || DateTime.fromObject({}, { zone: this.zone }), this, {
      ...options,
      numeric: "auto",
      units: ["years", "months", "days"],
      calendary: true
    });
  }
  /**
   * Return the min of several date times
   * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum
   * @return {DateTime} the min DateTime, or undefined if called with no argument
   */
  static min(...dateTimes) {
    if (!dateTimes.every(DateTime.isDateTime)) {
      throw new InvalidArgumentError("min requires all arguments be DateTimes");
    }
    return bestBy(dateTimes, (i4) => i4.valueOf(), Math.min);
  }
  /**
   * Return the max of several date times
   * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum
   * @return {DateTime} the max DateTime, or undefined if called with no argument
   */
  static max(...dateTimes) {
    if (!dateTimes.every(DateTime.isDateTime)) {
      throw new InvalidArgumentError("max requires all arguments be DateTimes");
    }
    return bestBy(dateTimes, (i4) => i4.valueOf(), Math.max);
  }
  // MISC
  /**
   * Explain how a string would be parsed by fromFormat()
   * @param {string} text - the string to parse
   * @param {string} fmt - the format the string is expected to be in (see description)
   * @param {Object} options - options taken by fromFormat()
   * @return {Object}
   */
  static fromFormatExplain(text, fmt, options = {}) {
    const { locale = null, numberingSystem = null } = options, localeToUse = Locale.fromOpts({
      locale,
      numberingSystem,
      defaultToEN: true
    });
    return explainFromTokens(localeToUse, text, fmt);
  }
  /**
   * @deprecated use fromFormatExplain instead
   */
  static fromStringExplain(text, fmt, options = {}) {
    return DateTime.fromFormatExplain(text, fmt, options);
  }
  // FORMAT PRESETS
  /**
   * {@link DateTime#toLocaleString} format like 10/14/1983
   * @type {Object}
   */
  static get DATE_SHORT() {
    return DATE_SHORT;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Oct 14, 1983'
   * @type {Object}
   */
  static get DATE_MED() {
    return DATE_MED;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983'
   * @type {Object}
   */
  static get DATE_MED_WITH_WEEKDAY() {
    return DATE_MED_WITH_WEEKDAY;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'October 14, 1983'
   * @type {Object}
   */
  static get DATE_FULL() {
    return DATE_FULL;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983'
   * @type {Object}
   */
  static get DATE_HUGE() {
    return DATE_HUGE;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get TIME_SIMPLE() {
    return TIME_SIMPLE;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get TIME_WITH_SECONDS() {
    return TIME_WITH_SECONDS;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get TIME_WITH_SHORT_OFFSET() {
    return TIME_WITH_SHORT_OFFSET;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get TIME_WITH_LONG_OFFSET() {
    return TIME_WITH_LONG_OFFSET;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30', always 24-hour.
   * @type {Object}
   */
  static get TIME_24_SIMPLE() {
    return TIME_24_SIMPLE;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour.
   * @type {Object}
   */
  static get TIME_24_WITH_SECONDS() {
    return TIME_24_WITH_SECONDS;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour.
   * @type {Object}
   */
  static get TIME_24_WITH_SHORT_OFFSET() {
    return TIME_24_WITH_SHORT_OFFSET;
  }
  /**
   * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.
   * @type {Object}
   */
  static get TIME_24_WITH_LONG_OFFSET() {
    return TIME_24_WITH_LONG_OFFSET;
  }
  /**
   * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_SHORT() {
    return DATETIME_SHORT;
  }
  /**
   * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_SHORT_WITH_SECONDS() {
    return DATETIME_SHORT_WITH_SECONDS;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_MED() {
    return DATETIME_MED;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_MED_WITH_SECONDS() {
    return DATETIME_MED_WITH_SECONDS;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_MED_WITH_WEEKDAY() {
    return DATETIME_MED_WITH_WEEKDAY;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_FULL() {
    return DATETIME_FULL;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_FULL_WITH_SECONDS() {
    return DATETIME_FULL_WITH_SECONDS;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_HUGE() {
    return DATETIME_HUGE;
  }
  /**
   * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.
   * @type {Object}
   */
  static get DATETIME_HUGE_WITH_SECONDS() {
    return DATETIME_HUGE_WITH_SECONDS;
  }
};
function friendlyDateTime(dateTimeish) {
  if (DateTime.isDateTime(dateTimeish)) {
    return dateTimeish;
  } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {
    return DateTime.fromJSDate(dateTimeish);
  } else if (dateTimeish && typeof dateTimeish === "object") {
    return DateTime.fromObject(dateTimeish);
  } else {
    throw new InvalidArgumentError(
      `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`
    );
  }
}

// node_modules/luxon/src/luxon.js
var VERSION = "2.5.2";

// src/utils/normalizers.ts
var P = __toESM(require_parsimmon_umd_min());

// node_modules/emoji-regex/index.mjs
var emoji_regex_default = () => {
  return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g;
};

// src/utils/normalizers.ts
function currentLocale() {
  if (typeof window === "undefined")
    return "en-US";
  return window.navigator.language;
}
function normalizeDuration(dur) {
  if (dur === void 0 || dur === null)
    return dur;
  return dur.shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds").normalize();
}
function renderMinimalDate(time, dateFormat, dateTimeFormat, locale) {
  if (time.second == 0 && time.minute == 0 && time.hour == 0) {
    return time.toLocal().toFormat(dateFormat, { locale });
  }
  return time.toLocal().toFormat(dateTimeFormat, { locale });
}
function renderMinimalDuration(dur) {
  dur = normalizeDuration(dur);
  let result = "";
  if (dur.years)
    result += `${dur.years} years, `;
  if (dur.months)
    result += `${dur.months} months, `;
  if (dur.weeks)
    result += `${dur.weeks} weeks, `;
  if (dur.days)
    result += `${dur.days} days, `;
  if (dur.hours)
    result += `${dur.hours} hours, `;
  if (dur.minutes)
    result += `${dur.minutes} minutes, `;
  if (dur.seconds)
    result += `${Math.round(dur.seconds)} seconds, `;
  if (dur.milliseconds)
    result += `${Math.round(dur.milliseconds)} ms, `;
  if (result.endsWith(", "))
    result = result.substring(0, result.length - 2);
  return result;
}
function getParentFolder(path) {
  return path.split("/").slice(0, -1).join("/");
}
function getFileTitle(path) {
  if (path.includes("/"))
    path = path.substring(path.lastIndexOf("/") + 1);
  if (path.endsWith(".md"))
    path = path.substring(0, path.length - 3);
  return path;
}
function extractSubtags(tags) {
  let result = [];
  for (let tag of typeof tags === "string" ? [tags] : tags) {
    result.push(tag);
    while (tag.includes("/")) {
      tag = tag.substring(0, tag.lastIndexOf("/"));
      result.push(tag);
    }
  }
  return result;
}
function escapeRegex(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
var HEADER_CANONICALIZER = P.alt(
  P.regex(new RegExp(emoji_regex_default(), "")),
  P.regex(/[0-9\p{Letter}_-]+/u),
  P.whitespace.map((_3) => " "),
  P.any.map((_3) => " ")
).many().map((result) => {
  return result.join("").split(/\s+/).join(" ").trim();
});
function normalizeHeaderForLink(header) {
  return HEADER_CANONICALIZER.tryParse(header);
}
function lineSpan(text, start, end) {
  start = Math.max(start, 0);
  end = Math.max(end, 0);
  if (start >= end)
    return ["", void 0];
  const startOffset = skipNewlines(text, 0, start);
  if (startOffset == -1)
    return ["", void 0];
  const endOffset = skipNewlines(text, startOffset, end - start);
  if (endOffset == -1)
    return [text.substring(startOffset), { start: startOffset, end: text.length }];
  else
    return [text.substring(startOffset, endOffset - 1), { start: startOffset, end: endOffset - 1 }];
}
function lineRange(text, start, end) {
  return lineSpan(text, start, end)[0];
}
function skipNewlines(text, start, count) {
  if (count == 0)
    return start;
  let position = start;
  while (count > 0) {
    position = text.indexOf("\n", position);
    if (position == -1)
      return -1;
    count--;
    position += 1;
  }
  return position;
}

// src/expression/link.ts
var Link = class {
  /** Create a link to a specific file. */
  static file(path, embed = false, display) {
    return new Link({
      path,
      embed,
      display,
      subpath: void 0,
      type: "file"
    });
  }
  /** Infer the type of the link from the full internal link path. */
  static infer(linkpath, embed = false, display) {
    if (linkpath.includes("#^")) {
      let split = linkpath.split("#^");
      return Link.block(split[0], split[1], embed, display);
    } else if (linkpath.includes("#")) {
      let split = linkpath.split("#");
      return Link.header(split[0], split[1], embed, display);
    } else
      return Link.file(linkpath, embed, display);
  }
  /** Create a link to a specific file and header in that file. */
  static header(path, header, embed, display) {
    return new Link({
      path,
      embed,
      display,
      subpath: normalizeHeaderForLink(header),
      type: "header"
    });
  }
  /** Create a link to a specific file and block in that file. */
  static block(path, blockId, embed, display) {
    return new Link({
      path,
      embed,
      display,
      subpath: blockId,
      type: "block"
    });
  }
  /** Load a link from it's raw JSON representation. */
  static fromObject(object) {
    return new Link(object);
  }
  /** Create a link by parsing it's interior part (inside of the '[[]]'). */
  static parseInner(rawlink) {
    let [link, display] = splitOnUnescapedPipe(rawlink);
    return Link.infer(link, false, display);
  }
  constructor(fields) {
    Object.assign(this, fields);
  }
  /** Update this link with a new path. */
  withPath(path) {
    return new Link(Object.assign({}, this, { path }));
  }
  /** Return a new link which points to the same location but with a new display value. */
  withDisplay(display) {
    return new Link(Object.assign({}, this, { display }));
  }
  /** Return a new link which has the given embedded status. */
  withEmbed(embed) {
    if (this.embed == embed)
      return this;
    return new Link(Object.assign({}, this, { embed }));
  }
  /** Convert a file link into a link to a specific header. */
  withHeader(header) {
    return Link.header(this.path, header, this.embed, this.display);
  }
  /** Convert a file link into a link to a specificb lock. */
  withBlock(block) {
    return Link.block(this.path, block, this.embed, this.display);
  }
  /** Checks for link equality (i.e., that the links are pointing to the same exact location). */
  equals(other) {
    if (other == void 0 || other == null)
      return false;
    return this.path == other.path && this.type == other.type && this.subpath == other.subpath;
  }
  /** Convert this link to it's markdown representation. */
  toString() {
    return this.markdown();
  }
  /** Convert this link to a raw object which is serialization-friendly. */
  toObject() {
    return {
      path: this.path,
      type: this.type,
      subpath: this.subpath,
      display: this.display,
      embed: this.embed
    };
  }
  /** Convert any link into a link to its file. */
  toFile() {
    return Link.file(this.path, this.embed, this.display);
  }
  /** Convert this link into an embedded link. */
  toEmbed() {
    return this.withEmbed(true);
  }
  /** Convert this link into a non-embedded link. */
  fromEmbed() {
    return this.withEmbed(false);
  }
  /** Convert this link to markdown so it can be rendered. */
  markdown() {
    let result = (this.embed ? "!" : "") + "[[" + this.obsidianLink();
    result += "|";
    result += this.displayOrDefault();
    result += "]]";
    return result;
  }
  /** Obtain the display for this link if present, or return a simple default display. */
  displayOrDefault() {
    if (this.display) {
      return this.display;
    } else {
      let result = getFileTitle(this.path);
      if (this.type == "header" || this.type == "block")
        result += " > " + this.subpath;
      return result;
    }
  }
  /** Convert the inner part of the link to something that Obsidian can open / understand. */
  obsidianLink() {
    var _a, _b;
    const escaped = this.path.replace("|", "\\|");
    if (this.type == "header")
      return escaped + "#" + ((_a = this.subpath) == null ? void 0 : _a.replace("|", "\\|"));
    if (this.type == "block")
      return escaped + "#^" + ((_b = this.subpath) == null ? void 0 : _b.replace("|", "\\|"));
    else
      return escaped;
  }
  /** The stripped name of the file this link points to. */
  fileName() {
    return getFileTitle(this.path);
  }
};
function splitOnUnescapedPipe(link) {
  let pipe = -1;
  while ((pipe = link.indexOf("|", pipe + 1)) >= 0) {
    if (pipe > 0 && link[pipe - 1] == "\\")
      continue;
    return [link.substring(0, pipe).replace(/\\\|/g, "|"), link.substring(pipe + 1)];
  }
  return [link.replace(/\\\|/g, "|"), void 0];
}

// src/expression/parser.ts
var P2 = __toESM(require_parsimmon_umd_min());

// src/expression/literal.ts
var Literals;
((Literals2) => {
  Literals2.DEFAULT_TO_STRING = {
    nullRepresentation: "-",
    dateFormat: "MMMM dd, yyyy",
    dateTimeFormat: "h:mm a - MMMM dd, yyyy"
  };
  function toString(field, setting = Literals2.DEFAULT_TO_STRING, recursive = false) {
    let wrapped = wrapValue(field);
    if (!wrapped)
      return setting.nullRepresentation;
    switch (wrapped.type) {
      case "null":
        return setting.nullRepresentation;
      case "string":
        return wrapped.value;
      case "number":
      case "boolean":
        return "" + wrapped.value;
      case "link":
        return wrapped.value.markdown();
      case "function":
        return "<function>";
      case "array":
        let result = "";
        if (recursive)
          result += "[";
        result += wrapped.value.map((f4) => toString(f4, setting, true)).join(", ");
        if (recursive)
          result += "]";
        return result;
      case "object":
        return "{ " + Object.entries(wrapped.value).map((e3) => e3[0] + ": " + toString(e3[1], setting, true)).join(", ") + " }";
      case "date":
        return renderMinimalDate(wrapped.value, setting.dateFormat, setting.dateTimeFormat);
      case "duration":
        return renderMinimalDuration(wrapped.value);
    }
  }
  Literals2.toString = toString;
  function wrapValue(val) {
    if (isNull(val))
      return { type: "null", value: null };
    else if (isNumber2(val))
      return { type: "number", value: val };
    else if (isString2(val))
      return { type: "string", value: val };
    else if (isBoolean(val))
      return { type: "boolean", value: val };
    else if (isDuration(val))
      return { type: "duration", value: val };
    else if (isDate2(val))
      return { type: "date", value: val };
    else if (isArray(val))
      return { type: "array", value: val };
    else if (isLink(val))
      return { type: "link", value: val };
    else if (isFunction(val))
      return { type: "function", value: val };
    else if (isObject(val))
      return { type: "object", value: val };
    else
      return void 0;
  }
  Literals2.wrapValue = wrapValue;
  function mapLeaves(val, func) {
    if (isObject(val)) {
      let result = {};
      for (let [key, value] of Object.entries(val))
        result[key] = mapLeaves(value, func);
      return result;
    } else if (isArray(val)) {
      let result = [];
      for (let value of val)
        result.push(mapLeaves(value, func));
      return result;
    } else {
      return func(val);
    }
  }
  Literals2.mapLeaves = mapLeaves;
  function equals(first, second) {
    return compare(first, second) == 0;
  }
  Literals2.equals = equals;
  function compare(val1, val2, linkNormalizer) {
    var _a, _b;
    if (val1 === val2)
      return 0;
    if (val1 === void 0)
      val1 = null;
    if (val2 === void 0)
      val2 = null;
    if (val1 === null && val2 === null)
      return 0;
    else if (val1 === null)
      return -1;
    else if (val2 === null)
      return 1;
    let wrap1 = wrapValue(val1);
    let wrap2 = wrapValue(val2);
    if (wrap1 === void 0 && wrap2 === void 0)
      return 0;
    else if (wrap1 === void 0)
      return -1;
    else if (wrap2 === void 0)
      return 1;
    if (wrap1.type != wrap2.type)
      return wrap1.type.localeCompare(wrap2.type);
    if (wrap1.value === wrap2.value)
      return 0;
    switch (wrap1.type) {
      case "string":
        return wrap1.value.localeCompare(wrap2.value);
      case "number":
        if (wrap1.value < wrap2.value)
          return -1;
        else if (wrap1.value == wrap2.value)
          return 0;
        return 1;
      case "null":
        return 0;
      case "boolean":
        if (wrap1.value == wrap2.value)
          return 0;
        else
          return wrap1.value ? 1 : -1;
      case "link":
        let link1 = wrap1.value;
        let link2 = wrap2.value;
        let normalize = linkNormalizer != null ? linkNormalizer : (x4) => x4;
        let pathCompare = normalize(link1.path).localeCompare(normalize(link2.path));
        if (pathCompare != 0)
          return pathCompare;
        let typeCompare = link1.type.localeCompare(link2.type);
        if (typeCompare != 0)
          return typeCompare;
        if (link1.subpath && !link2.subpath)
          return 1;
        if (!link1.subpath && link2.subpath)
          return -1;
        if (!link1.subpath && !link2.subpath)
          return 0;
        return ((_a = link1.subpath) != null ? _a : "").localeCompare((_b = link2.subpath) != null ? _b : "");
      case "date":
        return wrap1.value < wrap2.value ? -1 : wrap1.value.equals(wrap2.value) ? 0 : 1;
      case "duration":
        return wrap1.value < wrap2.value ? -1 : wrap1.value.equals(wrap2.value) ? 0 : 1;
      case "array":
        let f1 = wrap1.value;
        let f22 = wrap2.value;
        for (let index = 0; index < Math.min(f1.length, f22.length); index++) {
          let comp = compare(f1[index], f22[index]);
          if (comp != 0)
            return comp;
        }
        return f1.length - f22.length;
      case "object":
        let o1 = wrap1.value;
        let o22 = wrap2.value;
        let k1 = Array.from(Object.keys(o1));
        let k22 = Array.from(Object.keys(o22));
        k1.sort();
        k22.sort();
        let keyCompare = compare(k1, k22);
        if (keyCompare != 0)
          return keyCompare;
        for (let key of k1) {
          let comp = compare(o1[key], o22[key]);
          if (comp != 0)
            return comp;
        }
        return 0;
      case "function":
        return 0;
    }
  }
  Literals2.compare = compare;
  function typeOf(val) {
    var _a;
    return (_a = wrapValue(val)) == null ? void 0 : _a.type;
  }
  Literals2.typeOf = typeOf;
  function isTruthy(field) {
    let wrapped = wrapValue(field);
    if (!wrapped)
      return false;
    switch (wrapped.type) {
      case "number":
        return wrapped.value != 0;
      case "string":
        return wrapped.value.length > 0;
      case "boolean":
        return wrapped.value;
      case "link":
        return !!wrapped.value.path;
      case "date":
        return wrapped.value.toMillis() != 0;
      case "duration":
        return wrapped.value.as("seconds") != 0;
      case "object":
        return Object.keys(wrapped.value).length > 0;
      case "array":
        return wrapped.value.length > 0;
      case "null":
        return false;
      case "function":
        return true;
    }
  }
  Literals2.isTruthy = isTruthy;
  function deepCopy(field) {
    if (field === null || field === void 0)
      return field;
    if (Literals2.isArray(field)) {
      return [].concat(field.map((v3) => deepCopy(v3)));
    } else if (Literals2.isObject(field)) {
      let result = {};
      for (let [key, value] of Object.entries(field))
        result[key] = deepCopy(value);
      return result;
    } else {
      return field;
    }
  }
  Literals2.deepCopy = deepCopy;
  function isString2(val) {
    return typeof val == "string";
  }
  Literals2.isString = isString2;
  function isNumber2(val) {
    return typeof val == "number";
  }
  Literals2.isNumber = isNumber2;
  function isDate2(val) {
    return val instanceof DateTime;
  }
  Literals2.isDate = isDate2;
  function isDuration(val) {
    return val instanceof Duration;
  }
  Literals2.isDuration = isDuration;
  function isNull(val) {
    return val === null || val === void 0;
  }
  Literals2.isNull = isNull;
  function isArray(val) {
    return Array.isArray(val);
  }
  Literals2.isArray = isArray;
  function isBoolean(val) {
    return typeof val === "boolean";
  }
  Literals2.isBoolean = isBoolean;
  function isLink(val) {
    return val instanceof Link;
  }
  Literals2.isLink = isLink;
  function isObject(val) {
    return val !== void 0 && typeof val == "object" && !isArray(val) && !isDuration(val) && !isDate2(val) && !isLink(val) && !isNull(val);
  }
  Literals2.isObject = isObject;
  function isFunction(val) {
    return typeof val == "function";
  }
  Literals2.isFunction = isFunction;
})(Literals || (Literals = {}));
var Groupings;
((Groupings2) => {
  function isElementGroup(entry) {
    return Literals.isObject(entry) && Object.keys(entry).length == 2 && "key" in entry && "rows" in entry;
  }
  Groupings2.isElementGroup = isElementGroup;
  function isGrouping(entry) {
    for (let element of entry)
      if (!isElementGroup(element))
        return false;
    return true;
  }
  Groupings2.isGrouping = isGrouping;
  function isLeaf(entry) {
    for (let element of entry)
      if (isElementGroup(element))
        return false;
    return true;
  }
  Groupings2.isLeaf = isLeaf;
  function count(elements) {
    if (isElementGroup(elements)) {
      return count(elements.rows);
    } else if (isGrouping(elements)) {
      let result = 0;
      for (let subgroup of elements)
        result += count(subgroup.rows);
      return result;
    } else {
      return elements.length;
    }
  }
  Groupings2.count = count;
  function slice(elements, start, end) {
    if (end <= start)
      return [];
    if (isLeaf(elements))
      return elements.slice(start, end);
    let index = 0, seen = 0;
    while (index < elements.length && seen + count(elements[index]) <= start) {
      seen += count(elements[index]);
      index++;
    }
    if (index >= elements.length)
      return [];
    const result = [];
    while (index < elements.length && seen < end) {
      const group = elements[index];
      const groupSize = count(group);
      const groupStart = Math.max(seen, start);
      const groupEnd = Math.min(groupSize + seen, end);
      result.push({
        key: group.key,
        rows: slice(group.rows, groupStart - seen, groupEnd - seen)
      });
      seen += groupSize;
      index++;
    }
    return result;
  }
  Groupings2.slice = slice;
})(Groupings || (Groupings = {}));

// src/api/result.ts
var Success = class {
  constructor(value) {
    this.value = value;
    this.successful = true;
  }
  map(f4) {
    return new Success(f4(this.value));
  }
  flatMap(f4) {
    return f4(this.value);
  }
  mapErr(f4) {
    return this.castErr();
  }
  bimap(succ, _fail) {
    return this.map(succ).castErr();
  }
  orElse(_value) {
    return this.value;
  }
  cast() {
    return this;
  }
  castErr() {
    return this;
  }
  orElseThrow(_message) {
    return this.value;
  }
};
var Failure = class {
  constructor(error) {
    this.error = error;
    this.successful = false;
  }
  map(_f) {
    return this.cast();
  }
  flatMap(_f) {
    return this.cast();
  }
  mapErr(f4) {
    return new Failure(f4(this.error));
  }
  bimap(_succ, fail) {
    return this.mapErr(fail).cast();
  }
  orElse(value) {
    return value;
  }
  cast() {
    return this;
  }
  castErr() {
    return this;
  }
  orElseThrow(message) {
    if (message)
      throw new Error(message(this.error));
    else
      throw new Error("" + this.error);
  }
};
var Result;
((Result2) => {
  function success(value) {
    return new Success(value);
  }
  Result2.success = success;
  function failure(error) {
    return new Failure(error);
  }
  Result2.failure = failure;
  function flatMap2(first, second, f4) {
    if (first.successful) {
      if (second.successful)
        return f4(first.value, second.value);
      else
        return failure(second.error);
    } else {
      return failure(first.error);
    }
  }
  Result2.flatMap2 = flatMap2;
  function map2(first, second, f4) {
    return flatMap2(first, second, (a3, b3) => success(f4(a3, b3)));
  }
  Result2.map2 = map2;
  function mapAll(input2, func) {
    const result = [];
    for (const element of input2) {
      const output = func(element);
      if (!output.successful)
        return output.cast();
      result.push(output.value);
    }
    return Result2.success(result);
  }
  Result2.mapAll = mapAll;
  function trying(call) {
    try {
      return Result2.success(call());
    } catch (error) {
      return Result2.failure(error);
    }
  }
  Result2.trying = trying;
  async function async(promise) {
    try {
      return Result2.success(await promise);
    } catch (error) {
      return Result2.failure(error);
    }
  }
  Result2.async = async;
})(Result || (Result = {}));

// src/expression/filters.ts
var Filters;
((Filters2) => {
  Filters2.EVERYTHING = { type: "everything" };
  Filters2.NOTHING = { type: "nothing" };
  Filters2.EMPTY_SET = /* @__PURE__ */ new Set();
  function atom(set) {
    if (set.size == 0)
      return Filters2.NOTHING;
    return { type: "atom", value: set };
  }
  Filters2.atom = atom;
  function constant(value) {
    if (value)
      return Filters2.EVERYTHING;
    else
      return Filters2.NOTHING;
  }
  Filters2.constant = constant;
  function nullableAtom(set) {
    return set !== void 0 ? atom(set) : Filters2.NOTHING;
  }
  Filters2.nullableAtom = nullableAtom;
  function negated(set) {
    if (set.size == 0)
      return Filters2.EVERYTHING;
    return { type: "negated", value: set };
  }
  Filters2.negated = negated;
  function negate(filter) {
    switch (filter.type) {
      case "everything":
        return Filters2.NOTHING;
      case "nothing":
        return Filters2.EVERYTHING;
      case "atom":
        return negated(filter.value);
      case "negated":
        return atom(filter.value);
    }
  }
  Filters2.negate = negate;
  function empty(filter) {
    switch (filter.type) {
      case "everything":
        return false;
      case "negated":
        return false;
      case "atom":
        return filter.value.size == 0;
      case "nothing":
        return true;
    }
  }
  Filters2.empty = empty;
  function resolve(filter, everything) {
    switch (filter.type) {
      case "everything":
        return everything;
      case "nothing":
        return Filters2.EMPTY_SET;
      case "atom":
        return filter.value;
      case "negated":
        return setIntersectNegation(everything, filter.value);
    }
  }
  Filters2.resolve = resolve;
  function intersect(elements) {
    return lazyIntersect(elements, (x4) => x4);
  }
  Filters2.intersect = intersect;
  function lazyIntersect(elements, produce) {
    return lazyFailableIntersection(elements, (x4) => Result.success(produce(x4))).orElseThrow();
  }
  Filters2.lazyIntersect = lazyIntersect;
  function lazyFailableIntersection(elements, produce) {
    const atoms = [];
    const negations = [];
    for (let element of elements) {
      const maybeFilter = produce(element);
      if (!maybeFilter.successful)
        return maybeFilter.cast();
      const filter = maybeFilter.value;
      if (filter === void 0)
        continue;
      if (empty(filter))
        return Result.success(Filters2.NOTHING);
      if (filter.type === "everything")
        continue;
      if (filter.type == "atom")
        atoms.push(filter.value);
      else if (filter.type == "negated")
        negations.push(filter.value);
    }
    if (atoms.length == 0 && negations.length == 0) {
      return Result.success(Filters2.EVERYTHING);
    } else if (atoms.length > 0 && negations.length == 0) {
      return Result.success(atom(setIntersect(atoms)));
    } else if (atoms.length == 0 && negations.length > 0) {
      return Result.success(negated(setUnion(negations)));
    } else {
      return Result.success(Filters2.atom(setIntersectNegation(setIntersect(atoms), setUnion(negations))));
    }
  }
  Filters2.lazyFailableIntersection = lazyFailableIntersection;
  function union2(filters) {
    return lazyUnion(filters, (x4) => x4);
  }
  Filters2.union = union2;
  function lazyUnion(elements, produce) {
    return lazyFailableUnion(elements, (x4) => Result.success(produce(x4))).orElseThrow();
  }
  Filters2.lazyUnion = lazyUnion;
  function lazyFailableUnion(elements, produce) {
    const atoms = [];
    const negations = [];
    for (let element of elements) {
      const maybeFilter = produce(element);
      if (!maybeFilter.successful)
        return maybeFilter.cast();
      const filter = maybeFilter.value;
      if (filter === void 0)
        continue;
      if (filter.type === "everything")
        return Result.success(Filters2.EVERYTHING);
      if (empty(filter))
        continue;
      if (filter.type == "atom")
        atoms.push(filter.value);
      else if (filter.type == "negated")
        negations.push(filter.value);
    }
    if (atoms.length == 0 && negations.length == 0) {
      return Result.success(Filters2.NOTHING);
    } else if (atoms.length > 0 && negations.length == 0) {
      return Result.success(Filters2.atom(setUnion(atoms)));
    } else if (atoms.length == 0 && negations.length > 0) {
      return Result.success(Filters2.negated(setIntersect(negations)));
    } else {
      return Result.success(negated(setIntersectNegation(setIntersect(negations), setUnion(atoms))));
    }
  }
  Filters2.lazyFailableUnion = lazyFailableUnion;
  function setIntersect(sets) {
    if (sets.length == 0)
      return /* @__PURE__ */ new Set();
    else if (sets.length == 1)
      return sets[0];
    let sorted = [].concat(sets).sort((a3, b3) => a3.size - b3.size);
    while (sorted.length > 1) {
      const result = /* @__PURE__ */ new Set();
      const largest = sorted.pop();
      for (let element of sorted[0]) {
        if (largest.has(element))
          result.add(element);
      }
      sorted[0] = result;
    }
    return sorted[0];
  }
  Filters2.setIntersect = setIntersect;
  function setUnion(sets) {
    if (sets.length == 0)
      return /* @__PURE__ */ new Set();
    else if (sets.length == 1)
      return sets[0];
    const result = /* @__PURE__ */ new Set();
    for (const set of sets) {
      for (const element of set) {
        result.add(element);
      }
    }
    return result;
  }
  Filters2.setUnion = setUnion;
  function setIntersectNegation(atom2, negated2) {
    if (atom2.size > negated2.size) {
      const result = new Set(atom2);
      for (let element of negated2) {
        result.delete(element);
      }
      return result;
    } else {
      const result = /* @__PURE__ */ new Set();
      for (let element of atom2) {
        if (negated2.has(element))
          continue;
        result.add(element);
      }
      return result;
    }
  }
  Filters2.setIntersectNegation = setIntersectNegation;
})(Filters || (Filters = {}));

// src/expression/expression.ts
var Expressions;
((Expressions2) => {
  Expressions2.ROW = "$row";
  function variable(name) {
    return { type: "variable", name };
  }
  Expressions2.variable = variable;
  function literal(value) {
    return { type: "literal", value };
  }
  Expressions2.literal = literal;
  function binaryOp(left, op, right) {
    return { type: "binaryop", left, op, right };
  }
  Expressions2.binaryOp = binaryOp;
  function index(obj, index2) {
    return { type: "binaryop", left: obj, right: index2, op: "index" };
  }
  Expressions2.index = index;
  function indexVariable(name) {
    let parts = name.split(".");
    let result = Expressions2.variable(parts[0]);
    for (let index2 = 1; index2 < parts.length; index2++) {
      result = Expressions2.index(result, Expressions2.literal(parts[index2]));
    }
    return result;
  }
  Expressions2.indexVariable = indexVariable;
  function lambda(args, value) {
    return { type: "lambda", arguments: args, value };
  }
  Expressions2.lambda = lambda;
  function method(target, func2, args) {
    return { type: "method", target, func: func2, arguments: args };
  }
  Expressions2.method = method;
  function func(func2, args) {
    return { type: "function", func: func2, arguments: args };
  }
  Expressions2.func = func;
  function list(values) {
    return { type: "list", values };
  }
  Expressions2.list = list;
  function object(values) {
    return { type: "object", values };
  }
  Expressions2.object = object;
  function negate(child) {
    return { type: "negated", child };
  }
  Expressions2.negate = negate;
  function isCompareOp(op) {
    return op == "<=" || op == "<" || op == ">" || op == ">=" || op == "!=" || op == "=";
  }
  Expressions2.isCompareOp = isCompareOp;
  function unboundVariables(expr, bound = /* @__PURE__ */ new Set([Expressions2.ROW])) {
    switch (expr.type) {
      case "binaryop":
        if (expr.op === "index" && expr.left.type == "variable" && expr.left.name == Expressions2.ROW && expr.right.type == "literal" && Literals.isString(expr.right.value)) {
          if (bound.has(expr.right.value))
            return /* @__PURE__ */ new Set();
          else
            return /* @__PURE__ */ new Set([expr.right.value]);
        }
        return Filters.setUnion([unboundVariables(expr.left, bound), unboundVariables(expr.right, bound)]);
      case "function":
        const funcArgsBound = expr.arguments.map((a3) => unboundVariables(a3, bound));
        const funcExprBound = unboundVariables(expr.func, bound);
        return Filters.setUnion(funcArgsBound.concat(funcExprBound));
      case "method":
        const methodArgsBound = expr.arguments.map((a3) => unboundVariables(a3, bound));
        const targetBound = unboundVariables(expr.target, bound);
        return Filters.setUnion(methodArgsBound.concat(targetBound));
      case "lambda":
        const newBound = bound != null ? bound : /* @__PURE__ */ new Set();
        for (const arg of expr.arguments)
          newBound.add(arg);
        return unboundVariables(expr.value, newBound);
      case "list":
        return Filters.setUnion(expr.values.map((v3) => unboundVariables(v3, bound)));
      case "negated":
        return unboundVariables(expr.child, bound);
      case "object":
        return Filters.setUnion(Object.values(expr.values).map((v3) => unboundVariables(v3, bound)));
      case "variable":
        if (bound && bound.has(expr.name))
          return /* @__PURE__ */ new Set();
        else
          return /* @__PURE__ */ new Set([expr.name]);
      case "literal":
        return /* @__PURE__ */ new Set();
    }
  }
  Expressions2.unboundVariables = unboundVariables;
  function toString(expr) {
    switch (expr.type) {
      case "binaryop":
        if (expr.op === "index") {
          return `${toString(expr.left)}[${toString(expr.right)}]`;
        }
        return `${toString(expr.left)} ${expr.op} ${toString(expr.right)}`;
      case "function":
        return `${toString(expr.func)}(${expr.arguments.map(toString).join(", ")})`;
      case "method":
        return `${toString(expr.target)}.${expr.func}(${expr.arguments.map(toString).join(", ")})`;
      case "lambda":
        return `(${expr.arguments.join(", ")}) => ${toString(expr.value)}`;
      case "list":
        return `[${expr.values.map(toString).join(", ")}]`;
      case "negated":
        return `!${toString(expr.child)}`;
      case "object":
        return `{${Object.entries(expr.values).map(([k4, v3]) => `${k4}: ${toString(v3)}`).join(", ")}}`;
      case "variable":
        return expr.name;
      case "literal":
        const wrapped = Literals.wrapValue(expr.value);
        if (!wrapped)
          return "null";
        switch (wrapped.type) {
          case "string":
            return `"${wrapped.value}"`;
          default:
            return Literals.toString(wrapped.value);
        }
    }
  }
  Expressions2.toString = toString;
  Expressions2.NULL = Expressions2.literal(null);
})(Expressions || (Expressions = {}));

// src/expression/parser.ts
var PRIMITIVES = P2.createLanguage({
  number: (_3) => P2.regexp(/-?[0-9]+(\.[0-9]+)?/).map((str) => Number.parseFloat(str)).desc("number"),
  // A quote-surrounded string which supports escape characters ('\').
  string: (q4) => P2.string('"').then(
    P2.alt(q4.escapeCharacter, P2.noneOf('"\\')).atLeast(0).map((chars2) => chars2.join(""))
  ).skip(P2.string('"')).desc("string"),
  escapeCharacter: (_3) => P2.string("\\").then(P2.any).map((escaped) => {
    if (escaped === '"')
      return '"';
    if (escaped === "\\")
      return "\\";
    else
      return "\\" + escaped;
  }),
  // A boolean true/false value.
  bool: (_3) => P2.regexp(/true|false|True|False/).map((str) => str.toLowerCase() == "true").desc("boolean"),
  // A tag of the form '#stuff/hello-there'.
  tag: (_3) => P2.seqMap(
    P2.string("#"),
    P2.alt(P2.regexp(/[^\u2000-\u206F\u2E00-\u2E7F'!"#$%&()*+,.:;<=>?@^`{|}~\[\]\\\s]/).desc("text")).many(),
    (start, rest) => start + rest.join("")
  ).desc("tag"),
  // A variable identifier, which is alphanumeric and must start with a letter or... emoji.
  identifier: (_3) => P2.seqMap(
    P2.alt(P2.regexp(/[\p{Letter}$]/u), P2.regexp(EMOJI_REGEX).desc("text")),
    P2.alt(P2.regexp(/[0-9\p{Letter}$_-]/u), P2.regexp(EMOJI_REGEX).desc("text")).many(),
    (first, rest) => first + rest.join("")
  ).desc("variable"),
  // An Obsidian link of the form [[<link>]].
  link: (_3) => P2.regexp(/\[\[([^\[\]]*?)\]\]/u, 1).map((linkInner) => Link.parseInner(linkInner)).desc("file link"),
  // An embeddable link which can start with '!'. This overlaps with the normal negation operator, so it is only
  // provided for metadata parsing.
  embedLink: (q4) => P2.seqMap(P2.string("!").atMost(1), q4.link, (p3, l4) => {
    if (p3.length > 0)
      l4.embed = true;
    return l4;
  }).desc("file link"),
  // Binary plus or minus operator.
  binaryPlusMinus: (_3) => P2.regexp(/\+|-/).map((str) => str).desc("'+' or '-'"),
  // Binary times or divide operator.
  binaryMulDiv: (_3) => P2.regexp(/\*|\/|%/).map((str) => str).desc("'*' or '/' or '%'"),
  // Binary comparison operator.
  binaryCompareOp: (_3) => P2.regexp(/>=|<=|!=|>|<|=/).map((str) => str).desc("'>=' or '<=' or '!=' or '=' or '>' or '<'"),
  // Binary boolean combination operator.
  binaryAndOp: (_3) => P2.regexp(/and|&/i).map((_str) => "&").desc("'and'"),
  binaryOrOp: (_3) => P2.regexp(/or|\|/i).map((_str) => "|").desc("'or'"),
  // A date which can be YYYY-MM[-DDTHH:mm:ss].
  rootDate: (_3) => P2.seqMap(P2.regexp(/\d{4}/), P2.string("-"), P2.regexp(/\d{2}/), (year, _4, month) => {
    return DateTime.fromObject({ year: Number.parseInt(year), month: Number.parseInt(month) });
  }).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"),
  dateShorthand: (_3) => P2.alt(
    ...Object.keys(DATE_SHORTHANDS).sort((a3, b3) => b3.length - a3.length).map(P2.string)
  ),
  date: (q4) => chainOpt(
    q4.rootDate,
    (ym) => P2.seqMap(P2.string("-"), P2.regexp(/\d{2}/), (_3, day) => ym.set({ day: Number.parseInt(day) })),
    (ymd) => P2.seqMap(P2.string("T"), P2.regexp(/\d{2}/), (_3, hour) => ymd.set({ hour: Number.parseInt(hour) })),
    (ymdh) => P2.seqMap(
      P2.string(":"),
      P2.regexp(/\d{2}/),
      (_3, minute) => ymdh.set({ minute: Number.parseInt(minute) })
    ),
    (ymdhm) => P2.seqMap(
      P2.string(":"),
      P2.regexp(/\d{2}/),
      (_3, second) => ymdhm.set({ second: Number.parseInt(second) })
    ),
    (ymdhms) => P2.alt(
      P2.seqMap(
        P2.string("."),
        P2.regexp(/\d{3}/),
        (_3, millisecond) => ymdhms.set({ millisecond: Number.parseInt(millisecond) })
      ),
      P2.succeed(ymdhms)
      // pass
    ),
    (dt) => P2.alt(
      P2.seqMap(
        P2.string("+").or(P2.string("-")),
        P2.regexp(/\d{1,2}(:\d{2})?/),
        (pm, hr) => dt.setZone("UTC" + pm + hr, { keepLocalTime: true })
      ),
      P2.seqMap(P2.string("Z"), () => dt.setZone("utc", { keepLocalTime: true })),
      P2.seqMap(
        P2.string("["),
        P2.regexp(/[0-9A-Za-z+-\/]+/u),
        P2.string("]"),
        (_a, zone, _b) => dt.setZone(zone, { keepLocalTime: true })
      )
    )
  ).assert((dt) => dt.isValid, "valid date").desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"),
  // A date, plus various shorthand times of day it could be.
  datePlus: (q4) => P2.alt(
    q4.dateShorthand.map((d3) => DATE_SHORTHANDS[d3]()),
    q4.date
  ).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS] or in shorthand"),
  // A duration of time.
  durationType: (_3) => P2.alt(
    ...Object.keys(DURATION_TYPES).sort((a3, b3) => b3.length - a3.length).map(P2.string)
  ),
  duration: (q4) => P2.seqMap(
    q4.number,
    P2.optWhitespace,
    q4.durationType,
    (count, _3, t4) => DURATION_TYPES[t4].mapUnits((x4) => x4 * count)
  ).sepBy1(P2.string(",").trim(P2.optWhitespace).or(P2.optWhitespace)).map((durations) => durations.reduce((p3, c3) => p3.plus(c3))).desc("duration like 4hr2min"),
  // A raw null value.
  rawNull: (_3) => P2.string("null"),
  // Inline field value parsing.
  atomInlineField: (q4) => P2.alt(
    q4.date,
    q4.duration.map((d3) => normalizeDuration(d3)),
    q4.string,
    q4.tag,
    q4.embedLink,
    q4.bool,
    q4.number,
    q4.rawNull
  ),
  inlineFieldList: (q4) => q4.atomInlineField.sepBy(P2.string(",").trim(P2.optWhitespace).lookahead(q4.atomInlineField)),
  inlineField: (q4) => P2.alt(
    P2.seqMap(
      q4.atomInlineField,
      P2.string(",").trim(P2.optWhitespace),
      q4.inlineFieldList,
      (f4, _s, l4) => [f4].concat(l4)
    ),
    q4.atomInlineField
  )
});
var EMOJI_REGEX = new RegExp(emoji_regex_default(), "");
var DURATION_TYPES = {
  year: Duration.fromObject({ years: 1 }),
  years: Duration.fromObject({ years: 1 }),
  yr: Duration.fromObject({ years: 1 }),
  yrs: Duration.fromObject({ years: 1 }),
  month: Duration.fromObject({ months: 1 }),
  months: Duration.fromObject({ months: 1 }),
  mo: Duration.fromObject({ months: 1 }),
  mos: Duration.fromObject({ months: 1 }),
  week: Duration.fromObject({ weeks: 1 }),
  weeks: Duration.fromObject({ weeks: 1 }),
  wk: Duration.fromObject({ weeks: 1 }),
  wks: Duration.fromObject({ weeks: 1 }),
  w: Duration.fromObject({ weeks: 1 }),
  day: Duration.fromObject({ days: 1 }),
  days: Duration.fromObject({ days: 1 }),
  d: Duration.fromObject({ days: 1 }),
  hour: Duration.fromObject({ hours: 1 }),
  hours: Duration.fromObject({ hours: 1 }),
  hr: Duration.fromObject({ hours: 1 }),
  hrs: Duration.fromObject({ hours: 1 }),
  h: Duration.fromObject({ hours: 1 }),
  minute: Duration.fromObject({ minutes: 1 }),
  minutes: Duration.fromObject({ minutes: 1 }),
  min: Duration.fromObject({ minutes: 1 }),
  mins: Duration.fromObject({ minutes: 1 }),
  m: Duration.fromObject({ minutes: 1 }),
  second: Duration.fromObject({ seconds: 1 }),
  seconds: Duration.fromObject({ seconds: 1 }),
  sec: Duration.fromObject({ seconds: 1 }),
  secs: Duration.fromObject({ seconds: 1 }),
  s: Duration.fromObject({ seconds: 1 })
};
var DATE_SHORTHANDS = {
  now: () => DateTime.local(),
  today: () => DateTime.local().startOf("day"),
  yesterday: () => DateTime.local().startOf("day").minus(Duration.fromObject({ days: 1 })),
  tomorrow: () => DateTime.local().startOf("day").plus(Duration.fromObject({ days: 1 })),
  sow: () => DateTime.local().startOf("week"),
  "start-of-week": () => DateTime.local().startOf("week"),
  eow: () => DateTime.local().endOf("week"),
  "end-of-week": () => DateTime.local().endOf("week"),
  soy: () => DateTime.local().startOf("year"),
  "start-of-year": () => DateTime.local().startOf("year"),
  eoy: () => DateTime.local().endOf("year"),
  "end-of-year": () => DateTime.local().endOf("year"),
  som: () => DateTime.local().startOf("month"),
  "start-of-month": () => DateTime.local().startOf("month"),
  eom: () => DateTime.local().endOf("month"),
  "end-of-month": () => DateTime.local().endOf("month")
};
var EXPRESSION = P2.createLanguage({
  // Field parsing.
  variable: (_3) => PRIMITIVES.identifier.map(Expressions.variable).desc("variable"),
  number: (_3) => PRIMITIVES.number.map(Expressions.literal).desc("number"),
  string: (_3) => PRIMITIVES.string.map(Expressions.literal).desc("string"),
  bool: (_3) => PRIMITIVES.bool.map(Expressions.literal).desc("boolean"),
  date: (_3) => createFunction("date", PRIMITIVES.datePlus).map(([_func, date]) => Expressions.literal(date)).desc("date"),
  duration: (_3) => createFunction("dur", PRIMITIVES.duration).map(([_func, dur]) => Expressions.literal(dur)).desc("duration"),
  null: (_3) => PRIMITIVES.rawNull.map((_4) => Expressions.NULL),
  link: (_3) => PRIMITIVES.link.map(Expressions.literal),
  list: (q4) => q4.expression.sepBy(P2.string(",").trim(P2.optWhitespace)).wrap(P2.string("[").skip(P2.optWhitespace), P2.optWhitespace.then(P2.string("]"))).map((l4) => Expressions.list(l4)).desc("list"),
  object: (q4) => P2.seqMap(
    PRIMITIVES.identifier.or(PRIMITIVES.string),
    P2.string(":").trim(P2.optWhitespace),
    q4.expression,
    (name, _sep, value) => {
      return { name, value };
    }
  ).sepBy(P2.string(",").trim(P2.optWhitespace)).wrap(P2.string("{").skip(P2.optWhitespace), P2.optWhitespace.then(P2.string("}"))).map((vals) => {
    let res = {};
    for (let entry of vals)
      res[entry.name] = entry.value;
    return Expressions.object(res);
  }).desc("object ('{ a: 1, b: 2 }')"),
  atom: (q4) => P2.alt(
    // Place embed links above negated fields as they are the special parser case '![[thing]]' and are generally unambigious.
    PRIMITIVES.embedLink.map((l4) => Expressions.literal(l4)),
    q4.negated,
    q4.link,
    q4.list,
    q4.object,
    q4.lambda,
    q4.parens,
    q4.bool,
    q4.number,
    q4.string,
    q4.date,
    q4.duration,
    q4.null,
    q4.variable
  ),
  index: (q4) => P2.seqMap(
    q4.atom,
    P2.alt(q4.methodPostfix, q4.functionPostfix, q4.indexPostfix, q4.dotPostfix).many(),
    (obj, postfixes) => {
      let result = obj;
      for (let post of postfixes) {
        switch (post.type) {
          case "dot":
            result = Expressions.index(result, Expressions.literal(post.expr));
            break;
          case "index":
            result = Expressions.index(result, post.expr);
            break;
          case "function":
            result = Expressions.func(result, post.exprs);
            break;
          case "method":
            result = Expressions.method(result, post.func, post.exprs);
            break;
        }
      }
      return result;
    }
  ),
  negated: (q4) => P2.seqMap(P2.string("!"), q4.index, (_3, field) => Expressions.negate(field)).desc("negated field"),
  parens: (q4) => q4.expression.trim(P2.optWhitespace).wrap(P2.string("("), P2.string(")")),
  lambda: (q4) => P2.seqMap(
    PRIMITIVES.identifier.sepBy(P2.string(",").trim(P2.optWhitespace)).wrap(P2.string("(").trim(P2.optWhitespace), P2.string(")").trim(P2.optWhitespace)),
    P2.string("=>").trim(P2.optWhitespace),
    q4.expression,
    (ident, _ignore, value) => {
      return { type: "lambda", arguments: ident, value };
    }
  ),
  dotPostfix: (q4) => P2.string(".").then(PRIMITIVES.identifier).map((expr) => ({ type: "dot", expr })),
  // Indexing into something: a[b].
  indexPostfix: (q4) => q4.expression.trim(P2.optWhitespace).wrap(P2.string("["), P2.string("]")).map((expr) => {
    return { type: "index", expr };
  }),
  // Call on a variable directly: var().
  functionPostfix: (q4) => q4.expression.sepBy(P2.string(",").trim(P2.optWhitespace)).trim(P2.optWhitespace).wrap(P2.string("("), P2.string(")")).map((exprs) => {
    return { type: "function", exprs };
  }),
  // Full method call: .thing().
  methodPostfix: (q4) => P2.seqMap(
    P2.string("."),
    PRIMITIVES.identifier.trim(P2.optWhitespace),
    q4.expression.sepBy(P2.string(",").trim(P2.optWhitespace)).trim(P2.optWhitespace).wrap(P2.string("("), P2.string(")")),
    (_3, func, exprs) => {
      return { type: "method", func, exprs };
    }
  ),
  // The precedence hierarchy of operators - multiply/divide, add/subtract, compare, and then boolean operations.
  binaryMulDiv: (q4) => createBinaryParser(q4.index, PRIMITIVES.binaryMulDiv, Expressions.binaryOp),
  binaryPlusMinus: (q4) => createBinaryParser(q4.binaryMulDiv, PRIMITIVES.binaryPlusMinus, Expressions.binaryOp),
  binaryCompare: (q4) => createBinaryParser(q4.binaryPlusMinus, PRIMITIVES.binaryCompareOp, Expressions.binaryOp),
  binaryBoolean: (q4) => createBinaryParser(q4.binaryCompare, PRIMITIVES.binaryAndOp.or(PRIMITIVES.binaryOrOp), Expressions.binaryOp),
  binaryOp: (q4) => q4.binaryBoolean,
  expression: (q4) => q4.binaryOp
});
var QUERY = P2.createLanguage({
  queryTag: (_3) => PRIMITIVES.tag.map((value) => ({ type: "tagged", value })),
  queryId: (_3) => createFunction("id", PRIMITIVES.string).map(([_4, id]) => ({ type: "id", value: id })),
  queryType: (_3) => P2.string("@").then(PRIMITIVES.identifier).map((value) => ({ type: "typed", value })),
  queryPath: (_3) => createFunction(P2.regexp(/e?path/i).desc("[e]path"), PRIMITIVES.string).map(([func, path]) => ({
    type: "path",
    value: path,
    exact: func.toLowerCase() === "epath"
  })),
  queryParentOf: (q4) => createFunction(P2.regexp(/parentof|supertree/i).desc("parentof"), q4.query).map(([func, children]) => ({
    type: "parent-of",
    children,
    inclusive: func.toLowerCase() === "supertree"
  })),
  queryChildOf: (q4) => createFunction(P2.regexp(/childof|subtree/i).desc("childof"), q4.query).map(([func, parents]) => ({
    type: "child-of",
    parents,
    inclusive: func.toLowerCase() === "subtree"
  })),
  querySimpleLinked: (_3) => PRIMITIVES.link.map((link) => ({
    type: "linked",
    source: { type: "link", value: link },
    direction: "incoming"
  })),
  queryLinked: (q4) => createFunction(P2.regexp(/linksto|linkedfrom|connected/i).desc("connected"), q4.query).map(([func, source]) => ({
    type: "linked",
    // When writing syntax like `linksto([[link]])`, [[link]] will also be interpreted as a linked query, so unwrap it if present.
    source: source.type == "linked" && source.source.type == "link" ? source.source : source,
    direction: func.toLowerCase() == "linksto" ? "incoming" : func.toLowerCase() == "linkedfrom" ? "outgoing" : "both"
  })),
  queryExists: (_3) => createFunction(P2.regexp(/exists/i).desc("exists"), PRIMITIVES.identifier.or(PRIMITIVES.string)).map(
    ([_func, ident]) => ({
      type: "field",
      value: ident
    })
  ),
  queryQuotedExpression: (q4) => createFunction(P2.regexp(/expr/i).desc("expr"), EXPRESSION.expression).map(([_3, expr]) => ({
    type: "expression",
    expression: expr
  })),
  queryRawExpression: (q4) => EXPRESSION.binaryCompare.map((expr) => ({ type: "expression", expression: expr })),
  queryParens: (q4) => q4.query.trim(P2.optWhitespace).wrap(P2.string("("), P2.string(")")),
  queryNegate: (q4) => P2.string("!").skip(P2.optWhitespace).then(q4.queryAtom).map((value) => ({
    type: "not",
    element: value
  })),
  queryAtom: (q4) => P2.alt(
    q4.queryParens,
    q4.queryNegate,
    q4.querySimpleLinked,
    q4.queryTag,
    q4.queryType,
    q4.queryId,
    q4.queryExists,
    q4.queryChildOf,
    q4.queryParentOf,
    q4.queryLinked,
    q4.queryPath,
    q4.queryQuotedExpression,
    // Expressions are essentially the "catch-all" of otherwise unparseable terms, so they should go absolute last.
    q4.queryRawExpression
  ),
  queryAnds: (q4) => createBinaryParser(q4.queryAtom, PRIMITIVES.binaryAndOp, (left, _op, right) => ({
    type: "and",
    elements: [left, right]
  })),
  queryOrs: (q4) => createBinaryParser(q4.queryAnds, PRIMITIVES.binaryOrOp, (left, _op, right) => ({
    type: "or",
    elements: [left, right]
  })),
  query: (q4) => q4.queryOrs.trim(P2.optWhitespace)
});
function createBinaryParser(child, sep, combine) {
  return P2.seqMap(child, P2.seq(P2.optWhitespace, sep, P2.optWhitespace, child).many(), (first, rest) => {
    if (rest.length == 0)
      return first;
    let node = combine(first, rest[0][1], rest[0][3]);
    for (let index = 1; index < rest.length; index++) {
      node = combine(node, rest[index][1], rest[index][3]);
    }
    return node;
  });
}
function createFunction(func, args) {
  const realFunc = typeof func === "string" ? P2.string(func) : func;
  return P2.seqMap(
    realFunc.skip(P2.optWhitespace),
    args.trim(P2.optWhitespace).wrap(P2.string("("), P2.string(")")),
    (f4, a3) => [f4, a3]
  );
}
function chainOpt(base, ...funcs) {
  return P2.custom((_success, _failure) => {
    return (input2, i4) => {
      let result = base._(input2, i4);
      if (!result.status)
        return result;
      for (let func of funcs) {
        const value = result.value;
        const next2 = func(value)._(input2, result.index);
        if (!next2.status)
          return result;
        result = next2;
      }
      return result;
    };
  });
}

// src/ui/markdown.tsx
var import_obsidian = require("obsidian");

// src/utils/media.ts
var IMAGE_EXTENSIONS = Object.freeze(
  /* @__PURE__ */ new Set([
    ".tif",
    ".tiff",
    ".gif",
    ".png",
    ".apng",
    ".avif",
    ".jpg",
    ".jpeg",
    ".jfif",
    ".pjepg",
    ".pjp",
    ".svg",
    ".webp",
    ".bmp",
    ".ico",
    ".cur"
  ])
);
function isImageEmbed(link) {
  if (!link.path.contains("."))
    return false;
  let extension = link.path.substring(link.path.lastIndexOf("."));
  return link.type == "file" && link.embed && IMAGE_EXTENSIONS.has(extension);
}
function extractImageDimensions(link) {
  if (!link.display)
    return void 0;
  let match3 = /^(\d+)x(\d+)$/iu.exec(link.display);
  if (match3)
    return [parseInt(match3[1]), parseInt(match3[2])];
  let match22 = /^(\d+)/.exec(link.display);
  if (match22)
    return [parseInt(match22[1])];
  return void 0;
}

// node_modules/preact/dist/preact.module.js
var preact_module_exports = {};
__export(preact_module_exports, {
  Component: () => x,
  Fragment: () => k,
  cloneElement: () => J,
  createContext: () => K,
  createElement: () => _,
  createRef: () => b,
  h: () => _,
  hydrate: () => G,
  isValidElement: () => t,
  options: () => l2,
  render: () => E,
  toChildArray: () => H
});
var n2;
var l2;
var u;
var t;
var i;
var r;
var o;
var e;
var f;
var c;
var s2;
var a;
var h;
var p = {};
var v = [];
var y = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;
var w = Array.isArray;
function d(n3, l4) {
  for (var u4 in l4)
    n3[u4] = l4[u4];
  return n3;
}
function g(n3) {
  n3 && n3.parentNode && n3.parentNode.removeChild(n3);
}
function _(l4, u4, t4) {
  var i4, r3, o3, e3 = {};
  for (o3 in u4)
    "key" == o3 ? i4 = u4[o3] : "ref" == o3 ? r3 = u4[o3] : e3[o3] = u4[o3];
  if (arguments.length > 2 && (e3.children = arguments.length > 3 ? n2.call(arguments, 2) : t4), "function" == typeof l4 && null != l4.defaultProps)
    for (o3 in l4.defaultProps)
      void 0 === e3[o3] && (e3[o3] = l4.defaultProps[o3]);
  return m(l4, e3, i4, r3, null);
}
function m(n3, t4, i4, r3, o3) {
  var e3 = { type: n3, props: t4, key: i4, ref: r3, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: void 0, __v: null == o3 ? ++u : o3, __i: -1, __u: 0 };
  return null == o3 && null != l2.vnode && l2.vnode(e3), e3;
}
function b() {
  return { current: null };
}
function k(n3) {
  return n3.children;
}
function x(n3, l4) {
  this.props = n3, this.context = l4;
}
function S(n3, l4) {
  if (null == l4)
    return n3.__ ? S(n3.__, n3.__i + 1) : null;
  for (var u4; l4 < n3.__k.length; l4++)
    if (null != (u4 = n3.__k[l4]) && null != u4.__e)
      return u4.__e;
  return "function" == typeof n3.type ? S(n3) : null;
}
function C(n3) {
  var l4, u4;
  if (null != (n3 = n3.__) && null != n3.__c) {
    for (n3.__e = n3.__c.base = null, l4 = 0; l4 < n3.__k.length; l4++)
      if (null != (u4 = n3.__k[l4]) && null != u4.__e) {
        n3.__e = n3.__c.base = u4.__e;
        break;
      }
    return C(n3);
  }
}
function M(n3) {
  (!n3.__d && (n3.__d = true) && i.push(n3) && !$.__r++ || r != l2.debounceRendering) && ((r = l2.debounceRendering) || o)($);
}
function $() {
  for (var n3, u4, t4, r3, o3, f4, c3, s4 = 1; i.length; )
    i.length > s4 && i.sort(e), n3 = i.shift(), s4 = i.length, n3.__d && (t4 = void 0, o3 = (r3 = (u4 = n3).__v).__e, f4 = [], c3 = [], u4.__P && ((t4 = d({}, r3)).__v = r3.__v + 1, l2.vnode && l2.vnode(t4), O(u4.__P, t4, r3, u4.__n, u4.__P.namespaceURI, 32 & r3.__u ? [o3] : null, f4, null == o3 ? S(r3) : o3, !!(32 & r3.__u), c3), t4.__v = r3.__v, t4.__.__k[t4.__i] = t4, z(f4, t4, c3), t4.__e != o3 && C(t4)));
  $.__r = 0;
}
function I(n3, l4, u4, t4, i4, r3, o3, e3, f4, c3, s4) {
  var a3, h3, y3, w4, d3, g4, _3 = t4 && t4.__k || v, m3 = l4.length;
  for (f4 = P3(u4, l4, _3, f4, m3), a3 = 0; a3 < m3; a3++)
    null != (y3 = u4.__k[a3]) && (h3 = -1 == y3.__i ? p : _3[y3.__i] || p, y3.__i = a3, g4 = O(n3, y3, h3, i4, r3, o3, e3, f4, c3, s4), w4 = y3.__e, y3.ref && h3.ref != y3.ref && (h3.ref && q(h3.ref, null, y3), s4.push(y3.ref, y3.__c || w4, y3)), null == d3 && null != w4 && (d3 = w4), 4 & y3.__u || h3.__k === y3.__k ? f4 = A(y3, f4, n3) : "function" == typeof y3.type && void 0 !== g4 ? f4 = g4 : w4 && (f4 = w4.nextSibling), y3.__u &= -7);
  return u4.__e = d3, f4;
}
function P3(n3, l4, u4, t4, i4) {
  var r3, o3, e3, f4, c3, s4 = u4.length, a3 = s4, h3 = 0;
  for (n3.__k = new Array(i4), r3 = 0; r3 < i4; r3++)
    null != (o3 = l4[r3]) && "boolean" != typeof o3 && "function" != typeof o3 ? (f4 = r3 + h3, (o3 = n3.__k[r3] = "string" == typeof o3 || "number" == typeof o3 || "bigint" == typeof o3 || o3.constructor == String ? m(null, o3, null, null, null) : w(o3) ? m(k, { children: o3 }, null, null, null) : null == o3.constructor && o3.__b > 0 ? m(o3.type, o3.props, o3.key, o3.ref ? o3.ref : null, o3.__v) : o3).__ = n3, o3.__b = n3.__b + 1, e3 = null, -1 != (c3 = o3.__i = L(o3, u4, f4, a3)) && (a3--, (e3 = u4[c3]) && (e3.__u |= 2)), null == e3 || null == e3.__v ? (-1 == c3 && (i4 > s4 ? h3-- : i4 < s4 && h3++), "function" != typeof o3.type && (o3.__u |= 4)) : c3 != f4 && (c3 == f4 - 1 ? h3-- : c3 == f4 + 1 ? h3++ : (c3 > f4 ? h3-- : h3++, o3.__u |= 4))) : n3.__k[r3] = null;
  if (a3)
    for (r3 = 0; r3 < s4; r3++)
      null != (e3 = u4[r3]) && 0 == (2 & e3.__u) && (e3.__e == t4 && (t4 = S(e3)), B(e3, e3));
  return t4;
}
function A(n3, l4, u4) {
  var t4, i4;
  if ("function" == typeof n3.type) {
    for (t4 = n3.__k, i4 = 0; t4 && i4 < t4.length; i4++)
      t4[i4] && (t4[i4].__ = n3, l4 = A(t4[i4], l4, u4));
    return l4;
  }
  n3.__e != l4 && (l4 && n3.type && !u4.contains(l4) && (l4 = S(n3)), u4.insertBefore(n3.__e, l4 || null), l4 = n3.__e);
  do {
    l4 = l4 && l4.nextSibling;
  } while (null != l4 && 8 == l4.nodeType);
  return l4;
}
function H(n3, l4) {
  return l4 = l4 || [], null == n3 || "boolean" == typeof n3 || (w(n3) ? n3.some(function(n4) {
    H(n4, l4);
  }) : l4.push(n3)), l4;
}
function L(n3, l4, u4, t4) {
  var i4, r3, o3 = n3.key, e3 = n3.type, f4 = l4[u4];
  if (null === f4 && null == n3.key || f4 && o3 == f4.key && e3 == f4.type && 0 == (2 & f4.__u))
    return u4;
  if (t4 > (null != f4 && 0 == (2 & f4.__u) ? 1 : 0))
    for (i4 = u4 - 1, r3 = u4 + 1; i4 >= 0 || r3 < l4.length; ) {
      if (i4 >= 0) {
        if ((f4 = l4[i4]) && 0 == (2 & f4.__u) && o3 == f4.key && e3 == f4.type)
          return i4;
        i4--;
      }
      if (r3 < l4.length) {
        if ((f4 = l4[r3]) && 0 == (2 & f4.__u) && o3 == f4.key && e3 == f4.type)
          return r3;
        r3++;
      }
    }
  return -1;
}
function T(n3, l4, u4) {
  "-" == l4[0] ? n3.setProperty(l4, null == u4 ? "" : u4) : n3[l4] = null == u4 ? "" : "number" != typeof u4 || y.test(l4) ? u4 : u4 + "px";
}
function j(n3, l4, u4, t4, i4) {
  var r3, o3;
  n:
    if ("style" == l4)
      if ("string" == typeof u4)
        n3.style.cssText = u4;
      else {
        if ("string" == typeof t4 && (n3.style.cssText = t4 = ""), t4)
          for (l4 in t4)
            u4 && l4 in u4 || T(n3.style, l4, "");
        if (u4)
          for (l4 in u4)
            t4 && u4[l4] == t4[l4] || T(n3.style, l4, u4[l4]);
      }
    else if ("o" == l4[0] && "n" == l4[1])
      r3 = l4 != (l4 = l4.replace(f, "$1")), o3 = l4.toLowerCase(), l4 = o3 in n3 || "onFocusOut" == l4 || "onFocusIn" == l4 ? o3.slice(2) : l4.slice(2), n3.l || (n3.l = {}), n3.l[l4 + r3] = u4, u4 ? t4 ? u4.u = t4.u : (u4.u = c, n3.addEventListener(l4, r3 ? a : s2, r3)) : n3.removeEventListener(l4, r3 ? a : s2, r3);
    else {
      if ("http://www.w3.org/2000/svg" == i4)
        l4 = l4.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s");
      else if ("width" != l4 && "height" != l4 && "href" != l4 && "list" != l4 && "form" != l4 && "tabIndex" != l4 && "download" != l4 && "rowSpan" != l4 && "colSpan" != l4 && "role" != l4 && "popover" != l4 && l4 in n3)
        try {
          n3[l4] = null == u4 ? "" : u4;
          break n;
        } catch (n4) {
        }
      "function" == typeof u4 || (null == u4 || false === u4 && "-" != l4[4] ? n3.removeAttribute(l4) : n3.setAttribute(l4, "popover" == l4 && 1 == u4 ? "" : u4));
    }
}
function F(n3) {
  return function(u4) {
    if (this.l) {
      var t4 = this.l[u4.type + n3];
      if (null == u4.t)
        u4.t = c++;
      else if (u4.t < t4.u)
        return;
      return t4(l2.event ? l2.event(u4) : u4);
    }
  };
}
function O(n3, u4, t4, i4, r3, o3, e3, f4, c3, s4) {
  var a3, h3, p3, v3, y3, _3, m3, b3, S2, C4, M3, $3, P7, A4, H3, L3, T4, j4 = u4.type;
  if (null != u4.constructor)
    return null;
  128 & t4.__u && (c3 = !!(32 & t4.__u), o3 = [f4 = u4.__e = t4.__e]), (a3 = l2.__b) && a3(u4);
  n:
    if ("function" == typeof j4)
      try {
        if (b3 = u4.props, S2 = "prototype" in j4 && j4.prototype.render, C4 = (a3 = j4.contextType) && i4[a3.__c], M3 = a3 ? C4 ? C4.props.value : a3.__ : i4, t4.__c ? m3 = (h3 = u4.__c = t4.__c).__ = h3.__E : (S2 ? u4.__c = h3 = new j4(b3, M3) : (u4.__c = h3 = new x(b3, M3), h3.constructor = j4, h3.render = D), C4 && C4.sub(h3), h3.props = b3, h3.state || (h3.state = {}), h3.context = M3, h3.__n = i4, p3 = h3.__d = true, h3.__h = [], h3._sb = []), S2 && null == h3.__s && (h3.__s = h3.state), S2 && null != j4.getDerivedStateFromProps && (h3.__s == h3.state && (h3.__s = d({}, h3.__s)), d(h3.__s, j4.getDerivedStateFromProps(b3, h3.__s))), v3 = h3.props, y3 = h3.state, h3.__v = u4, p3)
          S2 && null == j4.getDerivedStateFromProps && null != h3.componentWillMount && h3.componentWillMount(), S2 && null != h3.componentDidMount && h3.__h.push(h3.componentDidMount);
        else {
          if (S2 && null == j4.getDerivedStateFromProps && b3 !== v3 && null != h3.componentWillReceiveProps && h3.componentWillReceiveProps(b3, M3), !h3.__e && null != h3.shouldComponentUpdate && false === h3.shouldComponentUpdate(b3, h3.__s, M3) || u4.__v == t4.__v) {
            for (u4.__v != t4.__v && (h3.props = b3, h3.state = h3.__s, h3.__d = false), u4.__e = t4.__e, u4.__k = t4.__k, u4.__k.some(function(n4) {
              n4 && (n4.__ = u4);
            }), $3 = 0; $3 < h3._sb.length; $3++)
              h3.__h.push(h3._sb[$3]);
            h3._sb = [], h3.__h.length && e3.push(h3);
            break n;
          }
          null != h3.componentWillUpdate && h3.componentWillUpdate(b3, h3.__s, M3), S2 && null != h3.componentDidUpdate && h3.__h.push(function() {
            h3.componentDidUpdate(v3, y3, _3);
          });
        }
        if (h3.context = M3, h3.props = b3, h3.__P = n3, h3.__e = false, P7 = l2.__r, A4 = 0, S2) {
          for (h3.state = h3.__s, h3.__d = false, P7 && P7(u4), a3 = h3.render(h3.props, h3.state, h3.context), H3 = 0; H3 < h3._sb.length; H3++)
            h3.__h.push(h3._sb[H3]);
          h3._sb = [];
        } else
          do {
            h3.__d = false, P7 && P7(u4), a3 = h3.render(h3.props, h3.state, h3.context), h3.state = h3.__s;
          } while (h3.__d && ++A4 < 25);
        h3.state = h3.__s, null != h3.getChildContext && (i4 = d(d({}, i4), h3.getChildContext())), S2 && !p3 && null != h3.getSnapshotBeforeUpdate && (_3 = h3.getSnapshotBeforeUpdate(v3, y3)), L3 = a3, null != a3 && a3.type === k && null == a3.key && (L3 = N(a3.props.children)), f4 = I(n3, w(L3) ? L3 : [L3], u4, t4, i4, r3, o3, e3, f4, c3, s4), h3.base = u4.__e, u4.__u &= -161, h3.__h.length && e3.push(h3), m3 && (h3.__E = h3.__ = null);
      } catch (n4) {
        if (u4.__v = null, c3 || null != o3)
          if (n4.then) {
            for (u4.__u |= c3 ? 160 : 128; f4 && 8 == f4.nodeType && f4.nextSibling; )
              f4 = f4.nextSibling;
            o3[o3.indexOf(f4)] = null, u4.__e = f4;
          } else
            for (T4 = o3.length; T4--; )
              g(o3[T4]);
        else
          u4.__e = t4.__e, u4.__k = t4.__k;
        l2.__e(n4, u4, t4);
      }
    else
      null == o3 && u4.__v == t4.__v ? (u4.__k = t4.__k, u4.__e = t4.__e) : f4 = u4.__e = V(t4.__e, u4, t4, i4, r3, o3, e3, c3, s4);
  return (a3 = l2.diffed) && a3(u4), 128 & u4.__u ? void 0 : f4;
}
function z(n3, u4, t4) {
  for (var i4 = 0; i4 < t4.length; i4++)
    q(t4[i4], t4[++i4], t4[++i4]);
  l2.__c && l2.__c(u4, n3), n3.some(function(u5) {
    try {
      n3 = u5.__h, u5.__h = [], n3.some(function(n4) {
        n4.call(u5);
      });
    } catch (n4) {
      l2.__e(n4, u5.__v);
    }
  });
}
function N(n3) {
  return "object" != typeof n3 || null == n3 || n3.__b && n3.__b > 0 ? n3 : w(n3) ? n3.map(N) : d({}, n3);
}
function V(u4, t4, i4, r3, o3, e3, f4, c3, s4) {
  var a3, h3, v3, y3, d3, _3, m3, b3 = i4.props, k4 = t4.props, x4 = t4.type;
  if ("svg" == x4 ? o3 = "http://www.w3.org/2000/svg" : "math" == x4 ? o3 = "http://www.w3.org/1998/Math/MathML" : o3 || (o3 = "http://www.w3.org/1999/xhtml"), null != e3) {
    for (a3 = 0; a3 < e3.length; a3++)
      if ((d3 = e3[a3]) && "setAttribute" in d3 == !!x4 && (x4 ? d3.localName == x4 : 3 == d3.nodeType)) {
        u4 = d3, e3[a3] = null;
        break;
      }
  }
  if (null == u4) {
    if (null == x4)
      return document.createTextNode(k4);
    u4 = document.createElementNS(o3, x4, k4.is && k4), c3 && (l2.__m && l2.__m(t4, e3), c3 = false), e3 = null;
  }
  if (null == x4)
    b3 === k4 || c3 && u4.data == k4 || (u4.data = k4);
  else {
    if (e3 = e3 && n2.call(u4.childNodes), b3 = i4.props || p, !c3 && null != e3)
      for (b3 = {}, a3 = 0; a3 < u4.attributes.length; a3++)
        b3[(d3 = u4.attributes[a3]).name] = d3.value;
    for (a3 in b3)
      if (d3 = b3[a3], "children" == a3)
        ;
      else if ("dangerouslySetInnerHTML" == a3)
        v3 = d3;
      else if (!(a3 in k4)) {
        if ("value" == a3 && "defaultValue" in k4 || "checked" == a3 && "defaultChecked" in k4)
          continue;
        j(u4, a3, null, d3, o3);
      }
    for (a3 in k4)
      d3 = k4[a3], "children" == a3 ? y3 = d3 : "dangerouslySetInnerHTML" == a3 ? h3 = d3 : "value" == a3 ? _3 = d3 : "checked" == a3 ? m3 = d3 : c3 && "function" != typeof d3 || b3[a3] === d3 || j(u4, a3, d3, b3[a3], o3);
    if (h3)
      c3 || v3 && (h3.__html == v3.__html || h3.__html == u4.innerHTML) || (u4.innerHTML = h3.__html), t4.__k = [];
    else if (v3 && (u4.innerHTML = ""), I("template" == t4.type ? u4.content : u4, w(y3) ? y3 : [y3], t4, i4, r3, "foreignObject" == x4 ? "http://www.w3.org/1999/xhtml" : o3, e3, f4, e3 ? e3[0] : i4.__k && S(i4, 0), c3, s4), null != e3)
      for (a3 = e3.length; a3--; )
        g(e3[a3]);
    c3 || (a3 = "value", "progress" == x4 && null == _3 ? u4.removeAttribute("value") : null != _3 && (_3 !== u4[a3] || "progress" == x4 && !_3 || "option" == x4 && _3 != b3[a3]) && j(u4, a3, _3, b3[a3], o3), a3 = "checked", null != m3 && m3 != u4[a3] && j(u4, a3, m3, b3[a3], o3));
  }
  return u4;
}
function q(n3, u4, t4) {
  try {
    if ("function" == typeof n3) {
      var i4 = "function" == typeof n3.__u;
      i4 && n3.__u(), i4 && null == u4 || (n3.__u = n3(u4));
    } else
      n3.current = u4;
  } catch (n4) {
    l2.__e(n4, t4);
  }
}
function B(n3, u4, t4) {
  var i4, r3;
  if (l2.unmount && l2.unmount(n3), (i4 = n3.ref) && (i4.current && i4.current != n3.__e || q(i4, null, u4)), null != (i4 = n3.__c)) {
    if (i4.componentWillUnmount)
      try {
        i4.componentWillUnmount();
      } catch (n4) {
        l2.__e(n4, u4);
      }
    i4.base = i4.__P = null;
  }
  if (i4 = n3.__k)
    for (r3 = 0; r3 < i4.length; r3++)
      i4[r3] && B(i4[r3], u4, t4 || "function" != typeof n3.type);
  t4 || g(n3.__e), n3.__c = n3.__ = n3.__e = void 0;
}
function D(n3, l4, u4) {
  return this.constructor(n3, u4);
}
function E(u4, t4, i4) {
  var r3, o3, e3, f4;
  t4 == document && (t4 = document.documentElement), l2.__ && l2.__(u4, t4), o3 = (r3 = "function" == typeof i4) ? null : i4 && i4.__k || t4.__k, e3 = [], f4 = [], O(t4, u4 = (!r3 && i4 || t4).__k = _(k, null, [u4]), o3 || p, p, t4.namespaceURI, !r3 && i4 ? [i4] : o3 ? null : t4.firstChild ? n2.call(t4.childNodes) : null, e3, !r3 && i4 ? i4 : o3 ? o3.__e : t4.firstChild, r3, f4), z(e3, u4, f4);
}
function G(n3, l4) {
  E(n3, l4, G);
}
function J(l4, u4, t4) {
  var i4, r3, o3, e3, f4 = d({}, l4.props);
  for (o3 in l4.type && l4.type.defaultProps && (e3 = l4.type.defaultProps), u4)
    "key" == o3 ? i4 = u4[o3] : "ref" == o3 ? r3 = u4[o3] : f4[o3] = void 0 === u4[o3] && null != e3 ? e3[o3] : u4[o3];
  return arguments.length > 2 && (f4.children = arguments.length > 3 ? n2.call(arguments, 2) : t4), m(l4.type, f4, i4 || l4.key, r3 || l4.ref, null);
}
function K(n3) {
  function l4(n4) {
    var u4, t4;
    return this.getChildContext || (u4 = /* @__PURE__ */ new Set(), (t4 = {})[l4.__c] = this, this.getChildContext = function() {
      return t4;
    }, this.componentWillUnmount = function() {
      u4 = null;
    }, this.shouldComponentUpdate = function(n5) {
      this.props.value != n5.value && u4.forEach(function(n6) {
        n6.__e = true, M(n6);
      });
    }, this.sub = function(n5) {
      u4.add(n5);
      var l5 = n5.componentWillUnmount;
      n5.componentWillUnmount = function() {
        u4 && u4.delete(n5), l5 && l5.call(n5);
      };
    }), n4.children;
  }
  return l4.__c = "__cC" + h++, l4.__ = n3, l4.Provider = l4.__l = (l4.Consumer = function(n4, l5) {
    return n4.children(l5);
  }).contextType = l4, l4;
}
n2 = v.slice, l2 = { __e: function(n3, l4, u4, t4) {
  for (var i4, r3, o3; l4 = l4.__; )
    if ((i4 = l4.__c) && !i4.__)
      try {
        if ((r3 = i4.constructor) && null != r3.getDerivedStateFromError && (i4.setState(r3.getDerivedStateFromError(n3)), o3 = i4.__d), null != i4.componentDidCatch && (i4.componentDidCatch(n3, t4 || {}), o3 = i4.__d), o3)
          return i4.__E = i4;
      } catch (l5) {
        n3 = l5;
      }
  throw n3;
} }, u = 0, t = function(n3) {
  return null != n3 && null == n3.constructor;
}, x.prototype.setState = function(n3, l4) {
  var u4;
  u4 = null != this.__s && this.__s != this.state ? this.__s : this.__s = d({}, this.state), "function" == typeof n3 && (n3 = n3(d({}, u4), this.props)), n3 && d(u4, n3), null != n3 && this.__v && (l4 && this._sb.push(l4), M(this));
}, x.prototype.forceUpdate = function(n3) {
  this.__v && (this.__e = true, n3 && this.__h.push(n3), M(this));
}, x.prototype.render = k, i = [], o = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, e = function(n3, l4) {
  return n3.__v.__b - l4.__v.__b;
}, $.__r = 0, f = /(PointerCapture)$|Capture$/i, c = 0, s2 = F(false), a = F(true), h = 0;

// node_modules/preact/hooks/dist/hooks.module.js
var t2;
var r2;
var u2;
var i2;
var o2 = 0;
var f2 = [];
var c2 = l2;
var e2 = c2.__b;
var a2 = c2.__r;
var v2 = c2.diffed;
var l3 = c2.__c;
var m2 = c2.unmount;
var s3 = c2.__;
function p2(n3, t4) {
  c2.__h && c2.__h(r2, n3, o2 || t4), o2 = 0;
  var u4 = r2.__H || (r2.__H = { __: [], __h: [] });
  return n3 >= u4.__.length && u4.__.push({}), u4.__[n3];
}
function d2(n3) {
  return o2 = 1, h2(D2, n3);
}
function h2(n3, u4, i4) {
  var o3 = p2(t2++, 2);
  if (o3.t = n3, !o3.__c && (o3.__ = [i4 ? i4(u4) : D2(void 0, u4), function(n4) {
    var t4 = o3.__N ? o3.__N[0] : o3.__[0], r3 = o3.t(t4, n4);
    t4 !== r3 && (o3.__N = [r3, o3.__[1]], o3.__c.setState({}));
  }], o3.__c = r2, !r2.__f)) {
    var f4 = function(n4, t4, r3) {
      if (!o3.__c.__H)
        return true;
      var u5 = o3.__c.__H.__.filter(function(n5) {
        return !!n5.__c;
      });
      if (u5.every(function(n5) {
        return !n5.__N;
      }))
        return !c3 || c3.call(this, n4, t4, r3);
      var i5 = o3.__c.props !== n4;
      return u5.forEach(function(n5) {
        if (n5.__N) {
          var t5 = n5.__[0];
          n5.__ = n5.__N, n5.__N = void 0, t5 !== n5.__[0] && (i5 = true);
        }
      }), c3 && c3.call(this, n4, t4, r3) || i5;
    };
    r2.__f = true;
    var c3 = r2.shouldComponentUpdate, e3 = r2.componentWillUpdate;
    r2.componentWillUpdate = function(n4, t4, r3) {
      if (this.__e) {
        var u5 = c3;
        c3 = void 0, f4(n4, t4, r3), c3 = u5;
      }
      e3 && e3.call(this, n4, t4, r3);
    }, r2.shouldComponentUpdate = f4;
  }
  return o3.__N || o3.__;
}
function y2(n3, u4) {
  var i4 = p2(t2++, 3);
  !c2.__s && C2(i4.__H, u4) && (i4.__ = n3, i4.u = u4, r2.__H.__h.push(i4));
}
function _2(n3, u4) {
  var i4 = p2(t2++, 4);
  !c2.__s && C2(i4.__H, u4) && (i4.__ = n3, i4.u = u4, r2.__h.push(i4));
}
function A2(n3) {
  return o2 = 5, T2(function() {
    return { current: n3 };
  }, []);
}
function F2(n3, t4, r3) {
  o2 = 6, _2(function() {
    if ("function" == typeof n3) {
      var r4 = n3(t4());
      return function() {
        n3(null), r4 && "function" == typeof r4 && r4();
      };
    }
    if (n3)
      return n3.current = t4(), function() {
        return n3.current = null;
      };
  }, null == r3 ? r3 : r3.concat(n3));
}
function T2(n3, r3) {
  var u4 = p2(t2++, 7);
  return C2(u4.__H, r3) && (u4.__ = n3(), u4.__H = r3, u4.__h = n3), u4.__;
}
function q2(n3, t4) {
  return o2 = 8, T2(function() {
    return n3;
  }, t4);
}
function x2(n3) {
  var u4 = r2.context[n3.__c], i4 = p2(t2++, 9);
  return i4.c = n3, u4 ? (null == i4.__ && (i4.__ = true, u4.sub(r2)), u4.props.value) : n3.__;
}
function P4(n3, t4) {
  c2.useDebugValue && c2.useDebugValue(t4 ? t4(n3) : n3);
}
function b2(n3) {
  var u4 = p2(t2++, 10), i4 = d2();
  return u4.__ = n3, r2.componentDidCatch || (r2.componentDidCatch = function(n4, t4) {
    u4.__ && u4.__(n4, t4), i4[1](n4);
  }), [i4[0], function() {
    i4[1](void 0);
  }];
}
function g2() {
  var n3 = p2(t2++, 11);
  if (!n3.__) {
    for (var u4 = r2.__v; null !== u4 && !u4.__m && null !== u4.__; )
      u4 = u4.__;
    var i4 = u4.__m || (u4.__m = [0, 0]);
    n3.__ = "P" + i4[0] + "-" + i4[1]++;
  }
  return n3.__;
}
function j2() {
  for (var n3; n3 = f2.shift(); )
    if (n3.__P && n3.__H)
      try {
        n3.__H.__h.forEach(z2), n3.__H.__h.forEach(B2), n3.__H.__h = [];
      } catch (t4) {
        n3.__H.__h = [], c2.__e(t4, n3.__v);
      }
}
c2.__b = function(n3) {
  r2 = null, e2 && e2(n3);
}, c2.__ = function(n3, t4) {
  n3 && t4.__k && t4.__k.__m && (n3.__m = t4.__k.__m), s3 && s3(n3, t4);
}, c2.__r = function(n3) {
  a2 && a2(n3), t2 = 0;
  var i4 = (r2 = n3.__c).__H;
  i4 && (u2 === r2 ? (i4.__h = [], r2.__h = [], i4.__.forEach(function(n4) {
    n4.__N && (n4.__ = n4.__N), n4.u = n4.__N = void 0;
  })) : (i4.__h.forEach(z2), i4.__h.forEach(B2), i4.__h = [], t2 = 0)), u2 = r2;
}, c2.diffed = function(n3) {
  v2 && v2(n3);
  var t4 = n3.__c;
  t4 && t4.__H && (t4.__H.__h.length && (1 !== f2.push(t4) && i2 === c2.requestAnimationFrame || ((i2 = c2.requestAnimationFrame) || w2)(j2)), t4.__H.__.forEach(function(n4) {
    n4.u && (n4.__H = n4.u), n4.u = void 0;
  })), u2 = r2 = null;
}, c2.__c = function(n3, t4) {
  t4.some(function(n4) {
    try {
      n4.__h.forEach(z2), n4.__h = n4.__h.filter(function(n5) {
        return !n5.__ || B2(n5);
      });
    } catch (r3) {
      t4.some(function(n5) {
        n5.__h && (n5.__h = []);
      }), t4 = [], c2.__e(r3, n4.__v);
    }
  }), l3 && l3(n3, t4);
}, c2.unmount = function(n3) {
  m2 && m2(n3);
  var t4, r3 = n3.__c;
  r3 && r3.__H && (r3.__H.__.forEach(function(n4) {
    try {
      z2(n4);
    } catch (n5) {
      t4 = n5;
    }
  }), r3.__H = void 0, t4 && c2.__e(t4, r3.__v));
};
var k2 = "function" == typeof requestAnimationFrame;
function w2(n3) {
  var t4, r3 = function() {
    clearTimeout(u4), k2 && cancelAnimationFrame(t4), setTimeout(n3);
  }, u4 = setTimeout(r3, 35);
  k2 && (t4 = requestAnimationFrame(r3));
}
function z2(n3) {
  var t4 = r2, u4 = n3.__c;
  "function" == typeof u4 && (n3.__c = void 0, u4()), r2 = t4;
}
function B2(n3) {
  var t4 = r2;
  n3.__c = n3.__(), r2 = t4;
}
function C2(n3, t4) {
  return !n3 || n3.length !== t4.length || t4.some(function(t5, r3) {
    return t5 !== n3[r3];
  });
}
function D2(n3, t4) {
  return "function" == typeof t4 ? t4(n3) : t4;
}

// node_modules/preact/compat/dist/compat.module.js
function g3(n3, t4) {
  for (var e3 in t4)
    n3[e3] = t4[e3];
  return n3;
}
function E2(n3, t4) {
  for (var e3 in n3)
    if ("__source" !== e3 && !(e3 in t4))
      return true;
  for (var r3 in t4)
    if ("__source" !== r3 && n3[r3] !== t4[r3])
      return true;
  return false;
}
function C3(n3, t4) {
  var e3 = t4(), r3 = d2({ t: { __: e3, u: t4 } }), u4 = r3[0].t, o3 = r3[1];
  return _2(function() {
    u4.__ = e3, u4.u = t4, x3(u4) && o3({ t: u4 });
  }, [n3, e3, t4]), y2(function() {
    return x3(u4) && o3({ t: u4 }), n3(function() {
      x3(u4) && o3({ t: u4 });
    });
  }, [n3]), e3;
}
function x3(n3) {
  var t4, e3, r3 = n3.u, u4 = n3.__;
  try {
    var o3 = r3();
    return !((t4 = u4) === (e3 = o3) && (0 !== t4 || 1 / t4 == 1 / e3) || t4 != t4 && e3 != e3);
  } catch (n4) {
    return true;
  }
}
function R(n3) {
  n3();
}
function w3(n3) {
  return n3;
}
function k3() {
  return [false, R];
}
var I2 = _2;
function N2(n3, t4) {
  this.props = n3, this.context = t4;
}
function M2(n3, e3) {
  function r3(n4) {
    var t4 = this.props.ref, r4 = t4 == n4.ref;
    return !r4 && t4 && (t4.call ? t4(null) : t4.current = null), e3 ? !e3(this.props, n4) || !r4 : E2(this.props, n4);
  }
  function u4(e4) {
    return this.shouldComponentUpdate = r3, _(n3, e4);
  }
  return u4.displayName = "Memo(" + (n3.displayName || n3.name) + ")", u4.prototype.isReactComponent = true, u4.__f = true, u4;
}
(N2.prototype = new x()).isPureReactComponent = true, N2.prototype.shouldComponentUpdate = function(n3, t4) {
  return E2(this.props, n3) || E2(this.state, t4);
};
var T3 = l2.__b;
l2.__b = function(n3) {
  n3.type && n3.type.__f && n3.ref && (n3.props.ref = n3.ref, n3.ref = null), T3 && T3(n3);
};
var A3 = "undefined" != typeof Symbol && Symbol.for && Symbol.for("react.forward_ref") || 3911;
function D3(n3) {
  function t4(t5) {
    var e3 = g3({}, t5);
    return delete e3.ref, n3(e3, t5.ref || null);
  }
  return t4.$$typeof = A3, t4.render = t4, t4.prototype.isReactComponent = t4.__f = true, t4.displayName = "ForwardRef(" + (n3.displayName || n3.name) + ")", t4;
}
var L2 = function(n3, t4) {
  return null == n3 ? null : H(H(n3).map(t4));
};
var O2 = { map: L2, forEach: L2, count: function(n3) {
  return n3 ? H(n3).length : 0;
}, only: function(n3) {
  var t4 = H(n3);
  if (1 !== t4.length)
    throw "Children.only";
  return t4[0];
}, toArray: H };
var F3 = l2.__e;
l2.__e = function(n3, t4, e3, r3) {
  if (n3.then) {
    for (var u4, o3 = t4; o3 = o3.__; )
      if ((u4 = o3.__c) && u4.__c)
        return null == t4.__e && (t4.__e = e3.__e, t4.__k = e3.__k), u4.__c(n3, t4);
  }
  F3(n3, t4, e3, r3);
};
var U = l2.unmount;
function V2(n3, t4, e3) {
  return n3 && (n3.__c && n3.__c.__H && (n3.__c.__H.__.forEach(function(n4) {
    "function" == typeof n4.__c && n4.__c();
  }), n3.__c.__H = null), null != (n3 = g3({}, n3)).__c && (n3.__c.__P === e3 && (n3.__c.__P = t4), n3.__c.__e = true, n3.__c = null), n3.__k = n3.__k && n3.__k.map(function(n4) {
    return V2(n4, t4, e3);
  })), n3;
}
function W(n3, t4, e3) {
  return n3 && e3 && (n3.__v = null, n3.__k = n3.__k && n3.__k.map(function(n4) {
    return W(n4, t4, e3);
  }), n3.__c && n3.__c.__P === t4 && (n3.__e && e3.appendChild(n3.__e), n3.__c.__e = true, n3.__c.__P = e3)), n3;
}
function P5() {
  this.__u = 0, this.o = null, this.__b = null;
}
function j3(n3) {
  var t4 = n3.__.__c;
  return t4 && t4.__a && t4.__a(n3);
}
function z3(n3) {
  var e3, r3, u4;
  function o3(o4) {
    if (e3 || (e3 = n3()).then(function(n4) {
      r3 = n4.default || n4;
    }, function(n4) {
      u4 = n4;
    }), u4)
      throw u4;
    if (!r3)
      throw e3;
    return _(r3, o4);
  }
  return o3.displayName = "Lazy", o3.__f = true, o3;
}
function B3() {
  this.i = null, this.l = null;
}
l2.unmount = function(n3) {
  var t4 = n3.__c;
  t4 && t4.__R && t4.__R(), t4 && 32 & n3.__u && (n3.type = null), U && U(n3);
}, (P5.prototype = new x()).__c = function(n3, t4) {
  var e3 = t4.__c, r3 = this;
  null == r3.o && (r3.o = []), r3.o.push(e3);
  var u4 = j3(r3.__v), o3 = false, i4 = function() {
    o3 || (o3 = true, e3.__R = null, u4 ? u4(l4) : l4());
  };
  e3.__R = i4;
  var l4 = function() {
    if (!--r3.__u) {
      if (r3.state.__a) {
        var n4 = r3.state.__a;
        r3.__v.__k[0] = W(n4, n4.__c.__P, n4.__c.__O);
      }
      var t5;
      for (r3.setState({ __a: r3.__b = null }); t5 = r3.o.pop(); )
        t5.forceUpdate();
    }
  };
  r3.__u++ || 32 & t4.__u || r3.setState({ __a: r3.__b = r3.__v.__k[0] }), n3.then(i4, i4);
}, P5.prototype.componentWillUnmount = function() {
  this.o = [];
}, P5.prototype.render = function(n3, e3) {
  if (this.__b) {
    if (this.__v.__k) {
      var r3 = document.createElement("div"), o3 = this.__v.__k[0].__c;
      this.__v.__k[0] = V2(this.__b, r3, o3.__O = o3.__P);
    }
    this.__b = null;
  }
  var i4 = e3.__a && _(k, null, n3.fallback);
  return i4 && (i4.__u &= -33), [_(k, null, e3.__a ? null : n3.children), i4];
};
var H2 = function(n3, t4, e3) {
  if (++e3[1] === e3[0] && n3.l.delete(t4), n3.props.revealOrder && ("t" !== n3.props.revealOrder[0] || !n3.l.size))
    for (e3 = n3.i; e3; ) {
      for (; e3.length > 3; )
        e3.pop()();
      if (e3[1] < e3[0])
        break;
      n3.i = e3 = e3[2];
    }
};
function Z(n3) {
  return this.getChildContext = function() {
    return n3.context;
  }, n3.children;
}
function Y(n3) {
  var e3 = this, r3 = n3.h;
  if (e3.componentWillUnmount = function() {
    E(null, e3.v), e3.v = null, e3.h = null;
  }, e3.h && e3.h !== r3 && e3.componentWillUnmount(), !e3.v) {
    for (var u4 = e3.__v; null !== u4 && !u4.__m && null !== u4.__; )
      u4 = u4.__;
    e3.h = r3, e3.v = { nodeType: 1, parentNode: r3, childNodes: [], __k: { __m: u4.__m }, contains: function() {
      return true;
    }, insertBefore: function(n4, t4) {
      this.childNodes.push(n4), e3.h.insertBefore(n4, t4);
    }, removeChild: function(n4) {
      this.childNodes.splice(this.childNodes.indexOf(n4) >>> 1, 1), e3.h.removeChild(n4);
    } };
  }
  E(_(Z, { context: e3.context }, n3.__v), e3.v);
}
function $2(n3, e3) {
  var r3 = _(Y, { __v: n3, h: e3 });
  return r3.containerInfo = e3, r3;
}
(B3.prototype = new x()).__a = function(n3) {
  var t4 = this, e3 = j3(t4.__v), r3 = t4.l.get(n3);
  return r3[0]++, function(u4) {
    var o3 = function() {
      t4.props.revealOrder ? (r3.push(u4), H2(t4, n3, r3)) : u4();
    };
    e3 ? e3(o3) : o3();
  };
}, B3.prototype.render = function(n3) {
  this.i = null, this.l = /* @__PURE__ */ new Map();
  var t4 = H(n3.children);
  n3.revealOrder && "b" === n3.revealOrder[0] && t4.reverse();
  for (var e3 = t4.length; e3--; )
    this.l.set(t4[e3], this.i = [1, 0, this.i]);
  return n3.children;
}, B3.prototype.componentDidUpdate = B3.prototype.componentDidMount = function() {
  var n3 = this;
  this.l.forEach(function(t4, e3) {
    H2(n3, e3, t4);
  });
};
var q3 = "undefined" != typeof Symbol && Symbol.for && Symbol.for("react.element") || 60103;
var G2 = /^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/;
var J2 = /^on(Ani|Tra|Tou|BeforeInp|Compo)/;
var K2 = /[A-Z0-9]/g;
var Q = "undefined" != typeof document;
var X = function(n3) {
  return ("undefined" != typeof Symbol && "symbol" == typeof Symbol() ? /fil|che|rad/ : /fil|che|ra/).test(n3);
};
function nn(n3, t4, e3) {
  return null == t4.__k && (t4.textContent = ""), E(n3, t4), "function" == typeof e3 && e3(), n3 ? n3.__c : null;
}
function tn(n3, t4, e3) {
  return G(n3, t4), "function" == typeof e3 && e3(), n3 ? n3.__c : null;
}
x.prototype.isReactComponent = {}, ["componentWillMount", "componentWillReceiveProps", "componentWillUpdate"].forEach(function(t4) {
  Object.defineProperty(x.prototype, t4, { configurable: true, get: function() {
    return this["UNSAFE_" + t4];
  }, set: function(n3) {
    Object.defineProperty(this, t4, { configurable: true, writable: true, value: n3 });
  } });
});
var en = l2.event;
function rn() {
}
function un() {
  return this.cancelBubble;
}
function on() {
  return this.defaultPrevented;
}
l2.event = function(n3) {
  return en && (n3 = en(n3)), n3.persist = rn, n3.isPropagationStopped = un, n3.isDefaultPrevented = on, n3.nativeEvent = n3;
};
var ln;
var cn = { enumerable: false, configurable: true, get: function() {
  return this.class;
} };
var fn = l2.vnode;
l2.vnode = function(n3) {
  "string" == typeof n3.type && function(n4) {
    var t4 = n4.props, e3 = n4.type, u4 = {}, o3 = -1 === e3.indexOf("-");
    for (var i4 in t4) {
      var l4 = t4[i4];
      if (!("value" === i4 && "defaultValue" in t4 && null == l4 || Q && "children" === i4 && "noscript" === e3 || "class" === i4 || "className" === i4)) {
        var c3 = i4.toLowerCase();
        "defaultValue" === i4 && "value" in t4 && null == t4.value ? i4 = "value" : "download" === i4 && true === l4 ? l4 = "" : "translate" === c3 && "no" === l4 ? l4 = false : "o" === c3[0] && "n" === c3[1] ? "ondoubleclick" === c3 ? i4 = "ondblclick" : "onchange" !== c3 || "input" !== e3 && "textarea" !== e3 || X(t4.type) ? "onfocus" === c3 ? i4 = "onfocusin" : "onblur" === c3 ? i4 = "onfocusout" : J2.test(i4) && (i4 = c3) : c3 = i4 = "oninput" : o3 && G2.test(i4) ? i4 = i4.replace(K2, "-$&").toLowerCase() : null === l4 && (l4 = void 0), "oninput" === c3 && u4[i4 = c3] && (i4 = "oninputCapture"), u4[i4] = l4;
      }
    }
    "select" == e3 && u4.multiple && Array.isArray(u4.value) && (u4.value = H(t4.children).forEach(function(n5) {
      n5.props.selected = -1 != u4.value.indexOf(n5.props.value);
    })), "select" == e3 && null != u4.defaultValue && (u4.value = H(t4.children).forEach(function(n5) {
      n5.props.selected = u4.multiple ? -1 != u4.defaultValue.indexOf(n5.props.value) : u4.defaultValue == n5.props.value;
    })), t4.class && !t4.className ? (u4.class = t4.class, Object.defineProperty(u4, "className", cn)) : (t4.className && !t4.class || t4.class && t4.className) && (u4.class = u4.className = t4.className), n4.props = u4;
  }(n3), n3.$$typeof = q3, fn && fn(n3);
};
var an = l2.__r;
l2.__r = function(n3) {
  an && an(n3), ln = n3.__c;
};
var sn = l2.diffed;
l2.diffed = function(n3) {
  sn && sn(n3);
  var t4 = n3.props, e3 = n3.__e;
  null != e3 && "textarea" === n3.type && "value" in t4 && t4.value !== e3.value && (e3.value = null == t4.value ? "" : t4.value), ln = null;
};
var hn = { ReactCurrentDispatcher: { current: { readContext: function(n3) {
  return ln.__n[n3.__c].props.value;
}, useCallback: q2, useContext: x2, useDebugValue: P4, useDeferredValue: w3, useEffect: y2, useId: g2, useImperativeHandle: F2, useInsertionEffect: I2, useLayoutEffect: _2, useMemo: T2, useReducer: h2, useRef: A2, useState: d2, useSyncExternalStore: C3, useTransition: k3 } } };
function dn(n3) {
  return _.bind(null, n3);
}
function mn(n3) {
  return !!n3 && n3.$$typeof === q3;
}
function pn(n3) {
  return mn(n3) && n3.type === k;
}
function yn(n3) {
  return !!n3 && !!n3.displayName && ("string" == typeof n3.displayName || n3.displayName instanceof String) && n3.displayName.startsWith("Memo(");
}
function _n(n3) {
  return mn(n3) ? J.apply(null, arguments) : n3;
}
function bn(n3) {
  return !!n3.__k && (E(null, n3), true);
}
function Sn(n3) {
  return n3 && (n3.base || 1 === n3.nodeType && n3) || null;
}
var gn = function(n3, t4) {
  return n3(t4);
};
var En = function(n3, t4) {
  return n3(t4);
};
var Cn = k;
var xn = mn;
var Rn = { useState: d2, useId: g2, useReducer: h2, useEffect: y2, useLayoutEffect: _2, useInsertionEffect: I2, useTransition: k3, useDeferredValue: w3, useSyncExternalStore: C3, startTransition: R, useRef: A2, useImperativeHandle: F2, useMemo: T2, useCallback: q2, useContext: x2, useDebugValue: P4, version: "18.3.1", Children: O2, render: nn, hydrate: tn, unmountComponentAtNode: bn, createPortal: $2, createElement: _, createContext: K, createFactory: dn, cloneElement: _n, createRef: b, Fragment: k, isValidElement: mn, isElement: xn, isFragment: pn, isMemo: yn, findDOMNode: Sn, Component: x, PureComponent: N2, memo: M2, forwardRef: D3, flushSync: En, unstable_batchedUpdates: gn, StrictMode: Cn, Suspense: P5, SuspenseList: B3, lazy: z3, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: hn };

// node_modules/preact/jsx-runtime/dist/jsxRuntime.module.js
var f3 = 0;
var i3 = Array.isArray;
function u3(e3, t4, n3, o3, i4, u4) {
  t4 || (t4 = {});
  var a3, c3, p3 = t4;
  if ("ref" in p3)
    for (c3 in p3 = {}, t4)
      "ref" == c3 ? a3 = t4[c3] : p3[c3] = t4[c3];
  var l4 = { type: e3, props: p3, key: n3, ref: a3, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: void 0, __v: --f3, __i: -1, __u: 0, __source: i4, __self: u4 };
  if ("function" == typeof e3 && (a3 = e3.defaultProps))
    for (c3 in a3)
      void 0 === p3[c3] && (p3[c3] = a3[c3]);
  return l2.vnode && l2.vnode(l4), l4;
}

// src/api/ui/embed.tsx
function Embed({
  link,
  inline,
  sourcePath: maybeSourcePath
}) {
  var _a;
  const app = x2(APP_CONTEXT);
  const component = x2(COMPONENT_CONTEXT);
  const currentFile = x2(CURRENT_FILE_CONTEXT);
  const sourcePath = (_a = maybeSourcePath != null ? maybeSourcePath : currentFile) != null ? _a : "";
  const container = A2(null);
  const linkedFile = T2(
    () => app.metadataCache.getFirstLinkpathDest(link.path, sourcePath),
    [link.path, sourcePath]
  );
  y2(() => {
    if (!container.current)
      return;
    if (!linkedFile)
      return;
    container.current.replaceChildren(...[]);
    const creator = app.embedRegistry.getEmbedCreator(linkedFile);
    let embedComponent = new creator(
      {
        linktext: link.path,
        sourcePath,
        showInline: inline,
        app,
        depth: 0,
        containerEl: container.current,
        displayMode: true
      },
      linkedFile,
      link.subpath
    );
    component.addChild(embedComponent);
    embedComponent.loadFile(linkedFile);
    return () => component.removeChild(embedComponent);
  }, [container.current, linkedFile, link.subpath]);
  if (!linkedFile) {
    return /* @__PURE__ */ u3(ErrorMessage, { message: `Could not find a page at linked location: ${link.path}` });
  } else {
    return /* @__PURE__ */ u3("div", { className: "dc-embed", ref: container });
  }
}
function LineSpanEmbed({
  path,
  start,
  end,
  explain,
  showExplain = true
}) {
  var _a;
  const content = useLineSpan(path, start, end);
  const explainer = explain != null ? explain : `${getFileTitle(path)} (${start} - ${end})`;
  const workspace = (_a = x2(APP_CONTEXT)) == null ? void 0 : _a.workspace;
  const onExplainClick = q2(
    (event) => workspace == null ? void 0 : workspace.openLinkText(path, path, event.shiftKey),
    [path]
  );
  switch (content.type) {
    case "loading":
      return /* @__PURE__ */ u3(ErrorMessage, { message: `Reading ${path} (${start} - ${end})` });
    case "file-not-found":
      return /* @__PURE__ */ u3(ErrorMessage, { message: `Could not find a file at path: ${content.path}` });
    case "error":
      return /* @__PURE__ */ u3(ErrorMessage, { message: content.message });
    case "loaded":
      return /* @__PURE__ */ u3("div", { className: "datacore-span-embed", children: [
        showExplain && /* @__PURE__ */ u3("a", { className: "datacore-embed-source", onClick: onExplainClick, children: explainer }),
        /* @__PURE__ */ u3(Markdown, { content: content.content, inline: false })
      ] });
  }
}
function useLineSpan(path, start, end) {
  const app = x2(APP_CONTEXT);
  const datacore = x2(DATACORE_CONTEXT);
  const [state2, update] = h2(
    (state3, event) => {
      if (state3.type == "loaded" && event.type !== "loaded")
        return state3;
      else
        return event;
    },
    { type: "loading" }
  );
  y2(() => {
    const file = app.vault.getFileByPath(path);
    if (file == null) {
      update({ type: "file-not-found", path });
      return;
    }
    (async () => {
      try {
        const content = await datacore.read(file);
        update({ type: "loaded", content: lineRange(content, start, end) });
      } catch (error) {
        update({ type: "error", message: error instanceof Error ? error.message : String(error) });
      }
    })();
  }, [path, start, end]);
  return state2;
}

// src/ui/markdown.tsx
var COMPONENT_CONTEXT = K(void 0);
var APP_CONTEXT = K(void 0);
var DATACORE_CONTEXT = K(void 0);
var SETTINGS_CONTEXT = K(void 0);
var CURRENT_FILE_CONTEXT = K("");
function DatacoreContextProvider({
  children,
  app,
  component,
  datacore,
  settings
}) {
  return /* @__PURE__ */ u3(COMPONENT_CONTEXT.Provider, { value: component, children: /* @__PURE__ */ u3(APP_CONTEXT.Provider, { value: app, children: /* @__PURE__ */ u3(DATACORE_CONTEXT.Provider, { value: datacore, children: /* @__PURE__ */ u3(SETTINGS_CONTEXT.Provider, { value: settings, children }) }) }) });
}
function RawLink({ link, sourcePath: maybeSourcePath }) {
  var _a, _b;
  const workspace = (_a = x2(APP_CONTEXT)) == null ? void 0 : _a.workspace;
  const currentPath = x2(CURRENT_FILE_CONTEXT);
  const sourcePath = (_b = maybeSourcePath != null ? maybeSourcePath : currentPath) != null ? _b : "";
  const parsed = T2(() => Literals.isLink(link) ? link : Link.infer(link), [link]);
  const onClick = q2(
    (event) => {
      const newtab = event.shiftKey;
      workspace == null ? void 0 : workspace.openLinkText(parsed.obsidianLink(), sourcePath, newtab);
    },
    [parsed, sourcePath]
  );
  return /* @__PURE__ */ u3(
    "a",
    {
      "aria-label": parsed.displayOrDefault(),
      onClick,
      className: "internal-link",
      target: "_blank",
      rel: "noopener",
      "data-tooltip-position": "top",
      "data-href": parsed.obsidianLink(),
      href: parsed.obsidianLink(),
      children: parsed.displayOrDefault()
    }
  );
}
var ObsidianLink = M2(RawLink);
function RawMarkdown({
  content,
  sourcePath: maybeSourcePath,
  inline = true,
  style,
  cls,
  onClick
}) {
  const container = A2(null);
  const component = x2(COMPONENT_CONTEXT);
  const defaultPath = x2(CURRENT_FILE_CONTEXT);
  const app = x2(APP_CONTEXT);
  const sourcePath = maybeSourcePath != null ? maybeSourcePath : defaultPath;
  y2(() => {
    if (!container.current)
      return;
    container.current.replaceChildren(...[]);
    (async () => {
      var _a;
      if (!container.current)
        return;
      await import_obsidian.MarkdownRenderer.render(app, content, container.current, sourcePath, component);
      if (!container.current)
        return;
      if (inline) {
        let paragraph = container.current.querySelector("p");
        while (paragraph) {
          let children = paragraph.childNodes;
          paragraph.replaceWith(...Array.from(children));
          paragraph = container.current.querySelector("p");
        }
      }
      let embed = container.current.querySelector("span.internal-embed:not(.is-loaded)");
      while (embed) {
        embed.empty();
        E(
          /* @__PURE__ */ u3(APP_CONTEXT.Provider, { value: app, children: /* @__PURE__ */ u3(
            Embed,
            {
              link: Link.parseInner((_a = embed.getAttribute("src")) != null ? _a : ""),
              sourcePath,
              inline: true
            }
          ) }),
          embed
        );
        embed.addClass("is-loaded");
        embed = container.current.querySelector("span.internal-embed:not(.is-loaded)");
      }
    })();
  }, [content, sourcePath, inline, container.current]);
  return /* @__PURE__ */ u3("span", { ref: container, style, className: cls, onClick });
}
var Markdown = M2(RawMarkdown);
function RawLit({
  value,
  sourcePath: maybeSourcePath,
  inline = false,
  depth = 0
}) {
  var _a, _b;
  const settings = x2(SETTINGS_CONTEXT);
  const app = x2(APP_CONTEXT);
  const defaultPath = x2(CURRENT_FILE_CONTEXT);
  const sourcePath = maybeSourcePath != null ? maybeSourcePath : defaultPath;
  if (depth >= settings.maxRecursiveRenderDepth)
    return /* @__PURE__ */ u3(k, { children: "..." });
  if (Literals.isNull(value) || value === void 0) {
    return /* @__PURE__ */ u3(Markdown, { inline, content: settings.renderNullAs, sourcePath });
  } else if (Literals.isString(value)) {
    return /* @__PURE__ */ u3(Markdown, { inline, content: value, sourcePath });
  } else if (Literals.isNumber(value)) {
    return /* @__PURE__ */ u3(k, { children: "" + value });
  } else if (Literals.isBoolean(value)) {
    return /* @__PURE__ */ u3(k, { children: "" + value });
  } else if (Literals.isDate(value)) {
    return /* @__PURE__ */ u3(k, { children: renderMinimalDate(value, settings.defaultDateFormat, settings.defaultDateTimeFormat, currentLocale()) });
  } else if (Literals.isDuration(value)) {
    return /* @__PURE__ */ u3(k, { children: renderMinimalDuration(value) });
  } else if (Literals.isLink(value)) {
    if (isImageEmbed(value)) {
      let realFile = app.metadataCache.getFirstLinkpathDest(value.path, sourcePath);
      if (!realFile)
        return /* @__PURE__ */ u3(Markdown, { content: value.markdown(), sourcePath });
      let dimensions = extractImageDimensions(value);
      let resourcePath = app.vault.getResourcePath(realFile);
      if (dimensions && dimensions.length == 2)
        return /* @__PURE__ */ u3("img", { alt: value.path, src: resourcePath, width: dimensions[0], height: dimensions[1] });
      else if (dimensions && dimensions.length == 1)
        return /* @__PURE__ */ u3("img", { alt: value.path, src: resourcePath, width: dimensions[0] });
      else
        return /* @__PURE__ */ u3("img", { alt: value.path, src: resourcePath });
    } else if (value.embed) {
      return /* @__PURE__ */ u3(Embed, { link: value, sourcePath, inline });
    }
    return /* @__PURE__ */ u3(ObsidianLink, { link: value, sourcePath });
  } else if (Literals.isFunction(value)) {
    return /* @__PURE__ */ u3(k, { children: "<function>" });
  } else if (Literals.isArray(value)) {
    if (!inline) {
      return /* @__PURE__ */ u3("ul", { className: "dataview dataview-ul dataview-result-list-ul", children: value.map((subvalue) => /* @__PURE__ */ u3("li", { className: "dataview-result-list-li", children: /* @__PURE__ */ u3(Lit, { value: subvalue, sourcePath, inline, depth: depth + 1 }) })) });
    } else {
      if (value.length == 0)
        return /* @__PURE__ */ u3(k, { children: "<Empty List>" });
      return /* @__PURE__ */ u3("span", { className: "dataview dataview-result-list-span", children: value.map((subvalue, index) => /* @__PURE__ */ u3(k, { children: [
        index == 0 ? "" : ", ",
        /* @__PURE__ */ u3(Lit, { value: subvalue, sourcePath, inline, depth: depth + 1 })
      ] })) });
    }
  } else if (Literals.isObject(value)) {
    if (((_a = value == null ? void 0 : value.constructor) == null ? void 0 : _a.name) && ((_b = value == null ? void 0 : value.constructor) == null ? void 0 : _b.name) != "Object") {
      return /* @__PURE__ */ u3(k, { children: [
        "<",
        value.constructor.name,
        ">"
      ] });
    }
    if (!inline) {
      return /* @__PURE__ */ u3("ul", { className: "dataview dataview-ul dataview-result-object-ul", children: Object.entries(value).map(([key, value2]) => /* @__PURE__ */ u3("li", { className: "dataview dataview-li dataview-result-object-li", children: [
        key,
        ": ",
        /* @__PURE__ */ u3(Lit, { value: value2, sourcePath, inline, depth: depth + 1 })
      ] })) });
    } else {
      if (Object.keys(value).length == 0)
        return /* @__PURE__ */ u3(k, { children: "<Empty Object>" });
      return /* @__PURE__ */ u3("span", { className: "dataview dataview-result-object-span", children: Object.entries(value).map(([key, value2], index) => /* @__PURE__ */ u3(k, { children: [
        index == 0 ? "" : ", ",
        key,
        ": ",
        /* @__PURE__ */ u3(Lit, { value: value2, sourcePath, inline, depth: depth + 1 })
      ] })) });
    }
  }
  return /* @__PURE__ */ u3(k, { children: [
    "<Unrecognized: ",
    JSON.stringify(value),
    ">"
  ] });
}
var Lit = M2(RawLit);
function ErrorMessage({
  title,
  message,
  error,
  reset
}) {
  return /* @__PURE__ */ u3("div", { className: "datacore-error-box", children: [
    title && /* @__PURE__ */ u3("h4", { className: "datacore-error-title", children: title }),
    message && /* @__PURE__ */ u3("p", { className: "datacore-error-message", children: message }),
    error && /* @__PURE__ */ u3("pre", { className: "datacore-error-pre", children: error }),
    reset && /* @__PURE__ */ u3("button", { className: "datacore-error-retry", onClick: reset, children: "Rerun" })
  ] });
}
function SimpleErrorBoundary({
  title,
  message,
  children
}) {
  const [error, reset] = b2();
  if (error) {
    return /* @__PURE__ */ u3(ErrorMessage, { title, message, error: error.stack, reset });
  } else {
    return /* @__PURE__ */ u3(k, { children });
  }
}

// src/ui/javascript.tsx
var import_obsidian3 = require("obsidian");

// node_modules/sucrase/dist/esm/parser/tokenizer/keywords.js
var ContextualKeyword;
(function(ContextualKeyword2) {
  const NONE = 0;
  ContextualKeyword2[ContextualKeyword2["NONE"] = NONE] = "NONE";
  const _abstract = NONE + 1;
  ContextualKeyword2[ContextualKeyword2["_abstract"] = _abstract] = "_abstract";
  const _accessor = _abstract + 1;
  ContextualKeyword2[ContextualKeyword2["_accessor"] = _accessor] = "_accessor";
  const _as = _accessor + 1;
  ContextualKeyword2[ContextualKeyword2["_as"] = _as] = "_as";
  const _assert = _as + 1;
  ContextualKeyword2[ContextualKeyword2["_assert"] = _assert] = "_assert";
  const _asserts = _assert + 1;
  ContextualKeyword2[ContextualKeyword2["_asserts"] = _asserts] = "_asserts";
  const _async = _asserts + 1;
  ContextualKeyword2[ContextualKeyword2["_async"] = _async] = "_async";
  const _await = _async + 1;
  ContextualKeyword2[ContextualKeyword2["_await"] = _await] = "_await";
  const _checks = _await + 1;
  ContextualKeyword2[ContextualKeyword2["_checks"] = _checks] = "_checks";
  const _constructor = _checks + 1;
  ContextualKeyword2[ContextualKeyword2["_constructor"] = _constructor] = "_constructor";
  const _declare = _constructor + 1;
  ContextualKeyword2[ContextualKeyword2["_declare"] = _declare] = "_declare";
  const _enum = _declare + 1;
  ContextualKeyword2[ContextualKeyword2["_enum"] = _enum] = "_enum";
  const _exports = _enum + 1;
  ContextualKeyword2[ContextualKeyword2["_exports"] = _exports] = "_exports";
  const _from = _exports + 1;
  ContextualKeyword2[ContextualKeyword2["_from"] = _from] = "_from";
  const _get = _from + 1;
  ContextualKeyword2[ContextualKeyword2["_get"] = _get] = "_get";
  const _global = _get + 1;
  ContextualKeyword2[ContextualKeyword2["_global"] = _global] = "_global";
  const _implements = _global + 1;
  ContextualKeyword2[ContextualKeyword2["_implements"] = _implements] = "_implements";
  const _infer = _implements + 1;
  ContextualKeyword2[ContextualKeyword2["_infer"] = _infer] = "_infer";
  const _interface = _infer + 1;
  ContextualKeyword2[ContextualKeyword2["_interface"] = _interface] = "_interface";
  const _is = _interface + 1;
  ContextualKeyword2[ContextualKeyword2["_is"] = _is] = "_is";
  const _keyof = _is + 1;
  ContextualKeyword2[ContextualKeyword2["_keyof"] = _keyof] = "_keyof";
  const _mixins = _keyof + 1;
  ContextualKeyword2[ContextualKeyword2["_mixins"] = _mixins] = "_mixins";
  const _module = _mixins + 1;
  ContextualKeyword2[ContextualKeyword2["_module"] = _module] = "_module";
  const _namespace = _module + 1;
  ContextualKeyword2[ContextualKeyword2["_namespace"] = _namespace] = "_namespace";
  const _of = _namespace + 1;
  ContextualKeyword2[ContextualKeyword2["_of"] = _of] = "_of";
  const _opaque = _of + 1;
  ContextualKeyword2[ContextualKeyword2["_opaque"] = _opaque] = "_opaque";
  const _out = _opaque + 1;
  ContextualKeyword2[ContextualKeyword2["_out"] = _out] = "_out";
  const _override = _out + 1;
  ContextualKeyword2[ContextualKeyword2["_override"] = _override] = "_override";
  const _private = _override + 1;
  ContextualKeyword2[ContextualKeyword2["_private"] = _private] = "_private";
  const _protected = _private + 1;
  ContextualKeyword2[ContextualKeyword2["_protected"] = _protected] = "_protected";
  const _proto = _protected + 1;
  ContextualKeyword2[ContextualKeyword2["_proto"] = _proto] = "_proto";
  const _public = _proto + 1;
  ContextualKeyword2[ContextualKeyword2["_public"] = _public] = "_public";
  const _readonly = _public + 1;
  ContextualKeyword2[ContextualKeyword2["_readonly"] = _readonly] = "_readonly";
  const _require = _readonly + 1;
  ContextualKeyword2[ContextualKeyword2["_require"] = _require] = "_require";
  const _satisfies = _require + 1;
  ContextualKeyword2[ContextualKeyword2["_satisfies"] = _satisfies] = "_satisfies";
  const _set = _satisfies + 1;
  ContextualKeyword2[ContextualKeyword2["_set"] = _set] = "_set";
  const _static = _set + 1;
  ContextualKeyword2[ContextualKeyword2["_static"] = _static] = "_static";
  const _symbol = _static + 1;
  ContextualKeyword2[ContextualKeyword2["_symbol"] = _symbol] = "_symbol";
  const _type = _symbol + 1;
  ContextualKeyword2[ContextualKeyword2["_type"] = _type] = "_type";
  const _unique = _type + 1;
  ContextualKeyword2[ContextualKeyword2["_unique"] = _unique] = "_unique";
  const _using = _unique + 1;
  ContextualKeyword2[ContextualKeyword2["_using"] = _using] = "_using";
})(ContextualKeyword || (ContextualKeyword = {}));

// node_modules/sucrase/dist/esm/parser/tokenizer/types.js
var TokenType;
(function(TokenType2) {
  const PRECEDENCE_MASK = 15;
  TokenType2[TokenType2["PRECEDENCE_MASK"] = PRECEDENCE_MASK] = "PRECEDENCE_MASK";
  const IS_KEYWORD = 1 << 4;
  TokenType2[TokenType2["IS_KEYWORD"] = IS_KEYWORD] = "IS_KEYWORD";
  const IS_ASSIGN = 1 << 5;
  TokenType2[TokenType2["IS_ASSIGN"] = IS_ASSIGN] = "IS_ASSIGN";
  const IS_RIGHT_ASSOCIATIVE = 1 << 6;
  TokenType2[TokenType2["IS_RIGHT_ASSOCIATIVE"] = IS_RIGHT_ASSOCIATIVE] = "IS_RIGHT_ASSOCIATIVE";
  const IS_PREFIX = 1 << 7;
  TokenType2[TokenType2["IS_PREFIX"] = IS_PREFIX] = "IS_PREFIX";
  const IS_POSTFIX = 1 << 8;
  TokenType2[TokenType2["IS_POSTFIX"] = IS_POSTFIX] = "IS_POSTFIX";
  const IS_EXPRESSION_START = 1 << 9;
  TokenType2[TokenType2["IS_EXPRESSION_START"] = IS_EXPRESSION_START] = "IS_EXPRESSION_START";
  const num = 512;
  TokenType2[TokenType2["num"] = num] = "num";
  const bigint = 1536;
  TokenType2[TokenType2["bigint"] = bigint] = "bigint";
  const decimal = 2560;
  TokenType2[TokenType2["decimal"] = decimal] = "decimal";
  const regexp3 = 3584;
  TokenType2[TokenType2["regexp"] = regexp3] = "regexp";
  const string2 = 4608;
  TokenType2[TokenType2["string"] = string2] = "string";
  const name = 5632;
  TokenType2[TokenType2["name"] = name] = "name";
  const eof = 6144;
  TokenType2[TokenType2["eof"] = eof] = "eof";
  const bracketL = 7680;
  TokenType2[TokenType2["bracketL"] = bracketL] = "bracketL";
  const bracketR = 8192;
  TokenType2[TokenType2["bracketR"] = bracketR] = "bracketR";
  const braceL = 9728;
  TokenType2[TokenType2["braceL"] = braceL] = "braceL";
  const braceBarL = 10752;
  TokenType2[TokenType2["braceBarL"] = braceBarL] = "braceBarL";
  const braceR = 11264;
  TokenType2[TokenType2["braceR"] = braceR] = "braceR";
  const braceBarR = 12288;
  TokenType2[TokenType2["braceBarR"] = braceBarR] = "braceBarR";
  const parenL = 13824;
  TokenType2[TokenType2["parenL"] = parenL] = "parenL";
  const parenR = 14336;
  TokenType2[TokenType2["parenR"] = parenR] = "parenR";
  const comma2 = 15360;
  TokenType2[TokenType2["comma"] = comma2] = "comma";
  const semi = 16384;
  TokenType2[TokenType2["semi"] = semi] = "semi";
  const colon = 17408;
  TokenType2[TokenType2["colon"] = colon] = "colon";
  const doubleColon = 18432;
  TokenType2[TokenType2["doubleColon"] = doubleColon] = "doubleColon";
  const dot = 19456;
  TokenType2[TokenType2["dot"] = dot] = "dot";
  const question = 20480;
  TokenType2[TokenType2["question"] = question] = "question";
  const questionDot = 21504;
  TokenType2[TokenType2["questionDot"] = questionDot] = "questionDot";
  const arrow = 22528;
  TokenType2[TokenType2["arrow"] = arrow] = "arrow";
  const template = 23552;
  TokenType2[TokenType2["template"] = template] = "template";
  const ellipsis = 24576;
  TokenType2[TokenType2["ellipsis"] = ellipsis] = "ellipsis";
  const backQuote = 25600;
  TokenType2[TokenType2["backQuote"] = backQuote] = "backQuote";
  const dollarBraceL = 27136;
  TokenType2[TokenType2["dollarBraceL"] = dollarBraceL] = "dollarBraceL";
  const at = 27648;
  TokenType2[TokenType2["at"] = at] = "at";
  const hash = 29184;
  TokenType2[TokenType2["hash"] = hash] = "hash";
  const eq = 29728;
  TokenType2[TokenType2["eq"] = eq] = "eq";
  const assign = 30752;
  TokenType2[TokenType2["assign"] = assign] = "assign";
  const preIncDec = 32640;
  TokenType2[TokenType2["preIncDec"] = preIncDec] = "preIncDec";
  const postIncDec = 33664;
  TokenType2[TokenType2["postIncDec"] = postIncDec] = "postIncDec";
  const bang = 34432;
  TokenType2[TokenType2["bang"] = bang] = "bang";
  const tilde = 35456;
  TokenType2[TokenType2["tilde"] = tilde] = "tilde";
  const pipeline = 35841;
  TokenType2[TokenType2["pipeline"] = pipeline] = "pipeline";
  const nullishCoalescing = 36866;
  TokenType2[TokenType2["nullishCoalescing"] = nullishCoalescing] = "nullishCoalescing";
  const logicalOR = 37890;
  TokenType2[TokenType2["logicalOR"] = logicalOR] = "logicalOR";
  const logicalAND = 38915;
  TokenType2[TokenType2["logicalAND"] = logicalAND] = "logicalAND";
  const bitwiseOR = 39940;
  TokenType2[TokenType2["bitwiseOR"] = bitwiseOR] = "bitwiseOR";
  const bitwiseXOR = 40965;
  TokenType2[TokenType2["bitwiseXOR"] = bitwiseXOR] = "bitwiseXOR";
  const bitwiseAND = 41990;
  TokenType2[TokenType2["bitwiseAND"] = bitwiseAND] = "bitwiseAND";
  const equality = 43015;
  TokenType2[TokenType2["equality"] = equality] = "equality";
  const lessThan = 44040;
  TokenType2[TokenType2["lessThan"] = lessThan] = "lessThan";
  const greaterThan = 45064;
  TokenType2[TokenType2["greaterThan"] = greaterThan] = "greaterThan";
  const relationalOrEqual = 46088;
  TokenType2[TokenType2["relationalOrEqual"] = relationalOrEqual] = "relationalOrEqual";
  const bitShiftL = 47113;
  TokenType2[TokenType2["bitShiftL"] = bitShiftL] = "bitShiftL";
  const bitShiftR = 48137;
  TokenType2[TokenType2["bitShiftR"] = bitShiftR] = "bitShiftR";
  const plus = 49802;
  TokenType2[TokenType2["plus"] = plus] = "plus";
  const minus = 50826;
  TokenType2[TokenType2["minus"] = minus] = "minus";
  const modulo = 51723;
  TokenType2[TokenType2["modulo"] = modulo] = "modulo";
  const star = 52235;
  TokenType2[TokenType2["star"] = star] = "star";
  const slash = 53259;
  TokenType2[TokenType2["slash"] = slash] = "slash";
  const exponent = 54348;
  TokenType2[TokenType2["exponent"] = exponent] = "exponent";
  const jsxName = 55296;
  TokenType2[TokenType2["jsxName"] = jsxName] = "jsxName";
  const jsxText = 56320;
  TokenType2[TokenType2["jsxText"] = jsxText] = "jsxText";
  const jsxEmptyText = 57344;
  TokenType2[TokenType2["jsxEmptyText"] = jsxEmptyText] = "jsxEmptyText";
  const jsxTagStart = 58880;
  TokenType2[TokenType2["jsxTagStart"] = jsxTagStart] = "jsxTagStart";
  const jsxTagEnd = 59392;
  TokenType2[TokenType2["jsxTagEnd"] = jsxTagEnd] = "jsxTagEnd";
  const typeParameterStart = 60928;
  TokenType2[TokenType2["typeParameterStart"] = typeParameterStart] = "typeParameterStart";
  const nonNullAssertion = 61440;
  TokenType2[TokenType2["nonNullAssertion"] = nonNullAssertion] = "nonNullAssertion";
  const _break = 62480;
  TokenType2[TokenType2["_break"] = _break] = "_break";
  const _case = 63504;
  TokenType2[TokenType2["_case"] = _case] = "_case";
  const _catch = 64528;
  TokenType2[TokenType2["_catch"] = _catch] = "_catch";
  const _continue = 65552;
  TokenType2[TokenType2["_continue"] = _continue] = "_continue";
  const _debugger = 66576;
  TokenType2[TokenType2["_debugger"] = _debugger] = "_debugger";
  const _default = 67600;
  TokenType2[TokenType2["_default"] = _default] = "_default";
  const _do = 68624;
  TokenType2[TokenType2["_do"] = _do] = "_do";
  const _else = 69648;
  TokenType2[TokenType2["_else"] = _else] = "_else";
  const _finally = 70672;
  TokenType2[TokenType2["_finally"] = _finally] = "_finally";
  const _for = 71696;
  TokenType2[TokenType2["_for"] = _for] = "_for";
  const _function = 73232;
  TokenType2[TokenType2["_function"] = _function] = "_function";
  const _if = 73744;
  TokenType2[TokenType2["_if"] = _if] = "_if";
  const _return = 74768;
  TokenType2[TokenType2["_return"] = _return] = "_return";
  const _switch = 75792;
  TokenType2[TokenType2["_switch"] = _switch] = "_switch";
  const _throw = 77456;
  TokenType2[TokenType2["_throw"] = _throw] = "_throw";
  const _try = 77840;
  TokenType2[TokenType2["_try"] = _try] = "_try";
  const _var = 78864;
  TokenType2[TokenType2["_var"] = _var] = "_var";
  const _let = 79888;
  TokenType2[TokenType2["_let"] = _let] = "_let";
  const _const = 80912;
  TokenType2[TokenType2["_const"] = _const] = "_const";
  const _while = 81936;
  TokenType2[TokenType2["_while"] = _while] = "_while";
  const _with = 82960;
  TokenType2[TokenType2["_with"] = _with] = "_with";
  const _new = 84496;
  TokenType2[TokenType2["_new"] = _new] = "_new";
  const _this = 85520;
  TokenType2[TokenType2["_this"] = _this] = "_this";
  const _super = 86544;
  TokenType2[TokenType2["_super"] = _super] = "_super";
  const _class = 87568;
  TokenType2[TokenType2["_class"] = _class] = "_class";
  const _extends = 88080;
  TokenType2[TokenType2["_extends"] = _extends] = "_extends";
  const _export = 89104;
  TokenType2[TokenType2["_export"] = _export] = "_export";
  const _import = 90640;
  TokenType2[TokenType2["_import"] = _import] = "_import";
  const _yield = 91664;
  TokenType2[TokenType2["_yield"] = _yield] = "_yield";
  const _null = 92688;
  TokenType2[TokenType2["_null"] = _null] = "_null";
  const _true = 93712;
  TokenType2[TokenType2["_true"] = _true] = "_true";
  const _false = 94736;
  TokenType2[TokenType2["_false"] = _false] = "_false";
  const _in = 95256;
  TokenType2[TokenType2["_in"] = _in] = "_in";
  const _instanceof = 96280;
  TokenType2[TokenType2["_instanceof"] = _instanceof] = "_instanceof";
  const _typeof = 97936;
  TokenType2[TokenType2["_typeof"] = _typeof] = "_typeof";
  const _void = 98960;
  TokenType2[TokenType2["_void"] = _void] = "_void";
  const _delete = 99984;
  TokenType2[TokenType2["_delete"] = _delete] = "_delete";
  const _async = 100880;
  TokenType2[TokenType2["_async"] = _async] = "_async";
  const _get = 101904;
  TokenType2[TokenType2["_get"] = _get] = "_get";
  const _set = 102928;
  TokenType2[TokenType2["_set"] = _set] = "_set";
  const _declare = 103952;
  TokenType2[TokenType2["_declare"] = _declare] = "_declare";
  const _readonly = 104976;
  TokenType2[TokenType2["_readonly"] = _readonly] = "_readonly";
  const _abstract = 106e3;
  TokenType2[TokenType2["_abstract"] = _abstract] = "_abstract";
  const _static = 107024;
  TokenType2[TokenType2["_static"] = _static] = "_static";
  const _public = 107536;
  TokenType2[TokenType2["_public"] = _public] = "_public";
  const _private = 108560;
  TokenType2[TokenType2["_private"] = _private] = "_private";
  const _protected = 109584;
  TokenType2[TokenType2["_protected"] = _protected] = "_protected";
  const _override = 110608;
  TokenType2[TokenType2["_override"] = _override] = "_override";
  const _as = 112144;
  TokenType2[TokenType2["_as"] = _as] = "_as";
  const _enum = 113168;
  TokenType2[TokenType2["_enum"] = _enum] = "_enum";
  const _type = 114192;
  TokenType2[TokenType2["_type"] = _type] = "_type";
  const _implements = 115216;
  TokenType2[TokenType2["_implements"] = _implements] = "_implements";
})(TokenType || (TokenType = {}));
function formatTokenType(tokenType) {
  switch (tokenType) {
    case TokenType.num:
      return "num";
    case TokenType.bigint:
      return "bigint";
    case TokenType.decimal:
      return "decimal";
    case TokenType.regexp:
      return "regexp";
    case TokenType.string:
      return "string";
    case TokenType.name:
      return "name";
    case TokenType.eof:
      return "eof";
    case TokenType.bracketL:
      return "[";
    case TokenType.bracketR:
      return "]";
    case TokenType.braceL:
      return "{";
    case TokenType.braceBarL:
      return "{|";
    case TokenType.braceR:
      return "}";
    case TokenType.braceBarR:
      return "|}";
    case TokenType.parenL:
      return "(";
    case TokenType.parenR:
      return ")";
    case TokenType.comma:
      return ",";
    case TokenType.semi:
      return ";";
    case TokenType.colon:
      return ":";
    case TokenType.doubleColon:
      return "::";
    case TokenType.dot:
      return ".";
    case TokenType.question:
      return "?";
    case TokenType.questionDot:
      return "?.";
    case TokenType.arrow:
      return "=>";
    case TokenType.template:
      return "template";
    case TokenType.ellipsis:
      return "...";
    case TokenType.backQuote:
      return "`";
    case TokenType.dollarBraceL:
      return "${";
    case TokenType.at:
      return "@";
    case TokenType.hash:
      return "#";
    case TokenType.eq:
      return "=";
    case TokenType.assign:
      return "_=";
    case TokenType.preIncDec:
      return "++/--";
    case TokenType.postIncDec:
      return "++/--";
    case TokenType.bang:
      return "!";
    case TokenType.tilde:
      return "~";
    case TokenType.pipeline:
      return "|>";
    case TokenType.nullishCoalescing:
      return "??";
    case TokenType.logicalOR:
      return "||";
    case TokenType.logicalAND:
      return "&&";
    case TokenType.bitwiseOR:
      return "|";
    case TokenType.bitwiseXOR:
      return "^";
    case TokenType.bitwiseAND:
      return "&";
    case TokenType.equality:
      return "==/!=";
    case TokenType.lessThan:
      return "<";
    case TokenType.greaterThan:
      return ">";
    case TokenType.relationalOrEqual:
      return "<=/>=";
    case TokenType.bitShiftL:
      return "<<";
    case TokenType.bitShiftR:
      return ">>/>>>";
    case TokenType.plus:
      return "+";
    case TokenType.minus:
      return "-";
    case TokenType.modulo:
      return "%";
    case TokenType.star:
      return "*";
    case TokenType.slash:
      return "/";
    case TokenType.exponent:
      return "**";
    case TokenType.jsxName:
      return "jsxName";
    case TokenType.jsxText:
      return "jsxText";
    case TokenType.jsxEmptyText:
      return "jsxEmptyText";
    case TokenType.jsxTagStart:
      return "jsxTagStart";
    case TokenType.jsxTagEnd:
      return "jsxTagEnd";
    case TokenType.typeParameterStart:
      return "typeParameterStart";
    case TokenType.nonNullAssertion:
      return "nonNullAssertion";
    case TokenType._break:
      return "break";
    case TokenType._case:
      return "case";
    case TokenType._catch:
      return "catch";
    case TokenType._continue:
      return "continue";
    case TokenType._debugger:
      return "debugger";
    case TokenType._default:
      return "default";
    case TokenType._do:
      return "do";
    case TokenType._else:
      return "else";
    case TokenType._finally:
      return "finally";
    case TokenType._for:
      return "for";
    case TokenType._function:
      return "function";
    case TokenType._if:
      return "if";
    case TokenType._return:
      return "return";
    case TokenType._switch:
      return "switch";
    case TokenType._throw:
      return "throw";
    case TokenType._try:
      return "try";
    case TokenType._var:
      return "var";
    case TokenType._let:
      return "let";
    case TokenType._const:
      return "const";
    case TokenType._while:
      return "while";
    case TokenType._with:
      return "with";
    case TokenType._new:
      return "new";
    case TokenType._this:
      return "this";
    case TokenType._super:
      return "super";
    case TokenType._class:
      return "class";
    case TokenType._extends:
      return "extends";
    case TokenType._export:
      return "export";
    case TokenType._import:
      return "import";
    case TokenType._yield:
      return "yield";
    case TokenType._null:
      return "null";
    case TokenType._true:
      return "true";
    case TokenType._false:
      return "false";
    case TokenType._in:
      return "in";
    case TokenType._instanceof:
      return "instanceof";
    case TokenType._typeof:
      return "typeof";
    case TokenType._void:
      return "void";
    case TokenType._delete:
      return "delete";
    case TokenType._async:
      return "async";
    case TokenType._get:
      return "get";
    case TokenType._set:
      return "set";
    case TokenType._declare:
      return "declare";
    case TokenType._readonly:
      return "readonly";
    case TokenType._abstract:
      return "abstract";
    case TokenType._static:
      return "static";
    case TokenType._public:
      return "public";
    case TokenType._private:
      return "private";
    case TokenType._protected:
      return "protected";
    case TokenType._override:
      return "override";
    case TokenType._as:
      return "as";
    case TokenType._enum:
      return "enum";
    case TokenType._type:
      return "type";
    case TokenType._implements:
      return "implements";
    default:
      return "";
  }
}

// node_modules/sucrase/dist/esm/parser/tokenizer/state.js
var Scope = class {
  constructor(startTokenIndex, endTokenIndex, isFunctionScope) {
    this.startTokenIndex = startTokenIndex;
    this.endTokenIndex = endTokenIndex;
    this.isFunctionScope = isFunctionScope;
  }
};
var StateSnapshot = class {
  constructor(potentialArrowAt, noAnonFunctionType, inDisallowConditionalTypesContext, tokensLength, scopesLength, pos, type, contextualKeyword, start, end, isType, scopeDepth, error) {
    ;
    this.potentialArrowAt = potentialArrowAt;
    this.noAnonFunctionType = noAnonFunctionType;
    this.inDisallowConditionalTypesContext = inDisallowConditionalTypesContext;
    this.tokensLength = tokensLength;
    this.scopesLength = scopesLength;
    this.pos = pos;
    this.type = type;
    this.contextualKeyword = contextualKeyword;
    this.start = start;
    this.end = end;
    this.isType = isType;
    this.scopeDepth = scopeDepth;
    this.error = error;
  }
};
var State = class {
  constructor() {
    State.prototype.__init.call(this);
    State.prototype.__init2.call(this);
    State.prototype.__init3.call(this);
    State.prototype.__init4.call(this);
    State.prototype.__init5.call(this);
    State.prototype.__init6.call(this);
    State.prototype.__init7.call(this);
    State.prototype.__init8.call(this);
    State.prototype.__init9.call(this);
    State.prototype.__init10.call(this);
    State.prototype.__init11.call(this);
    State.prototype.__init12.call(this);
    State.prototype.__init13.call(this);
  }
  // Used to signify the start of a potential arrow function
  __init() {
    this.potentialArrowAt = -1;
  }
  // Used by Flow to handle an edge case involving function type parsing.
  __init2() {
    this.noAnonFunctionType = false;
  }
  // Used by TypeScript to handle ambiguities when parsing conditional types.
  __init3() {
    this.inDisallowConditionalTypesContext = false;
  }
  // Token store.
  __init4() {
    this.tokens = [];
  }
  // Array of all observed scopes, ordered by their ending position.
  __init5() {
    this.scopes = [];
  }
  // The current position of the tokenizer in the input.
  __init6() {
    this.pos = 0;
  }
  // Information about the current token.
  __init7() {
    this.type = TokenType.eof;
  }
  __init8() {
    this.contextualKeyword = ContextualKeyword.NONE;
  }
  __init9() {
    this.start = 0;
  }
  __init10() {
    this.end = 0;
  }
  __init11() {
    this.isType = false;
  }
  __init12() {
    this.scopeDepth = 0;
  }
  /**
   * If the parser is in an error state, then the token is always tt.eof and all functions can
   * keep executing but should be written so they don't get into an infinite loop in this situation.
   *
   * This approach, combined with the ability to snapshot and restore state, allows us to implement
   * backtracking without exceptions and without needing to explicitly propagate error states
   * everywhere.
   */
  __init13() {
    this.error = null;
  }
  snapshot() {
    return new StateSnapshot(
      this.potentialArrowAt,
      this.noAnonFunctionType,
      this.inDisallowConditionalTypesContext,
      this.tokens.length,
      this.scopes.length,
      this.pos,
      this.type,
      this.contextualKeyword,
      this.start,
      this.end,
      this.isType,
      this.scopeDepth,
      this.error
    );
  }
  restoreFromSnapshot(snapshot) {
    this.potentialArrowAt = snapshot.potentialArrowAt;
    this.noAnonFunctionType = snapshot.noAnonFunctionType;
    this.inDisallowConditionalTypesContext = snapshot.inDisallowConditionalTypesContext;
    this.tokens.length = snapshot.tokensLength;
    this.scopes.length = snapshot.scopesLength;
    this.pos = snapshot.pos;
    this.type = snapshot.type;
    this.contextualKeyword = snapshot.contextualKeyword;
    this.start = snapshot.start;
    this.end = snapshot.end;
    this.isType = snapshot.isType;
    this.scopeDepth = snapshot.scopeDepth;
    this.error = snapshot.error;
  }
};

// node_modules/sucrase/dist/esm/parser/util/charcodes.js
var charCodes;
(function(charCodes2) {
  const backSpace = 8;
  charCodes2[charCodes2["backSpace"] = backSpace] = "backSpace";
  const lineFeed = 10;
  charCodes2[charCodes2["lineFeed"] = lineFeed] = "lineFeed";
  const tab = 9;
  charCodes2[charCodes2["tab"] = tab] = "tab";
  const carriageReturn = 13;
  charCodes2[charCodes2["carriageReturn"] = carriageReturn] = "carriageReturn";
  const shiftOut = 14;
  charCodes2[charCodes2["shiftOut"] = shiftOut] = "shiftOut";
  const space = 32;
  charCodes2[charCodes2["space"] = space] = "space";
  const exclamationMark = 33;
  charCodes2[charCodes2["exclamationMark"] = exclamationMark] = "exclamationMark";
  const quotationMark = 34;
  charCodes2[charCodes2["quotationMark"] = quotationMark] = "quotationMark";
  const numberSign = 35;
  charCodes2[charCodes2["numberSign"] = numberSign] = "numberSign";
  const dollarSign = 36;
  charCodes2[charCodes2["dollarSign"] = dollarSign] = "dollarSign";
  const percentSign = 37;
  charCodes2[charCodes2["percentSign"] = percentSign] = "percentSign";
  const ampersand = 38;
  charCodes2[charCodes2["ampersand"] = ampersand] = "ampersand";
  const apostrophe = 39;
  charCodes2[charCodes2["apostrophe"] = apostrophe] = "apostrophe";
  const leftParenthesis = 40;
  charCodes2[charCodes2["leftParenthesis"] = leftParenthesis] = "leftParenthesis";
  const rightParenthesis = 41;
  charCodes2[charCodes2["rightParenthesis"] = rightParenthesis] = "rightParenthesis";
  const asterisk = 42;
  charCodes2[charCodes2["asterisk"] = asterisk] = "asterisk";
  const plusSign = 43;
  charCodes2[charCodes2["plusSign"] = plusSign] = "plusSign";
  const comma2 = 44;
  charCodes2[charCodes2["comma"] = comma2] = "comma";
  const dash = 45;
  charCodes2[charCodes2["dash"] = dash] = "dash";
  const dot = 46;
  charCodes2[charCodes2["dot"] = dot] = "dot";
  const slash = 47;
  charCodes2[charCodes2["slash"] = slash] = "slash";
  const digit0 = 48;
  charCodes2[charCodes2["digit0"] = digit0] = "digit0";
  const digit1 = 49;
  charCodes2[charCodes2["digit1"] = digit1] = "digit1";
  const digit2 = 50;
  charCodes2[charCodes2["digit2"] = digit2] = "digit2";
  const digit3 = 51;
  charCodes2[charCodes2["digit3"] = digit3] = "digit3";
  const digit4 = 52;
  charCodes2[charCodes2["digit4"] = digit4] = "digit4";
  const digit5 = 53;
  charCodes2[charCodes2["digit5"] = digit5] = "digit5";
  const digit6 = 54;
  charCodes2[charCodes2["digit6"] = digit6] = "digit6";
  const digit7 = 55;
  charCodes2[charCodes2["digit7"] = digit7] = "digit7";
  const digit8 = 56;
  charCodes2[charCodes2["digit8"] = digit8] = "digit8";
  const digit9 = 57;
  charCodes2[charCodes2["digit9"] = digit9] = "digit9";
  const colon = 58;
  charCodes2[charCodes2["colon"] = colon] = "colon";
  const semicolon3 = 59;
  charCodes2[charCodes2["semicolon"] = semicolon3] = "semicolon";
  const lessThan = 60;
  charCodes2[charCodes2["lessThan"] = lessThan] = "lessThan";
  const equalsTo = 61;
  charCodes2[charCodes2["equalsTo"] = equalsTo] = "equalsTo";
  const greaterThan = 62;
  charCodes2[charCodes2["greaterThan"] = greaterThan] = "greaterThan";
  const questionMark = 63;
  charCodes2[charCodes2["questionMark"] = questionMark] = "questionMark";
  const atSign = 64;
  charCodes2[charCodes2["atSign"] = atSign] = "atSign";
  const uppercaseA = 65;
  charCodes2[charCodes2["uppercaseA"] = uppercaseA] = "uppercaseA";
  const uppercaseB = 66;
  charCodes2[charCodes2["uppercaseB"] = uppercaseB] = "uppercaseB";
  const uppercaseC = 67;
  charCodes2[charCodes2["uppercaseC"] = uppercaseC] = "uppercaseC";
  const uppercaseD = 68;
  charCodes2[charCodes2["uppercaseD"] = uppercaseD] = "uppercaseD";
  const uppercaseE = 69;
  charCodes2[charCodes2["uppercaseE"] = uppercaseE] = "uppercaseE";
  const uppercaseF = 70;
  charCodes2[charCodes2["uppercaseF"] = uppercaseF] = "uppercaseF";
  const uppercaseG = 71;
  charCodes2[charCodes2["uppercaseG"] = uppercaseG] = "uppercaseG";
  const uppercaseH = 72;
  charCodes2[charCodes2["uppercaseH"] = uppercaseH] = "uppercaseH";
  const uppercaseI = 73;
  charCodes2[charCodes2["uppercaseI"] = uppercaseI] = "uppercaseI";
  const uppercaseJ = 74;
  charCodes2[charCodes2["uppercaseJ"] = uppercaseJ] = "uppercaseJ";
  const uppercaseK = 75;
  charCodes2[charCodes2["uppercaseK"] = uppercaseK] = "uppercaseK";
  const uppercaseL = 76;
  charCodes2[charCodes2["uppercaseL"] = uppercaseL] = "uppercaseL";
  const uppercaseM = 77;
  charCodes2[charCodes2["uppercaseM"] = uppercaseM] = "uppercaseM";
  const uppercaseN = 78;
  charCodes2[charCodes2["uppercaseN"] = uppercaseN] = "uppercaseN";
  const uppercaseO = 79;
  charCodes2[charCodes2["uppercaseO"] = uppercaseO] = "uppercaseO";
  const uppercaseP = 80;
  charCodes2[charCodes2["uppercaseP"] = uppercaseP] = "uppercaseP";
  const uppercaseQ = 81;
  charCodes2[charCodes2["uppercaseQ"] = uppercaseQ] = "uppercaseQ";
  const uppercaseR = 82;
  charCodes2[charCodes2["uppercaseR"] = uppercaseR] = "uppercaseR";
  const uppercaseS = 83;
  charCodes2[charCodes2["uppercaseS"] = uppercaseS] = "uppercaseS";
  const uppercaseT = 84;
  charCodes2[charCodes2["uppercaseT"] = uppercaseT] = "uppercaseT";
  const uppercaseU = 85;
  charCodes2[charCodes2["uppercaseU"] = uppercaseU] = "uppercaseU";
  const uppercaseV = 86;
  charCodes2[charCodes2["uppercaseV"] = uppercaseV] = "uppercaseV";
  const uppercaseW = 87;
  charCodes2[charCodes2["uppercaseW"] = uppercaseW] = "uppercaseW";
  const uppercaseX = 88;
  charCodes2[charCodes2["uppercaseX"] = uppercaseX] = "uppercaseX";
  const uppercaseY = 89;
  charCodes2[charCodes2["uppercaseY"] = uppercaseY] = "uppercaseY";
  const uppercaseZ = 90;
  charCodes2[charCodes2["uppercaseZ"] = uppercaseZ] = "uppercaseZ";
  const leftSquareBracket = 91;
  charCodes2[charCodes2["leftSquareBracket"] = leftSquareBracket] = "leftSquareBracket";
  const backslash = 92;
  charCodes2[charCodes2["backslash"] = backslash] = "backslash";
  const rightSquareBracket = 93;
  charCodes2[charCodes2["rightSquareBracket"] = rightSquareBracket] = "rightSquareBracket";
  const caret = 94;
  charCodes2[charCodes2["caret"] = caret] = "caret";
  const underscore = 95;
  charCodes2[charCodes2["underscore"] = underscore] = "underscore";
  const graveAccent = 96;
  charCodes2[charCodes2["graveAccent"] = graveAccent] = "graveAccent";
  const lowercaseA = 97;
  charCodes2[charCodes2["lowercaseA"] = lowercaseA] = "lowercaseA";
  const lowercaseB = 98;
  charCodes2[charCodes2["lowercaseB"] = lowercaseB] = "lowercaseB";
  const lowercaseC = 99;
  charCodes2[charCodes2["lowercaseC"] = lowercaseC] = "lowercaseC";
  const lowercaseD = 100;
  charCodes2[charCodes2["lowercaseD"] = lowercaseD] = "lowercaseD";
  const lowercaseE = 101;
  charCodes2[charCodes2["lowercaseE"] = lowercaseE] = "lowercaseE";
  const lowercaseF = 102;
  charCodes2[charCodes2["lowercaseF"] = lowercaseF] = "lowercaseF";
  const lowercaseG = 103;
  charCodes2[charCodes2["lowercaseG"] = lowercaseG] = "lowercaseG";
  const lowercaseH = 104;
  charCodes2[charCodes2["lowercaseH"] = lowercaseH] = "lowercaseH";
  const lowercaseI = 105;
  charCodes2[charCodes2["lowercaseI"] = lowercaseI] = "lowercaseI";
  const lowercaseJ = 106;
  charCodes2[charCodes2["lowercaseJ"] = lowercaseJ] = "lowercaseJ";
  const lowercaseK = 107;
  charCodes2[charCodes2["lowercaseK"] = lowercaseK] = "lowercaseK";
  const lowercaseL = 108;
  charCodes2[charCodes2["lowercaseL"] = lowercaseL] = "lowercaseL";
  const lowercaseM = 109;
  charCodes2[charCodes2["lowercaseM"] = lowercaseM] = "lowercaseM";
  const lowercaseN = 110;
  charCodes2[charCodes2["lowercaseN"] = lowercaseN] = "lowercaseN";
  const lowercaseO = 111;
  charCodes2[charCodes2["lowercaseO"] = lowercaseO] = "lowercaseO";
  const lowercaseP = 112;
  charCodes2[charCodes2["lowercaseP"] = lowercaseP] = "lowercaseP";
  const lowercaseQ = 113;
  charCodes2[charCodes2["lowercaseQ"] = lowercaseQ] = "lowercaseQ";
  const lowercaseR = 114;
  charCodes2[charCodes2["lowercaseR"] = lowercaseR] = "lowercaseR";
  const lowercaseS = 115;
  charCodes2[charCodes2["lowercaseS"] = lowercaseS] = "lowercaseS";
  const lowercaseT = 116;
  charCodes2[charCodes2["lowercaseT"] = lowercaseT] = "lowercaseT";
  const lowercaseU = 117;
  charCodes2[charCodes2["lowercaseU"] = lowercaseU] = "lowercaseU";
  const lowercaseV = 118;
  charCodes2[charCodes2["lowercaseV"] = lowercaseV] = "lowercaseV";
  const lowercaseW = 119;
  charCodes2[charCodes2["lowercaseW"] = lowercaseW] = "lowercaseW";
  const lowercaseX = 120;
  charCodes2[charCodes2["lowercaseX"] = lowercaseX] = "lowercaseX";
  const lowercaseY = 121;
  charCodes2[charCodes2["lowercaseY"] = lowercaseY] = "lowercaseY";
  const lowercaseZ = 122;
  charCodes2[charCodes2["lowercaseZ"] = lowercaseZ] = "lowercaseZ";
  const leftCurlyBrace = 123;
  charCodes2[charCodes2["leftCurlyBrace"] = leftCurlyBrace] = "leftCurlyBrace";
  const verticalBar = 124;
  charCodes2[charCodes2["verticalBar"] = verticalBar] = "verticalBar";
  const rightCurlyBrace = 125;
  charCodes2[charCodes2["rightCurlyBrace"] = rightCurlyBrace] = "rightCurlyBrace";
  const tilde = 126;
  charCodes2[charCodes2["tilde"] = tilde] = "tilde";
  const nonBreakingSpace = 160;
  charCodes2[charCodes2["nonBreakingSpace"] = nonBreakingSpace] = "nonBreakingSpace";
  const oghamSpaceMark = 5760;
  charCodes2[charCodes2["oghamSpaceMark"] = oghamSpaceMark] = "oghamSpaceMark";
  const lineSeparator = 8232;
  charCodes2[charCodes2["lineSeparator"] = lineSeparator] = "lineSeparator";
  const paragraphSeparator = 8233;
  charCodes2[charCodes2["paragraphSeparator"] = paragraphSeparator] = "paragraphSeparator";
})(charCodes || (charCodes = {}));

// node_modules/sucrase/dist/esm/parser/traverser/base.js
var isJSXEnabled;
var isTypeScriptEnabled;
var isFlowEnabled;
var state;
var input;
var nextContextId;
function getNextContextId() {
  return nextContextId++;
}
function augmentError(error) {
  if ("pos" in error) {
    const loc = locationForIndex(error.pos);
    error.message += ` (${loc.line}:${loc.column})`;
    error.loc = loc;
  }
  return error;
}
var Loc = class {
  constructor(line, column) {
    this.line = line;
    this.column = column;
  }
};
function locationForIndex(pos) {
  let line = 1;
  let column = 1;
  for (let i4 = 0; i4 < pos; i4++) {
    if (input.charCodeAt(i4) === charCodes.lineFeed) {
      line++;
      column = 1;
    } else {
      column++;
    }
  }
  return new Loc(line, column);
}
function initParser(inputCode, isJSXEnabledArg, isTypeScriptEnabledArg, isFlowEnabledArg) {
  input = inputCode;
  state = new State();
  nextContextId = 1;
  isJSXEnabled = isJSXEnabledArg;
  isTypeScriptEnabled = isTypeScriptEnabledArg;
  isFlowEnabled = isFlowEnabledArg;
}

// node_modules/sucrase/dist/esm/parser/traverser/util.js
function isContextual(contextualKeyword) {
  return state.contextualKeyword === contextualKeyword;
}
function isLookaheadContextual(contextualKeyword) {
  const l4 = lookaheadTypeAndKeyword();
  return l4.type === TokenType.name && l4.contextualKeyword === contextualKeyword;
}
function eatContextual(contextualKeyword) {
  return state.contextualKeyword === contextualKeyword && eat(TokenType.name);
}
function expectContextual(contextualKeyword) {
  if (!eatContextual(contextualKeyword)) {
    unexpected();
  }
}
function canInsertSemicolon() {
  return match2(TokenType.eof) || match2(TokenType.braceR) || hasPrecedingLineBreak();
}
function hasPrecedingLineBreak() {
  const prevToken = state.tokens[state.tokens.length - 1];
  const lastTokEnd = prevToken ? prevToken.end : 0;
  for (let i4 = lastTokEnd; i4 < state.start; i4++) {
    const code = input.charCodeAt(i4);
    if (code === charCodes.lineFeed || code === charCodes.carriageReturn || code === 8232 || code === 8233) {
      return true;
    }
  }
  return false;
}
function hasFollowingLineBreak() {
  const nextStart = nextTokenStart();
  for (let i4 = state.end; i4 < nextStart; i4++) {
    const code = input.charCodeAt(i4);
    if (code === charCodes.lineFeed || code === charCodes.carriageReturn || code === 8232 || code === 8233) {
      return true;
    }
  }
  return false;
}
function isLineTerminator() {
  return eat(TokenType.semi) || canInsertSemicolon();
}
function semicolon() {
  if (!isLineTerminator()) {
    unexpected('Unexpected token, expected ";"');
  }
}
function expect(type) {
  const matched = eat(type);
  if (!matched) {
    unexpected(`Unexpected token, expected "${formatTokenType(type)}"`);
  }
}
function unexpected(message = "Unexpected token", pos = state.start) {
  if (state.error) {
    return;
  }
  const err = new SyntaxError(message);
  err.pos = pos;
  state.error = err;
  state.pos = input.length;
  finishToken(TokenType.eof);
}

// node_modules/sucrase/dist/esm/parser/util/whitespace.js
var WHITESPACE_CHARS = [
  9,
  11,
  12,
  charCodes.space,
  charCodes.nonBreakingSpace,
  charCodes.oghamSpaceMark,
  8192,
  // EN QUAD
  8193,
  // EM QUAD
  8194,
  // EN SPACE
  8195,
  // EM SPACE
  8196,
  // THREE-PER-EM SPACE
  8197,
  // FOUR-PER-EM SPACE
  8198,
  // SIX-PER-EM SPACE
  8199,
  // FIGURE SPACE
  8200,
  // PUNCTUATION SPACE
  8201,
  // THIN SPACE
  8202,
  // HAIR SPACE
  8239,
  // NARROW NO-BREAK SPACE
  8287,
  // MEDIUM MATHEMATICAL SPACE
  12288,
  // IDEOGRAPHIC SPACE
  65279
  // ZERO WIDTH NO-BREAK SPACE
];
var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
var IS_WHITESPACE = new Uint8Array(65536);
for (const char of WHITESPACE_CHARS) {
  IS_WHITESPACE[char] = 1;
}

// node_modules/sucrase/dist/esm/parser/util/identifier.js
function computeIsIdentifierChar(code) {
  if (code < 48)
    return code === 36;
  if (code < 58)
    return true;
  if (code < 65)
    return false;
  if (code < 91)
    return true;
  if (code < 97)
    return code === 95;
  if (code < 123)
    return true;
  if (code < 128)
    return false;
  throw new Error("Should not be called with non-ASCII char code.");
}
var IS_IDENTIFIER_CHAR = new Uint8Array(65536);
for (let i4 = 0; i4 < 128; i4++) {
  IS_IDENTIFIER_CHAR[i4] = computeIsIdentifierChar(i4) ? 1 : 0;
}
for (let i4 = 128; i4 < 65536; i4++) {
  IS_IDENTIFIER_CHAR[i4] = 1;
}
for (const whitespaceChar of WHITESPACE_CHARS) {
  IS_IDENTIFIER_CHAR[whitespaceChar] = 0;
}
IS_IDENTIFIER_CHAR[8232] = 0;
IS_IDENTIFIER_CHAR[8233] = 0;
var IS_IDENTIFIER_START = IS_IDENTIFIER_CHAR.slice();
for (let numChar = charCodes.digit0; numChar <= charCodes.digit9; numChar++) {
  IS_IDENTIFIER_START[numChar] = 0;
}

// node_modules/sucrase/dist/esm/parser/tokenizer/readWordTree.js
var READ_WORD_TREE = new Int32Array([
  // ""
  -1,
  27,
  783,
  918,
  1755,
  2376,
  2862,
  3483,
  -1,
  3699,
  -1,
  4617,
  4752,
  4833,
  5130,
  5508,
  5940,
  -1,
  6480,
  6939,
  7749,
  8181,
  8451,
  8613,
  -1,
  8829,
  -1,
  // "a"
  -1,
  -1,
  54,
  243,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  432,
  -1,
  -1,
  -1,
  675,
  -1,
  -1,
  -1,
  // "ab"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  81,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "abs"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  108,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "abst"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  135,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "abstr"
  -1,
  162,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "abstra"
  -1,
  -1,
  -1,
  189,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "abstrac"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  216,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "abstract"
  ContextualKeyword._abstract << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "ac"
  -1,
  -1,
  -1,
  270,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "acc"
  -1,
  -1,
  -1,
  -1,
  -1,
  297,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "acce"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  324,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "acces"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  351,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "access"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  378,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "accesso"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  405,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "accessor"
  ContextualKeyword._accessor << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "as"
  ContextualKeyword._as << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  459,
  -1,
  -1,
  -1,
  -1,
  -1,
  594,
  -1,
  // "ass"
  -1,
  -1,
  -1,
  -1,
  -1,
  486,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "asse"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  513,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "asser"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  540,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "assert"
  ContextualKeyword._assert << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  567,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "asserts"
  ContextualKeyword._asserts << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "asy"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  621,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "asyn"
  -1,
  -1,
  -1,
  648,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "async"
  ContextualKeyword._async << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "aw"
  -1,
  702,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "awa"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  729,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "awai"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  756,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "await"
  ContextualKeyword._await << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "b"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  810,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "br"
  -1,
  -1,
  -1,
  -1,
  -1,
  837,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "bre"
  -1,
  864,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "brea"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  891,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "break"
  (TokenType._break << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "c"
  -1,
  945,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1107,
  -1,
  -1,
  -1,
  1242,
  -1,
  -1,
  1350,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "ca"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  972,
  1026,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "cas"
  -1,
  -1,
  -1,
  -1,
  -1,
  999,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "case"
  (TokenType._case << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "cat"
  -1,
  -1,
  -1,
  1053,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "catc"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1080,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "catch"
  (TokenType._catch << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "ch"
  -1,
  -1,
  -1,
  -1,
  -1,
  1134,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "che"
  -1,
  -1,
  -1,
  1161,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "chec"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1188,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "check"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1215,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "checks"
  ContextualKeyword._checks << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "cl"
  -1,
  1269,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "cla"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1296,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "clas"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1323,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "class"
  (TokenType._class << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "co"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1377,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "con"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1404,
  1620,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "cons"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1431,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "const"
  (TokenType._const << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1458,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "constr"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1485,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "constru"
  -1,
  -1,
  -1,
  1512,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "construc"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1539,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "construct"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1566,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "constructo"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1593,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "constructor"
  ContextualKeyword._constructor << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "cont"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1647,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "conti"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1674,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "contin"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1701,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "continu"
  -1,
  -1,
  -1,
  -1,
  -1,
  1728,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "continue"
  (TokenType._continue << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "d"
  -1,
  -1,
  -1,
  -1,
  -1,
  1782,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2349,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "de"
  -1,
  -1,
  1809,
  1971,
  -1,
  -1,
  2106,
  -1,
  -1,
  -1,
  -1,
  -1,
  2241,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "deb"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1836,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "debu"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1863,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "debug"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1890,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "debugg"
  -1,
  -1,
  -1,
  -1,
  -1,
  1917,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "debugge"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1944,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "debugger"
  (TokenType._debugger << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "dec"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1998,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "decl"
  -1,
  2025,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "decla"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2052,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "declar"
  -1,
  -1,
  -1,
  -1,
  -1,
  2079,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "declare"
  ContextualKeyword._declare << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "def"
  -1,
  2133,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "defa"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2160,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "defau"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2187,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "defaul"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2214,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "default"
  (TokenType._default << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "del"
  -1,
  -1,
  -1,
  -1,
  -1,
  2268,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "dele"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2295,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "delet"
  -1,
  -1,
  -1,
  -1,
  -1,
  2322,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "delete"
  (TokenType._delete << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "do"
  (TokenType._do << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "e"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2403,
  -1,
  2484,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2565,
  -1,
  -1,
  // "el"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2430,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "els"
  -1,
  -1,
  -1,
  -1,
  -1,
  2457,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "else"
  (TokenType._else << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "en"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2511,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "enu"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2538,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "enum"
  ContextualKeyword._enum << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "ex"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2592,
  -1,
  -1,
  -1,
  2727,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "exp"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2619,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "expo"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2646,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "expor"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2673,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "export"
  (TokenType._export << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2700,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "exports"
  ContextualKeyword._exports << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "ext"
  -1,
  -1,
  -1,
  -1,
  -1,
  2754,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "exte"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2781,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "exten"
  -1,
  -1,
  -1,
  -1,
  2808,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "extend"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2835,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "extends"
  (TokenType._extends << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "f"
  -1,
  2889,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2997,
  -1,
  -1,
  -1,
  -1,
  -1,
  3159,
  -1,
  -1,
  3213,
  -1,
  -1,
  3294,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "fa"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2916,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "fal"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2943,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "fals"
  -1,
  -1,
  -1,
  -1,
  -1,
  2970,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "false"
  (TokenType._false << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "fi"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3024,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "fin"
  -1,
  3051,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "fina"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3078,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "final"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3105,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "finall"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3132,
  -1,
  // "finally"
  (TokenType._finally << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "fo"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3186,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "for"
  (TokenType._for << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "fr"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3240,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "fro"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3267,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "from"
  ContextualKeyword._from << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "fu"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3321,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "fun"
  -1,
  -1,
  -1,
  3348,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "func"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3375,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "funct"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3402,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "functi"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3429,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "functio"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3456,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "function"
  (TokenType._function << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "g"
  -1,
  -1,
  -1,
  -1,
  -1,
  3510,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3564,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "ge"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3537,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "get"
  ContextualKeyword._get << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "gl"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3591,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "glo"
  -1,
  -1,
  3618,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "glob"
  -1,
  3645,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "globa"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3672,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "global"
  ContextualKeyword._global << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "i"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3726,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3753,
  4077,
  -1,
  -1,
  -1,
  -1,
  4590,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "if"
  (TokenType._if << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "im"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3780,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "imp"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3807,
  -1,
  -1,
  3996,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "impl"
  -1,
  -1,
  -1,
  -1,
  -1,
  3834,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "imple"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3861,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "implem"
  -1,
  -1,
  -1,
  -1,
  -1,
  3888,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "impleme"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3915,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "implemen"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3942,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "implement"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3969,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "implements"
  ContextualKeyword._implements << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "impo"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4023,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "impor"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4050,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "import"
  (TokenType._import << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "in"
  (TokenType._in << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4104,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4185,
  4401,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "inf"
  -1,
  -1,
  -1,
  -1,
  -1,
  4131,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "infe"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4158,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "infer"
  ContextualKeyword._infer << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "ins"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4212,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "inst"
  -1,
  4239,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "insta"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4266,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "instan"
  -1,
  -1,
  -1,
  4293,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "instanc"
  -1,
  -1,
  -1,
  -1,
  -1,
  4320,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "instance"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4347,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "instanceo"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4374,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "instanceof"
  (TokenType._instanceof << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "int"
  -1,
  -1,
  -1,
  -1,
  -1,
  4428,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "inte"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4455,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "inter"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4482,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "interf"
  -1,
  4509,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "interfa"
  -1,
  -1,
  -1,
  4536,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "interfac"
  -1,
  -1,
  -1,
  -1,
  -1,
  4563,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "interface"
  ContextualKeyword._interface << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "is"
  ContextualKeyword._is << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "k"
  -1,
  -1,
  -1,
  -1,
  -1,
  4644,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "ke"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4671,
  -1,
  // "key"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4698,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "keyo"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4725,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "keyof"
  ContextualKeyword._keyof << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "l"
  -1,
  -1,
  -1,
  -1,
  -1,
  4779,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "le"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4806,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "let"
  (TokenType._let << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "m"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4860,
  -1,
  -1,
  -1,
  -1,
  -1,
  4995,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "mi"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4887,
  -1,
  -1,
  // "mix"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4914,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "mixi"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4941,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "mixin"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4968,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "mixins"
  ContextualKeyword._mixins << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "mo"
  -1,
  -1,
  -1,
  -1,
  5022,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "mod"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5049,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "modu"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5076,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "modul"
  -1,
  -1,
  -1,
  -1,
  -1,
  5103,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "module"
  ContextualKeyword._module << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "n"
  -1,
  5157,
  -1,
  -1,
  -1,
  5373,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5427,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "na"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5184,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "nam"
  -1,
  -1,
  -1,
  -1,
  -1,
  5211,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "name"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5238,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "names"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5265,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "namesp"
  -1,
  5292,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "namespa"
  -1,
  -1,
  -1,
  5319,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "namespac"
  -1,
  -1,
  -1,
  -1,
  -1,
  5346,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "namespace"
  ContextualKeyword._namespace << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "ne"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5400,
  -1,
  -1,
  -1,
  // "new"
  (TokenType._new << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "nu"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5454,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "nul"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5481,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "null"
  (TokenType._null << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "o"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5535,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5562,
  -1,
  -1,
  -1,
  -1,
  5697,
  5751,
  -1,
  -1,
  -1,
  -1,
  // "of"
  ContextualKeyword._of << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "op"
  -1,
  5589,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "opa"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5616,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "opaq"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5643,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "opaqu"
  -1,
  -1,
  -1,
  -1,
  -1,
  5670,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "opaque"
  ContextualKeyword._opaque << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "ou"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5724,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "out"
  ContextualKeyword._out << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "ov"
  -1,
  -1,
  -1,
  -1,
  -1,
  5778,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "ove"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5805,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "over"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5832,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "overr"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5859,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "overri"
  -1,
  -1,
  -1,
  -1,
  5886,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "overrid"
  -1,
  -1,
  -1,
  -1,
  -1,
  5913,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "override"
  ContextualKeyword._override << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "p"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5967,
  -1,
  -1,
  6345,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "pr"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5994,
  -1,
  -1,
  -1,
  -1,
  -1,
  6129,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "pri"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6021,
  -1,
  -1,
  -1,
  -1,
  // "priv"
  -1,
  6048,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "priva"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6075,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "privat"
  -1,
  -1,
  -1,
  -1,
  -1,
  6102,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "private"
  ContextualKeyword._private << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "pro"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6156,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "prot"
  -1,
  -1,
  -1,
  -1,
  -1,
  6183,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6318,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "prote"
  -1,
  -1,
  -1,
  6210,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "protec"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6237,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "protect"
  -1,
  -1,
  -1,
  -1,
  -1,
  6264,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "protecte"
  -1,
  -1,
  -1,
  -1,
  6291,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "protected"
  ContextualKeyword._protected << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "proto"
  ContextualKeyword._proto << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "pu"
  -1,
  -1,
  6372,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "pub"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6399,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "publ"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6426,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "publi"
  -1,
  -1,
  -1,
  6453,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "public"
  ContextualKeyword._public << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "r"
  -1,
  -1,
  -1,
  -1,
  -1,
  6507,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "re"
  -1,
  6534,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6696,
  -1,
  -1,
  6831,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "rea"
  -1,
  -1,
  -1,
  -1,
  6561,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "read"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6588,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "reado"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6615,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "readon"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6642,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "readonl"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6669,
  -1,
  // "readonly"
  ContextualKeyword._readonly << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "req"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6723,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "requ"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6750,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "requi"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6777,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "requir"
  -1,
  -1,
  -1,
  -1,
  -1,
  6804,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "require"
  ContextualKeyword._require << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "ret"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6858,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "retu"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6885,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "retur"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6912,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "return"
  (TokenType._return << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "s"
  -1,
  6966,
  -1,
  -1,
  -1,
  7182,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7236,
  7371,
  -1,
  7479,
  -1,
  7614,
  -1,
  // "sa"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6993,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "sat"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7020,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "sati"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7047,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "satis"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7074,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "satisf"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7101,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "satisfi"
  -1,
  -1,
  -1,
  -1,
  -1,
  7128,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "satisfie"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7155,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "satisfies"
  ContextualKeyword._satisfies << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "se"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7209,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "set"
  ContextualKeyword._set << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "st"
  -1,
  7263,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "sta"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7290,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "stat"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7317,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "stati"
  -1,
  -1,
  -1,
  7344,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "static"
  ContextualKeyword._static << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "su"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7398,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "sup"
  -1,
  -1,
  -1,
  -1,
  -1,
  7425,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "supe"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7452,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "super"
  (TokenType._super << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "sw"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7506,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "swi"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7533,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "swit"
  -1,
  -1,
  -1,
  7560,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "switc"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7587,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "switch"
  (TokenType._switch << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "sy"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7641,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "sym"
  -1,
  -1,
  7668,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "symb"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7695,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "symbo"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7722,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "symbol"
  ContextualKeyword._symbol << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "t"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7776,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7938,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8046,
  -1,
  // "th"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7803,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7857,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "thi"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7830,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "this"
  (TokenType._this << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "thr"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7884,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "thro"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7911,
  -1,
  -1,
  -1,
  // "throw"
  (TokenType._throw << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "tr"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7965,
  -1,
  -1,
  -1,
  8019,
  -1,
  // "tru"
  -1,
  -1,
  -1,
  -1,
  -1,
  7992,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "true"
  (TokenType._true << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "try"
  (TokenType._try << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "ty"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8073,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "typ"
  -1,
  -1,
  -1,
  -1,
  -1,
  8100,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "type"
  ContextualKeyword._type << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8127,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "typeo"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8154,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "typeof"
  (TokenType._typeof << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "u"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8208,
  -1,
  -1,
  -1,
  -1,
  8343,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "un"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8235,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "uni"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8262,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "uniq"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8289,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "uniqu"
  -1,
  -1,
  -1,
  -1,
  -1,
  8316,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "unique"
  ContextualKeyword._unique << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "us"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8370,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "usi"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8397,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "usin"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8424,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "using"
  ContextualKeyword._using << 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "v"
  -1,
  8478,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8532,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "va"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8505,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "var"
  (TokenType._var << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "vo"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8559,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "voi"
  -1,
  -1,
  -1,
  -1,
  8586,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "void"
  (TokenType._void << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "w"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8640,
  8748,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "wh"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8667,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "whi"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8694,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "whil"
  -1,
  -1,
  -1,
  -1,
  -1,
  8721,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "while"
  (TokenType._while << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "wi"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8775,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "wit"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8802,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "with"
  (TokenType._with << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "y"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8856,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "yi"
  -1,
  -1,
  -1,
  -1,
  -1,
  8883,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "yie"
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8910,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "yiel"
  -1,
  -1,
  -1,
  -1,
  8937,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  // "yield"
  (TokenType._yield << 1) + 1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1
]);

// node_modules/sucrase/dist/esm/parser/tokenizer/readWord.js
function readWord() {
  let treePos = 0;
  let code = 0;
  let pos = state.pos;
  while (pos < input.length) {
    code = input.charCodeAt(pos);
    if (code < charCodes.lowercaseA || code > charCodes.lowercaseZ) {
      break;
    }
    const next2 = READ_WORD_TREE[treePos + (code - charCodes.lowercaseA) + 1];
    if (next2 === -1) {
      break;
    } else {
      treePos = next2;
      pos++;
    }
  }
  const keywordValue = READ_WORD_TREE[treePos];
  if (keywordValue > -1 && !IS_IDENTIFIER_CHAR[code]) {
    state.pos = pos;
    if (keywordValue & 1) {
      finishToken(keywordValue >>> 1);
    } else {
      finishToken(TokenType.name, keywordValue >>> 1);
    }
    return;
  }
  while (pos < input.length) {
    const ch = input.charCodeAt(pos);
    if (IS_IDENTIFIER_CHAR[ch]) {
      pos++;
    } else if (ch === charCodes.backslash) {
      pos += 2;
      if (input.charCodeAt(pos) === charCodes.leftCurlyBrace) {
        while (pos < input.length && input.charCodeAt(pos) !== charCodes.rightCurlyBrace) {
          pos++;
        }
        pos++;
      }
    } else if (ch === charCodes.atSign && input.charCodeAt(pos + 1) === charCodes.atSign) {
      pos += 2;
    } else {
      break;
    }
  }
  state.pos = pos;
  finishToken(TokenType.name);
}

// node_modules/sucrase/dist/esm/parser/tokenizer/index.js
var IdentifierRole;
(function(IdentifierRole2) {
  const Access = 0;
  IdentifierRole2[IdentifierRole2["Access"] = Access] = "Access";
  const ExportAccess = Access + 1;
  IdentifierRole2[IdentifierRole2["ExportAccess"] = ExportAccess] = "ExportAccess";
  const TopLevelDeclaration = ExportAccess + 1;
  IdentifierRole2[IdentifierRole2["TopLevelDeclaration"] = TopLevelDeclaration] = "TopLevelDeclaration";
  const FunctionScopedDeclaration = TopLevelDeclaration + 1;
  IdentifierRole2[IdentifierRole2["FunctionScopedDeclaration"] = FunctionScopedDeclaration] = "FunctionScopedDeclaration";
  const BlockScopedDeclaration = FunctionScopedDeclaration + 1;
  IdentifierRole2[IdentifierRole2["BlockScopedDeclaration"] = BlockScopedDeclaration] = "BlockScopedDeclaration";
  const ObjectShorthandTopLevelDeclaration = BlockScopedDeclaration + 1;
  IdentifierRole2[IdentifierRole2["ObjectShorthandTopLevelDeclaration"] = ObjectShorthandTopLevelDeclaration] = "ObjectShorthandTopLevelDeclaration";
  const ObjectShorthandFunctionScopedDeclaration = ObjectShorthandTopLevelDeclaration + 1;
  IdentifierRole2[IdentifierRole2["ObjectShorthandFunctionScopedDeclaration"] = ObjectShorthandFunctionScopedDeclaration] = "ObjectShorthandFunctionScopedDeclaration";
  const ObjectShorthandBlockScopedDeclaration = ObjectShorthandFunctionScopedDeclaration + 1;
  IdentifierRole2[IdentifierRole2["ObjectShorthandBlockScopedDeclaration"] = ObjectShorthandBlockScopedDeclaration] = "ObjectShorthandBlockScopedDeclaration";
  const ObjectShorthand = ObjectShorthandBlockScopedDeclaration + 1;
  IdentifierRole2[IdentifierRole2["ObjectShorthand"] = ObjectShorthand] = "ObjectShorthand";
  const ImportDeclaration = ObjectShorthand + 1;
  IdentifierRole2[IdentifierRole2["ImportDeclaration"] = ImportDeclaration] = "ImportDeclaration";
  const ObjectKey = ImportDeclaration + 1;
  IdentifierRole2[IdentifierRole2["ObjectKey"] = ObjectKey] = "ObjectKey";
  const ImportAccess = ObjectKey + 1;
  IdentifierRole2[IdentifierRole2["ImportAccess"] = ImportAccess] = "ImportAccess";
})(IdentifierRole || (IdentifierRole = {}));
var JSXRole;
(function(JSXRole2) {
  const NoChildren = 0;
  JSXRole2[JSXRole2["NoChildren"] = NoChildren] = "NoChildren";
  const OneChild = NoChildren + 1;
  JSXRole2[JSXRole2["OneChild"] = OneChild] = "OneChild";
  const StaticChildren = OneChild + 1;
  JSXRole2[JSXRole2["StaticChildren"] = StaticChildren] = "StaticChildren";
  const KeyAfterPropSpread = StaticChildren + 1;
  JSXRole2[JSXRole2["KeyAfterPropSpread"] = KeyAfterPropSpread] = "KeyAfterPropSpread";
})(JSXRole || (JSXRole = {}));
function isDeclaration(token) {
  const role = token.identifierRole;
  return role === IdentifierRole.TopLevelDeclaration || role === IdentifierRole.FunctionScopedDeclaration || role === IdentifierRole.BlockScopedDeclaration || role === IdentifierRole.ObjectShorthandTopLevelDeclaration || role === IdentifierRole.ObjectShorthandFunctionScopedDeclaration || role === IdentifierRole.ObjectShorthandBlockScopedDeclaration;
}
function isNonTopLevelDeclaration(token) {
  const role = token.identifierRole;
  return role === IdentifierRole.FunctionScopedDeclaration || role === IdentifierRole.BlockScopedDeclaration || role === IdentifierRole.ObjectShorthandFunctionScopedDeclaration || role === IdentifierRole.ObjectShorthandBlockScopedDeclaration;
}
function isTopLevelDeclaration(token) {
  const role = token.identifierRole;
  return role === IdentifierRole.TopLevelDeclaration || role === IdentifierRole.ObjectShorthandTopLevelDeclaration || role === IdentifierRole.ImportDeclaration;
}
function isBlockScopedDeclaration(token) {
  const role = token.identifierRole;
  return role === IdentifierRole.TopLevelDeclaration || role === IdentifierRole.BlockScopedDeclaration || role === IdentifierRole.ObjectShorthandTopLevelDeclaration || role === IdentifierRole.ObjectShorthandBlockScopedDeclaration;
}
function isFunctionScopedDeclaration(token) {
  const role = token.identifierRole;
  return role === IdentifierRole.FunctionScopedDeclaration || role === IdentifierRole.ObjectShorthandFunctionScopedDeclaration;
}
function isObjectShorthandDeclaration(token) {
  return token.identifierRole === IdentifierRole.ObjectShorthandTopLevelDeclaration || token.identifierRole === IdentifierRole.ObjectShorthandBlockScopedDeclaration || token.identifierRole === IdentifierRole.ObjectShorthandFunctionScopedDeclaration;
}
var Token = class {
  constructor() {
    this.type = state.type;
    this.contextualKeyword = state.contextualKeyword;
    this.start = state.start;
    this.end = state.end;
    this.scopeDepth = state.scopeDepth;
    this.isType = state.isType;
    this.identifierRole = null;
    this.jsxRole = null;
    this.shadowsGlobal = false;
    this.isAsyncOperation = false;
    this.contextId = null;
    this.rhsEndIndex = null;
    this.isExpression = false;
    this.numNullishCoalesceStarts = 0;
    this.numNullishCoalesceEnds = 0;
    this.isOptionalChainStart = false;
    this.isOptionalChainEnd = false;
    this.subscriptStartIndex = null;
    this.nullishStartIndex = null;
  }
  // Initially false for all tokens, then may be computed in a follow-up step that does scope
  // analysis.
  // Initially false for all tokens, but may be set during transform to mark it as containing an
  // await operation.
  // For assignments, the index of the RHS. For export tokens, the end of the export.
  // For class tokens, records if the class is a class expression or a class statement.
  // Number of times to insert a `nullishCoalesce(` snippet before this token.
  // Number of times to insert a `)` snippet after this token.
  // If true, insert an `optionalChain([` snippet before this token.
  // If true, insert a `])` snippet after this token.
  // Tag for `.`, `?.`, `[`, `?.[`, `(`, and `?.(` to denote the "root" token for this
  // subscript chain. This can be used to determine if this chain is an optional chain.
  // Tag for `??` operators to denote the root token for this nullish coalescing call.
};
function next() {
  state.tokens.push(new Token());
  nextToken();
}
function nextTemplateToken() {
  state.tokens.push(new Token());
  state.start = state.pos;
  readTmplToken();
}
function retokenizeSlashAsRegex() {
  if (state.type === TokenType.assign) {
    --state.pos;
  }
  readRegexp();
}
function pushTypeContext(existingTokensInType) {
  for (let i4 = state.tokens.length - existingTokensInType; i4 < state.tokens.length; i4++) {
    state.tokens[i4].isType = true;
  }
  const oldIsType = state.isType;
  state.isType = true;
  return oldIsType;
}
function popTypeContext(oldIsType) {
  state.isType = oldIsType;
}
function eat(type) {
  if (match2(type)) {
    next();
    return true;
  } else {
    return false;
  }
}
function eatTypeToken(tokenType) {
  const oldIsType = state.isType;
  state.isType = true;
  eat(tokenType);
  state.isType = oldIsType;
}
function match2(type) {
  return state.type === type;
}
function lookaheadType() {
  const snapshot = state.snapshot();
  next();
  const type = state.type;
  state.restoreFromSnapshot(snapshot);
  return type;
}
var TypeAndKeyword = class {
  constructor(type, contextualKeyword) {
    this.type = type;
    this.contextualKeyword = contextualKeyword;
  }
};
function lookaheadTypeAndKeyword() {
  const snapshot = state.snapshot();
  next();
  const type = state.type;
  const contextualKeyword = state.contextualKeyword;
  state.restoreFromSnapshot(snapshot);
  return new TypeAndKeyword(type, contextualKeyword);
}
function nextTokenStart() {
  return nextTokenStartSince(state.pos);
}
function nextTokenStartSince(pos) {
  skipWhiteSpace.lastIndex = pos;
  const skip = skipWhiteSpace.exec(input);
  return pos + skip[0].length;
}
function lookaheadCharCode() {
  return input.charCodeAt(nextTokenStart());
}
function nextToken() {
  skipSpace();
  state.start = state.pos;
  if (state.pos >= input.length) {
    const tokens = state.tokens;
    if (tokens.length >= 2 && tokens[tokens.length - 1].start >= input.length && tokens[tokens.length - 2].start >= input.length) {
      unexpected("Unexpectedly reached the end of input.");
    }
    finishToken(TokenType.eof);
    return;
  }
  readToken(input.charCodeAt(state.pos));
}
function readToken(code) {
  if (IS_IDENTIFIER_START[code] || code === charCodes.backslash || code === charCodes.atSign && input.charCodeAt(state.pos + 1) === charCodes.atSign) {
    readWord();
  } else {
    getTokenFromCode(code);
  }
}
function skipBlockComment() {
  while (input.charCodeAt(state.pos) !== charCodes.asterisk || input.charCodeAt(state.pos + 1) !== charCodes.slash) {
    state.pos++;
    if (state.pos > input.length) {
      unexpected("Unterminated comment", state.pos - 2);
      return;
    }
  }
  state.pos += 2;
}
function skipLineComment(startSkip) {
  let ch = input.charCodeAt(state.pos += startSkip);
  if (state.pos < input.length) {
    while (ch !== charCodes.lineFeed && ch !== charCodes.carriageReturn && ch !== charCodes.lineSeparator && ch !== charCodes.paragraphSeparator && ++state.pos < input.length) {
      ch = input.charCodeAt(state.pos);
    }
  }
}
function skipSpace() {
  while (state.pos < input.length) {
    const ch = input.charCodeAt(state.pos);
    switch (ch) {
      case charCodes.carriageReturn:
        if (input.charCodeAt(state.pos + 1) === charCodes.lineFeed) {
          ++state.pos;
        }
      case charCodes.lineFeed:
      case charCodes.lineSeparator:
      case charCodes.paragraphSeparator:
        ++state.pos;
        break;
      case charCodes.slash:
        switch (input.charCodeAt(state.pos + 1)) {
          case charCodes.asterisk:
            state.pos += 2;
            skipBlockComment();
            break;
          case charCodes.slash:
            skipLineComment(2);
            break;
          default:
            return;
        }
        break;
      default:
        if (IS_WHITESPACE[ch]) {
          ++state.pos;
        } else {
          return;
        }
    }
  }
}
function finishToken(type, contextualKeyword = ContextualKeyword.NONE) {
  state.end = state.pos;
  state.type = type;
  state.contextualKeyword = contextualKeyword;
}
function readToken_dot() {
  const nextChar = input.charCodeAt(state.pos + 1);
  if (nextChar >= charCodes.digit0 && nextChar <= charCodes.digit9) {
    readNumber(true);
    return;
  }
  if (nextChar === charCodes.dot && input.charCodeAt(state.pos + 2) === charCodes.dot) {
    state.pos += 3;
    finishToken(TokenType.ellipsis);
  } else {
    ++state.pos;
    finishToken(TokenType.dot);
  }
}
function readToken_slash() {
  const nextChar = input.charCodeAt(state.pos + 1);
  if (nextChar === charCodes.equalsTo) {
    finishOp(TokenType.assign, 2);
  } else {
    finishOp(TokenType.slash, 1);
  }
}
function readToken_mult_modulo(code) {
  let tokenType = code === charCodes.asterisk ? TokenType.star : TokenType.modulo;
  let width = 1;
  let nextChar = input.charCodeAt(state.pos + 1);
  if (code === charCodes.asterisk && nextChar === charCodes.asterisk) {
    width++;
    nextChar = input.charCodeAt(state.pos + 2);
    tokenType = TokenType.exponent;
  }
  if (nextChar === charCodes.equalsTo && input.charCodeAt(state.pos + 2) !== charCodes.greaterThan) {
    width++;
    tokenType = TokenType.assign;
  }
  finishOp(tokenType, width);
}
function readToken_pipe_amp(code) {
  const nextChar = input.charCodeAt(state.pos + 1);
  if (nextChar === code) {
    if (input.charCodeAt(state.pos + 2) === charCodes.equalsTo) {
      finishOp(TokenType.assign, 3);
    } else {
      finishOp(code === charCodes.verticalBar ? TokenType.logicalOR : TokenType.logicalAND, 2);
    }
    return;
  }
  if (code === charCodes.verticalBar) {
    if (nextChar === charCodes.greaterThan) {
      finishOp(TokenType.pipeline, 2);
      return;
    } else if (nextChar === charCodes.rightCurlyBrace && isFlowEnabled) {
      finishOp(TokenType.braceBarR, 2);
      return;
    }
  }
  if (nextChar === charCodes.equalsTo) {
    finishOp(TokenType.assign, 2);
    return;
  }
  finishOp(code === charCodes.verticalBar ? TokenType.bitwiseOR : TokenType.bitwiseAND, 1);
}
function readToken_caret() {
  const nextChar = input.charCodeAt(state.pos + 1);
  if (nextChar === charCodes.equalsTo) {
    finishOp(TokenType.assign, 2);
  } else {
    finishOp(TokenType.bitwiseXOR, 1);
  }
}
function readToken_plus_min(code) {
  const nextChar = input.charCodeAt(state.pos + 1);
  if (nextChar === code) {
    finishOp(TokenType.preIncDec, 2);
    return;
  }
  if (nextChar === charCodes.equalsTo) {
    finishOp(TokenType.assign, 2);
  } else if (code === charCodes.plusSign) {
    finishOp(TokenType.plus, 1);
  } else {
    finishOp(TokenType.minus, 1);
  }
}
function readToken_lt() {
  const nextChar = input.charCodeAt(state.pos + 1);
  if (nextChar === charCodes.lessThan) {
    if (input.charCodeAt(state.pos + 2) === charCodes.equalsTo) {
      finishOp(TokenType.assign, 3);
      return;
    }
    if (state.isType) {
      finishOp(TokenType.lessThan, 1);
    } else {
      finishOp(TokenType.bitShiftL, 2);
    }
    return;
  }
  if (nextChar === charCodes.equalsTo) {
    finishOp(TokenType.relationalOrEqual, 2);
  } else {
    finishOp(TokenType.lessThan, 1);
  }
}
function readToken_gt() {
  if (state.isType) {
    finishOp(TokenType.greaterThan, 1);
    return;
  }
  const nextChar = input.charCodeAt(state.pos + 1);
  if (nextChar === charCodes.greaterThan) {
    const size = input.charCodeAt(state.pos + 2) === charCodes.greaterThan ? 3 : 2;
    if (input.charCodeAt(state.pos + size) === charCodes.equalsTo) {
      finishOp(TokenType.assign, size + 1);
      return;
    }
    finishOp(TokenType.bitShiftR, size);
    return;
  }
  if (nextChar === charCodes.equalsTo) {
    finishOp(TokenType.relationalOrEqual, 2);
  } else {
    finishOp(TokenType.greaterThan, 1);
  }
}
function rescan_gt() {
  if (state.type === TokenType.greaterThan) {
    state.pos -= 1;
    readToken_gt();
  }
}
function readToken_eq_excl(code) {
  const nextChar = input.charCodeAt(state.pos + 1);
  if (nextChar === charCodes.equalsTo) {
    finishOp(TokenType.equality, input.charCodeAt(state.pos + 2) === charCodes.equalsTo ? 3 : 2);
    return;
  }
  if (code === charCodes.equalsTo && nextChar === charCodes.greaterThan) {
    state.pos += 2;
    finishToken(TokenType.arrow);
    return;
  }
  finishOp(code === charCodes.equalsTo ? TokenType.eq : TokenType.bang, 1);
}
function readToken_question() {
  const nextChar = input.charCodeAt(state.pos + 1);
  const nextChar2 = input.charCodeAt(state.pos + 2);
  if (nextChar === charCodes.questionMark && // In Flow (but not TypeScript), ??string is a valid type that should be
  // tokenized as two individual ? tokens.
  !(isFlowEnabled && state.isType)) {
    if (nextChar2 === charCodes.equalsTo) {
      finishOp(TokenType.assign, 3);
    } else {
      finishOp(TokenType.nullishCoalescing, 2);
    }
  } else if (nextChar === charCodes.dot && !(nextChar2 >= charCodes.digit0 && nextChar2 <= charCodes.digit9)) {
    state.pos += 2;
    finishToken(TokenType.questionDot);
  } else {
    ++state.pos;
    finishToken(TokenType.question);
  }
}
function getTokenFromCode(code) {
  switch (code) {
    case charCodes.numberSign:
      ++state.pos;
      finishToken(TokenType.hash);
      return;
    case charCodes.dot:
      readToken_dot();
      return;
    case charCodes.leftParenthesis:
      ++state.pos;
      finishToken(TokenType.parenL);
      return;
    case charCodes.rightParenthesis:
      ++state.pos;
      finishToken(TokenType.parenR);
      return;
    case charCodes.semicolon:
      ++state.pos;
      finishToken(TokenType.semi);
      return;
    case charCodes.comma:
      ++state.pos;
      finishToken(TokenType.comma);
      return;
    case charCodes.leftSquareBracket:
      ++state.pos;
      finishToken(TokenType.bracketL);
      return;
    case charCodes.rightSquareBracket:
      ++state.pos;
      finishToken(TokenType.bracketR);
      return;
    case charCodes.leftCurlyBrace:
      if (isFlowEnabled && input.charCodeAt(state.pos + 1) === charCodes.verticalBar) {
        finishOp(TokenType.braceBarL, 2);
      } else {
        ++state.pos;
        finishToken(TokenType.braceL);
      }
      return;
    case charCodes.rightCurlyBrace:
      ++state.pos;
      finishToken(TokenType.braceR);
      return;
    case charCodes.colon:
      if (input.charCodeAt(state.pos + 1) === charCodes.colon) {
        finishOp(TokenType.doubleColon, 2);
      } else {
        ++state.pos;
        finishToken(TokenType.colon);
      }
      return;
    case charCodes.questionMark:
      readToken_question();
      return;
    case charCodes.atSign:
      ++state.pos;
      finishToken(TokenType.at);
      return;
    case charCodes.graveAccent:
      ++state.pos;
      finishToken(TokenType.backQuote);
      return;
    case charCodes.digit0: {
      const nextChar = input.charCodeAt(state.pos + 1);
      if (nextChar === charCodes.lowercaseX || nextChar === charCodes.uppercaseX || nextChar === charCodes.lowercaseO || nextChar === charCodes.uppercaseO || nextChar === charCodes.lowercaseB || nextChar === charCodes.uppercaseB) {
        readRadixNumber();
        return;
      }
    }
    case charCodes.digit1:
    case charCodes.digit2:
    case charCodes.digit3:
    case charCodes.digit4:
    case charCodes.digit5:
    case charCodes.digit6:
    case charCodes.digit7:
    case charCodes.digit8:
    case charCodes.digit9:
      readNumber(false);
      return;
    case charCodes.quotationMark:
    case charCodes.apostrophe:
      readString(code);
      return;
    case charCodes.slash:
      readToken_slash();
      return;
    case charCodes.percentSign:
    case charCodes.asterisk:
      readToken_mult_modulo(code);
      return;
    case charCodes.verticalBar:
    case charCodes.ampersand:
      readToken_pipe_amp(code);
      return;
    case charCodes.caret:
      readToken_caret();
      return;
    case charCodes.plusSign:
    case charCodes.dash:
      readToken_plus_min(code);
      return;
    case charCodes.lessThan:
      readToken_lt();
      return;
    case charCodes.greaterThan:
      readToken_gt();
      return;
    case charCodes.equalsTo:
    case charCodes.exclamationMark:
      readToken_eq_excl(code);
      return;
    case charCodes.tilde:
      finishOp(TokenType.tilde, 1);
      return;
    default:
      break;
  }
  unexpected(`Unexpected character '${String.fromCharCode(code)}'`, state.pos);
}
function finishOp(type, size) {
  state.pos += size;
  finishToken(type);
}
function readRegexp() {
  const start = state.pos;
  let escaped = false;
  let inClass = false;
  for (; ; ) {
    if (state.pos >= input.length) {
      unexpected("Unterminated regular expression", start);
      return;
    }
    const code = input.charCodeAt(state.pos);
    if (escaped) {
      escaped = false;
    } else {
      if (code === charCodes.leftSquareBracket) {
        inClass = true;
      } else if (code === charCodes.rightSquareBracket && inClass) {
        inClass = false;
      } else if (code === charCodes.slash && !inClass) {
        break;
      }
      escaped = code === charCodes.backslash;
    }
    ++state.pos;
  }
  ++state.pos;
  skipWord();
  finishToken(TokenType.regexp);
}
function readInt() {
  while (true) {
    const code = input.charCodeAt(state.pos);
    if (code >= charCodes.digit0 && code <= charCodes.digit9 || code === charCodes.underscore) {
      state.pos++;
    } else {
      break;
    }
  }
}
function readRadixNumber() {
  state.pos += 2;
  while (true) {
    const code = input.charCodeAt(state.pos);
    if (code >= charCodes.digit0 && code <= charCodes.digit9 || code >= charCodes.lowercaseA && code <= charCodes.lowercaseF || code >= charCodes.uppercaseA && code <= charCodes.uppercaseF || code === charCodes.underscore) {
      state.pos++;
    } else {
      break;
    }
  }
  const nextChar = input.charCodeAt(state.pos);
  if (nextChar === charCodes.lowercaseN) {
    ++state.pos;
    finishToken(TokenType.bigint);
  } else {
    finishToken(TokenType.num);
  }
}
function readNumber(startsWithDot) {
  let isBigInt = false;
  let isDecimal = false;
  if (!startsWithDot) {
    readInt();
  }
  let nextChar = input.charCodeAt(state.pos);
  if (nextChar === charCodes.dot) {
    ++state.pos;
    readInt();
    nextChar = input.charCodeAt(state.pos);
  }
  if (nextChar === charCodes.uppercaseE || nextChar === charCodes.lowercaseE) {
    nextChar = input.charCodeAt(++state.pos);
    if (nextChar === charCodes.plusSign || nextChar === charCodes.dash) {
      ++state.pos;
    }
    readInt();
    nextChar = input.charCodeAt(state.pos);
  }
  if (nextChar === charCodes.lowercaseN) {
    ++state.pos;
    isBigInt = true;
  } else if (nextChar === charCodes.lowercaseM) {
    ++state.pos;
    isDecimal = true;
  }
  if (isBigInt) {
    finishToken(TokenType.bigint);
    return;
  }
  if (isDecimal) {
    finishToken(TokenType.decimal);
    return;
  }
  finishToken(TokenType.num);
}
function readString(quote) {
  state.pos++;
  for (; ; ) {
    if (state.pos >= input.length) {
      unexpected("Unterminated string constant");
      return;
    }
    const ch = input.charCodeAt(state.pos);
    if (ch === charCodes.backslash) {
      state.pos++;
    } else if (ch === quote) {
      break;
    }
    state.pos++;
  }
  state.pos++;
  finishToken(TokenType.string);
}
function readTmplToken() {
  for (; ; ) {
    if (state.pos >= input.length) {
      unexpected("Unterminated template");
      return;
    }
    const ch = input.charCodeAt(state.pos);
    if (ch === charCodes.graveAccent || ch === charCodes.dollarSign && input.charCodeAt(state.pos + 1) === charCodes.leftCurlyBrace) {
      if (state.pos === state.start && match2(TokenType.template)) {
        if (ch === charCodes.dollarSign) {
          state.pos += 2;
          finishToken(TokenType.dollarBraceL);
          return;
        } else {
          ++state.pos;
          finishToken(TokenType.backQuote);
          return;
        }
      }
      finishToken(TokenType.template);
      return;
    }
    if (ch === charCodes.backslash) {
      state.pos++;
    }
    state.pos++;
  }
}
function skipWord() {
  while (state.pos < input.length) {
    const ch = input.charCodeAt(state.pos);
    if (IS_IDENTIFIER_CHAR[ch]) {
      state.pos++;
    } else if (ch === charCodes.backslash) {
      state.pos += 2;
      if (input.charCodeAt(state.pos) === charCodes.leftCurlyBrace) {
        while (state.pos < input.length && input.charCodeAt(state.pos) !== charCodes.rightCurlyBrace) {
          state.pos++;
        }
        state.pos++;
      }
    } else {
      break;
    }
  }
}

// node_modules/sucrase/dist/esm/util/getImportExportSpecifierInfo.js
function getImportExportSpecifierInfo(tokens, index = tokens.currentIndex()) {
  let endIndex = index + 1;
  if (isSpecifierEnd(tokens, endIndex)) {
    const name = tokens.identifierNameAtIndex(index);
    return {
      isType: false,
      leftName: name,
      rightName: name,
      endIndex
    };
  }
  endIndex++;
  if (isSpecifierEnd(tokens, endIndex)) {
    return {
      isType: true,
      leftName: null,
      rightName: null,
      endIndex
    };
  }
  endIndex++;
  if (isSpecifierEnd(tokens, endIndex)) {
    return {
      isType: false,
      leftName: tokens.identifierNameAtIndex(index),
      rightName: tokens.identifierNameAtIndex(index + 2),
      endIndex
    };
  }
  endIndex++;
  if (isSpecifierEnd(tokens, endIndex)) {
    return {
      isType: true,
      leftName: null,
      rightName: null,
      endIndex
    };
  }
  throw new Error(`Unexpected import/export specifier at ${index}`);
}
function isSpecifierEnd(tokens, index) {
  const token = tokens.tokens[index];
  return token.type === TokenType.braceR || token.type === TokenType.comma;
}

// node_modules/sucrase/dist/esm/parser/plugins/jsx/xhtml.js
var xhtml_default = /* @__PURE__ */ new Map([
  ["quot", '"'],
  ["amp", "&"],
  ["apos", "'"],
  ["lt", "<"],
  ["gt", ">"],
  ["nbsp", "\xA0"],
  ["iexcl", "\xA1"],
  ["cent", "\xA2"],
  ["pound", "\xA3"],
  ["curren", "\xA4"],
  ["yen", "\xA5"],
  ["brvbar", "\xA6"],
  ["sect", "\xA7"],
  ["uml", "\xA8"],
  ["copy", "\xA9"],
  ["ordf", "\xAA"],
  ["laquo", "\xAB"],
  ["not", "\xAC"],
  ["shy", "\xAD"],
  ["reg", "\xAE"],
  ["macr", "\xAF"],
  ["deg", "\xB0"],
  ["plusmn", "\xB1"],
  ["sup2", "\xB2"],
  ["sup3", "\xB3"],
  ["acute", "\xB4"],
  ["micro", "\xB5"],
  ["para", "\xB6"],
  ["middot", "\xB7"],
  ["cedil", "\xB8"],
  ["sup1", "\xB9"],
  ["ordm", "\xBA"],
  ["raquo", "\xBB"],
  ["frac14", "\xBC"],
  ["frac12", "\xBD"],
  ["frac34", "\xBE"],
  ["iquest", "\xBF"],
  ["Agrave", "\xC0"],
  ["Aacute", "\xC1"],
  ["Acirc", "\xC2"],
  ["Atilde", "\xC3"],
  ["Auml", "\xC4"],
  ["Aring", "\xC5"],
  ["AElig", "\xC6"],
  ["Ccedil", "\xC7"],
  ["Egrave", "\xC8"],
  ["Eacute", "\xC9"],
  ["Ecirc", "\xCA"],
  ["Euml", "\xCB"],
  ["Igrave", "\xCC"],
  ["Iacute", "\xCD"],
  ["Icirc", "\xCE"],
  ["Iuml", "\xCF"],
  ["ETH", "\xD0"],
  ["Ntilde", "\xD1"],
  ["Ograve", "\xD2"],
  ["Oacute", "\xD3"],
  ["Ocirc", "\xD4"],
  ["Otilde", "\xD5"],
  ["Ouml", "\xD6"],
  ["times", "\xD7"],
  ["Oslash", "\xD8"],
  ["Ugrave", "\xD9"],
  ["Uacute", "\xDA"],
  ["Ucirc", "\xDB"],
  ["Uuml", "\xDC"],
  ["Yacute", "\xDD"],
  ["THORN", "\xDE"],
  ["szlig", "\xDF"],
  ["agrave", "\xE0"],
  ["aacute", "\xE1"],
  ["acirc", "\xE2"],
  ["atilde", "\xE3"],
  ["auml", "\xE4"],
  ["aring", "\xE5"],
  ["aelig", "\xE6"],
  ["ccedil", "\xE7"],
  ["egrave", "\xE8"],
  ["eacute", "\xE9"],
  ["ecirc", "\xEA"],
  ["euml", "\xEB"],
  ["igrave", "\xEC"],
  ["iacute", "\xED"],
  ["icirc", "\xEE"],
  ["iuml", "\xEF"],
  ["eth", "\xF0"],
  ["ntilde", "\xF1"],
  ["ograve", "\xF2"],
  ["oacute", "\xF3"],
  ["ocirc", "\xF4"],
  ["otilde", "\xF5"],
  ["ouml", "\xF6"],
  ["divide", "\xF7"],
  ["oslash", "\xF8"],
  ["ugrave", "\xF9"],
  ["uacute", "\xFA"],
  ["ucirc", "\xFB"],
  ["uuml", "\xFC"],
  ["yacute", "\xFD"],
  ["thorn", "\xFE"],
  ["yuml", "\xFF"],
  ["OElig", "\u0152"],
  ["oelig", "\u0153"],
  ["Scaron", "\u0160"],
  ["scaron", "\u0161"],
  ["Yuml", "\u0178"],
  ["fnof", "\u0192"],
  ["circ", "\u02C6"],
  ["tilde", "\u02DC"],
  ["Alpha", "\u0391"],
  ["Beta", "\u0392"],
  ["Gamma", "\u0393"],
  ["Delta", "\u0394"],
  ["Epsilon", "\u0395"],
  ["Zeta", "\u0396"],
  ["Eta", "\u0397"],
  ["Theta", "\u0398"],
  ["Iota", "\u0399"],
  ["Kappa", "\u039A"],
  ["Lambda", "\u039B"],
  ["Mu", "\u039C"],
  ["Nu", "\u039D"],
  ["Xi", "\u039E"],
  ["Omicron", "\u039F"],
  ["Pi", "\u03A0"],
  ["Rho", "\u03A1"],
  ["Sigma", "\u03A3"],
  ["Tau", "\u03A4"],
  ["Upsilon", "\u03A5"],
  ["Phi", "\u03A6"],
  ["Chi", "\u03A7"],
  ["Psi", "\u03A8"],
  ["Omega", "\u03A9"],
  ["alpha", "\u03B1"],
  ["beta", "\u03B2"],
  ["gamma", "\u03B3"],
  ["delta", "\u03B4"],
  ["epsilon", "\u03B5"],
  ["zeta", "\u03B6"],
  ["eta", "\u03B7"],
  ["theta", "\u03B8"],
  ["iota", "\u03B9"],
  ["kappa", "\u03BA"],
  ["lambda", "\u03BB"],
  ["mu", "\u03BC"],
  ["nu", "\u03BD"],
  ["xi", "\u03BE"],
  ["omicron", "\u03BF"],
  ["pi", "\u03C0"],
  ["rho", "\u03C1"],
  ["sigmaf", "\u03C2"],
  ["sigma", "\u03C3"],
  ["tau", "\u03C4"],
  ["upsilon", "\u03C5"],
  ["phi", "\u03C6"],
  ["chi", "\u03C7"],
  ["psi", "\u03C8"],
  ["omega", "\u03C9"],
  ["thetasym", "\u03D1"],
  ["upsih", "\u03D2"],
  ["piv", "\u03D6"],
  ["ensp", "\u2002"],
  ["emsp", "\u2003"],
  ["thinsp", "\u2009"],
  ["zwnj", "\u200C"],
  ["zwj", "\u200D"],
  ["lrm", "\u200E"],
  ["rlm", "\u200F"],
  ["ndash", "\u2013"],
  ["mdash", "\u2014"],
  ["lsquo", "\u2018"],
  ["rsquo", "\u2019"],
  ["sbquo", "\u201A"],
  ["ldquo", "\u201C"],
  ["rdquo", "\u201D"],
  ["bdquo", "\u201E"],
  ["dagger", "\u2020"],
  ["Dagger", "\u2021"],
  ["bull", "\u2022"],
  ["hellip", "\u2026"],
  ["permil", "\u2030"],
  ["prime", "\u2032"],
  ["Prime", "\u2033"],
  ["lsaquo", "\u2039"],
  ["rsaquo", "\u203A"],
  ["oline", "\u203E"],
  ["frasl", "\u2044"],
  ["euro", "\u20AC"],
  ["image", "\u2111"],
  ["weierp", "\u2118"],
  ["real", "\u211C"],
  ["trade", "\u2122"],
  ["alefsym", "\u2135"],
  ["larr", "\u2190"],
  ["uarr", "\u2191"],
  ["rarr", "\u2192"],
  ["darr", "\u2193"],
  ["harr", "\u2194"],
  ["crarr", "\u21B5"],
  ["lArr", "\u21D0"],
  ["uArr", "\u21D1"],
  ["rArr", "\u21D2"],
  ["dArr", "\u21D3"],
  ["hArr", "\u21D4"],
  ["forall", "\u2200"],
  ["part", "\u2202"],
  ["exist", "\u2203"],
  ["empty", "\u2205"],
  ["nabla", "\u2207"],
  ["isin", "\u2208"],
  ["notin", "\u2209"],
  ["ni", "\u220B"],
  ["prod", "\u220F"],
  ["sum", "\u2211"],
  ["minus", "\u2212"],
  ["lowast", "\u2217"],
  ["radic", "\u221A"],
  ["prop", "\u221D"],
  ["infin", "\u221E"],
  ["ang", "\u2220"],
  ["and", "\u2227"],
  ["or", "\u2228"],
  ["cap", "\u2229"],
  ["cup", "\u222A"],
  ["int", "\u222B"],
  ["there4", "\u2234"],
  ["sim", "\u223C"],
  ["cong", "\u2245"],
  ["asymp", "\u2248"],
  ["ne", "\u2260"],
  ["equiv", "\u2261"],
  ["le", "\u2264"],
  ["ge", "\u2265"],
  ["sub", "\u2282"],
  ["sup", "\u2283"],
  ["nsub", "\u2284"],
  ["sube", "\u2286"],
  ["supe", "\u2287"],
  ["oplus", "\u2295"],
  ["otimes", "\u2297"],
  ["perp", "\u22A5"],
  ["sdot", "\u22C5"],
  ["lceil", "\u2308"],
  ["rceil", "\u2309"],
  ["lfloor", "\u230A"],
  ["rfloor", "\u230B"],
  ["lang", "\u2329"],
  ["rang", "\u232A"],
  ["loz", "\u25CA"],
  ["spades", "\u2660"],
  ["clubs", "\u2663"],
  ["hearts", "\u2665"],
  ["diams", "\u2666"]
]);

// node_modules/sucrase/dist/esm/util/getJSXPragmaInfo.js
function getJSXPragmaInfo(options) {
  const [base, suffix] = splitPragma(options.jsxPragma || "React.createElement");
  const [fragmentBase, fragmentSuffix] = splitPragma(options.jsxFragmentPragma || "React.Fragment");
  return { base, suffix, fragmentBase, fragmentSuffix };
}
function splitPragma(pragma) {
  let dotIndex = pragma.indexOf(".");
  if (dotIndex === -1) {
    dotIndex = pragma.length;
  }
  return [pragma.slice(0, dotIndex), pragma.slice(dotIndex)];
}

// node_modules/sucrase/dist/esm/transformers/Transformer.js
var Transformer = class {
  // Return true if anything was processed, false otherwise.
  getPrefixCode() {
    return "";
  }
  getHoistedCode() {
    return "";
  }
  getSuffixCode() {
    return "";
  }
};

// node_modules/sucrase/dist/esm/transformers/JSXTransformer.js
var JSXTransformer = class extends Transformer {
  // State for calculating the line number of each JSX tag in development.
  __init() {
    this.lastLineNumber = 1;
  }
  __init2() {
    this.lastIndex = 0;
  }
  // In development, variable name holding the name of the current file.
  __init3() {
    this.filenameVarName = null;
  }
  // Mapping of claimed names for imports in the automatic transform, e,g.
  // {jsx: "_jsx"}. This determines which imports to generate in the prefix.
  __init4() {
    this.esmAutomaticImportNameResolutions = {};
  }
  // When automatically adding imports in CJS mode, we store the variable name
  // holding the imported CJS module so we can require it in the prefix.
  __init5() {
    this.cjsAutomaticModuleNameResolutions = {};
  }
  constructor(rootTransformer, tokens, importProcessor, nameManager, options) {
    super();
    this.rootTransformer = rootTransformer;
    this.tokens = tokens;
    this.importProcessor = importProcessor;
    this.nameManager = nameManager;
    this.options = options;
    JSXTransformer.prototype.__init.call(this);
    JSXTransformer.prototype.__init2.call(this);
    JSXTransformer.prototype.__init3.call(this);
    JSXTransformer.prototype.__init4.call(this);
    JSXTransformer.prototype.__init5.call(this);
    ;
    this.jsxPragmaInfo = getJSXPragmaInfo(options);
    this.isAutomaticRuntime = options.jsxRuntime === "automatic";
    this.jsxImportSource = options.jsxImportSource || "react";
  }
  process() {
    if (this.tokens.matches1(TokenType.jsxTagStart)) {
      this.processJSXTag();
      return true;
    }
    return false;
  }
  getPrefixCode() {
    let prefix = "";
    if (this.filenameVarName) {
      prefix += `const ${this.filenameVarName} = ${JSON.stringify(this.options.filePath || "")};`;
    }
    if (this.isAutomaticRuntime) {
      if (this.importProcessor) {
        for (const [path, resolvedName] of Object.entries(this.cjsAutomaticModuleNameResolutions)) {
          prefix += `var ${resolvedName} = require("${path}");`;
        }
      } else {
        const { createElement: createElementResolution, ...otherResolutions } = this.esmAutomaticImportNameResolutions;
        if (createElementResolution) {
          prefix += `import {createElement as ${createElementResolution}} from "${this.jsxImportSource}";`;
        }
        const importSpecifiers = Object.entries(otherResolutions).map(([name, resolvedName]) => `${name} as ${resolvedName}`).join(", ");
        if (importSpecifiers) {
          const importPath = this.jsxImportSource + (this.options.production ? "/jsx-runtime" : "/jsx-dev-runtime");
          prefix += `import {${importSpecifiers}} from "${importPath}";`;
        }
      }
    }
    return prefix;
  }
  processJSXTag() {
    const { jsxRole, start } = this.tokens.currentToken();
    const elementLocationCode = this.options.production ? null : this.getElementLocationCode(start);
    if (this.isAutomaticRuntime && jsxRole !== JSXRole.KeyAfterPropSpread) {
      this.transformTagToJSXFunc(elementLocationCode, jsxRole);
    } else {
      this.transformTagToCreateElement(elementLocationCode);
    }
  }
  getElementLocationCode(firstTokenStart) {
    const lineNumber = this.getLineNumberForIndex(firstTokenStart);
    return `lineNumber: ${lineNumber}`;
  }
  /**
   * Get the line number for this source position. This is calculated lazily and
   * must be called in increasing order by index.
   */
  getLineNumberForIndex(index) {
    const code = this.tokens.code;
    while (this.lastIndex < index && this.lastIndex < code.length) {
      if (code[this.lastIndex] === "\n") {
        this.lastLineNumber++;
      }
      this.lastIndex++;
    }
    return this.lastLineNumber;
  }
  /**
   * Convert the current JSX element to a call to jsx, jsxs, or jsxDEV. This is
   * the primary transformation for the automatic transform.
   *
   * Example:
   * <div a={1} key={2}>Hello{x}</div>
   * becomes
   * jsxs('div', {a: 1, children: ["Hello", x]}, 2)
   */
  transformTagToJSXFunc(elementLocationCode, jsxRole) {
    const isStatic = jsxRole === JSXRole.StaticChildren;
    this.tokens.replaceToken(this.getJSXFuncInvocationCode(isStatic));
    let keyCode = null;
    if (this.tokens.matches1(TokenType.jsxTagEnd)) {
      this.tokens.replaceToken(`${this.getFragmentCode()}, {`);
      this.processAutomaticChildrenAndEndProps(jsxRole);
    } else {
      this.processTagIntro();
      this.tokens.appendCode(", {");
      keyCode = this.processProps(true);
      if (this.tokens.matches2(TokenType.slash, TokenType.jsxTagEnd)) {
        this.tokens.appendCode("}");
      } else if (this.tokens.matches1(TokenType.jsxTagEnd)) {
        this.tokens.removeToken();
        this.processAutomaticChildrenAndEndProps(jsxRole);
      } else {
        throw new Error("Expected either /> or > at the end of the tag.");
      }
      if (keyCode) {
        this.tokens.appendCode(`, ${keyCode}`);
      }
    }
    if (!this.options.production) {
      if (keyCode === null) {
        this.tokens.appendCode(", void 0");
      }
      this.tokens.appendCode(`, ${isStatic}, ${this.getDevSource(elementLocationCode)}, this`);
    }
    this.tokens.removeInitialToken();
    while (!this.tokens.matches1(TokenType.jsxTagEnd)) {
      this.tokens.removeToken();
    }
    this.tokens.replaceToken(")");
  }
  /**
   * Convert the current JSX element to a createElement call. In the classic
   * runtime, this is the only case. In the automatic runtime, this is called
   * as a fallback in some situations.
   *
   * Example:
   * <div a={1} key={2}>Hello{x}</div>
   * becomes
   * React.createElement('div', {a: 1, key: 2}, "Hello", x)
   */
  transformTagToCreateElement(elementLocationCode) {
    this.tokens.replaceToken(this.getCreateElementInvocationCode());
    if (this.tokens.matches1(TokenType.jsxTagEnd)) {
      this.tokens.replaceToken(`${this.getFragmentCode()}, null`);
      this.processChildren(true);
    } else {
      this.processTagIntro();
      this.processPropsObjectWithDevInfo(elementLocationCode);
      if (this.tokens.matches2(TokenType.slash, TokenType.jsxTagEnd)) {
      } else if (this.tokens.matches1(TokenType.jsxTagEnd)) {
        this.tokens.removeToken();
        this.processChildren(true);
      } else {
        throw new Error("Expected either /> or > at the end of the tag.");
      }
    }
    this.tokens.removeInitialToken();
    while (!this.tokens.matches1(TokenType.jsxTagEnd)) {
      this.tokens.removeToken();
    }
    this.tokens.replaceToken(")");
  }
  /**
   * Get the code for the relevant function for this context: jsx, jsxs,
   * or jsxDEV. The following open-paren is included as well.
   *
   * These functions are only used for the automatic runtime, so they are always
   * auto-imported, but the auto-import will be either CJS or ESM based on the
   * target module format.
   */
  getJSXFuncInvocationCode(isStatic) {
    if (this.options.production) {
      if (isStatic) {
        return this.claimAutoImportedFuncInvocation("jsxs", "/jsx-runtime");
      } else {
        return this.claimAutoImportedFuncInvocation("jsx", "/jsx-runtime");
      }
    } else {
      return this.claimAutoImportedFuncInvocation("jsxDEV", "/jsx-dev-runtime");
    }
  }
  /**
   * Return the code to use for the createElement function, e.g.
   * `React.createElement`, including the following open-paren.
   *
   * This is the main function to use for the classic runtime. For the
   * automatic runtime, this function is used as a fallback function to
   * preserve behavior when there is a prop spread followed by an explicit
   * key. In that automatic runtime case, the function should be automatically
   * imported.
   */
  getCreateElementInvocationCode() {
    if (this.isAutomaticRuntime) {
      return this.claimAutoImportedFuncInvocation("createElement", "");
    } else {
      const { jsxPragmaInfo } = this;
      const resolvedPragmaBaseName = this.importProcessor ? this.importProcessor.getIdentifierReplacement(jsxPragmaInfo.base) || jsxPragmaInfo.base : jsxPragmaInfo.base;
      return `${resolvedPragmaBaseName}${jsxPragmaInfo.suffix}(`;
    }
  }
  /**
   * Return the code to use as the component when compiling a shorthand
   * fragment, e.g. `React.Fragment`.
   *
   * This may be called from either the classic or automatic runtime, and
   * the value should be auto-imported for the automatic runtime.
   */
  getFragmentCode() {
    if (this.isAutomaticRuntime) {
      return this.claimAutoImportedName(
        "Fragment",
        this.options.production ? "/jsx-runtime" : "/jsx-dev-runtime"
      );
    } else {
      const { jsxPragmaInfo } = this;
      const resolvedFragmentPragmaBaseName = this.importProcessor ? this.importProcessor.getIdentifierReplacement(jsxPragmaInfo.fragmentBase) || jsxPragmaInfo.fragmentBase : jsxPragmaInfo.fragmentBase;
      return resolvedFragmentPragmaBaseName + jsxPragmaInfo.fragmentSuffix;
    }
  }
  /**
   * Return code that invokes the given function.
   *
   * When the imports transform is enabled, use the CJSImportTransformer
   * strategy of using `.call(void 0, ...` to avoid passing a `this` value in a
   * situation that would otherwise look like a method call.
   */
  claimAutoImportedFuncInvocation(funcName, importPathSuffix) {
    const funcCode = this.claimAutoImportedName(funcName, importPathSuffix);
    if (this.importProcessor) {
      return `${funcCode}.call(void 0, `;
    } else {
      return `${funcCode}(`;
    }
  }
  claimAutoImportedName(funcName, importPathSuffix) {
    if (this.importProcessor) {
      const path = this.jsxImportSource + importPathSuffix;
      if (!this.cjsAutomaticModuleNameResolutions[path]) {
        this.cjsAutomaticModuleNameResolutions[path] = this.importProcessor.getFreeIdentifierForPath(path);
      }
      return `${this.cjsAutomaticModuleNameResolutions[path]}.${funcName}`;
    } else {
      if (!this.esmAutomaticImportNameResolutions[funcName]) {
        this.esmAutomaticImportNameResolutions[funcName] = this.nameManager.claimFreeName(
          `_${funcName}`
        );
      }
      return this.esmAutomaticImportNameResolutions[funcName];
    }
  }
  /**
   * Process the first part of a tag, before any props.
   */
  processTagIntro() {
    let introEnd = this.tokens.currentIndex() + 1;
    while (this.tokens.tokens[introEnd].isType || !this.tokens.matches2AtIndex(introEnd - 1, TokenType.jsxName, TokenType.jsxName) && !this.tokens.matches2AtIndex(introEnd - 1, TokenType.greaterThan, TokenType.jsxName) && !this.tokens.matches1AtIndex(introEnd, TokenType.braceL) && !this.tokens.matches1AtIndex(introEnd, TokenType.jsxTagEnd) && !this.tokens.matches2AtIndex(introEnd, TokenType.slash, TokenType.jsxTagEnd)) {
      introEnd++;
    }
    if (introEnd === this.tokens.currentIndex() + 1) {
      const tagName = this.tokens.identifierName();
      if (startsWithLowerCase(tagName)) {
        this.tokens.replaceToken(`'${tagName}'`);
      }
    }
    while (this.tokens.currentIndex() < introEnd) {
      this.rootTransformer.processToken();
    }
  }
  /**
   * Starting at the beginning of the props, add the props argument to
   * React.createElement, including the comma before it.
   */
  processPropsObjectWithDevInfo(elementLocationCode) {
    const devProps = this.options.production ? "" : `__self: this, __source: ${this.getDevSource(elementLocationCode)}`;
    if (!this.tokens.matches1(TokenType.jsxName) && !this.tokens.matches1(TokenType.braceL)) {
      if (devProps) {
        this.tokens.appendCode(`, {${devProps}}`);
      } else {
        this.tokens.appendCode(`, null`);
      }
      return;
    }
    this.tokens.appendCode(`, {`);
    this.processProps(false);
    if (devProps) {
      this.tokens.appendCode(` ${devProps}}`);
    } else {
      this.tokens.appendCode("}");
    }
  }
  /**
   * Transform the core part of the props, assuming that a { has already been
   * inserted before us and that a } will be inserted after us.
   *
   * If extractKeyCode is true (i.e. when using any jsx... function), any prop
   * named "key" has its code captured and returned rather than being emitted to
   * the output code. This shifts line numbers, and emitting the code later will
   * correct line numbers again. If no key is found or if extractKeyCode is
   * false, this function returns null.
   */
  processProps(extractKeyCode) {
    let keyCode = null;
    while (true) {
      if (this.tokens.matches2(TokenType.jsxName, TokenType.eq)) {
        const propName = this.tokens.identifierName();
        if (extractKeyCode && propName === "key") {
          if (keyCode !== null) {
            this.tokens.appendCode(keyCode.replace(/[^\n]/g, ""));
          }
          this.tokens.removeToken();
          this.tokens.removeToken();
          const snapshot = this.tokens.snapshot();
          this.processPropValue();
          keyCode = this.tokens.dangerouslyGetAndRemoveCodeSinceSnapshot(snapshot);
          continue;
        } else {
          this.processPropName(propName);
          this.tokens.replaceToken(": ");
          this.processPropValue();
        }
      } else if (this.tokens.matches1(TokenType.jsxName)) {
        const propName = this.tokens.identifierName();
        this.processPropName(propName);
        this.tokens.appendCode(": true");
      } else if (this.tokens.matches1(TokenType.braceL)) {
        this.tokens.replaceToken("");
        this.rootTransformer.processBalancedCode();
        this.tokens.replaceToken("");
      } else {
        break;
      }
      this.tokens.appendCode(",");
    }
    return keyCode;
  }
  processPropName(propName) {
    if (propName.includes("-")) {
      this.tokens.replaceToken(`'${propName}'`);
    } else {
      this.tokens.copyToken();
    }
  }
  processPropValue() {
    if (this.tokens.matches1(TokenType.braceL)) {
      this.tokens.replaceToken("");
      this.rootTransformer.processBalancedCode();
      this.tokens.replaceToken("");
    } else if (this.tokens.matches1(TokenType.jsxTagStart)) {
      this.processJSXTag();
    } else {
      this.processStringPropValue();
    }
  }
  processStringPropValue() {
    const token = this.tokens.currentToken();
    const valueCode = this.tokens.code.slice(token.start + 1, token.end - 1);
    const replacementCode = formatJSXTextReplacement(valueCode);
    const literalCode = formatJSXStringValueLiteral(valueCode);
    this.tokens.replaceToken(literalCode + replacementCode);
  }
  /**
   * Starting in the middle of the props object literal, produce an additional
   * prop for the children and close the object literal.
   */
  processAutomaticChildrenAndEndProps(jsxRole) {
    if (jsxRole === JSXRole.StaticChildren) {
      this.tokens.appendCode(" children: [");
      this.processChildren(false);
      this.tokens.appendCode("]}");
    } else {
      if (jsxRole === JSXRole.OneChild) {
        this.tokens.appendCode(" children: ");
      }
      this.processChildren(false);
      this.tokens.appendCode("}");
    }
  }
  /**
   * Transform children into a comma-separated list, which will be either
   * arguments to createElement or array elements of a children prop.
   */
  processChildren(needsInitialComma) {
    let needsComma = needsInitialComma;
    while (true) {
      if (this.tokens.matches2(TokenType.jsxTagStart, TokenType.slash)) {
        return;
      }
      let didEmitElement = false;
      if (this.tokens.matches1(TokenType.braceL)) {
        if (this.tokens.matches2(TokenType.braceL, TokenType.braceR)) {
          this.tokens.replaceToken("");
          this.tokens.replaceToken("");
        } else {
          this.tokens.replaceToken(needsComma ? ", " : "");
          this.rootTransformer.processBalancedCode();
          this.tokens.replaceToken("");
          didEmitElement = true;
        }
      } else if (this.tokens.matches1(TokenType.jsxTagStart)) {
        this.tokens.appendCode(needsComma ? ", " : "");
        this.processJSXTag();
        didEmitElement = true;
      } else if (this.tokens.matches1(TokenType.jsxText) || this.tokens.matches1(TokenType.jsxEmptyText)) {
        didEmitElement = this.processChildTextElement(needsComma);
      } else {
        throw new Error("Unexpected token when processing JSX children.");
      }
      if (didEmitElement) {
        needsComma = true;
      }
    }
  }
  /**
   * Turn a JSX text element into a string literal, or nothing at all if the JSX
   * text resolves to the empty string.
   *
   * Returns true if a string literal is emitted, false otherwise.
   */
  processChildTextElement(needsComma) {
    const token = this.tokens.currentToken();
    const valueCode = this.tokens.code.slice(token.start, token.end);
    const replacementCode = formatJSXTextReplacement(valueCode);
    const literalCode = formatJSXTextLiteral(valueCode);
    if (literalCode === '""') {
      this.tokens.replaceToken(replacementCode);
      return false;
    } else {
      this.tokens.replaceToken(`${needsComma ? ", " : ""}${literalCode}${replacementCode}`);
      return true;
    }
  }
  getDevSource(elementLocationCode) {
    return `{fileName: ${this.getFilenameVarName()}, ${elementLocationCode}}`;
  }
  getFilenameVarName() {
    if (!this.filenameVarName) {
      this.filenameVarName = this.nameManager.claimFreeName("_jsxFileName");
    }
    return this.filenameVarName;
  }
};
function startsWithLowerCase(s4) {
  const firstChar = s4.charCodeAt(0);
  return firstChar >= charCodes.lowercaseA && firstChar <= charCodes.lowercaseZ;
}
function formatJSXTextLiteral(text) {
  let result = "";
  let whitespace2 = "";
  let isInInitialLineWhitespace = false;
  let seenNonWhitespace = false;
  for (let i4 = 0; i4 < text.length; i4++) {
    const c3 = text[i4];
    if (c3 === " " || c3 === "	" || c3 === "\r") {
      if (!isInInitialLineWhitespace) {
        whitespace2 += c3;
      }
    } else if (c3 === "\n") {
      whitespace2 = "";
      isInInitialLineWhitespace = true;
    } else {
      if (seenNonWhitespace && isInInitialLineWhitespace) {
        result += " ";
      }
      result += whitespace2;
      whitespace2 = "";
      if (c3 === "&") {
        const { entity, newI } = processEntity(text, i4 + 1);
        i4 = newI - 1;
        result += entity;
      } else {
        result += c3;
      }
      seenNonWhitespace = true;
      isInInitialLineWhitespace = false;
    }
  }
  if (!isInInitialLineWhitespace) {
    result += whitespace2;
  }
  return JSON.stringify(result);
}
function formatJSXTextReplacement(text) {
  let numNewlines = 0;
  let numSpaces = 0;
  for (const c3 of text) {
    if (c3 === "\n") {
      numNewlines++;
      numSpaces = 0;
    } else if (c3 === " ") {
      numSpaces++;
    }
  }
  return "\n".repeat(numNewlines) + " ".repeat(numSpaces);
}
function formatJSXStringValueLiteral(text) {
  let result = "";
  for (let i4 = 0; i4 < text.length; i4++) {
    const c3 = text[i4];
    if (c3 === "\n") {
      if (/\s/.test(text[i4 + 1])) {
        result += " ";
        while (i4 < text.length && /\s/.test(text[i4 + 1])) {
          i4++;
        }
      } else {
        result += "\n";
      }
    } else if (c3 === "&") {
      const { entity, newI } = processEntity(text, i4 + 1);
      result += entity;
      i4 = newI - 1;
    } else {
      result += c3;
    }
  }
  return JSON.stringify(result);
}
function processEntity(text, indexAfterAmpersand) {
  let str = "";
  let count = 0;
  let entity;
  let i4 = indexAfterAmpersand;
  if (text[i4] === "#") {
    let radix = 10;
    i4++;
    let numStart;
    if (text[i4] === "x") {
      radix = 16;
      i4++;
      numStart = i4;
      while (i4 < text.length && isHexDigit(text.charCodeAt(i4))) {
        i4++;
      }
    } else {
      numStart = i4;
      while (i4 < text.length && isDecimalDigit(text.charCodeAt(i4))) {
        i4++;
      }
    }
    if (text[i4] === ";") {
      const numStr = text.slice(numStart, i4);
      if (numStr) {
        i4++;
        entity = String.fromCodePoint(parseInt(numStr, radix));
      }
    }
  } else {
    while (i4 < text.length && count++ < 10) {
      const ch = text[i4];
      i4++;
      if (ch === ";") {
        entity = xhtml_default.get(str);
        break;
      }
      str += ch;
    }
  }
  if (!entity) {
    return { entity: "&", newI: indexAfterAmpersand };
  }
  return { entity, newI: i4 };
}
function isDecimalDigit(code) {
  return code >= charCodes.digit0 && code <= charCodes.digit9;
}
function isHexDigit(code) {
  return code >= charCodes.digit0 && code <= charCodes.digit9 || code >= charCodes.lowercaseA && code <= charCodes.lowercaseF || code >= charCodes.uppercaseA && code <= charCodes.uppercaseF;
}

// node_modules/sucrase/dist/esm/util/getNonTypeIdentifiers.js
function getNonTypeIdentifiers(tokens, options) {
  const jsxPragmaInfo = getJSXPragmaInfo(options);
  const nonTypeIdentifiers = /* @__PURE__ */ new Set();
  for (let i4 = 0; i4 < tokens.tokens.length; i4++) {
    const token = tokens.tokens[i4];
    if (token.type === TokenType.name && !token.isType && (token.identifierRole === IdentifierRole.Access || token.identifierRole === IdentifierRole.ObjectShorthand || token.identifierRole === IdentifierRole.ExportAccess) && !token.shadowsGlobal) {
      nonTypeIdentifiers.add(tokens.identifierNameForToken(token));
    }
    if (token.type === TokenType.jsxTagStart) {
      nonTypeIdentifiers.add(jsxPragmaInfo.base);
    }
    if (token.type === TokenType.jsxTagStart && i4 + 1 < tokens.tokens.length && tokens.tokens[i4 + 1].type === TokenType.jsxTagEnd) {
      nonTypeIdentifiers.add(jsxPragmaInfo.base);
      nonTypeIdentifiers.add(jsxPragmaInfo.fragmentBase);
    }
    if (token.type === TokenType.jsxName && token.identifierRole === IdentifierRole.Access) {
      const identifierName = tokens.identifierNameForToken(token);
      if (!startsWithLowerCase(identifierName) || tokens.tokens[i4 + 1].type === TokenType.dot) {
        nonTypeIdentifiers.add(tokens.identifierNameForToken(token));
      }
    }
  }
  return nonTypeIdentifiers;
}

// node_modules/sucrase/dist/esm/CJSImportProcessor.js
var CJSImportProcessor = class {
  __init() {
    this.nonTypeIdentifiers = /* @__PURE__ */ new Set();
  }
  __init2() {
    this.importInfoByPath = /* @__PURE__ */ new Map();
  }
  __init3() {
    this.importsToReplace = /* @__PURE__ */ new Map();
  }
  __init4() {
    this.identifierReplacements = /* @__PURE__ */ new Map();
  }
  __init5() {
    this.exportBindingsByLocalName = /* @__PURE__ */ new Map();
  }
  constructor(nameManager, tokens, enableLegacyTypeScriptModuleInterop, options, isTypeScriptTransformEnabled, keepUnusedImports, helperManager) {
    ;
    this.nameManager = nameManager;
    this.tokens = tokens;
    this.enableLegacyTypeScriptModuleInterop = enableLegacyTypeScriptModuleInterop;
    this.options = options;
    this.isTypeScriptTransformEnabled = isTypeScriptTransformEnabled;
    this.keepUnusedImports = keepUnusedImports;
    this.helperManager = helperManager;
    CJSImportProcessor.prototype.__init.call(this);
    CJSImportProcessor.prototype.__init2.call(this);
    CJSImportProcessor.prototype.__init3.call(this);
    CJSImportProcessor.prototype.__init4.call(this);
    CJSImportProcessor.prototype.__init5.call(this);
  }
  preprocessTokens() {
    for (let i4 = 0; i4 < this.tokens.tokens.length; i4++) {
      if (this.tokens.matches1AtIndex(i4, TokenType._import) && !this.tokens.matches3AtIndex(i4, TokenType._import, TokenType.name, TokenType.eq)) {
        this.preprocessImportAtIndex(i4);
      }
      if (this.tokens.matches1AtIndex(i4, TokenType._export) && !this.tokens.matches2AtIndex(i4, TokenType._export, TokenType.eq)) {
        this.preprocessExportAtIndex(i4);
      }
    }
    this.generateImportReplacements();
  }
  /**
   * In TypeScript, import statements that only import types should be removed.
   * This includes `import {} from 'foo';`, but not `import 'foo';`.
   */
  pruneTypeOnlyImports() {
    this.nonTypeIdentifiers = getNonTypeIdentifiers(this.tokens, this.options);
    for (const [path, importInfo] of this.importInfoByPath.entries()) {
      if (importInfo.hasBareImport || importInfo.hasStarExport || importInfo.exportStarNames.length > 0 || importInfo.namedExports.length > 0) {
        continue;
      }
      const names = [
        ...importInfo.defaultNames,
        ...importInfo.wildcardNames,
        ...importInfo.namedImports.map(({ localName }) => localName)
      ];
      if (names.every((name) => this.shouldAutomaticallyElideImportedName(name))) {
        this.importsToReplace.set(path, "");
      }
    }
  }
  shouldAutomaticallyElideImportedName(name) {
    return this.isTypeScriptTransformEnabled && !this.keepUnusedImports && !this.nonTypeIdentifiers.has(name);
  }
  generateImportReplacements() {
    for (const [path, importInfo] of this.importInfoByPath.entries()) {
      const {
        defaultNames,
        wildcardNames,
        namedImports,
        namedExports,
        exportStarNames,
        hasStarExport
      } = importInfo;
      if (defaultNames.length === 0 && wildcardNames.length === 0 && namedImports.length === 0 && namedExports.length === 0 && exportStarNames.length === 0 && !hasStarExport) {
        this.importsToReplace.set(path, `require('${path}');`);
        continue;
      }
      const primaryImportName = this.getFreeIdentifierForPath(path);
      let secondaryImportName;
      if (this.enableLegacyTypeScriptModuleInterop) {
        secondaryImportName = primaryImportName;
      } else {
        secondaryImportName = wildcardNames.length > 0 ? wildcardNames[0] : this.getFreeIdentifierForPath(path);
      }
      let requireCode = `var ${primaryImportName} = require('${path}');`;
      if (wildcardNames.length > 0) {
        for (const wildcardName of wildcardNames) {
          const moduleExpr = this.enableLegacyTypeScriptModuleInterop ? primaryImportName : `${this.helperManager.getHelperName("interopRequireWildcard")}(${primaryImportName})`;
          requireCode += ` var ${wildcardName} = ${moduleExpr};`;
        }
      } else if (exportStarNames.length > 0 && secondaryImportName !== primaryImportName) {
        requireCode += ` var ${secondaryImportName} = ${this.helperManager.getHelperName(
          "interopRequireWildcard"
        )}(${primaryImportName});`;
      } else if (defaultNames.length > 0 && secondaryImportName !== primaryImportName) {
        requireCode += ` var ${secondaryImportName} = ${this.helperManager.getHelperName(
          "interopRequireDefault"
        )}(${primaryImportName});`;
      }
      for (const { importedName, localName } of namedExports) {
        requireCode += ` ${this.helperManager.getHelperName(
          "createNamedExportFrom"
        )}(${primaryImportName}, '${localName}', '${importedName}');`;
      }
      for (const exportStarName of exportStarNames) {
        requireCode += ` exports.${exportStarName} = ${secondaryImportName};`;
      }
      if (hasStarExport) {
        requireCode += ` ${this.helperManager.getHelperName(
          "createStarExport"
        )}(${primaryImportName});`;
      }
      this.importsToReplace.set(path, requireCode);
      for (const defaultName of defaultNames) {
        this.identifierReplacements.set(defaultName, `${secondaryImportName}.default`);
      }
      for (const { importedName, localName } of namedImports) {
        this.identifierReplacements.set(localName, `${primaryImportName}.${importedName}`);
      }
    }
  }
  getFreeIdentifierForPath(path) {
    const components = path.split("/");
    const lastComponent = components[components.length - 1];
    const baseName = lastComponent.replace(/\W/g, "");
    return this.nameManager.claimFreeName(`_${baseName}`);
  }
  preprocessImportAtIndex(index) {
    const defaultNames = [];
    const wildcardNames = [];
    const namedImports = [];
    index++;
    if ((this.tokens.matchesContextualAtIndex(index, ContextualKeyword._type) || this.tokens.matches1AtIndex(index, TokenType._typeof)) && !this.tokens.matches1AtIndex(index + 1, TokenType.comma) && !this.tokens.matchesContextualAtIndex(index + 1, ContextualKeyword._from)) {
      return;
    }
    if (this.tokens.matches1AtIndex(index, TokenType.parenL)) {
      return;
    }
    if (this.tokens.matches1AtIndex(index, TokenType.name)) {
      defaultNames.push(this.tokens.identifierNameAtIndex(index));
      index++;
      if (this.tokens.matches1AtIndex(index, TokenType.comma)) {
        index++;
      }
    }
    if (this.tokens.matches1AtIndex(index, TokenType.star)) {
      index += 2;
      wildcardNames.push(this.tokens.identifierNameAtIndex(index));
      index++;
    }
    if (this.tokens.matches1AtIndex(index, TokenType.braceL)) {
      const result = this.getNamedImports(index + 1);
      index = result.newIndex;
      for (const namedImport of result.namedImports) {
        if (namedImport.importedName === "default") {
          defaultNames.push(namedImport.localName);
        } else {
          namedImports.push(namedImport);
        }
      }
    }
    if (this.tokens.matchesContextualAtIndex(index, ContextualKeyword._from)) {
      index++;
    }
    if (!this.tokens.matches1AtIndex(index, TokenType.string)) {
      throw new Error("Expected string token at the end of import statement.");
    }
    const path = this.tokens.stringValueAtIndex(index);
    const importInfo = this.getImportInfo(path);
    importInfo.defaultNames.push(...defaultNames);
    importInfo.wildcardNames.push(...wildcardNames);
    importInfo.namedImports.push(...namedImports);
    if (defaultNames.length === 0 && wildcardNames.length === 0 && namedImports.length === 0) {
      importInfo.hasBareImport = true;
    }
  }
  preprocessExportAtIndex(index) {
    if (this.tokens.matches2AtIndex(index, TokenType._export, TokenType._var) || this.tokens.matches2AtIndex(index, TokenType._export, TokenType._let) || this.tokens.matches2AtIndex(index, TokenType._export, TokenType._const)) {
      this.preprocessVarExportAtIndex(index);
    } else if (this.tokens.matches2AtIndex(index, TokenType._export, TokenType._function) || this.tokens.matches2AtIndex(index, TokenType._export, TokenType._class)) {
      const exportName = this.tokens.identifierNameAtIndex(index + 2);
      this.addExportBinding(exportName, exportName);
    } else if (this.tokens.matches3AtIndex(index, TokenType._export, TokenType.name, TokenType._function)) {
      const exportName = this.tokens.identifierNameAtIndex(index + 3);
      this.addExportBinding(exportName, exportName);
    } else if (this.tokens.matches2AtIndex(index, TokenType._export, TokenType.braceL)) {
      this.preprocessNamedExportAtIndex(index);
    } else if (this.tokens.matches2AtIndex(index, TokenType._export, TokenType.star)) {
      this.preprocessExportStarAtIndex(index);
    }
  }
  preprocessVarExportAtIndex(index) {
    let depth = 0;
    for (let i4 = index + 2; ; i4++) {
      if (this.tokens.matches1AtIndex(i4, TokenType.braceL) || this.tokens.matches1AtIndex(i4, TokenType.dollarBraceL) || this.tokens.matches1AtIndex(i4, TokenType.bracketL)) {
        depth++;
      } else if (this.tokens.matches1AtIndex(i4, TokenType.braceR) || this.tokens.matches1AtIndex(i4, TokenType.bracketR)) {
        depth--;
      } else if (depth === 0 && !this.tokens.matches1AtIndex(i4, TokenType.name)) {
        break;
      } else if (this.tokens.matches1AtIndex(1, TokenType.eq)) {
        const endIndex = this.tokens.currentToken().rhsEndIndex;
        if (endIndex == null) {
          throw new Error("Expected = token with an end index.");
        }
        i4 = endIndex - 1;
      } else {
        const token = this.tokens.tokens[i4];
        if (isDeclaration(token)) {
          const exportName = this.tokens.identifierNameAtIndex(i4);
          this.identifierReplacements.set(exportName, `exports.${exportName}`);
        }
      }
    }
  }
  /**
   * Walk this export statement just in case it's an export...from statement.
   * If it is, combine it into the import info for that path. Otherwise, just
   * bail out; it'll be handled later.
   */
  preprocessNamedExportAtIndex(index) {
    index += 2;
    const { newIndex, namedImports } = this.getNamedImports(index);
    index = newIndex;
    if (this.tokens.matchesContextualAtIndex(index, ContextualKeyword._from)) {
      index++;
    } else {
      for (const { importedName: localName, localName: exportedName } of namedImports) {
        this.addExportBinding(localName, exportedName);
      }
      return;
    }
    if (!this.tokens.matches1AtIndex(index, TokenType.string)) {
      throw new Error("Expected string token at the end of import statement.");
    }
    const path = this.tokens.stringValueAtIndex(index);
    const importInfo = this.getImportInfo(path);
    importInfo.namedExports.push(...namedImports);
  }
  preprocessExportStarAtIndex(index) {
    let exportedName = null;
    if (this.tokens.matches3AtIndex(index, TokenType._export, TokenType.star, TokenType._as)) {
      index += 3;
      exportedName = this.tokens.identifierNameAtIndex(index);
      index += 2;
    } else {
      index += 3;
    }
    if (!this.tokens.matches1AtIndex(index, TokenType.string)) {
      throw new Error("Expected string token at the end of star export statement.");
    }
    const path = this.tokens.stringValueAtIndex(index);
    const importInfo = this.getImportInfo(path);
    if (exportedName !== null) {
      importInfo.exportStarNames.push(exportedName);
    } else {
      importInfo.hasStarExport = true;
    }
  }
  getNamedImports(index) {
    const namedImports = [];
    while (true) {
      if (this.tokens.matches1AtIndex(index, TokenType.braceR)) {
        index++;
        break;
      }
      const specifierInfo = getImportExportSpecifierInfo(this.tokens, index);
      index = specifierInfo.endIndex;
      if (!specifierInfo.isType) {
        namedImports.push({
          importedName: specifierInfo.leftName,
          localName: specifierInfo.rightName
        });
      }
      if (this.tokens.matches2AtIndex(index, TokenType.comma, TokenType.braceR)) {
        index += 2;
        break;
      } else if (this.tokens.matches1AtIndex(index, TokenType.braceR)) {
        index++;
        break;
      } else if (this.tokens.matches1AtIndex(index, TokenType.comma)) {
        index++;
      } else {
        throw new Error(`Unexpected token: ${JSON.stringify(this.tokens.tokens[index])}`);
      }
    }
    return { newIndex: index, namedImports };
  }
  /**
   * Get a mutable import info object for this path, creating one if it doesn't
   * exist yet.
   */
  getImportInfo(path) {
    const existingInfo = this.importInfoByPath.get(path);
    if (existingInfo) {
      return existingInfo;
    }
    const newInfo = {
      defaultNames: [],
      wildcardNames: [],
      namedImports: [],
      namedExports: [],
      hasBareImport: false,
      exportStarNames: [],
      hasStarExport: false
    };
    this.importInfoByPath.set(path, newInfo);
    return newInfo;
  }
  addExportBinding(localName, exportedName) {
    if (!this.exportBindingsByLocalName.has(localName)) {
      this.exportBindingsByLocalName.set(localName, []);
    }
    this.exportBindingsByLocalName.get(localName).push(exportedName);
  }
  /**
   * Return the code to use for the import for this path, or the empty string if
   * the code has already been "claimed" by a previous import.
   */
  claimImportCode(importPath) {
    const result = this.importsToReplace.get(importPath);
    this.importsToReplace.set(importPath, "");
    return result || "";
  }
  getIdentifierReplacement(identifierName) {
    return this.identifierReplacements.get(identifierName) || null;
  }
  /**
   * Return a string like `exports.foo = exports.bar`.
   */
  resolveExportBinding(assignedName) {
    const exportedNames = this.exportBindingsByLocalName.get(assignedName);
    if (!exportedNames || exportedNames.length === 0) {
      return null;
    }
    return exportedNames.map((exportedName) => `exports.${exportedName}`).join(" = ");
  }
  /**
   * Return all imported/exported names where we might be interested in whether usages of those
   * names are shadowed.
   */
  getGlobalNames() {
    return /* @__PURE__ */ new Set([
      ...this.identifierReplacements.keys(),
      ...this.exportBindingsByLocalName.keys()
    ]);
  }
};

// node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
var comma = ",".charCodeAt(0);
var semicolon2 = ";".charCodeAt(0);
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var intToChar = new Uint8Array(64);
var charToInt = new Uint8Array(128);
for (let i4 = 0; i4 < chars.length; i4++) {
  const c3 = chars.charCodeAt(i4);
  intToChar[i4] = c3;
  charToInt[c3] = i4;
}
function encodeInteger(builder, num, relative) {
  let delta = num - relative;
  delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
  do {
    let clamped = delta & 31;
    delta >>>= 5;
    if (delta > 0)
      clamped |= 32;
    builder.write(intToChar[clamped]);
  } while (delta > 0);
  return num;
}
var bufLength = 1024 * 16;
var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
  decode(buf) {
    const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
    return out.toString();
  }
} : {
  decode(buf) {
    let out = "";
    for (let i4 = 0; i4 < buf.length; i4++) {
      out += String.fromCharCode(buf[i4]);
    }
    return out;
  }
};
var StringWriter = class {
  constructor() {
    this.pos = 0;
    this.out = "";
    this.buffer = new Uint8Array(bufLength);
  }
  write(v3) {
    const { buffer } = this;
    buffer[this.pos++] = v3;
    if (this.pos === bufLength) {
      this.out += td.decode(buffer);
      this.pos = 0;
    }
  }
  flush() {
    const { buffer, out, pos } = this;
    return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  }
};
function encode(decoded) {
  const writer = new StringWriter();
  let sourcesIndex = 0;
  let sourceLine = 0;
  let sourceColumn = 0;
  let namesIndex = 0;
  for (let i4 = 0; i4 < decoded.length; i4++) {
    const line = decoded[i4];
    if (i4 > 0)
      writer.write(semicolon2);
    if (line.length === 0)
      continue;
    let genColumn = 0;
    for (let j4 = 0; j4 < line.length; j4++) {
      const segment = line[j4];
      if (j4 > 0)
        writer.write(comma);
      genColumn = encodeInteger(writer, segment[0], genColumn);
      if (segment.length === 1)
        continue;
      sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
      sourceLine = encodeInteger(writer, segment[2], sourceLine);
      sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
      if (segment.length === 4)
        continue;
      namesIndex = encodeInteger(writer, segment[4], namesIndex);
    }
  }
  return writer.flush();
}

// node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
var import_resolve_uri = __toESM(require_resolve_uri_umd(), 1);

// node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs
var SetArray = class {
  constructor() {
    this._indexes = { __proto__: null };
    this.array = [];
  }
};
function cast(set) {
  return set;
}
function get(setarr, key) {
  return cast(setarr)._indexes[key];
}
function put(setarr, key) {
  const index = get(setarr, key);
  if (index !== void 0)
    return index;
  const { array: array2, _indexes: indexes } = cast(setarr);
  const length = array2.push(key);
  return indexes[key] = length - 1;
}
var COLUMN = 0;
var SOURCES_INDEX = 1;
var SOURCE_LINE = 2;
var SOURCE_COLUMN = 3;
var NAMES_INDEX = 4;
var NO_NAME = -1;
var GenMapping = class {
  constructor({ file, sourceRoot } = {}) {
    this._names = new SetArray();
    this._sources = new SetArray();
    this._sourcesContent = [];
    this._mappings = [];
    this.file = file;
    this.sourceRoot = sourceRoot;
    this._ignoreList = new SetArray();
  }
};
function cast2(map) {
  return map;
}
var maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
  return addSegmentInternal(
    true,
    map,
    genLine,
    genColumn,
    source,
    sourceLine,
    sourceColumn,
    name,
    content
  );
};
function toDecodedMap(map) {
  const {
    _mappings: mappings,
    _sources: sources,
    _sourcesContent: sourcesContent,
    _names: names,
    _ignoreList: ignoreList
    // _originalScopes: originalScopes,
    // _generatedRanges: generatedRanges,
  } = cast2(map);
  removeEmptyFinalLines(mappings);
  return {
    version: 3,
    file: map.file || void 0,
    names: names.array,
    sourceRoot: map.sourceRoot || void 0,
    sources: sources.array,
    sourcesContent,
    mappings,
    // originalScopes,
    // generatedRanges,
    ignoreList: ignoreList.array
  };
}
function toEncodedMap(map) {
  const decoded = toDecodedMap(map);
  return Object.assign({}, decoded, {
    // originalScopes: decoded.originalScopes.map((os) => encodeOriginalScopes(os)),
    // generatedRanges: encodeGeneratedRanges(decoded.generatedRanges as GeneratedRange[]),
    mappings: encode(decoded.mappings)
  });
}
function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
  const {
    _mappings: mappings,
    _sources: sources,
    _sourcesContent: sourcesContent,
    _names: names
    // _originalScopes: originalScopes,
  } = cast2(map);
  const line = getIndex(mappings, genLine);
  const index = getColumnIndex(line, genColumn);
  if (!source) {
    if (skipable && skipSourceless(line, index))
      return;
    return insert(line, index, [genColumn]);
  }
  assert(sourceLine);
  assert(sourceColumn);
  const sourcesIndex = put(sources, source);
  const namesIndex = name ? put(names, name) : NO_NAME;
  if (sourcesIndex === sourcesContent.length)
    sourcesContent[sourcesIndex] = content != null ? content : null;
  if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
    return;
  }
  return insert(
    line,
    index,
    name ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] : [genColumn, sourcesIndex, sourceLine, sourceColumn]
  );
}
function assert(_val) {
}
function getIndex(arr, index) {
  for (let i4 = arr.length; i4 <= index; i4++) {
    arr[i4] = [];
  }
  return arr[index];
}
function getColumnIndex(line, genColumn) {
  let index = line.length;
  for (let i4 = index - 1; i4 >= 0; index = i4--) {
    const current = line[i4];
    if (genColumn >= current[COLUMN])
      break;
  }
  return index;
}
function insert(array2, index, value) {
  for (let i4 = array2.length; i4 > index; i4--) {
    array2[i4] = array2[i4 - 1];
  }
  array2[index] = value;
}
function removeEmptyFinalLines(mappings) {
  const { length } = mappings;
  let len = length;
  for (let i4 = len - 1; i4 >= 0; len = i4, i4--) {
    if (mappings[i4].length > 0)
      break;
  }
  if (len < length)
    mappings.length = len;
}
function skipSourceless(line, index) {
  if (index === 0)
    return true;
  const prev = line[index - 1];
  return prev.length === 1;
}
function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
  if (index === 0)
    return false;
  const prev = line[index - 1];
  if (prev.length === 1)
    return false;
  return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME);
}

// node_modules/sucrase/dist/esm/computeSourceMap.js
function computeSourceMap({ code: generatedCode, mappings: rawMappings }, filePath, options, source, tokens) {
  const sourceColumns = computeSourceColumns(source, tokens);
  const map = new GenMapping({ file: options.compiledFilename });
  let tokenIndex = 0;
  let currentMapping = rawMappings[0];
  while (currentMapping === void 0 && tokenIndex < rawMappings.length - 1) {
    tokenIndex++;
    currentMapping = rawMappings[tokenIndex];
  }
  let line = 0;
  let lineStart = 0;
  if (currentMapping !== lineStart) {
    maybeAddSegment(map, line, 0, filePath, line, 0);
  }
  for (let i4 = 0; i4 < generatedCode.length; i4++) {
    if (i4 === currentMapping) {
      const genColumn = currentMapping - lineStart;
      const sourceColumn = sourceColumns[tokenIndex];
      maybeAddSegment(map, line, genColumn, filePath, line, sourceColumn);
      while ((currentMapping === i4 || currentMapping === void 0) && tokenIndex < rawMappings.length - 1) {
        tokenIndex++;
        currentMapping = rawMappings[tokenIndex];
      }
    }
    if (generatedCode.charCodeAt(i4) === charCodes.lineFeed) {
      line++;
      lineStart = i4 + 1;
      if (currentMapping !== lineStart) {
        maybeAddSegment(map, line, 0, filePath, line, 0);
      }
    }
  }
  const { sourceRoot, sourcesContent, ...sourceMap } = toEncodedMap(map);
  return sourceMap;
}
function computeSourceColumns(code, tokens) {
  const sourceColumns = new Array(tokens.length);
  let tokenIndex = 0;
  let currentMapping = tokens[tokenIndex].start;
  let lineStart = 0;
  for (let i4 = 0; i4 < code.length; i4++) {
    if (i4 === currentMapping) {
      sourceColumns[tokenIndex] = currentMapping - lineStart;
      tokenIndex++;
      currentMapping = tokens[tokenIndex].start;
    }
    if (code.charCodeAt(i4) === charCodes.lineFeed) {
      lineStart = i4 + 1;
    }
  }
  return sourceColumns;
}

// node_modules/sucrase/dist/esm/HelperManager.js
var HELPERS = {
  require: `
    import {createRequire as CREATE_REQUIRE_NAME} from "module";
    const require = CREATE_REQUIRE_NAME(import.meta.url);
  `,
  interopRequireWildcard: `
    function interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      } else {
        var newObj = {};
        if (obj != null) {
          for (var key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
              newObj[key] = obj[key];
            }
          }
        }
        newObj.default = obj;
        return newObj;
      }
    }
  `,
  interopRequireDefault: `
    function interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { default: obj };
    }
  `,
  createNamedExportFrom: `
    function createNamedExportFrom(obj, localName, importedName) {
      Object.defineProperty(exports, localName, {enumerable: true, configurable: true, get: () => obj[importedName]});
    }
  `,
  // Note that TypeScript and Babel do this differently; TypeScript does a simple existence
  // check in the exports object and does a plain assignment, whereas Babel uses
  // defineProperty and builds an object of explicitly-exported names so that star exports can
  // always take lower precedence. For now, we do the easier TypeScript thing.
  createStarExport: `
    function createStarExport(obj) {
      Object.keys(obj)
        .filter((key) => key !== "default" && key !== "__esModule")
        .forEach((key) => {
          if (exports.hasOwnProperty(key)) {
            return;
          }
          Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]});
        });
    }
  `,
  nullishCoalesce: `
    function nullishCoalesce(lhs, rhsFn) {
      if (lhs != null) {
        return lhs;
      } else {
        return rhsFn();
      }
    }
  `,
  asyncNullishCoalesce: `
    async function asyncNullishCoalesce(lhs, rhsFn) {
      if (lhs != null) {
        return lhs;
      } else {
        return await rhsFn();
      }
    }
  `,
  optionalChain: `
    function optionalChain(ops) {
      let lastAccessLHS = undefined;
      let value = ops[0];
      let i = 1;
      while (i < ops.length) {
        const op = ops[i];
        const fn = ops[i + 1];
        i += 2;
        if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {
          return undefined;
        }
        if (op === 'access' || op === 'optionalAccess') {
          lastAccessLHS = value;
          value = fn(value);
        } else if (op === 'call' || op === 'optionalCall') {
          value = fn((...args) => value.call(lastAccessLHS, ...args));
          lastAccessLHS = undefined;
        }
      }
      return value;
    }
  `,
  asyncOptionalChain: `
    async function asyncOptionalChain(ops) {
      let lastAccessLHS = undefined;
      let value = ops[0];
      let i = 1;
      while (i < ops.length) {
        const op = ops[i];
        const fn = ops[i + 1];
        i += 2;
        if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {
          return undefined;
        }
        if (op === 'access' || op === 'optionalAccess') {
          lastAccessLHS = value;
          value = await fn(value);
        } else if (op === 'call' || op === 'optionalCall') {
          value = await fn((...args) => value.call(lastAccessLHS, ...args));
          lastAccessLHS = undefined;
        }
      }
      return value;
    }
  `,
  optionalChainDelete: `
    function optionalChainDelete(ops) {
      const result = OPTIONAL_CHAIN_NAME(ops);
      return result == null ? true : result;
    }
  `,
  asyncOptionalChainDelete: `
    async function asyncOptionalChainDelete(ops) {
      const result = await ASYNC_OPTIONAL_CHAIN_NAME(ops);
      return result == null ? true : result;
    }
  `
};
var HelperManager = class {
  __init() {
    this.helperNames = {};
  }
  __init2() {
    this.createRequireName = null;
  }
  constructor(nameManager) {
    ;
    this.nameManager = nameManager;
    HelperManager.prototype.__init.call(this);
    HelperManager.prototype.__init2.call(this);
  }
  getHelperName(baseName) {
    let helperName = this.helperNames[baseName];
    if (helperName) {
      return helperName;
    }
    helperName = this.nameManager.claimFreeName(`_${baseName}`);
    this.helperNames[baseName] = helperName;
    return helperName;
  }
  emitHelpers() {
    let resultCode = "";
    if (this.helperNames.optionalChainDelete) {
      this.getHelperName("optionalChain");
    }
    if (this.helperNames.asyncOptionalChainDelete) {
      this.getHelperName("asyncOptionalChain");
    }
    for (const [baseName, helperCodeTemplate] of Object.entries(HELPERS)) {
      const helperName = this.helperNames[baseName];
      let helperCode = helperCodeTemplate;
      if (baseName === "optionalChainDelete") {
        helperCode = helperCode.replace("OPTIONAL_CHAIN_NAME", this.helperNames.optionalChain);
      } else if (baseName === "asyncOptionalChainDelete") {
        helperCode = helperCode.replace(
          "ASYNC_OPTIONAL_CHAIN_NAME",
          this.helperNames.asyncOptionalChain
        );
      } else if (baseName === "require") {
        if (this.createRequireName === null) {
          this.createRequireName = this.nameManager.claimFreeName("_createRequire");
        }
        helperCode = helperCode.replace(/CREATE_REQUIRE_NAME/g, this.createRequireName);
      }
      if (helperName) {
        resultCode += " ";
        resultCode += helperCode.replace(baseName, helperName).replace(/\s+/g, " ").trim();
      }
    }
    return resultCode;
  }
};

// node_modules/sucrase/dist/esm/identifyShadowedGlobals.js
function identifyShadowedGlobals(tokens, scopes, globalNames) {
  if (!hasShadowedGlobals(tokens, globalNames)) {
    return;
  }
  markShadowedGlobals(tokens, scopes, globalNames);
}
function hasShadowedGlobals(tokens, globalNames) {
  for (const token of tokens.tokens) {
    if (token.type === TokenType.name && !token.isType && isNonTopLevelDeclaration(token) && globalNames.has(tokens.identifierNameForToken(token))) {
      return true;
    }
  }
  return false;
}
function markShadowedGlobals(tokens, scopes, globalNames) {
  const scopeStack = [];
  let scopeIndex = scopes.length - 1;
  for (let i4 = tokens.tokens.length - 1; ; i4--) {
    while (scopeStack.length > 0 && scopeStack[scopeStack.length - 1].startTokenIndex === i4 + 1) {
      scopeStack.pop();
    }
    while (scopeIndex >= 0 && scopes[scopeIndex].endTokenIndex === i4 + 1) {
      scopeStack.push(scopes[scopeIndex]);
      scopeIndex--;
    }
    if (i4 < 0) {
      break;
    }
    const token = tokens.tokens[i4];
    const name = tokens.identifierNameForToken(token);
    if (scopeStack.length > 1 && !token.isType && token.type === TokenType.name && globalNames.has(name)) {
      if (isBlockScopedDeclaration(token)) {
        markShadowedForScope(scopeStack[scopeStack.length - 1], tokens, name);
      } else if (isFunctionScopedDeclaration(token)) {
        let stackIndex = scopeStack.length - 1;
        while (stackIndex > 0 && !scopeStack[stackIndex].isFunctionScope) {
          stackIndex--;
        }
        if (stackIndex < 0) {
          throw new Error("Did not find parent function scope.");
        }
        markShadowedForScope(scopeStack[stackIndex], tokens, name);
      }
    }
  }
  if (scopeStack.length > 0) {
    throw new Error("Expected empty scope stack after processing file.");
  }
}
function markShadowedForScope(scope, tokens, name) {
  for (let i4 = scope.startTokenIndex; i4 < scope.endTokenIndex; i4++) {
    const token = tokens.tokens[i4];
    if ((token.type === TokenType.name || token.type === TokenType.jsxName) && tokens.identifierNameForToken(token) === name) {
      token.shadowsGlobal = true;
    }
  }
}

// node_modules/sucrase/dist/esm/util/getIdentifierNames.js
function getIdentifierNames(code, tokens) {
  const names = [];
  for (const token of tokens) {
    if (token.type === TokenType.name) {
      names.push(code.slice(token.start, token.end));
    }
  }
  return names;
}

// node_modules/sucrase/dist/esm/NameManager.js
var NameManager = class {
  __init() {
    this.usedNames = /* @__PURE__ */ new Set();
  }
  constructor(code, tokens) {
    ;
    NameManager.prototype.__init.call(this);
    this.usedNames = new Set(getIdentifierNames(code, tokens));
  }
  claimFreeName(name) {
    const newName = this.findFreeName(name);
    this.usedNames.add(newName);
    return newName;
  }
  findFreeName(name) {
    if (!this.usedNames.has(name)) {
      return name;
    }
    let suffixNum = 2;
    while (this.usedNames.has(name + String(suffixNum))) {
      suffixNum++;
    }
    return name + String(suffixNum);
  }
};

// node_modules/sucrase/dist/esm/Options.js
var import_ts_interface_checker = __toESM(require_dist());

// node_modules/sucrase/dist/esm/Options-gen-types.js
var t3 = __toESM(require_dist());
var Transform = t3.union(
  t3.lit("jsx"),
  t3.lit("typescript"),
  t3.lit("flow"),
  t3.lit("imports"),
  t3.lit("react-hot-loader"),
  t3.lit("jest")
);
var SourceMapOptions = t3.iface([], {
  compiledFilename: "string"
});
var Options = t3.iface([], {
  transforms: t3.array("Transform"),
  disableESTransforms: t3.opt("boolean"),
  jsxRuntime: t3.opt(t3.union(t3.lit("classic"), t3.lit("automatic"), t3.lit("preserve"))),
  production: t3.opt("boolean"),
  jsxImportSource: t3.opt("string"),
  jsxPragma: t3.opt("string"),
  jsxFragmentPragma: t3.opt("string"),
  keepUnusedImports: t3.opt("boolean"),
  preserveDynamicImport: t3.opt("boolean"),
  injectCreateRequireForImportRequire: t3.opt("boolean"),
  enableLegacyTypeScriptModuleInterop: t3.opt("boolean"),
  enableLegacyBabel5ModuleInterop: t3.opt("boolean"),
  sourceMapOptions: t3.opt("SourceMapOptions"),
  filePath: t3.opt("string")
});
var exportedTypeSuite = {
  Transform,
  SourceMapOptions,
  Options
};
var Options_gen_types_default = exportedTypeSuite;

// node_modules/sucrase/dist/esm/Options.js
var { Options: OptionsChecker } = (0, import_ts_interface_checker.createCheckers)(Options_gen_types_default);
function validateOptions(options) {
  OptionsChecker.strictCheck(options);
}

// node_modules/sucrase/dist/esm/parser/traverser/lval.js
function parseSpread() {
  next();
  parseMaybeAssign(false);
}
function parseRest(isBlockScope) {
  next();
  parseBindingAtom(isBlockScope);
}
function parseBindingIdentifier(isBlockScope) {
  parseIdentifier();
  markPriorBindingIdentifier(isBlockScope);
}
function parseImportedIdentifier() {
  parseIdentifier();
  state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.ImportDeclaration;
}
function markPriorBindingIdentifier(isBlockScope) {
  let identifierRole;
  if (state.scopeDepth === 0) {
    identifierRole = IdentifierRole.TopLevelDeclaration;
  } else if (isBlockScope) {
    identifierRole = IdentifierRole.BlockScopedDeclaration;
  } else {
    identifierRole = IdentifierRole.FunctionScopedDeclaration;
  }
  state.tokens[state.tokens.length - 1].identifierRole = identifierRole;
}
function parseBindingAtom(isBlockScope) {
  switch (state.type) {
    case TokenType._this: {
      const oldIsType = pushTypeContext(0);
      next();
      popTypeContext(oldIsType);
      return;
    }
    case TokenType._yield:
    case TokenType.name: {
      state.type = TokenType.name;
      parseBindingIdentifier(isBlockScope);
      return;
    }
    case TokenType.bracketL: {
      next();
      parseBindingList(
        TokenType.bracketR,
        isBlockScope,
        true
        /* allowEmpty */
      );
      return;
    }
    case TokenType.braceL:
      parseObj(true, isBlockScope);
      return;
    default:
      unexpected();
  }
}
function parseBindingList(close, isBlockScope, allowEmpty = false, allowModifiers = false, contextId = 0) {
  let first = true;
  let hasRemovedComma = false;
  const firstItemTokenIndex = state.tokens.length;
  while (!eat(close) && !state.error) {
    if (first) {
      first = false;
    } else {
      expect(TokenType.comma);
      state.tokens[state.tokens.length - 1].contextId = contextId;
      if (!hasRemovedComma && state.tokens[firstItemTokenIndex].isType) {
        state.tokens[state.tokens.length - 1].isType = true;
        hasRemovedComma = true;
      }
    }
    if (allowEmpty && match2(TokenType.comma)) {
    } else if (eat(close)) {
      break;
    } else if (match2(TokenType.ellipsis)) {
      parseRest(isBlockScope);
      parseAssignableListItemTypes();
      eat(TokenType.comma);
      expect(close);
      break;
    } else {
      parseAssignableListItem(allowModifiers, isBlockScope);
    }
  }
}
function parseAssignableListItem(allowModifiers, isBlockScope) {
  if (allowModifiers) {
    tsParseModifiers([
      ContextualKeyword._public,
      ContextualKeyword._protected,
      ContextualKeyword._private,
      ContextualKeyword._readonly,
      ContextualKeyword._override
    ]);
  }
  parseMaybeDefault(isBlockScope);
  parseAssignableListItemTypes();
  parseMaybeDefault(
    isBlockScope,
    true
    /* leftAlreadyParsed */
  );
}
function parseAssignableListItemTypes() {
  if (isFlowEnabled) {
    flowParseAssignableListItemTypes();
  } else if (isTypeScriptEnabled) {
    tsParseAssignableListItemTypes();
  }
}
function parseMaybeDefault(isBlockScope, leftAlreadyParsed = false) {
  if (!leftAlreadyParsed) {
    parseBindingAtom(isBlockScope);
  }
  if (!eat(TokenType.eq)) {
    return;
  }
  const eqIndex = state.tokens.length - 1;
  parseMaybeAssign();
  state.tokens[eqIndex].rhsEndIndex = state.tokens.length;
}

// node_modules/sucrase/dist/esm/parser/plugins/typescript.js
function tsIsIdentifier() {
  return match2(TokenType.name);
}
function isLiteralPropertyName() {
  return match2(TokenType.name) || Boolean(state.type & TokenType.IS_KEYWORD) || match2(TokenType.string) || match2(TokenType.num) || match2(TokenType.bigint) || match2(TokenType.decimal);
}
function tsNextTokenCanFollowModifier() {
  const snapshot = state.snapshot();
  next();
  const canFollowModifier = (match2(TokenType.bracketL) || match2(TokenType.braceL) || match2(TokenType.star) || match2(TokenType.ellipsis) || match2(TokenType.hash) || isLiteralPropertyName()) && !hasPrecedingLineBreak();
  if (canFollowModifier) {
    return true;
  } else {
    state.restoreFromSnapshot(snapshot);
    return false;
  }
}
function tsParseModifiers(allowedModifiers) {
  while (true) {
    const modifier = tsParseModifier(allowedModifiers);
    if (modifier === null) {
      break;
    }
  }
}
function tsParseModifier(allowedModifiers) {
  if (!match2(TokenType.name)) {
    return null;
  }
  const modifier = state.contextualKeyword;
  if (allowedModifiers.indexOf(modifier) !== -1 && tsNextTokenCanFollowModifier()) {
    switch (modifier) {
      case ContextualKeyword._readonly:
        state.tokens[state.tokens.length - 1].type = TokenType._readonly;
        break;
      case ContextualKeyword._abstract:
        state.tokens[state.tokens.length - 1].type = TokenType._abstract;
        break;
      case ContextualKeyword._static:
        state.tokens[state.tokens.length - 1].type = TokenType._static;
        break;
      case ContextualKeyword._public:
        state.tokens[state.tokens.length - 1].type = TokenType._public;
        break;
      case ContextualKeyword._private:
        state.tokens[state.tokens.length - 1].type = TokenType._private;
        break;
      case ContextualKeyword._protected:
        state.tokens[state.tokens.length - 1].type = TokenType._protected;
        break;
      case ContextualKeyword._override:
        state.tokens[state.tokens.length - 1].type = TokenType._override;
        break;
      case ContextualKeyword._declare:
        state.tokens[state.tokens.length - 1].type = TokenType._declare;
        break;
      default:
        break;
    }
    return modifier;
  }
  return null;
}
function tsParseEntityName() {
  parseIdentifier();
  while (eat(TokenType.dot)) {
    parseIdentifier();
  }
}
function tsParseTypeReference() {
  tsParseEntityName();
  if (!hasPrecedingLineBreak() && match2(TokenType.lessThan)) {
    tsParseTypeArguments();
  }
}
function tsParseThisTypePredicate() {
  next();
  tsParseTypeAnnotation();
}
function tsParseThisTypeNode() {
  next();
}
function tsParseTypeQuery() {
  expect(TokenType._typeof);
  if (match2(TokenType._import)) {
    tsParseImportType();
  } else {
    tsParseEntityName();
  }
  if (!hasPrecedingLineBreak() && match2(TokenType.lessThan)) {
    tsParseTypeArguments();
  }
}
function tsParseImportType() {
  expect(TokenType._import);
  expect(TokenType.parenL);
  expect(TokenType.string);
  expect(TokenType.parenR);
  if (eat(TokenType.dot)) {
    tsParseEntityName();
  }
  if (match2(TokenType.lessThan)) {
    tsParseTypeArguments();
  }
}
function tsParseTypeParameter() {
  eat(TokenType._const);
  const hadIn = eat(TokenType._in);
  const hadOut = eatContextual(ContextualKeyword._out);
  eat(TokenType._const);
  if ((hadIn || hadOut) && !match2(TokenType.name)) {
    state.tokens[state.tokens.length - 1].type = TokenType.name;
  } else {
    parseIdentifier();
  }
  if (eat(TokenType._extends)) {
    tsParseType();
  }
  if (eat(TokenType.eq)) {
    tsParseType();
  }
}
function tsTryParseTypeParameters() {
  if (match2(TokenType.lessThan)) {
    tsParseTypeParameters();
  }
}
function tsParseTypeParameters() {
  const oldIsType = pushTypeContext(0);
  if (match2(TokenType.lessThan) || match2(TokenType.typeParameterStart)) {
    next();
  } else {
    unexpected();
  }
  while (!eat(TokenType.greaterThan) && !state.error) {
    tsParseTypeParameter();
    eat(TokenType.comma);
  }
  popTypeContext(oldIsType);
}
function tsFillSignature(returnToken) {
  const returnTokenRequired = returnToken === TokenType.arrow;
  tsTryParseTypeParameters();
  expect(TokenType.parenL);
  state.scopeDepth++;
  tsParseBindingListForSignature(
    false
    /* isBlockScope */
  );
  state.scopeDepth--;
  if (returnTokenRequired) {
    tsParseTypeOrTypePredicateAnnotation(returnToken);
  } else if (match2(returnToken)) {
    tsParseTypeOrTypePredicateAnnotation(returnToken);
  }
}
function tsParseBindingListForSignature(isBlockScope) {
  parseBindingList(TokenType.parenR, isBlockScope);
}
function tsParseTypeMemberSemicolon() {
  if (!eat(TokenType.comma)) {
    semicolon();
  }
}
function tsParseSignatureMember() {
  tsFillSignature(TokenType.colon);
  tsParseTypeMemberSemicolon();
}
function tsIsUnambiguouslyIndexSignature() {
  const snapshot = state.snapshot();
  next();
  const isIndexSignature = eat(TokenType.name) && match2(TokenType.colon);
  state.restoreFromSnapshot(snapshot);
  return isIndexSignature;
}
function tsTryParseIndexSignature() {
  if (!(match2(TokenType.bracketL) && tsIsUnambiguouslyIndexSignature())) {
    return false;
  }
  const oldIsType = pushTypeContext(0);
  expect(TokenType.bracketL);
  parseIdentifier();
  tsParseTypeAnnotation();
  expect(TokenType.bracketR);
  tsTryParseTypeAnnotation();
  tsParseTypeMemberSemicolon();
  popTypeContext(oldIsType);
  return true;
}
function tsParsePropertyOrMethodSignature(isReadonly) {
  eat(TokenType.question);
  if (!isReadonly && (match2(TokenType.parenL) || match2(TokenType.lessThan))) {
    tsFillSignature(TokenType.colon);
    tsParseTypeMemberSemicolon();
  } else {
    tsTryParseTypeAnnotation();
    tsParseTypeMemberSemicolon();
  }
}
function tsParseTypeMember() {
  if (match2(TokenType.parenL) || match2(TokenType.lessThan)) {
    tsParseSignatureMember();
    return;
  }
  if (match2(TokenType._new)) {
    next();
    if (match2(TokenType.parenL) || match2(TokenType.lessThan)) {
      tsParseSignatureMember();
    } else {
      tsParsePropertyOrMethodSignature(false);
    }
    return;
  }
  const readonly = !!tsParseModifier([ContextualKeyword._readonly]);
  const found = tsTryParseIndexSignature();
  if (found) {
    return;
  }
  if ((isContextual(ContextualKeyword._get) || isContextual(ContextualKeyword._set)) && tsNextTokenCanFollowModifier()) {
  }
  parsePropertyName(
    -1
    /* Types don't need context IDs. */
  );
  tsParsePropertyOrMethodSignature(readonly);
}
function tsParseTypeLiteral() {
  tsParseObjectTypeMembers();
}
function tsParseObjectTypeMembers() {
  expect(TokenType.braceL);
  while (!eat(TokenType.braceR) && !state.error) {
    tsParseTypeMember();
  }
}
function tsLookaheadIsStartOfMappedType() {
  const snapshot = state.snapshot();
  const isStartOfMappedType = tsIsStartOfMappedType();
  state.restoreFromSnapshot(snapshot);
  return isStartOfMappedType;
}
function tsIsStartOfMappedType() {
  next();
  if (eat(TokenType.plus) || eat(TokenType.minus)) {
    return isContextual(ContextualKeyword._readonly);
  }
  if (isContextual(ContextualKeyword._readonly)) {
    next();
  }
  if (!match2(TokenType.bracketL)) {
    return false;
  }
  next();
  if (!tsIsIdentifier()) {
    return false;
  }
  next();
  return match2(TokenType._in);
}
function tsParseMappedTypeParameter() {
  parseIdentifier();
  expect(TokenType._in);
  tsParseType();
}
function tsParseMappedType() {
  expect(TokenType.braceL);
  if (match2(TokenType.plus) || match2(TokenType.minus)) {
    next();
    expectContextual(ContextualKeyword._readonly);
  } else {
    eatContextual(ContextualKeyword._readonly);
  }
  expect(TokenType.bracketL);
  tsParseMappedTypeParameter();
  if (eatContextual(ContextualKeyword._as)) {
    tsParseType();
  }
  expect(TokenType.bracketR);
  if (match2(TokenType.plus) || match2(TokenType.minus)) {
    next();
    expect(TokenType.question);
  } else {
    eat(TokenType.question);
  }
  tsTryParseType();
  semicolon();
  expect(TokenType.braceR);
}
function tsParseTupleType() {
  expect(TokenType.bracketL);
  while (!eat(TokenType.bracketR) && !state.error) {
    tsParseTupleElementType();
    eat(TokenType.comma);
  }
}
function tsParseTupleElementType() {
  if (eat(TokenType.ellipsis)) {
    tsParseType();
  } else {
    tsParseType();
    eat(TokenType.question);
  }
  if (eat(TokenType.colon)) {
    tsParseType();
  }
}
function tsParseParenthesizedType() {
  expect(TokenType.parenL);
  tsParseType();
  expect(TokenType.parenR);
}
function tsParseTemplateLiteralType() {
  nextTemplateToken();
  nextTemplateToken();
  while (!match2(TokenType.backQuote) && !state.error) {
    expect(TokenType.dollarBraceL);
    tsParseType();
    nextTemplateToken();
    nextTemplateToken();
  }
  next();
}
var FunctionType;
(function(FunctionType2) {
  const TSFunctionType = 0;
  FunctionType2[FunctionType2["TSFunctionType"] = TSFunctionType] = "TSFunctionType";
  const TSConstructorType = TSFunctionType + 1;
  FunctionType2[FunctionType2["TSConstructorType"] = TSConstructorType] = "TSConstructorType";
  const TSAbstractConstructorType = TSConstructorType + 1;
  FunctionType2[FunctionType2["TSAbstractConstructorType"] = TSAbstractConstructorType] = "TSAbstractConstructorType";
})(FunctionType || (FunctionType = {}));
function tsParseFunctionOrConstructorType(type) {
  if (type === FunctionType.TSAbstractConstructorType) {
    expectContextual(ContextualKeyword._abstract);
  }
  if (type === FunctionType.TSConstructorType || type === FunctionType.TSAbstractConstructorType) {
    expect(TokenType._new);
  }
  const oldInDisallowConditionalTypesContext = state.inDisallowConditionalTypesContext;
  state.inDisallowConditionalTypesContext = false;
  tsFillSignature(TokenType.arrow);
  state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
}
function tsParseNonArrayType() {
  switch (state.type) {
    case TokenType.name:
      tsParseTypeReference();
      return;
    case TokenType._void:
    case TokenType._null:
      next();
      return;
    case TokenType.string:
    case TokenType.num:
    case TokenType.bigint:
    case TokenType.decimal:
    case TokenType._true:
    case TokenType._false:
      parseLiteral();
      return;
    case TokenType.minus:
      next();
      parseLiteral();
      return;
    case TokenType._this: {
      tsParseThisTypeNode();
      if (isContextual(ContextualKeyword._is) && !hasPrecedingLineBreak()) {
        tsParseThisTypePredicate();
      }
      return;
    }
    case TokenType._typeof:
      tsParseTypeQuery();
      return;
    case TokenType._import:
      tsParseImportType();
      return;
    case TokenType.braceL:
      if (tsLookaheadIsStartOfMappedType()) {
        tsParseMappedType();
      } else {
        tsParseTypeLiteral();
      }
      return;
    case TokenType.bracketL:
      tsParseTupleType();
      return;
    case TokenType.parenL:
      tsParseParenthesizedType();
      return;
    case TokenType.backQuote:
      tsParseTemplateLiteralType();
      return;
    default:
      if (state.type & TokenType.IS_KEYWORD) {
        next();
        state.tokens[state.tokens.length - 1].type = TokenType.name;
        return;
      }
      break;
  }
  unexpected();
}
function tsParseArrayTypeOrHigher() {
  tsParseNonArrayType();
  while (!hasPrecedingLineBreak() && eat(TokenType.bracketL)) {
    if (!eat(TokenType.bracketR)) {
      tsParseType();
      expect(TokenType.bracketR);
    }
  }
}
function tsParseInferType() {
  expectContextual(ContextualKeyword._infer);
  parseIdentifier();
  if (match2(TokenType._extends)) {
    const snapshot = state.snapshot();
    expect(TokenType._extends);
    const oldInDisallowConditionalTypesContext = state.inDisallowConditionalTypesContext;
    state.inDisallowConditionalTypesContext = true;
    tsParseType();
    state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
    if (state.error || !state.inDisallowConditionalTypesContext && match2(TokenType.question)) {
      state.restoreFromSnapshot(snapshot);
    }
  }
}
function tsParseTypeOperatorOrHigher() {
  if (isContextual(ContextualKeyword._keyof) || isContextual(ContextualKeyword._unique) || isContextual(ContextualKeyword._readonly)) {
    next();
    tsParseTypeOperatorOrHigher();
  } else if (isContextual(ContextualKeyword._infer)) {
    tsParseInferType();
  } else {
    const oldInDisallowConditionalTypesContext = state.inDisallowConditionalTypesContext;
    state.inDisallowConditionalTypesContext = false;
    tsParseArrayTypeOrHigher();
    state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
  }
}
function tsParseIntersectionTypeOrHigher() {
  eat(TokenType.bitwiseAND);
  tsParseTypeOperatorOrHigher();
  if (match2(TokenType.bitwiseAND)) {
    while (eat(TokenType.bitwiseAND)) {
      tsParseTypeOperatorOrHigher();
    }
  }
}
function tsParseUnionTypeOrHigher() {
  eat(TokenType.bitwiseOR);
  tsParseIntersectionTypeOrHigher();
  if (match2(TokenType.bitwiseOR)) {
    while (eat(TokenType.bitwiseOR)) {
      tsParseIntersectionTypeOrHigher();
    }
  }
}
function tsIsStartOfFunctionType() {
  if (match2(TokenType.lessThan)) {
    return true;
  }
  return match2(TokenType.parenL) && tsLookaheadIsUnambiguouslyStartOfFunctionType();
}
function tsSkipParameterStart() {
  if (match2(TokenType.name) || match2(TokenType._this)) {
    next();
    return true;
  }
  if (match2(TokenType.braceL) || match2(TokenType.bracketL)) {
    let depth = 1;
    next();
    while (depth > 0 && !state.error) {
      if (match2(TokenType.braceL) || match2(TokenType.bracketL)) {
        depth++;
      } else if (match2(TokenType.braceR) || match2(TokenType.bracketR)) {
        depth--;
      }
      next();
    }
    return true;
  }
  return false;
}
function tsLookaheadIsUnambiguouslyStartOfFunctionType() {
  const snapshot = state.snapshot();
  const isUnambiguouslyStartOfFunctionType = tsIsUnambiguouslyStartOfFunctionType();
  state.restoreFromSnapshot(snapshot);
  return isUnambiguouslyStartOfFunctionType;
}
function tsIsUnambiguouslyStartOfFunctionType() {
  next();
  if (match2(TokenType.parenR) || match2(TokenType.ellipsis)) {
    return true;
  }
  if (tsSkipParameterStart()) {
    if (match2(TokenType.colon) || match2(TokenType.comma) || match2(TokenType.question) || match2(TokenType.eq)) {
      return true;
    }
    if (match2(TokenType.parenR)) {
      next();
      if (match2(TokenType.arrow)) {
        return true;
      }
    }
  }
  return false;
}
function tsParseTypeOrTypePredicateAnnotation(returnToken) {
  const oldIsType = pushTypeContext(0);
  expect(returnToken);
  const finishedReturn = tsParseTypePredicateOrAssertsPrefix();
  if (!finishedReturn) {
    tsParseType();
  }
  popTypeContext(oldIsType);
}
function tsTryParseTypeOrTypePredicateAnnotation() {
  if (match2(TokenType.colon)) {
    tsParseTypeOrTypePredicateAnnotation(TokenType.colon);
  }
}
function tsTryParseTypeAnnotation() {
  if (match2(TokenType.colon)) {
    tsParseTypeAnnotation();
  }
}
function tsTryParseType() {
  if (eat(TokenType.colon)) {
    tsParseType();
  }
}
function tsParseTypePredicateOrAssertsPrefix() {
  const snapshot = state.snapshot();
  if (isContextual(ContextualKeyword._asserts)) {
    next();
    if (eatContextual(ContextualKeyword._is)) {
      tsParseType();
      return true;
    } else if (tsIsIdentifier() || match2(TokenType._this)) {
      next();
      if (eatContextual(ContextualKeyword._is)) {
        tsParseType();
      }
      return true;
    } else {
      state.restoreFromSnapshot(snapshot);
      return false;
    }
  } else if (tsIsIdentifier() || match2(TokenType._this)) {
    next();
    if (isContextual(ContextualKeyword._is) && !hasPrecedingLineBreak()) {
      next();
      tsParseType();
      return true;
    } else {
      state.restoreFromSnapshot(snapshot);
      return false;
    }
  }
  return false;
}
function tsParseTypeAnnotation() {
  const oldIsType = pushTypeContext(0);
  expect(TokenType.colon);
  tsParseType();
  popTypeContext(oldIsType);
}
function tsParseType() {
  tsParseNonConditionalType();
  if (state.inDisallowConditionalTypesContext || hasPrecedingLineBreak() || !eat(TokenType._extends)) {
    return;
  }
  const oldInDisallowConditionalTypesContext = state.inDisallowConditionalTypesContext;
  state.inDisallowConditionalTypesContext = true;
  tsParseNonConditionalType();
  state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
  expect(TokenType.question);
  tsParseType();
  expect(TokenType.colon);
  tsParseType();
}
function isAbstractConstructorSignature() {
  return isContextual(ContextualKeyword._abstract) && lookaheadType() === TokenType._new;
}
function tsParseNonConditionalType() {
  if (tsIsStartOfFunctionType()) {
    tsParseFunctionOrConstructorType(FunctionType.TSFunctionType);
    return;
  }
  if (match2(TokenType._new)) {
    tsParseFunctionOrConstructorType(FunctionType.TSConstructorType);
    return;
  } else if (isAbstractConstructorSignature()) {
    tsParseFunctionOrConstructorType(FunctionType.TSAbstractConstructorType);
    return;
  }
  tsParseUnionTypeOrHigher();
}
function tsParseTypeAssertion() {
  const oldIsType = pushTypeContext(1);
  tsParseType();
  expect(TokenType.greaterThan);
  popTypeContext(oldIsType);
  parseMaybeUnary();
}
function tsTryParseJSXTypeArgument() {
  if (eat(TokenType.jsxTagStart)) {
    state.tokens[state.tokens.length - 1].type = TokenType.typeParameterStart;
    const oldIsType = pushTypeContext(1);
    while (!match2(TokenType.greaterThan) && !state.error) {
      tsParseType();
      eat(TokenType.comma);
    }
    nextJSXTagToken();
    popTypeContext(oldIsType);
  }
}
function tsParseHeritageClause() {
  while (!match2(TokenType.braceL) && !state.error) {
    tsParseExpressionWithTypeArguments();
    eat(TokenType.comma);
  }
}
function tsParseExpressionWithTypeArguments() {
  tsParseEntityName();
  if (match2(TokenType.lessThan)) {
    tsParseTypeArguments();
  }
}
function tsParseInterfaceDeclaration() {
  parseBindingIdentifier(false);
  tsTryParseTypeParameters();
  if (eat(TokenType._extends)) {
    tsParseHeritageClause();
  }
  tsParseObjectTypeMembers();
}
function tsParseTypeAliasDeclaration() {
  parseBindingIdentifier(false);
  tsTryParseTypeParameters();
  expect(TokenType.eq);
  tsParseType();
  semicolon();
}
function tsParseEnumMember() {
  if (match2(TokenType.string)) {
    parseLiteral();
  } else {
    parseIdentifier();
  }
  if (eat(TokenType.eq)) {
    const eqIndex = state.tokens.length - 1;
    parseMaybeAssign();
    state.tokens[eqIndex].rhsEndIndex = state.tokens.length;
  }
}
function tsParseEnumDeclaration() {
  parseBindingIdentifier(false);
  expect(TokenType.braceL);
  while (!eat(TokenType.braceR) && !state.error) {
    tsParseEnumMember();
    eat(TokenType.comma);
  }
}
function tsParseModuleBlock() {
  expect(TokenType.braceL);
  parseBlockBody(
    /* end */
    TokenType.braceR
  );
}
function tsParseModuleOrNamespaceDeclaration() {
  parseBindingIdentifier(false);
  if (eat(TokenType.dot)) {
    tsParseModuleOrNamespaceDeclaration();
  } else {
    tsParseModuleBlock();
  }
}
function tsParseAmbientExternalModuleDeclaration() {
  if (isContextual(ContextualKeyword._global)) {
    parseIdentifier();
  } else if (match2(TokenType.string)) {
    parseExprAtom();
  } else {
    unexpected();
  }
  if (match2(TokenType.braceL)) {
    tsParseModuleBlock();
  } else {
    semicolon();
  }
}
function tsParseImportEqualsDeclaration() {
  parseImportedIdentifier();
  expect(TokenType.eq);
  tsParseModuleReference();
  semicolon();
}
function tsIsExternalModuleReference() {
  return isContextual(ContextualKeyword._require) && lookaheadType() === TokenType.parenL;
}
function tsParseModuleReference() {
  if (tsIsExternalModuleReference()) {
    tsParseExternalModuleReference();
  } else {
    tsParseEntityName();
  }
}
function tsParseExternalModuleReference() {
  expectContextual(ContextualKeyword._require);
  expect(TokenType.parenL);
  if (!match2(TokenType.string)) {
    unexpected();
  }
  parseLiteral();
  expect(TokenType.parenR);
}
function tsTryParseDeclare() {
  if (isLineTerminator()) {
    return false;
  }
  switch (state.type) {
    case TokenType._function: {
      const oldIsType = pushTypeContext(1);
      next();
      const functionStart = state.start;
      parseFunction(
        functionStart,
        /* isStatement */
        true
      );
      popTypeContext(oldIsType);
      return true;
    }
    case TokenType._class: {
      const oldIsType = pushTypeContext(1);
      parseClass(
        /* isStatement */
        true,
        /* optionalId */
        false
      );
      popTypeContext(oldIsType);
      return true;
    }
    case TokenType._const: {
      if (match2(TokenType._const) && isLookaheadContextual(ContextualKeyword._enum)) {
        const oldIsType = pushTypeContext(1);
        expect(TokenType._const);
        expectContextual(ContextualKeyword._enum);
        state.tokens[state.tokens.length - 1].type = TokenType._enum;
        tsParseEnumDeclaration();
        popTypeContext(oldIsType);
        return true;
      }
    }
    case TokenType._var:
    case TokenType._let: {
      const oldIsType = pushTypeContext(1);
      parseVarStatement(state.type !== TokenType._var);
      popTypeContext(oldIsType);
      return true;
    }
    case TokenType.name: {
      const oldIsType = pushTypeContext(1);
      const contextualKeyword = state.contextualKeyword;
      let matched = false;
      if (contextualKeyword === ContextualKeyword._global) {
        tsParseAmbientExternalModuleDeclaration();
        matched = true;
      } else {
        matched = tsParseDeclaration(
          contextualKeyword,
          /* isBeforeToken */
          true
        );
      }
      popTypeContext(oldIsType);
      return matched;
    }
    default:
      return false;
  }
}
function tsTryParseExportDeclaration() {
  return tsParseDeclaration(
    state.contextualKeyword,
    /* isBeforeToken */
    true
  );
}
function tsParseExpressionStatement(contextualKeyword) {
  switch (contextualKeyword) {
    case ContextualKeyword._declare: {
      const declareTokenIndex = state.tokens.length - 1;
      const matched = tsTryParseDeclare();
      if (matched) {
        state.tokens[declareTokenIndex].type = TokenType._declare;
        return true;
      }
      break;
    }
    case ContextualKeyword._global:
      if (match2(TokenType.braceL)) {
        tsParseModuleBlock();
        return true;
      }
      break;
    default:
      return tsParseDeclaration(
        contextualKeyword,
        /* isBeforeToken */
        false
      );
  }
  return false;
}
function tsParseDeclaration(contextualKeyword, isBeforeToken) {
  switch (contextualKeyword) {
    case ContextualKeyword._abstract:
      if (tsCheckLineTerminator(isBeforeToken) && match2(TokenType._class)) {
        state.tokens[state.tokens.length - 1].type = TokenType._abstract;
        parseClass(
          /* isStatement */
          true,
          /* optionalId */
          false
        );
        return true;
      }
      break;
    case ContextualKeyword._enum:
      if (tsCheckLineTerminator(isBeforeToken) && match2(TokenType.name)) {
        state.tokens[state.tokens.length - 1].type = TokenType._enum;
        tsParseEnumDeclaration();
        return true;
      }
      break;
    case ContextualKeyword._interface:
      if (tsCheckLineTerminator(isBeforeToken) && match2(TokenType.name)) {
        const oldIsType = pushTypeContext(isBeforeToken ? 2 : 1);
        tsParseInterfaceDeclaration();
        popTypeContext(oldIsType);
        return true;
      }
      break;
    case ContextualKeyword._module:
      if (tsCheckLineTerminator(isBeforeToken)) {
        if (match2(TokenType.string)) {
          const oldIsType = pushTypeContext(isBeforeToken ? 2 : 1);
          tsParseAmbientExternalModuleDeclaration();
          popTypeContext(oldIsType);
          return true;
        } else if (match2(TokenType.name)) {
          const oldIsType = pushTypeContext(isBeforeToken ? 2 : 1);
          tsParseModuleOrNamespaceDeclaration();
          popTypeContext(oldIsType);
          return true;
        }
      }
      break;
    case ContextualKeyword._namespace:
      if (tsCheckLineTerminator(isBeforeToken) && match2(TokenType.name)) {
        const oldIsType = pushTypeContext(isBeforeToken ? 2 : 1);
        tsParseModuleOrNamespaceDeclaration();
        popTypeContext(oldIsType);
        return true;
      }
      break;
    case ContextualKeyword._type:
      if (tsCheckLineTerminator(isBeforeToken) && match2(TokenType.name)) {
        const oldIsType = pushTypeContext(isBeforeToken ? 2 : 1);
        tsParseTypeAliasDeclaration();
        popTypeContext(oldIsType);
        return true;
      }
      break;
    default:
      break;
  }
  return false;
}
function tsCheckLineTerminator(isBeforeToken) {
  if (isBeforeToken) {
    next();
    return true;
  } else {
    return !isLineTerminator();
  }
}
function tsTryParseGenericAsyncArrowFunction() {
  const snapshot = state.snapshot();
  tsParseTypeParameters();
  parseFunctionParams();
  tsTryParseTypeOrTypePredicateAnnotation();
  expect(TokenType.arrow);
  if (state.error) {
    state.restoreFromSnapshot(snapshot);
    return false;
  }
  parseFunctionBody(true);
  return true;
}
function tsParseTypeArgumentsWithPossibleBitshift() {
  if (state.type === TokenType.bitShiftL) {
    state.pos -= 1;
    finishToken(TokenType.lessThan);
  }
  tsParseTypeArguments();
}
function tsParseTypeArguments() {
  const oldIsType = pushTypeContext(0);
  expect(TokenType.lessThan);
  while (!match2(TokenType.greaterThan) && !state.error) {
    tsParseType();
    eat(TokenType.comma);
  }
  if (!oldIsType) {
    popTypeContext(oldIsType);
    rescan_gt();
    expect(TokenType.greaterThan);
    state.tokens[state.tokens.length - 1].isType = true;
  } else {
    expect(TokenType.greaterThan);
    popTypeContext(oldIsType);
  }
}
function tsIsDeclarationStart() {
  if (match2(TokenType.name)) {
    switch (state.contextualKeyword) {
      case ContextualKeyword._abstract:
      case ContextualKeyword._declare:
      case ContextualKeyword._enum:
      case ContextualKeyword._interface:
      case ContextualKeyword._module:
      case ContextualKeyword._namespace:
      case ContextualKeyword._type:
        return true;
      default:
        break;
    }
  }
  return false;
}
function tsParseFunctionBodyAndFinish(functionStart, funcContextId) {
  if (match2(TokenType.colon)) {
    tsParseTypeOrTypePredicateAnnotation(TokenType.colon);
  }
  if (!match2(TokenType.braceL) && isLineTerminator()) {
    let i4 = state.tokens.length - 1;
    while (i4 >= 0 && (state.tokens[i4].start >= functionStart || state.tokens[i4].type === TokenType._default || state.tokens[i4].type === TokenType._export)) {
      state.tokens[i4].isType = true;
      i4--;
    }
    return;
  }
  parseFunctionBody(false, funcContextId);
}
function tsParseSubscript(startTokenIndex, noCalls, stopState) {
  if (!hasPrecedingLineBreak() && eat(TokenType.bang)) {
    state.tokens[state.tokens.length - 1].type = TokenType.nonNullAssertion;
    return;
  }
  if (match2(TokenType.lessThan) || match2(TokenType.bitShiftL)) {
    const snapshot = state.snapshot();
    if (!noCalls && atPossibleAsync()) {
      const asyncArrowFn = tsTryParseGenericAsyncArrowFunction();
      if (asyncArrowFn) {
        return;
      }
    }
    tsParseTypeArgumentsWithPossibleBitshift();
    if (!noCalls && eat(TokenType.parenL)) {
      state.tokens[state.tokens.length - 1].subscriptStartIndex = startTokenIndex;
      parseCallExpressionArguments();
    } else if (match2(TokenType.backQuote)) {
      parseTemplate();
    } else if (
      // The remaining possible case is an instantiation expression, e.g.
      // Array<number> . Check for a few cases that would disqualify it and
      // cause us to bail out.
      // a<b>>c is not (a<b>)>c, but a<(b>>c)
      state.type === TokenType.greaterThan || // a<b>c is (a<b)>c
      state.type !== TokenType.parenL && Boolean(state.type & TokenType.IS_EXPRESSION_START) && !hasPrecedingLineBreak()
    ) {
      unexpected();
    }
    if (state.error) {
      state.restoreFromSnapshot(snapshot);
    } else {
      return;
    }
  } else if (!noCalls && match2(TokenType.questionDot) && lookaheadType() === TokenType.lessThan) {
    next();
    state.tokens[startTokenIndex].isOptionalChainStart = true;
    state.tokens[state.tokens.length - 1].subscriptStartIndex = startTokenIndex;
    tsParseTypeArguments();
    expect(TokenType.parenL);
    parseCallExpressionArguments();
  }
  baseParseSubscript(startTokenIndex, noCalls, stopState);
}
function tsTryParseExport() {
  if (eat(TokenType._import)) {
    if (isContextual(ContextualKeyword._type) && lookaheadType() !== TokenType.eq) {
      expectContextual(ContextualKeyword._type);
    }
    tsParseImportEqualsDeclaration();
    return true;
  } else if (eat(TokenType.eq)) {
    parseExpression();
    semicolon();
    return true;
  } else if (eatContextual(ContextualKeyword._as)) {
    expectContextual(ContextualKeyword._namespace);
    parseIdentifier();
    semicolon();
    return true;
  } else {
    if (isContextual(ContextualKeyword._type)) {
      const nextType = lookaheadType();
      if (nextType === TokenType.braceL || nextType === TokenType.star) {
        next();
      }
    }
    return false;
  }
}
function tsParseImportSpecifier() {
  parseIdentifier();
  if (match2(TokenType.comma) || match2(TokenType.braceR)) {
    state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.ImportDeclaration;
    return;
  }
  parseIdentifier();
  if (match2(TokenType.comma) || match2(TokenType.braceR)) {
    state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.ImportDeclaration;
    state.tokens[state.tokens.length - 2].isType = true;
    state.tokens[state.tokens.length - 1].isType = true;
    return;
  }
  parseIdentifier();
  if (match2(TokenType.comma) || match2(TokenType.braceR)) {
    state.tokens[state.tokens.length - 3].identifierRole = IdentifierRole.ImportAccess;
    state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.ImportDeclaration;
    return;
  }
  parseIdentifier();
  state.tokens[state.tokens.length - 3].identifierRole = IdentifierRole.ImportAccess;
  state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.ImportDeclaration;
  state.tokens[state.tokens.length - 4].isType = true;
  state.tokens[state.tokens.length - 3].isType = true;
  state.tokens[state.tokens.length - 2].isType = true;
  state.tokens[state.tokens.length - 1].isType = true;
}
function tsParseExportSpecifier() {
  parseIdentifier();
  if (match2(TokenType.comma) || match2(TokenType.braceR)) {
    state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.ExportAccess;
    return;
  }
  parseIdentifier();
  if (match2(TokenType.comma) || match2(TokenType.braceR)) {
    state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.ExportAccess;
    state.tokens[state.tokens.length - 2].isType = true;
    state.tokens[state.tokens.length - 1].isType = true;
    return;
  }
  parseIdentifier();
  if (match2(TokenType.comma) || match2(TokenType.braceR)) {
    state.tokens[state.tokens.length - 3].identifierRole = IdentifierRole.ExportAccess;
    return;
  }
  parseIdentifier();
  state.tokens[state.tokens.length - 3].identifierRole = IdentifierRole.ExportAccess;
  state.tokens[state.tokens.length - 4].isType = true;
  state.tokens[state.tokens.length - 3].isType = true;
  state.tokens[state.tokens.length - 2].isType = true;
  state.tokens[state.tokens.length - 1].isType = true;
}
function tsTryParseExportDefaultExpression() {
  if (isContextual(ContextualKeyword._abstract) && lookaheadType() === TokenType._class) {
    state.type = TokenType._abstract;
    next();
    parseClass(true, true);
    return true;
  }
  if (isContextual(ContextualKeyword._interface)) {
    const oldIsType = pushTypeContext(2);
    tsParseDeclaration(ContextualKeyword._interface, true);
    popTypeContext(oldIsType);
    return true;
  }
  return false;
}
function tsTryParseStatementContent() {
  if (state.type === TokenType._const) {
    const ahead = lookaheadTypeAndKeyword();
    if (ahead.type === TokenType.name && ahead.contextualKeyword === ContextualKeyword._enum) {
      expect(TokenType._const);
      expectContextual(ContextualKeyword._enum);
      state.tokens[state.tokens.length - 1].type = TokenType._enum;
      tsParseEnumDeclaration();
      return true;
    }
  }
  return false;
}
function tsTryParseClassMemberWithIsStatic(isStatic) {
  const memberStartIndexAfterStatic = state.tokens.length;
  tsParseModifiers([
    ContextualKeyword._abstract,
    ContextualKeyword._readonly,
    ContextualKeyword._declare,
    ContextualKeyword._static,
    ContextualKeyword._override
  ]);
  const modifiersEndIndex = state.tokens.length;
  const found = tsTryParseIndexSignature();
  if (found) {
    const memberStartIndex = isStatic ? memberStartIndexAfterStatic - 1 : memberStartIndexAfterStatic;
    for (let i4 = memberStartIndex; i4 < modifiersEndIndex; i4++) {
      state.tokens[i4].isType = true;
    }
    return true;
  }
  return false;
}
function tsParseIdentifierStatement(contextualKeyword) {
  const matched = tsParseExpressionStatement(contextualKeyword);
  if (!matched) {
    semicolon();
  }
}
function tsParseExportDeclaration() {
  const isDeclare = eatContextual(ContextualKeyword._declare);
  if (isDeclare) {
    state.tokens[state.tokens.length - 1].type = TokenType._declare;
  }
  let matchedDeclaration = false;
  if (match2(TokenType.name)) {
    if (isDeclare) {
      const oldIsType = pushTypeContext(2);
      matchedDeclaration = tsTryParseExportDeclaration();
      popTypeContext(oldIsType);
    } else {
      matchedDeclaration = tsTryParseExportDeclaration();
    }
  }
  if (!matchedDeclaration) {
    if (isDeclare) {
      const oldIsType = pushTypeContext(2);
      parseStatement(true);
      popTypeContext(oldIsType);
    } else {
      parseStatement(true);
    }
  }
}
function tsAfterParseClassSuper(hasSuper) {
  if (hasSuper && (match2(TokenType.lessThan) || match2(TokenType.bitShiftL))) {
    tsParseTypeArgumentsWithPossibleBitshift();
  }
  if (eatContextual(ContextualKeyword._implements)) {
    state.tokens[state.tokens.length - 1].type = TokenType._implements;
    const oldIsType = pushTypeContext(1);
    tsParseHeritageClause();
    popTypeContext(oldIsType);
  }
}
function tsStartParseObjPropValue() {
  tsTryParseTypeParameters();
}
function tsStartParseFunctionParams() {
  tsTryParseTypeParameters();
}
function tsAfterParseVarHead() {
  const oldIsType = pushTypeContext(0);
  if (!hasPrecedingLineBreak()) {
    eat(TokenType.bang);
  }
  tsTryParseTypeAnnotation();
  popTypeContext(oldIsType);
}
function tsStartParseAsyncArrowFromCallExpression() {
  if (match2(TokenType.colon)) {
    tsParseTypeAnnotation();
  }
}
function tsParseMaybeAssign(noIn, isWithinParens) {
  if (isJSXEnabled) {
    return tsParseMaybeAssignWithJSX(noIn, isWithinParens);
  } else {
    return tsParseMaybeAssignWithoutJSX(noIn, isWithinParens);
  }
}
function tsParseMaybeAssignWithJSX(noIn, isWithinParens) {
  if (!match2(TokenType.lessThan)) {
    return baseParseMaybeAssign(noIn, isWithinParens);
  }
  const snapshot = state.snapshot();
  let wasArrow = baseParseMaybeAssign(noIn, isWithinParens);
  if (state.error) {
    state.restoreFromSnapshot(snapshot);
  } else {
    return wasArrow;
  }
  state.type = TokenType.typeParameterStart;
  tsParseTypeParameters();
  wasArrow = baseParseMaybeAssign(noIn, isWithinParens);
  if (!wasArrow) {
    unexpected();
  }
  return wasArrow;
}
function tsParseMaybeAssignWithoutJSX(noIn, isWithinParens) {
  if (!match2(TokenType.lessThan)) {
    return baseParseMaybeAssign(noIn, isWithinParens);
  }
  const snapshot = state.snapshot();
  tsParseTypeParameters();
  const wasArrow = baseParseMaybeAssign(noIn, isWithinParens);
  if (!wasArrow) {
    unexpected();
  }
  if (state.error) {
    state.restoreFromSnapshot(snapshot);
  } else {
    return wasArrow;
  }
  return baseParseMaybeAssign(noIn, isWithinParens);
}
function tsParseArrow() {
  if (match2(TokenType.colon)) {
    const snapshot = state.snapshot();
    tsParseTypeOrTypePredicateAnnotation(TokenType.colon);
    if (canInsertSemicolon())
      unexpected();
    if (!match2(TokenType.arrow))
      unexpected();
    if (state.error) {
      state.restoreFromSnapshot(snapshot);
    }
  }
  return eat(TokenType.arrow);
}
function tsParseAssignableListItemTypes() {
  const oldIsType = pushTypeContext(0);
  eat(TokenType.question);
  tsTryParseTypeAnnotation();
  popTypeContext(oldIsType);
}
function tsParseMaybeDecoratorArguments() {
  if (match2(TokenType.lessThan) || match2(TokenType.bitShiftL)) {
    tsParseTypeArgumentsWithPossibleBitshift();
  }
  baseParseMaybeDecoratorArguments();
}

// node_modules/sucrase/dist/esm/parser/plugins/jsx/index.js
function jsxReadToken() {
  let sawNewline = false;
  let sawNonWhitespace = false;
  while (true) {
    if (state.pos >= input.length) {
      unexpected("Unterminated JSX contents");
      return;
    }
    const ch = input.charCodeAt(state.pos);
    if (ch === charCodes.lessThan || ch === charCodes.leftCurlyBrace) {
      if (state.pos === state.start) {
        if (ch === charCodes.lessThan) {
          state.pos++;
          finishToken(TokenType.jsxTagStart);
          return;
        }
        getTokenFromCode(ch);
        return;
      }
      if (sawNewline && !sawNonWhitespace) {
        finishToken(TokenType.jsxEmptyText);
      } else {
        finishToken(TokenType.jsxText);
      }
      return;
    }
    if (ch === charCodes.lineFeed) {
      sawNewline = true;
    } else if (ch !== charCodes.space && ch !== charCodes.carriageReturn && ch !== charCodes.tab) {
      sawNonWhitespace = true;
    }
    state.pos++;
  }
}
function jsxReadString(quote) {
  state.pos++;
  for (; ; ) {
    if (state.pos >= input.length) {
      unexpected("Unterminated string constant");
      return;
    }
    const ch = input.charCodeAt(state.pos);
    if (ch === quote) {
      state.pos++;
      break;
    }
    state.pos++;
  }
  finishToken(TokenType.string);
}
function jsxReadWord() {
  let ch;
  do {
    if (state.pos > input.length) {
      unexpected("Unexpectedly reached the end of input.");
      return;
    }
    ch = input.charCodeAt(++state.pos);
  } while (IS_IDENTIFIER_CHAR[ch] || ch === charCodes.dash);
  finishToken(TokenType.jsxName);
}
function jsxParseIdentifier() {
  nextJSXTagToken();
}
function jsxParseNamespacedName(identifierRole) {
  jsxParseIdentifier();
  if (!eat(TokenType.colon)) {
    state.tokens[state.tokens.length - 1].identifierRole = identifierRole;
    return;
  }
  jsxParseIdentifier();
}
function jsxParseElementName() {
  const firstTokenIndex = state.tokens.length;
  jsxParseNamespacedName(IdentifierRole.Access);
  let hadDot = false;
  while (match2(TokenType.dot)) {
    hadDot = true;
    nextJSXTagToken();
    jsxParseIdentifier();
  }
  if (!hadDot) {
    const firstToken = state.tokens[firstTokenIndex];
    const firstChar = input.charCodeAt(firstToken.start);
    if (firstChar >= charCodes.lowercaseA && firstChar <= charCodes.lowercaseZ) {
      firstToken.identifierRole = null;
    }
  }
}
function jsxParseAttributeValue() {
  switch (state.type) {
    case TokenType.braceL:
      next();
      parseExpression();
      nextJSXTagToken();
      return;
    case TokenType.jsxTagStart:
      jsxParseElement();
      nextJSXTagToken();
      return;
    case TokenType.string:
      nextJSXTagToken();
      return;
    default:
      unexpected("JSX value should be either an expression or a quoted JSX text");
  }
}
function jsxParseSpreadChild() {
  expect(TokenType.ellipsis);
  parseExpression();
}
function jsxParseOpeningElement(initialTokenIndex) {
  if (match2(TokenType.jsxTagEnd)) {
    return false;
  }
  jsxParseElementName();
  if (isTypeScriptEnabled) {
    tsTryParseJSXTypeArgument();
  }
  let hasSeenPropSpread = false;
  while (!match2(TokenType.slash) && !match2(TokenType.jsxTagEnd) && !state.error) {
    if (eat(TokenType.braceL)) {
      hasSeenPropSpread = true;
      expect(TokenType.ellipsis);
      parseMaybeAssign();
      nextJSXTagToken();
      continue;
    }
    if (hasSeenPropSpread && state.end - state.start === 3 && input.charCodeAt(state.start) === charCodes.lowercaseK && input.charCodeAt(state.start + 1) === charCodes.lowercaseE && input.charCodeAt(state.start + 2) === charCodes.lowercaseY) {
      state.tokens[initialTokenIndex].jsxRole = JSXRole.KeyAfterPropSpread;
    }
    jsxParseNamespacedName(IdentifierRole.ObjectKey);
    if (match2(TokenType.eq)) {
      nextJSXTagToken();
      jsxParseAttributeValue();
    }
  }
  const isSelfClosing = match2(TokenType.slash);
  if (isSelfClosing) {
    nextJSXTagToken();
  }
  return isSelfClosing;
}
function jsxParseClosingElement() {
  if (match2(TokenType.jsxTagEnd)) {
    return;
  }
  jsxParseElementName();
}
function jsxParseElementAt() {
  const initialTokenIndex = state.tokens.length - 1;
  state.tokens[initialTokenIndex].jsxRole = JSXRole.NoChildren;
  let numExplicitChildren = 0;
  const isSelfClosing = jsxParseOpeningElement(initialTokenIndex);
  if (!isSelfClosing) {
    nextJSXExprToken();
    while (true) {
      switch (state.type) {
        case TokenType.jsxTagStart:
          nextJSXTagToken();
          if (match2(TokenType.slash)) {
            nextJSXTagToken();
            jsxParseClosingElement();
            if (state.tokens[initialTokenIndex].jsxRole !== JSXRole.KeyAfterPropSpread) {
              if (numExplicitChildren === 1) {
                state.tokens[initialTokenIndex].jsxRole = JSXRole.OneChild;
              } else if (numExplicitChildren > 1) {
                state.tokens[initialTokenIndex].jsxRole = JSXRole.StaticChildren;
              }
            }
            return;
          }
          numExplicitChildren++;
          jsxParseElementAt();
          nextJSXExprToken();
          break;
        case TokenType.jsxText:
          numExplicitChildren++;
          nextJSXExprToken();
          break;
        case TokenType.jsxEmptyText:
          nextJSXExprToken();
          break;
        case TokenType.braceL:
          next();
          if (match2(TokenType.ellipsis)) {
            jsxParseSpreadChild();
            nextJSXExprToken();
            numExplicitChildren += 2;
          } else {
            if (!match2(TokenType.braceR)) {
              numExplicitChildren++;
              parseExpression();
            }
            nextJSXExprToken();
          }
          break;
        default:
          unexpected();
          return;
      }
    }
  }
}
function jsxParseElement() {
  nextJSXTagToken();
  jsxParseElementAt();
}
function nextJSXTagToken() {
  state.tokens.push(new Token());
  skipSpace();
  state.start = state.pos;
  const code = input.charCodeAt(state.pos);
  if (IS_IDENTIFIER_START[code]) {
    jsxReadWord();
  } else if (code === charCodes.quotationMark || code === charCodes.apostrophe) {
    jsxReadString(code);
  } else {
    ++state.pos;
    switch (code) {
      case charCodes.greaterThan:
        finishToken(TokenType.jsxTagEnd);
        break;
      case charCodes.lessThan:
        finishToken(TokenType.jsxTagStart);
        break;
      case charCodes.slash:
        finishToken(TokenType.slash);
        break;
      case charCodes.equalsTo:
        finishToken(TokenType.eq);
        break;
      case charCodes.leftCurlyBrace:
        finishToken(TokenType.braceL);
        break;
      case charCodes.dot:
        finishToken(TokenType.dot);
        break;
      case charCodes.colon:
        finishToken(TokenType.colon);
        break;
      default:
        unexpected();
    }
  }
}
function nextJSXExprToken() {
  state.tokens.push(new Token());
  state.start = state.pos;
  jsxReadToken();
}

// node_modules/sucrase/dist/esm/parser/plugins/types.js
function typedParseConditional(noIn) {
  if (match2(TokenType.question)) {
    const nextType = lookaheadType();
    if (nextType === TokenType.colon || nextType === TokenType.comma || nextType === TokenType.parenR) {
      return;
    }
  }
  baseParseConditional(noIn);
}
function typedParseParenItem() {
  eatTypeToken(TokenType.question);
  if (match2(TokenType.colon)) {
    if (isTypeScriptEnabled) {
      tsParseTypeAnnotation();
    } else if (isFlowEnabled) {
      flowParseTypeAnnotation();
    }
  }
}

// node_modules/sucrase/dist/esm/parser/traverser/expression.js
var StopState = class {
  constructor(stop) {
    this.stop = stop;
  }
};
function parseExpression(noIn = false) {
  parseMaybeAssign(noIn);
  if (match2(TokenType.comma)) {
    while (eat(TokenType.comma)) {
      parseMaybeAssign(noIn);
    }
  }
}
function parseMaybeAssign(noIn = false, isWithinParens = false) {
  if (isTypeScriptEnabled) {
    return tsParseMaybeAssign(noIn, isWithinParens);
  } else if (isFlowEnabled) {
    return flowParseMaybeAssign(noIn, isWithinParens);
  } else {
    return baseParseMaybeAssign(noIn, isWithinParens);
  }
}
function baseParseMaybeAssign(noIn, isWithinParens) {
  if (match2(TokenType._yield)) {
    parseYield();
    return false;
  }
  if (match2(TokenType.parenL) || match2(TokenType.name) || match2(TokenType._yield)) {
    state.potentialArrowAt = state.start;
  }
  const wasArrow = parseMaybeConditional(noIn);
  if (isWithinParens) {
    parseParenItem();
  }
  if (state.type & TokenType.IS_ASSIGN) {
    next();
    parseMaybeAssign(noIn);
    return false;
  }
  return wasArrow;
}
function parseMaybeConditional(noIn) {
  const wasArrow = parseExprOps(noIn);
  if (wasArrow) {
    return true;
  }
  parseConditional(noIn);
  return false;
}
function parseConditional(noIn) {
  if (isTypeScriptEnabled || isFlowEnabled) {
    typedParseConditional(noIn);
  } else {
    baseParseConditional(noIn);
  }
}
function baseParseConditional(noIn) {
  if (eat(TokenType.question)) {
    parseMaybeAssign();
    expect(TokenType.colon);
    parseMaybeAssign(noIn);
  }
}
function parseExprOps(noIn) {
  const startTokenIndex = state.tokens.length;
  const wasArrow = parseMaybeUnary();
  if (wasArrow) {
    return true;
  }
  parseExprOp(startTokenIndex, -1, noIn);
  return false;
}
function parseExprOp(startTokenIndex, minPrec, noIn) {
  if (isTypeScriptEnabled && (TokenType._in & TokenType.PRECEDENCE_MASK) > minPrec && !hasPrecedingLineBreak() && (eatContextual(ContextualKeyword._as) || eatContextual(ContextualKeyword._satisfies))) {
    const oldIsType = pushTypeContext(1);
    tsParseType();
    popTypeContext(oldIsType);
    rescan_gt();
    parseExprOp(startTokenIndex, minPrec, noIn);
    return;
  }
  const prec = state.type & TokenType.PRECEDENCE_MASK;
  if (prec > 0 && (!noIn || !match2(TokenType._in))) {
    if (prec > minPrec) {
      const op = state.type;
      next();
      if (op === TokenType.nullishCoalescing) {
        state.tokens[state.tokens.length - 1].nullishStartIndex = startTokenIndex;
      }
      const rhsStartTokenIndex = state.tokens.length;
      parseMaybeUnary();
      parseExprOp(rhsStartTokenIndex, op & TokenType.IS_RIGHT_ASSOCIATIVE ? prec - 1 : prec, noIn);
      if (op === TokenType.nullishCoalescing) {
        state.tokens[startTokenIndex].numNullishCoalesceStarts++;
        state.tokens[state.tokens.length - 1].numNullishCoalesceEnds++;
      }
      parseExprOp(startTokenIndex, minPrec, noIn);
    }
  }
}
function parseMaybeUnary() {
  if (isTypeScriptEnabled && !isJSXEnabled && eat(TokenType.lessThan)) {
    tsParseTypeAssertion();
    return false;
  }
  if (isContextual(ContextualKeyword._module) && lookaheadCharCode() === charCodes.leftCurlyBrace && !hasFollowingLineBreak()) {
    parseModuleExpression();
    return false;
  }
  if (state.type & TokenType.IS_PREFIX) {
    next();
    parseMaybeUnary();
    return false;
  }
  const wasArrow = parseExprSubscripts();
  if (wasArrow) {
    return true;
  }
  while (state.type & TokenType.IS_POSTFIX && !canInsertSemicolon()) {
    if (state.type === TokenType.preIncDec) {
      state.type = TokenType.postIncDec;
    }
    next();
  }
  return false;
}
function parseExprSubscripts() {
  const startTokenIndex = state.tokens.length;
  const wasArrow = parseExprAtom();
  if (wasArrow) {
    return true;
  }
  parseSubscripts(startTokenIndex);
  if (state.tokens.length > startTokenIndex && state.tokens[startTokenIndex].isOptionalChainStart) {
    state.tokens[state.tokens.length - 1].isOptionalChainEnd = true;
  }
  return false;
}
function parseSubscripts(startTokenIndex, noCalls = false) {
  if (isFlowEnabled) {
    flowParseSubscripts(startTokenIndex, noCalls);
  } else {
    baseParseSubscripts(startTokenIndex, noCalls);
  }
}
function baseParseSubscripts(startTokenIndex, noCalls = false) {
  const stopState = new StopState(false);
  do {
    parseSubscript(startTokenIndex, noCalls, stopState);
  } while (!stopState.stop && !state.error);
}
function parseSubscript(startTokenIndex, noCalls, stopState) {
  if (isTypeScriptEnabled) {
    tsParseSubscript(startTokenIndex, noCalls, stopState);
  } else if (isFlowEnabled) {
    flowParseSubscript(startTokenIndex, noCalls, stopState);
  } else {
    baseParseSubscript(startTokenIndex, noCalls, stopState);
  }
}
function baseParseSubscript(startTokenIndex, noCalls, stopState) {
  if (!noCalls && eat(TokenType.doubleColon)) {
    parseNoCallExpr();
    stopState.stop = true;
    parseSubscripts(startTokenIndex, noCalls);
  } else if (match2(TokenType.questionDot)) {
    state.tokens[startTokenIndex].isOptionalChainStart = true;
    if (noCalls && lookaheadType() === TokenType.parenL) {
      stopState.stop = true;
      return;
    }
    next();
    state.tokens[state.tokens.length - 1].subscriptStartIndex = startTokenIndex;
    if (eat(TokenType.bracketL)) {
      parseExpression();
      expect(TokenType.bracketR);
    } else if (eat(TokenType.parenL)) {
      parseCallExpressionArguments();
    } else {
      parseMaybePrivateName();
    }
  } else if (eat(TokenType.dot)) {
    state.tokens[state.tokens.length - 1].subscriptStartIndex = startTokenIndex;
    parseMaybePrivateName();
  } else if (eat(TokenType.bracketL)) {
    state.tokens[state.tokens.length - 1].subscriptStartIndex = startTokenIndex;
    parseExpression();
    expect(TokenType.bracketR);
  } else if (!noCalls && match2(TokenType.parenL)) {
    if (atPossibleAsync()) {
      const snapshot = state.snapshot();
      const asyncStartTokenIndex = state.tokens.length;
      next();
      state.tokens[state.tokens.length - 1].subscriptStartIndex = startTokenIndex;
      const callContextId = getNextContextId();
      state.tokens[state.tokens.length - 1].contextId = callContextId;
      parseCallExpressionArguments();
      state.tokens[state.tokens.length - 1].contextId = callContextId;
      if (shouldParseAsyncArrow()) {
        state.restoreFromSnapshot(snapshot);
        stopState.stop = true;
        state.scopeDepth++;
        parseFunctionParams();
        parseAsyncArrowFromCallExpression(asyncStartTokenIndex);
      }
    } else {
      next();
      state.tokens[state.tokens.length - 1].subscriptStartIndex = startTokenIndex;
      const callContextId = getNextContextId();
      state.tokens[state.tokens.length - 1].contextId = callContextId;
      parseCallExpressionArguments();
      state.tokens[state.tokens.length - 1].contextId = callContextId;
    }
  } else if (match2(TokenType.backQuote)) {
    parseTemplate();
  } else {
    stopState.stop = true;
  }
}
function atPossibleAsync() {
  return state.tokens[state.tokens.length - 1].contextualKeyword === ContextualKeyword._async && !canInsertSemicolon();
}
function parseCallExpressionArguments() {
  let first = true;
  while (!eat(TokenType.parenR) && !state.error) {
    if (first) {
      first = false;
    } else {
      expect(TokenType.comma);
      if (eat(TokenType.parenR)) {
        break;
      }
    }
    parseExprListItem(false);
  }
}
function shouldParseAsyncArrow() {
  return match2(TokenType.colon) || match2(TokenType.arrow);
}
function parseAsyncArrowFromCallExpression(startTokenIndex) {
  if (isTypeScriptEnabled) {
    tsStartParseAsyncArrowFromCallExpression();
  } else if (isFlowEnabled) {
    flowStartParseAsyncArrowFromCallExpression();
  }
  expect(TokenType.arrow);
  parseArrowExpression(startTokenIndex);
}
function parseNoCallExpr() {
  const startTokenIndex = state.tokens.length;
  parseExprAtom();
  parseSubscripts(startTokenIndex, true);
}
function parseExprAtom() {
  if (eat(TokenType.modulo)) {
    parseIdentifier();
    return false;
  }
  if (match2(TokenType.jsxText) || match2(TokenType.jsxEmptyText)) {
    parseLiteral();
    return false;
  } else if (match2(TokenType.lessThan) && isJSXEnabled) {
    state.type = TokenType.jsxTagStart;
    jsxParseElement();
    next();
    return false;
  }
  const canBeArrow = state.potentialArrowAt === state.start;
  switch (state.type) {
    case TokenType.slash:
    case TokenType.assign:
      retokenizeSlashAsRegex();
    case TokenType._super:
    case TokenType._this:
    case TokenType.regexp:
    case TokenType.num:
    case TokenType.bigint:
    case TokenType.decimal:
    case TokenType.string:
    case TokenType._null:
    case TokenType._true:
    case TokenType._false:
      next();
      return false;
    case TokenType._import:
      next();
      if (match2(TokenType.dot)) {
        state.tokens[state.tokens.length - 1].type = TokenType.name;
        next();
        parseIdentifier();
      }
      return false;
    case TokenType.name: {
      const startTokenIndex = state.tokens.length;
      const functionStart = state.start;
      const contextualKeyword = state.contextualKeyword;
      parseIdentifier();
      if (contextualKeyword === ContextualKeyword._await) {
        parseAwait();
        return false;
      } else if (contextualKeyword === ContextualKeyword._async && match2(TokenType._function) && !canInsertSemicolon()) {
        next();
        parseFunction(functionStart, false);
        return false;
      } else if (canBeArrow && contextualKeyword === ContextualKeyword._async && !canInsertSemicolon() && match2(TokenType.name)) {
        state.scopeDepth++;
        parseBindingIdentifier(false);
        expect(TokenType.arrow);
        parseArrowExpression(startTokenIndex);
        return true;
      } else if (match2(TokenType._do) && !canInsertSemicolon()) {
        next();
        parseBlock();
        return false;
      }
      if (canBeArrow && !canInsertSemicolon() && match2(TokenType.arrow)) {
        state.scopeDepth++;
        markPriorBindingIdentifier(false);
        expect(TokenType.arrow);
        parseArrowExpression(startTokenIndex);
        return true;
      }
      state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.Access;
      return false;
    }
    case TokenType._do: {
      next();
      parseBlock();
      return false;
    }
    case TokenType.parenL: {
      const wasArrow = parseParenAndDistinguishExpression(canBeArrow);
      return wasArrow;
    }
    case TokenType.bracketL:
      next();
      parseExprList(TokenType.bracketR, true);
      return false;
    case TokenType.braceL:
      parseObj(false, false);
      return false;
    case TokenType._function:
      parseFunctionExpression();
      return false;
    case TokenType.at:
      parseDecorators();
    case TokenType._class:
      parseClass(false);
      return false;
    case TokenType._new:
      parseNew();
      return false;
    case TokenType.backQuote:
      parseTemplate();
      return false;
    case TokenType.doubleColon: {
      next();
      parseNoCallExpr();
      return false;
    }
    case TokenType.hash: {
      const code = lookaheadCharCode();
      if (IS_IDENTIFIER_START[code] || code === charCodes.backslash) {
        parseMaybePrivateName();
      } else {
        next();
      }
      return false;
    }
    default:
      unexpected();
      return false;
  }
}
function parseMaybePrivateName() {
  eat(TokenType.hash);
  parseIdentifier();
}
function parseFunctionExpression() {
  const functionStart = state.start;
  parseIdentifier();
  if (eat(TokenType.dot)) {
    parseIdentifier();
  }
  parseFunction(functionStart, false);
}
function parseLiteral() {
  next();
}
function parseParenExpression() {
  expect(TokenType.parenL);
  parseExpression();
  expect(TokenType.parenR);
}
function parseParenAndDistinguishExpression(canBeArrow) {
  const snapshot = state.snapshot();
  const startTokenIndex = state.tokens.length;
  expect(TokenType.parenL);
  let first = true;
  while (!match2(TokenType.parenR) && !state.error) {
    if (first) {
      first = false;
    } else {
      expect(TokenType.comma);
      if (match2(TokenType.parenR)) {
        break;
      }
    }
    if (match2(TokenType.ellipsis)) {
      parseRest(
        false
        /* isBlockScope */
      );
      parseParenItem();
      break;
    } else {
      parseMaybeAssign(false, true);
    }
  }
  expect(TokenType.parenR);
  if (canBeArrow && shouldParseArrow()) {
    const wasArrow = parseArrow();
    if (wasArrow) {
      state.restoreFromSnapshot(snapshot);
      state.scopeDepth++;
      parseFunctionParams();
      parseArrow();
      parseArrowExpression(startTokenIndex);
      if (state.error) {
        state.restoreFromSnapshot(snapshot);
        parseParenAndDistinguishExpression(false);
        return false;
      }
      return true;
    }
  }
  return false;
}
function shouldParseArrow() {
  return match2(TokenType.colon) || !canInsertSemicolon();
}
function parseArrow() {
  if (isTypeScriptEnabled) {
    return tsParseArrow();
  } else if (isFlowEnabled) {
    return flowParseArrow();
  } else {
    return eat(TokenType.arrow);
  }
}
function parseParenItem() {
  if (isTypeScriptEnabled || isFlowEnabled) {
    typedParseParenItem();
  }
}
function parseNew() {
  expect(TokenType._new);
  if (eat(TokenType.dot)) {
    parseIdentifier();
    return;
  }
  parseNewCallee();
  if (isFlowEnabled) {
    flowStartParseNewArguments();
  }
  if (eat(TokenType.parenL)) {
    parseExprList(TokenType.parenR);
  }
}
function parseNewCallee() {
  parseNoCallExpr();
  eat(TokenType.questionDot);
}
function parseTemplate() {
  nextTemplateToken();
  nextTemplateToken();
  while (!match2(TokenType.backQuote) && !state.error) {
    expect(TokenType.dollarBraceL);
    parseExpression();
    nextTemplateToken();
    nextTemplateToken();
  }
  next();
}
function parseObj(isPattern, isBlockScope) {
  const contextId = getNextContextId();
  let first = true;
  next();
  state.tokens[state.tokens.length - 1].contextId = contextId;
  while (!eat(TokenType.braceR) && !state.error) {
    if (first) {
      first = false;
    } else {
      expect(TokenType.comma);
      if (eat(TokenType.braceR)) {
        break;
      }
    }
    let isGenerator = false;
    if (match2(TokenType.ellipsis)) {
      const previousIndex = state.tokens.length;
      parseSpread();
      if (isPattern) {
        if (state.tokens.length === previousIndex + 2) {
          markPriorBindingIdentifier(isBlockScope);
        }
        if (eat(TokenType.braceR)) {
          break;
        }
      }
      continue;
    }
    if (!isPattern) {
      isGenerator = eat(TokenType.star);
    }
    if (!isPattern && isContextual(ContextualKeyword._async)) {
      if (isGenerator)
        unexpected();
      parseIdentifier();
      if (match2(TokenType.colon) || match2(TokenType.parenL) || match2(TokenType.braceR) || match2(TokenType.eq) || match2(TokenType.comma)) {
      } else {
        if (match2(TokenType.star)) {
          next();
          isGenerator = true;
        }
        parsePropertyName(contextId);
      }
    } else {
      parsePropertyName(contextId);
    }
    parseObjPropValue(isPattern, isBlockScope, contextId);
  }
  state.tokens[state.tokens.length - 1].contextId = contextId;
}
function isGetterOrSetterMethod(isPattern) {
  return !isPattern && (match2(TokenType.string) || // get "string"() {}
  match2(TokenType.num) || // get 1() {}
  match2(TokenType.bracketL) || // get ["string"]() {}
  match2(TokenType.name) || // get foo() {}
  !!(state.type & TokenType.IS_KEYWORD));
}
function parseObjectMethod(isPattern, objectContextId) {
  const functionStart = state.start;
  if (match2(TokenType.parenL)) {
    if (isPattern)
      unexpected();
    parseMethod(
      functionStart,
      /* isConstructor */
      false
    );
    return true;
  }
  if (isGetterOrSetterMethod(isPattern)) {
    parsePropertyName(objectContextId);
    parseMethod(
      functionStart,
      /* isConstructor */
      false
    );
    return true;
  }
  return false;
}
function parseObjectProperty(isPattern, isBlockScope) {
  if (eat(TokenType.colon)) {
    if (isPattern) {
      parseMaybeDefault(isBlockScope);
    } else {
      parseMaybeAssign(false);
    }
    return;
  }
  let identifierRole;
  if (isPattern) {
    if (state.scopeDepth === 0) {
      identifierRole = IdentifierRole.ObjectShorthandTopLevelDeclaration;
    } else if (isBlockScope) {
      identifierRole = IdentifierRole.ObjectShorthandBlockScopedDeclaration;
    } else {
      identifierRole = IdentifierRole.ObjectShorthandFunctionScopedDeclaration;
    }
  } else {
    identifierRole = IdentifierRole.ObjectShorthand;
  }
  state.tokens[state.tokens.length - 1].identifierRole = identifierRole;
  parseMaybeDefault(isBlockScope, true);
}
function parseObjPropValue(isPattern, isBlockScope, objectContextId) {
  if (isTypeScriptEnabled) {
    tsStartParseObjPropValue();
  } else if (isFlowEnabled) {
    flowStartParseObjPropValue();
  }
  const wasMethod = parseObjectMethod(isPattern, objectContextId);
  if (!wasMethod) {
    parseObjectProperty(isPattern, isBlockScope);
  }
}
function parsePropertyName(objectContextId) {
  if (isFlowEnabled) {
    flowParseVariance();
  }
  if (eat(TokenType.bracketL)) {
    state.tokens[state.tokens.length - 1].contextId = objectContextId;
    parseMaybeAssign();
    expect(TokenType.bracketR);
    state.tokens[state.tokens.length - 1].contextId = objectContextId;
  } else {
    if (match2(TokenType.num) || match2(TokenType.string) || match2(TokenType.bigint) || match2(TokenType.decimal)) {
      parseExprAtom();
    } else {
      parseMaybePrivateName();
    }
    state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.ObjectKey;
    state.tokens[state.tokens.length - 1].contextId = objectContextId;
  }
}
function parseMethod(functionStart, isConstructor) {
  const funcContextId = getNextContextId();
  state.scopeDepth++;
  const startTokenIndex = state.tokens.length;
  const allowModifiers = isConstructor;
  parseFunctionParams(allowModifiers, funcContextId);
  parseFunctionBodyAndFinish(functionStart, funcContextId);
  const endTokenIndex = state.tokens.length;
  state.scopes.push(new Scope(startTokenIndex, endTokenIndex, true));
  state.scopeDepth--;
}
function parseArrowExpression(startTokenIndex) {
  parseFunctionBody(true);
  const endTokenIndex = state.tokens.length;
  state.scopes.push(new Scope(startTokenIndex, endTokenIndex, true));
  state.scopeDepth--;
}
function parseFunctionBodyAndFinish(functionStart, funcContextId = 0) {
  if (isTypeScriptEnabled) {
    tsParseFunctionBodyAndFinish(functionStart, funcContextId);
  } else if (isFlowEnabled) {
    flowParseFunctionBodyAndFinish(funcContextId);
  } else {
    parseFunctionBody(false, funcContextId);
  }
}
function parseFunctionBody(allowExpression, funcContextId = 0) {
  const isExpression = allowExpression && !match2(TokenType.braceL);
  if (isExpression) {
    parseMaybeAssign();
  } else {
    parseBlock(true, funcContextId);
  }
}
function parseExprList(close, allowEmpty = false) {
  let first = true;
  while (!eat(close) && !state.error) {
    if (first) {
      first = false;
    } else {
      expect(TokenType.comma);
      if (eat(close))
        break;
    }
    parseExprListItem(allowEmpty);
  }
}
function parseExprListItem(allowEmpty) {
  if (allowEmpty && match2(TokenType.comma)) {
  } else if (match2(TokenType.ellipsis)) {
    parseSpread();
    parseParenItem();
  } else if (match2(TokenType.question)) {
    next();
  } else {
    parseMaybeAssign(false, true);
  }
}
function parseIdentifier() {
  next();
  state.tokens[state.tokens.length - 1].type = TokenType.name;
}
function parseAwait() {
  parseMaybeUnary();
}
function parseYield() {
  next();
  if (!match2(TokenType.semi) && !canInsertSemicolon()) {
    eat(TokenType.star);
    parseMaybeAssign();
  }
}
function parseModuleExpression() {
  expectContextual(ContextualKeyword._module);
  expect(TokenType.braceL);
  parseBlockBody(TokenType.braceR);
}

// node_modules/sucrase/dist/esm/parser/plugins/flow.js
function isMaybeDefaultImport(lookahead) {
  return (lookahead.type === TokenType.name || !!(lookahead.type & TokenType.IS_KEYWORD)) && lookahead.contextualKeyword !== ContextualKeyword._from;
}
function flowParseTypeInitialiser(tok) {
  const oldIsType = pushTypeContext(0);
  expect(tok || TokenType.colon);
  flowParseType();
  popTypeContext(oldIsType);
}
function flowParsePredicate() {
  expect(TokenType.modulo);
  expectContextual(ContextualKeyword._checks);
  if (eat(TokenType.parenL)) {
    parseExpression();
    expect(TokenType.parenR);
  }
}
function flowParseTypeAndPredicateInitialiser() {
  const oldIsType = pushTypeContext(0);
  expect(TokenType.colon);
  if (match2(TokenType.modulo)) {
    flowParsePredicate();
  } else {
    flowParseType();
    if (match2(TokenType.modulo)) {
      flowParsePredicate();
    }
  }
  popTypeContext(oldIsType);
}
function flowParseDeclareClass() {
  next();
  flowParseInterfaceish(
    /* isClass */
    true
  );
}
function flowParseDeclareFunction() {
  next();
  parseIdentifier();
  if (match2(TokenType.lessThan)) {
    flowParseTypeParameterDeclaration();
  }
  expect(TokenType.parenL);
  flowParseFunctionTypeParams();
  expect(TokenType.parenR);
  flowParseTypeAndPredicateInitialiser();
  semicolon();
}
function flowParseDeclare() {
  if (match2(TokenType._class)) {
    flowParseDeclareClass();
  } else if (match2(TokenType._function)) {
    flowParseDeclareFunction();
  } else if (match2(TokenType._var)) {
    flowParseDeclareVariable();
  } else if (eatContextual(ContextualKeyword._module)) {
    if (eat(TokenType.dot)) {
      flowParseDeclareModuleExports();
    } else {
      flowParseDeclareModule();
    }
  } else if (isContextual(ContextualKeyword._type)) {
    flowParseDeclareTypeAlias();
  } else if (isContextual(ContextualKeyword._opaque)) {
    flowParseDeclareOpaqueType();
  } else if (isContextual(ContextualKeyword._interface)) {
    flowParseDeclareInterface();
  } else if (match2(TokenType._export)) {
    flowParseDeclareExportDeclaration();
  } else {
    unexpected();
  }
}
function flowParseDeclareVariable() {
  next();
  flowParseTypeAnnotatableIdentifier();
  semicolon();
}
function flowParseDeclareModule() {
  if (match2(TokenType.string)) {
    parseExprAtom();
  } else {
    parseIdentifier();
  }
  expect(TokenType.braceL);
  while (!match2(TokenType.braceR) && !state.error) {
    if (match2(TokenType._import)) {
      next();
      parseImport();
    } else {
      unexpected();
    }
  }
  expect(TokenType.braceR);
}
function flowParseDeclareExportDeclaration() {
  expect(TokenType._export);
  if (eat(TokenType._default)) {
    if (match2(TokenType._function) || match2(TokenType._class)) {
      flowParseDeclare();
    } else {
      flowParseType();
      semicolon();
    }
  } else if (match2(TokenType._var) || // declare export var ...
  match2(TokenType._function) || // declare export function ...
  match2(TokenType._class) || // declare export class ...
  isContextual(ContextualKeyword._opaque)) {
    flowParseDeclare();
  } else if (match2(TokenType.star) || // declare export * from ''
  match2(TokenType.braceL) || // declare export {} ...
  isContextual(ContextualKeyword._interface) || // declare export interface ...
  isContextual(ContextualKeyword._type) || // declare export type ...
  isContextual(ContextualKeyword._opaque)) {
    parseExport();
  } else {
    unexpected();
  }
}
function flowParseDeclareModuleExports() {
  expectContextual(ContextualKeyword._exports);
  flowParseTypeAnnotation();
  semicolon();
}
function flowParseDeclareTypeAlias() {
  next();
  flowParseTypeAlias();
}
function flowParseDeclareOpaqueType() {
  next();
  flowParseOpaqueType(true);
}
function flowParseDeclareInterface() {
  next();
  flowParseInterfaceish();
}
function flowParseInterfaceish(isClass = false) {
  flowParseRestrictedIdentifier();
  if (match2(TokenType.lessThan)) {
    flowParseTypeParameterDeclaration();
  }
  if (eat(TokenType._extends)) {
    do {
      flowParseInterfaceExtends();
    } while (!isClass && eat(TokenType.comma));
  }
  if (isContextual(ContextualKeyword._mixins)) {
    next();
    do {
      flowParseInterfaceExtends();
    } while (eat(TokenType.comma));
  }
  if (isContextual(ContextualKeyword._implements)) {
    next();
    do {
      flowParseInterfaceExtends();
    } while (eat(TokenType.comma));
  }
  flowParseObjectType(isClass, false, isClass);
}
function flowParseInterfaceExtends() {
  flowParseQualifiedTypeIdentifier(false);
  if (match2(TokenType.lessThan)) {
    flowParseTypeParameterInstantiation();
  }
}
function flowParseInterface() {
  flowParseInterfaceish();
}
function flowParseRestrictedIdentifier() {
  parseIdentifier();
}
function flowParseTypeAlias() {
  flowParseRestrictedIdentifier();
  if (match2(TokenType.lessThan)) {
    flowParseTypeParameterDeclaration();
  }
  flowParseTypeInitialiser(TokenType.eq);
  semicolon();
}
function flowParseOpaqueType(declare) {
  expectContextual(ContextualKeyword._type);
  flowParseRestrictedIdentifier();
  if (match2(TokenType.lessThan)) {
    flowParseTypeParameterDeclaration();
  }
  if (match2(TokenType.colon)) {
    flowParseTypeInitialiser(TokenType.colon);
  }
  if (!declare) {
    flowParseTypeInitialiser(TokenType.eq);
  }
  semicolon();
}
function flowParseTypeParameter() {
  flowParseVariance();
  flowParseTypeAnnotatableIdentifier();
  if (eat(TokenType.eq)) {
    flowParseType();
  }
}
function flowParseTypeParameterDeclaration() {
  const oldIsType = pushTypeContext(0);
  if (match2(TokenType.lessThan) || match2(TokenType.typeParameterStart)) {
    next();
  } else {
    unexpected();
  }
  do {
    flowParseTypeParameter();
    if (!match2(TokenType.greaterThan)) {
      expect(TokenType.comma);
    }
  } while (!match2(TokenType.greaterThan) && !state.error);
  expect(TokenType.greaterThan);
  popTypeContext(oldIsType);
}
function flowParseTypeParameterInstantiation() {
  const oldIsType = pushTypeContext(0);
  expect(TokenType.lessThan);
  while (!match2(TokenType.greaterThan) && !state.error) {
    flowParseType();
    if (!match2(TokenType.greaterThan)) {
      expect(TokenType.comma);
    }
  }
  expect(TokenType.greaterThan);
  popTypeContext(oldIsType);
}
function flowParseInterfaceType() {
  expectContextual(ContextualKeyword._interface);
  if (eat(TokenType._extends)) {
    do {
      flowParseInterfaceExtends();
    } while (eat(TokenType.comma));
  }
  flowParseObjectType(false, false, false);
}
function flowParseObjectPropertyKey() {
  if (match2(TokenType.num) || match2(TokenType.string)) {
    parseExprAtom();
  } else {
    parseIdentifier();
  }
}
function flowParseObjectTypeIndexer() {
  if (lookaheadType() === TokenType.colon) {
    flowParseObjectPropertyKey();
    flowParseTypeInitialiser();
  } else {
    flowParseType();
  }
  expect(TokenType.bracketR);
  flowParseTypeInitialiser();
}
function flowParseObjectTypeInternalSlot() {
  flowParseObjectPropertyKey();
  expect(TokenType.bracketR);
  expect(TokenType.bracketR);
  if (match2(TokenType.lessThan) || match2(TokenType.parenL)) {
    flowParseObjectTypeMethodish();
  } else {
    eat(TokenType.question);
    flowParseTypeInitialiser();
  }
}
function flowParseObjectTypeMethodish() {
  if (match2(TokenType.lessThan)) {
    flowParseTypeParameterDeclaration();
  }
  expect(TokenType.parenL);
  while (!match2(TokenType.parenR) && !match2(TokenType.ellipsis) && !state.error) {
    flowParseFunctionTypeParam();
    if (!match2(TokenType.parenR)) {
      expect(TokenType.comma);
    }
  }
  if (eat(TokenType.ellipsis)) {
    flowParseFunctionTypeParam();
  }
  expect(TokenType.parenR);
  flowParseTypeInitialiser();
}
function flowParseObjectTypeCallProperty() {
  flowParseObjectTypeMethodish();
}
function flowParseObjectType(allowStatic, allowExact, allowProto) {
  let endDelim;
  if (allowExact && match2(TokenType.braceBarL)) {
    expect(TokenType.braceBarL);
    endDelim = TokenType.braceBarR;
  } else {
    expect(TokenType.braceL);
    endDelim = TokenType.braceR;
  }
  while (!match2(endDelim) && !state.error) {
    if (allowProto && isContextual(ContextualKeyword._proto)) {
      const lookahead = lookaheadType();
      if (lookahead !== TokenType.colon && lookahead !== TokenType.question) {
        next();
        allowStatic = false;
      }
    }
    if (allowStatic && isContextual(ContextualKeyword._static)) {
      const lookahead = lookaheadType();
      if (lookahead !== TokenType.colon && lookahead !== TokenType.question) {
        next();
      }
    }
    flowParseVariance();
    if (eat(TokenType.bracketL)) {
      if (eat(TokenType.bracketL)) {
        flowParseObjectTypeInternalSlot();
      } else {
        flowParseObjectTypeIndexer();
      }
    } else if (match2(TokenType.parenL) || match2(TokenType.lessThan)) {
      flowParseObjectTypeCallProperty();
    } else {
      if (isContextual(ContextualKeyword._get) || isContextual(ContextualKeyword._set)) {
        const lookahead = lookaheadType();
        if (lookahead === TokenType.name || lookahead === TokenType.string || lookahead === TokenType.num) {
          next();
        }
      }
      flowParseObjectTypeProperty();
    }
    flowObjectTypeSemicolon();
  }
  expect(endDelim);
}
function flowParseObjectTypeProperty() {
  if (match2(TokenType.ellipsis)) {
    expect(TokenType.ellipsis);
    if (!eat(TokenType.comma)) {
      eat(TokenType.semi);
    }
    if (match2(TokenType.braceR)) {
      return;
    }
    flowParseType();
  } else {
    flowParseObjectPropertyKey();
    if (match2(TokenType.lessThan) || match2(TokenType.parenL)) {
      flowParseObjectTypeMethodish();
    } else {
      eat(TokenType.question);
      flowParseTypeInitialiser();
    }
  }
}
function flowObjectTypeSemicolon() {
  if (!eat(TokenType.semi) && !eat(TokenType.comma) && !match2(TokenType.braceR) && !match2(TokenType.braceBarR)) {
    unexpected();
  }
}
function flowParseQualifiedTypeIdentifier(initialIdAlreadyParsed) {
  if (!initialIdAlreadyParsed) {
    parseIdentifier();
  }
  while (eat(TokenType.dot)) {
    parseIdentifier();
  }
}
function flowParseGenericType() {
  flowParseQualifiedTypeIdentifier(true);
  if (match2(TokenType.lessThan)) {
    flowParseTypeParameterInstantiation();
  }
}
function flowParseTypeofType() {
  expect(TokenType._typeof);
  flowParsePrimaryType();
}
function flowParseTupleType() {
  expect(TokenType.bracketL);
  while (state.pos < input.length && !match2(TokenType.bracketR)) {
    flowParseType();
    if (match2(TokenType.bracketR)) {
      break;
    }
    expect(TokenType.comma);
  }
  expect(TokenType.bracketR);
}
function flowParseFunctionTypeParam() {
  const lookahead = lookaheadType();
  if (lookahead === TokenType.colon || lookahead === TokenType.question) {
    parseIdentifier();
    eat(TokenType.question);
    flowParseTypeInitialiser();
  } else {
    flowParseType();
  }
}
function flowParseFunctionTypeParams() {
  while (!match2(TokenType.parenR) && !match2(TokenType.ellipsis) && !state.error) {
    flowParseFunctionTypeParam();
    if (!match2(TokenType.parenR)) {
      expect(TokenType.comma);
    }
  }
  if (eat(TokenType.ellipsis)) {
    flowParseFunctionTypeParam();
  }
}
function flowParsePrimaryType() {
  let isGroupedType = false;
  const oldNoAnonFunctionType = state.noAnonFunctionType;
  switch (state.type) {
    case TokenType.name: {
      if (isContextual(ContextualKeyword._interface)) {
        flowParseInterfaceType();
        return;
      }
      parseIdentifier();
      flowParseGenericType();
      return;
    }
    case TokenType.braceL:
      flowParseObjectType(false, false, false);
      return;
    case TokenType.braceBarL:
      flowParseObjectType(false, true, false);
      return;
    case TokenType.bracketL:
      flowParseTupleType();
      return;
    case TokenType.lessThan:
      flowParseTypeParameterDeclaration();
      expect(TokenType.parenL);
      flowParseFunctionTypeParams();
      expect(TokenType.parenR);
      expect(TokenType.arrow);
      flowParseType();
      return;
    case TokenType.parenL:
      next();
      if (!match2(TokenType.parenR) && !match2(TokenType.ellipsis)) {
        if (match2(TokenType.name)) {
          const token = lookaheadType();
          isGroupedType = token !== TokenType.question && token !== TokenType.colon;
        } else {
          isGroupedType = true;
        }
      }
      if (isGroupedType) {
        state.noAnonFunctionType = false;
        flowParseType();
        state.noAnonFunctionType = oldNoAnonFunctionType;
        if (state.noAnonFunctionType || !(match2(TokenType.comma) || match2(TokenType.parenR) && lookaheadType() === TokenType.arrow)) {
          expect(TokenType.parenR);
          return;
        } else {
          eat(TokenType.comma);
        }
      }
      flowParseFunctionTypeParams();
      expect(TokenType.parenR);
      expect(TokenType.arrow);
      flowParseType();
      return;
    case TokenType.minus:
      next();
      parseLiteral();
      return;
    case TokenType.string:
    case TokenType.num:
    case TokenType._true:
    case TokenType._false:
    case TokenType._null:
    case TokenType._this:
    case TokenType._void:
    case TokenType.star:
      next();
      return;
    default:
      if (state.type === TokenType._typeof) {
        flowParseTypeofType();
        return;
      } else if (state.type & TokenType.IS_KEYWORD) {
        next();
        state.tokens[state.tokens.length - 1].type = TokenType.name;
        return;
      }
  }
  unexpected();
}
function flowParsePostfixType() {
  flowParsePrimaryType();
  while (!canInsertSemicolon() && (match2(TokenType.bracketL) || match2(TokenType.questionDot))) {
    eat(TokenType.questionDot);
    expect(TokenType.bracketL);
    if (eat(TokenType.bracketR)) {
    } else {
      flowParseType();
      expect(TokenType.bracketR);
    }
  }
}
function flowParsePrefixType() {
  if (eat(TokenType.question)) {
    flowParsePrefixType();
  } else {
    flowParsePostfixType();
  }
}
function flowParseAnonFunctionWithoutParens() {
  flowParsePrefixType();
  if (!state.noAnonFunctionType && eat(TokenType.arrow)) {
    flowParseType();
  }
}
function flowParseIntersectionType() {
  eat(TokenType.bitwiseAND);
  flowParseAnonFunctionWithoutParens();
  while (eat(TokenType.bitwiseAND)) {
    flowParseAnonFunctionWithoutParens();
  }
}
function flowParseUnionType() {
  eat(TokenType.bitwiseOR);
  flowParseIntersectionType();
  while (eat(TokenType.bitwiseOR)) {
    flowParseIntersectionType();
  }
}
function flowParseType() {
  flowParseUnionType();
}
function flowParseTypeAnnotation() {
  flowParseTypeInitialiser();
}
function flowParseTypeAnnotatableIdentifier() {
  parseIdentifier();
  if (match2(TokenType.colon)) {
    flowParseTypeAnnotation();
  }
}
function flowParseVariance() {
  if (match2(TokenType.plus) || match2(TokenType.minus)) {
    next();
    state.tokens[state.tokens.length - 1].isType = true;
  }
}
function flowParseFunctionBodyAndFinish(funcContextId) {
  if (match2(TokenType.colon)) {
    flowParseTypeAndPredicateInitialiser();
  }
  parseFunctionBody(false, funcContextId);
}
function flowParseSubscript(startTokenIndex, noCalls, stopState) {
  if (match2(TokenType.questionDot) && lookaheadType() === TokenType.lessThan) {
    if (noCalls) {
      stopState.stop = true;
      return;
    }
    next();
    flowParseTypeParameterInstantiation();
    expect(TokenType.parenL);
    parseCallExpressionArguments();
    return;
  } else if (!noCalls && match2(TokenType.lessThan)) {
    const snapshot = state.snapshot();
    flowParseTypeParameterInstantiation();
    expect(TokenType.parenL);
    parseCallExpressionArguments();
    if (state.error) {
      state.restoreFromSnapshot(snapshot);
    } else {
      return;
    }
  }
  baseParseSubscript(startTokenIndex, noCalls, stopState);
}
function flowStartParseNewArguments() {
  if (match2(TokenType.lessThan)) {
    const snapshot = state.snapshot();
    flowParseTypeParameterInstantiation();
    if (state.error) {
      state.restoreFromSnapshot(snapshot);
    }
  }
}
function flowTryParseStatement() {
  if (match2(TokenType.name) && state.contextualKeyword === ContextualKeyword._interface) {
    const oldIsType = pushTypeContext(0);
    next();
    flowParseInterface();
    popTypeContext(oldIsType);
    return true;
  } else if (isContextual(ContextualKeyword._enum)) {
    flowParseEnumDeclaration();
    return true;
  }
  return false;
}
function flowTryParseExportDefaultExpression() {
  if (isContextual(ContextualKeyword._enum)) {
    flowParseEnumDeclaration();
    return true;
  }
  return false;
}
function flowParseIdentifierStatement(contextualKeyword) {
  if (contextualKeyword === ContextualKeyword._declare) {
    if (match2(TokenType._class) || match2(TokenType.name) || match2(TokenType._function) || match2(TokenType._var) || match2(TokenType._export)) {
      const oldIsType = pushTypeContext(1);
      flowParseDeclare();
      popTypeContext(oldIsType);
    }
  } else if (match2(TokenType.name)) {
    if (contextualKeyword === ContextualKeyword._interface) {
      const oldIsType = pushTypeContext(1);
      flowParseInterface();
      popTypeContext(oldIsType);
    } else if (contextualKeyword === ContextualKeyword._type) {
      const oldIsType = pushTypeContext(1);
      flowParseTypeAlias();
      popTypeContext(oldIsType);
    } else if (contextualKeyword === ContextualKeyword._opaque) {
      const oldIsType = pushTypeContext(1);
      flowParseOpaqueType(false);
      popTypeContext(oldIsType);
    }
  }
  semicolon();
}
function flowShouldParseExportDeclaration() {
  return isContextual(ContextualKeyword._type) || isContextual(ContextualKeyword._interface) || isContextual(ContextualKeyword._opaque) || isContextual(ContextualKeyword._enum);
}
function flowShouldDisallowExportDefaultSpecifier() {
  return match2(TokenType.name) && (state.contextualKeyword === ContextualKeyword._type || state.contextualKeyword === ContextualKeyword._interface || state.contextualKeyword === ContextualKeyword._opaque || state.contextualKeyword === ContextualKeyword._enum);
}
function flowParseExportDeclaration() {
  if (isContextual(ContextualKeyword._type)) {
    const oldIsType = pushTypeContext(1);
    next();
    if (match2(TokenType.braceL)) {
      parseExportSpecifiers();
      parseExportFrom();
    } else {
      flowParseTypeAlias();
    }
    popTypeContext(oldIsType);
  } else if (isContextual(ContextualKeyword._opaque)) {
    const oldIsType = pushTypeContext(1);
    next();
    flowParseOpaqueType(false);
    popTypeContext(oldIsType);
  } else if (isContextual(ContextualKeyword._interface)) {
    const oldIsType = pushTypeContext(1);
    next();
    flowParseInterface();
    popTypeContext(oldIsType);
  } else {
    parseStatement(true);
  }
}
function flowShouldParseExportStar() {
  return match2(TokenType.star) || isContextual(ContextualKeyword._type) && lookaheadType() === TokenType.star;
}
function flowParseExportStar() {
  if (eatContextual(ContextualKeyword._type)) {
    const oldIsType = pushTypeContext(2);
    baseParseExportStar();
    popTypeContext(oldIsType);
  } else {
    baseParseExportStar();
  }
}
function flowAfterParseClassSuper(hasSuper) {
  if (hasSuper && match2(TokenType.lessThan)) {
    flowParseTypeParameterInstantiation();
  }
  if (isContextual(ContextualKeyword._implements)) {
    const oldIsType = pushTypeContext(0);
    next();
    state.tokens[state.tokens.length - 1].type = TokenType._implements;
    do {
      flowParseRestrictedIdentifier();
      if (match2(TokenType.lessThan)) {
        flowParseTypeParameterInstantiation();
      }
    } while (eat(TokenType.comma));
    popTypeContext(oldIsType);
  }
}
function flowStartParseObjPropValue() {
  if (match2(TokenType.lessThan)) {
    flowParseTypeParameterDeclaration();
    if (!match2(TokenType.parenL))
      unexpected();
  }
}
function flowParseAssignableListItemTypes() {
  const oldIsType = pushTypeContext(0);
  eat(TokenType.question);
  if (match2(TokenType.colon)) {
    flowParseTypeAnnotation();
  }
  popTypeContext(oldIsType);
}
function flowStartParseImportSpecifiers() {
  if (match2(TokenType._typeof) || isContextual(ContextualKeyword._type)) {
    const lh = lookaheadTypeAndKeyword();
    if (isMaybeDefaultImport(lh) || lh.type === TokenType.braceL || lh.type === TokenType.star) {
      next();
    }
  }
}
function flowParseImportSpecifier() {
  const isTypeKeyword = state.contextualKeyword === ContextualKeyword._type || state.type === TokenType._typeof;
  if (isTypeKeyword) {
    next();
  } else {
    parseIdentifier();
  }
  if (isContextual(ContextualKeyword._as) && !isLookaheadContextual(ContextualKeyword._as)) {
    parseIdentifier();
    if (isTypeKeyword && !match2(TokenType.name) && !(state.type & TokenType.IS_KEYWORD)) {
    } else {
      parseIdentifier();
    }
  } else {
    if (isTypeKeyword && (match2(TokenType.name) || !!(state.type & TokenType.IS_KEYWORD))) {
      parseIdentifier();
    }
    if (eatContextual(ContextualKeyword._as)) {
      parseIdentifier();
    }
  }
}
function flowStartParseFunctionParams() {
  if (match2(TokenType.lessThan)) {
    const oldIsType = pushTypeContext(0);
    flowParseTypeParameterDeclaration();
    popTypeContext(oldIsType);
  }
}
function flowAfterParseVarHead() {
  if (match2(TokenType.colon)) {
    flowParseTypeAnnotation();
  }
}
function flowStartParseAsyncArrowFromCallExpression() {
  if (match2(TokenType.colon)) {
    const oldNoAnonFunctionType = state.noAnonFunctionType;
    state.noAnonFunctionType = true;
    flowParseTypeAnnotation();
    state.noAnonFunctionType = oldNoAnonFunctionType;
  }
}
function flowParseMaybeAssign(noIn, isWithinParens) {
  if (match2(TokenType.lessThan)) {
    const snapshot = state.snapshot();
    let wasArrow = baseParseMaybeAssign(noIn, isWithinParens);
    if (state.error) {
      state.restoreFromSnapshot(snapshot);
      state.type = TokenType.typeParameterStart;
    } else {
      return wasArrow;
    }
    const oldIsType = pushTypeContext(0);
    flowParseTypeParameterDeclaration();
    popTypeContext(oldIsType);
    wasArrow = baseParseMaybeAssign(noIn, isWithinParens);
    if (wasArrow) {
      return true;
    }
    unexpected();
  }
  return baseParseMaybeAssign(noIn, isWithinParens);
}
function flowParseArrow() {
  if (match2(TokenType.colon)) {
    const oldIsType = pushTypeContext(0);
    const snapshot = state.snapshot();
    const oldNoAnonFunctionType = state.noAnonFunctionType;
    state.noAnonFunctionType = true;
    flowParseTypeAndPredicateInitialiser();
    state.noAnonFunctionType = oldNoAnonFunctionType;
    if (canInsertSemicolon())
      unexpected();
    if (!match2(TokenType.arrow))
      unexpected();
    if (state.error) {
      state.restoreFromSnapshot(snapshot);
    }
    popTypeContext(oldIsType);
  }
  return eat(TokenType.arrow);
}
function flowParseSubscripts(startTokenIndex, noCalls = false) {
  if (state.tokens[state.tokens.length - 1].contextualKeyword === ContextualKeyword._async && match2(TokenType.lessThan)) {
    const snapshot = state.snapshot();
    const wasArrow = parseAsyncArrowWithTypeParameters();
    if (wasArrow && !state.error) {
      return;
    }
    state.restoreFromSnapshot(snapshot);
  }
  baseParseSubscripts(startTokenIndex, noCalls);
}
function parseAsyncArrowWithTypeParameters() {
  state.scopeDepth++;
  const startTokenIndex = state.tokens.length;
  parseFunctionParams();
  if (!parseArrow()) {
    return false;
  }
  parseArrowExpression(startTokenIndex);
  return true;
}
function flowParseEnumDeclaration() {
  expectContextual(ContextualKeyword._enum);
  state.tokens[state.tokens.length - 1].type = TokenType._enum;
  parseIdentifier();
  flowParseEnumBody();
}
function flowParseEnumBody() {
  if (eatContextual(ContextualKeyword._of)) {
    next();
  }
  expect(TokenType.braceL);
  flowParseEnumMembers();
  expect(TokenType.braceR);
}
function flowParseEnumMembers() {
  while (!match2(TokenType.braceR) && !state.error) {
    if (eat(TokenType.ellipsis)) {
      break;
    }
    flowParseEnumMember();
    if (!match2(TokenType.braceR)) {
      expect(TokenType.comma);
    }
  }
}
function flowParseEnumMember() {
  parseIdentifier();
  if (eat(TokenType.eq)) {
    next();
  }
}

// node_modules/sucrase/dist/esm/parser/traverser/statement.js
function parseTopLevel() {
  parseBlockBody(TokenType.eof);
  state.scopes.push(new Scope(0, state.tokens.length, true));
  if (state.scopeDepth !== 0) {
    throw new Error(`Invalid scope depth at end of file: ${state.scopeDepth}`);
  }
  return new File(state.tokens, state.scopes);
}
function parseStatement(declaration) {
  if (isFlowEnabled) {
    if (flowTryParseStatement()) {
      return;
    }
  }
  if (match2(TokenType.at)) {
    parseDecorators();
  }
  parseStatementContent(declaration);
}
function parseStatementContent(declaration) {
  if (isTypeScriptEnabled) {
    if (tsTryParseStatementContent()) {
      return;
    }
  }
  const starttype = state.type;
  switch (starttype) {
    case TokenType._break:
    case TokenType._continue:
      parseBreakContinueStatement();
      return;
    case TokenType._debugger:
      parseDebuggerStatement();
      return;
    case TokenType._do:
      parseDoStatement();
      return;
    case TokenType._for:
      parseForStatement();
      return;
    case TokenType._function:
      if (lookaheadType() === TokenType.dot)
        break;
      if (!declaration)
        unexpected();
      parseFunctionStatement();
      return;
    case TokenType._class:
      if (!declaration)
        unexpected();
      parseClass(true);
      return;
    case TokenType._if:
      parseIfStatement();
      return;
    case TokenType._return:
      parseReturnStatement();
      return;
    case TokenType._switch:
      parseSwitchStatement();
      return;
    case TokenType._throw:
      parseThrowStatement();
      return;
    case TokenType._try:
      parseTryStatement();
      return;
    case TokenType._let:
    case TokenType._const:
      if (!declaration)
        unexpected();
    case TokenType._var:
      parseVarStatement(starttype !== TokenType._var);
      return;
    case TokenType._while:
      parseWhileStatement();
      return;
    case TokenType.braceL:
      parseBlock();
      return;
    case TokenType.semi:
      parseEmptyStatement();
      return;
    case TokenType._export:
    case TokenType._import: {
      const nextType = lookaheadType();
      if (nextType === TokenType.parenL || nextType === TokenType.dot) {
        break;
      }
      next();
      if (starttype === TokenType._import) {
        parseImport();
      } else {
        parseExport();
      }
      return;
    }
    case TokenType.name:
      if (state.contextualKeyword === ContextualKeyword._async) {
        const functionStart = state.start;
        const snapshot = state.snapshot();
        next();
        if (match2(TokenType._function) && !canInsertSemicolon()) {
          expect(TokenType._function);
          parseFunction(functionStart, true);
          return;
        } else {
          state.restoreFromSnapshot(snapshot);
        }
      } else if (state.contextualKeyword === ContextualKeyword._using && !hasFollowingLineBreak() && // Statements like `using[0]` and `using in foo` aren't actual using
      // declarations.
      lookaheadType() === TokenType.name) {
        parseVarStatement(true);
        return;
      } else if (startsAwaitUsing()) {
        expectContextual(ContextualKeyword._await);
        parseVarStatement(true);
        return;
      }
    default:
      break;
  }
  const initialTokensLength = state.tokens.length;
  parseExpression();
  let simpleName = null;
  if (state.tokens.length === initialTokensLength + 1) {
    const token = state.tokens[state.tokens.length - 1];
    if (token.type === TokenType.name) {
      simpleName = token.contextualKeyword;
    }
  }
  if (simpleName == null) {
    semicolon();
    return;
  }
  if (eat(TokenType.colon)) {
    parseLabeledStatement();
  } else {
    parseIdentifierStatement(simpleName);
  }
}
function startsAwaitUsing() {
  if (!isContextual(ContextualKeyword._await)) {
    return false;
  }
  const snapshot = state.snapshot();
  next();
  if (!isContextual(ContextualKeyword._using) || hasPrecedingLineBreak()) {
    state.restoreFromSnapshot(snapshot);
    return false;
  }
  next();
  if (!match2(TokenType.name) || hasPrecedingLineBreak()) {
    state.restoreFromSnapshot(snapshot);
    return false;
  }
  state.restoreFromSnapshot(snapshot);
  return true;
}
function parseDecorators() {
  while (match2(TokenType.at)) {
    parseDecorator();
  }
}
function parseDecorator() {
  next();
  if (eat(TokenType.parenL)) {
    parseExpression();
    expect(TokenType.parenR);
  } else {
    parseIdentifier();
    while (eat(TokenType.dot)) {
      parseIdentifier();
    }
    parseMaybeDecoratorArguments();
  }
}
function parseMaybeDecoratorArguments() {
  if (isTypeScriptEnabled) {
    tsParseMaybeDecoratorArguments();
  } else {
    baseParseMaybeDecoratorArguments();
  }
}
function baseParseMaybeDecoratorArguments() {
  if (eat(TokenType.parenL)) {
    parseCallExpressionArguments();
  }
}
function parseBreakContinueStatement() {
  next();
  if (!isLineTerminator()) {
    parseIdentifier();
    semicolon();
  }
}
function parseDebuggerStatement() {
  next();
  semicolon();
}
function parseDoStatement() {
  next();
  parseStatement(false);
  expect(TokenType._while);
  parseParenExpression();
  eat(TokenType.semi);
}
function parseForStatement() {
  state.scopeDepth++;
  const startTokenIndex = state.tokens.length;
  parseAmbiguousForStatement();
  const endTokenIndex = state.tokens.length;
  state.scopes.push(new Scope(startTokenIndex, endTokenIndex, false));
  state.scopeDepth--;
}
function isUsingInLoop() {
  if (!isContextual(ContextualKeyword._using)) {
    return false;
  }
  if (isLookaheadContextual(ContextualKeyword._of)) {
    return false;
  }
  return true;
}
function parseAmbiguousForStatement() {
  next();
  let forAwait = false;
  if (isContextual(ContextualKeyword._await)) {
    forAwait = true;
    next();
  }
  expect(TokenType.parenL);
  if (match2(TokenType.semi)) {
    if (forAwait) {
      unexpected();
    }
    parseFor();
    return;
  }
  const isAwaitUsing = startsAwaitUsing();
  if (isAwaitUsing || match2(TokenType._var) || match2(TokenType._let) || match2(TokenType._const) || isUsingInLoop()) {
    if (isAwaitUsing) {
      expectContextual(ContextualKeyword._await);
    }
    next();
    parseVar(true, state.type !== TokenType._var);
    if (match2(TokenType._in) || isContextual(ContextualKeyword._of)) {
      parseForIn(forAwait);
      return;
    }
    parseFor();
    return;
  }
  parseExpression(true);
  if (match2(TokenType._in) || isContextual(ContextualKeyword._of)) {
    parseForIn(forAwait);
    return;
  }
  if (forAwait) {
    unexpected();
  }
  parseFor();
}
function parseFunctionStatement() {
  const functionStart = state.start;
  next();
  parseFunction(functionStart, true);
}
function parseIfStatement() {
  next();
  parseParenExpression();
  parseStatement(false);
  if (eat(TokenType._else)) {
    parseStatement(false);
  }
}
function parseReturnStatement() {
  next();
  if (!isLineTerminator()) {
    parseExpression();
    semicolon();
  }
}
function parseSwitchStatement() {
  next();
  parseParenExpression();
  state.scopeDepth++;
  const startTokenIndex = state.tokens.length;
  expect(TokenType.braceL);
  while (!match2(TokenType.braceR) && !state.error) {
    if (match2(TokenType._case) || match2(TokenType._default)) {
      const isCase = match2(TokenType._case);
      next();
      if (isCase) {
        parseExpression();
      }
      expect(TokenType.colon);
    } else {
      parseStatement(true);
    }
  }
  next();
  const endTokenIndex = state.tokens.length;
  state.scopes.push(new Scope(startTokenIndex, endTokenIndex, false));
  state.scopeDepth--;
}
function parseThrowStatement() {
  next();
  parseExpression();
  semicolon();
}
function parseCatchClauseParam() {
  parseBindingAtom(
    true
    /* isBlockScope */
  );
  if (isTypeScriptEnabled) {
    tsTryParseTypeAnnotation();
  }
}
function parseTryStatement() {
  next();
  parseBlock();
  if (match2(TokenType._catch)) {
    next();
    let catchBindingStartTokenIndex = null;
    if (match2(TokenType.parenL)) {
      state.scopeDepth++;
      catchBindingStartTokenIndex = state.tokens.length;
      expect(TokenType.parenL);
      parseCatchClauseParam();
      expect(TokenType.parenR);
    }
    parseBlock();
    if (catchBindingStartTokenIndex != null) {
      const endTokenIndex = state.tokens.length;
      state.scopes.push(new Scope(catchBindingStartTokenIndex, endTokenIndex, false));
      state.scopeDepth--;
    }
  }
  if (eat(TokenType._finally)) {
    parseBlock();
  }
}
function parseVarStatement(isBlockScope) {
  next();
  parseVar(false, isBlockScope);
  semicolon();
}
function parseWhileStatement() {
  next();
  parseParenExpression();
  parseStatement(false);
}
function parseEmptyStatement() {
  next();
}
function parseLabeledStatement() {
  parseStatement(true);
}
function parseIdentifierStatement(contextualKeyword) {
  if (isTypeScriptEnabled) {
    tsParseIdentifierStatement(contextualKeyword);
  } else if (isFlowEnabled) {
    flowParseIdentifierStatement(contextualKeyword);
  } else {
    semicolon();
  }
}
function parseBlock(isFunctionScope = false, contextId = 0) {
  const startTokenIndex = state.tokens.length;
  state.scopeDepth++;
  expect(TokenType.braceL);
  if (contextId) {
    state.tokens[state.tokens.length - 1].contextId = contextId;
  }
  parseBlockBody(TokenType.braceR);
  if (contextId) {
    state.tokens[state.tokens.length - 1].contextId = contextId;
  }
  const endTokenIndex = state.tokens.length;
  state.scopes.push(new Scope(startTokenIndex, endTokenIndex, isFunctionScope));
  state.scopeDepth--;
}
function parseBlockBody(end) {
  while (!eat(end) && !state.error) {
    parseStatement(true);
  }
}
function parseFor() {
  expect(TokenType.semi);
  if (!match2(TokenType.semi)) {
    parseExpression();
  }
  expect(TokenType.semi);
  if (!match2(TokenType.parenR)) {
    parseExpression();
  }
  expect(TokenType.parenR);
  parseStatement(false);
}
function parseForIn(forAwait) {
  if (forAwait) {
    eatContextual(ContextualKeyword._of);
  } else {
    next();
  }
  parseExpression();
  expect(TokenType.parenR);
  parseStatement(false);
}
function parseVar(isFor, isBlockScope) {
  while (true) {
    parseVarHead(isBlockScope);
    if (eat(TokenType.eq)) {
      const eqIndex = state.tokens.length - 1;
      parseMaybeAssign(isFor);
      state.tokens[eqIndex].rhsEndIndex = state.tokens.length;
    }
    if (!eat(TokenType.comma)) {
      break;
    }
  }
}
function parseVarHead(isBlockScope) {
  parseBindingAtom(isBlockScope);
  if (isTypeScriptEnabled) {
    tsAfterParseVarHead();
  } else if (isFlowEnabled) {
    flowAfterParseVarHead();
  }
}
function parseFunction(functionStart, isStatement, optionalId = false) {
  if (match2(TokenType.star)) {
    next();
  }
  if (isStatement && !optionalId && !match2(TokenType.name) && !match2(TokenType._yield)) {
    unexpected();
  }
  let nameScopeStartTokenIndex = null;
  if (match2(TokenType.name)) {
    if (!isStatement) {
      nameScopeStartTokenIndex = state.tokens.length;
      state.scopeDepth++;
    }
    parseBindingIdentifier(false);
  }
  const startTokenIndex = state.tokens.length;
  state.scopeDepth++;
  parseFunctionParams();
  parseFunctionBodyAndFinish(functionStart);
  const endTokenIndex = state.tokens.length;
  state.scopes.push(new Scope(startTokenIndex, endTokenIndex, true));
  state.scopeDepth--;
  if (nameScopeStartTokenIndex !== null) {
    state.scopes.push(new Scope(nameScopeStartTokenIndex, endTokenIndex, true));
    state.scopeDepth--;
  }
}
function parseFunctionParams(allowModifiers = false, funcContextId = 0) {
  if (isTypeScriptEnabled) {
    tsStartParseFunctionParams();
  } else if (isFlowEnabled) {
    flowStartParseFunctionParams();
  }
  expect(TokenType.parenL);
  if (funcContextId) {
    state.tokens[state.tokens.length - 1].contextId = funcContextId;
  }
  parseBindingList(
    TokenType.parenR,
    false,
    false,
    allowModifiers,
    funcContextId
  );
  if (funcContextId) {
    state.tokens[state.tokens.length - 1].contextId = funcContextId;
  }
}
function parseClass(isStatement, optionalId = false) {
  const contextId = getNextContextId();
  next();
  state.tokens[state.tokens.length - 1].contextId = contextId;
  state.tokens[state.tokens.length - 1].isExpression = !isStatement;
  let nameScopeStartTokenIndex = null;
  if (!isStatement) {
    nameScopeStartTokenIndex = state.tokens.length;
    state.scopeDepth++;
  }
  parseClassId(isStatement, optionalId);
  parseClassSuper();
  const openBraceIndex = state.tokens.length;
  parseClassBody(contextId);
  if (state.error) {
    return;
  }
  state.tokens[openBraceIndex].contextId = contextId;
  state.tokens[state.tokens.length - 1].contextId = contextId;
  if (nameScopeStartTokenIndex !== null) {
    const endTokenIndex = state.tokens.length;
    state.scopes.push(new Scope(nameScopeStartTokenIndex, endTokenIndex, false));
    state.scopeDepth--;
  }
}
function isClassProperty() {
  return match2(TokenType.eq) || match2(TokenType.semi) || match2(TokenType.braceR) || match2(TokenType.bang) || match2(TokenType.colon);
}
function isClassMethod() {
  return match2(TokenType.parenL) || match2(TokenType.lessThan);
}
function parseClassBody(classContextId) {
  expect(TokenType.braceL);
  while (!eat(TokenType.braceR) && !state.error) {
    if (eat(TokenType.semi)) {
      continue;
    }
    if (match2(TokenType.at)) {
      parseDecorator();
      continue;
    }
    const memberStart = state.start;
    parseClassMember(memberStart, classContextId);
  }
}
function parseClassMember(memberStart, classContextId) {
  if (isTypeScriptEnabled) {
    tsParseModifiers([
      ContextualKeyword._declare,
      ContextualKeyword._public,
      ContextualKeyword._protected,
      ContextualKeyword._private,
      ContextualKeyword._override
    ]);
  }
  let isStatic = false;
  if (match2(TokenType.name) && state.contextualKeyword === ContextualKeyword._static) {
    parseIdentifier();
    if (isClassMethod()) {
      parseClassMethod(
        memberStart,
        /* isConstructor */
        false
      );
      return;
    } else if (isClassProperty()) {
      parseClassProperty();
      return;
    }
    state.tokens[state.tokens.length - 1].type = TokenType._static;
    isStatic = true;
    if (match2(TokenType.braceL)) {
      state.tokens[state.tokens.length - 1].contextId = classContextId;
      parseBlock();
      return;
    }
  }
  parseClassMemberWithIsStatic(memberStart, isStatic, classContextId);
}
function parseClassMemberWithIsStatic(memberStart, isStatic, classContextId) {
  if (isTypeScriptEnabled) {
    if (tsTryParseClassMemberWithIsStatic(isStatic)) {
      return;
    }
  }
  if (eat(TokenType.star)) {
    parseClassPropertyName(classContextId);
    parseClassMethod(
      memberStart,
      /* isConstructor */
      false
    );
    return;
  }
  parseClassPropertyName(classContextId);
  let isConstructor = false;
  const token = state.tokens[state.tokens.length - 1];
  if (token.contextualKeyword === ContextualKeyword._constructor) {
    isConstructor = true;
  }
  parsePostMemberNameModifiers();
  if (isClassMethod()) {
    parseClassMethod(memberStart, isConstructor);
  } else if (isClassProperty()) {
    parseClassProperty();
  } else if (token.contextualKeyword === ContextualKeyword._async && !isLineTerminator()) {
    state.tokens[state.tokens.length - 1].type = TokenType._async;
    const isGenerator = match2(TokenType.star);
    if (isGenerator) {
      next();
    }
    parseClassPropertyName(classContextId);
    parsePostMemberNameModifiers();
    parseClassMethod(
      memberStart,
      false
      /* isConstructor */
    );
  } else if ((token.contextualKeyword === ContextualKeyword._get || token.contextualKeyword === ContextualKeyword._set) && !(isLineTerminator() && match2(TokenType.star))) {
    if (token.contextualKeyword === ContextualKeyword._get) {
      state.tokens[state.tokens.length - 1].type = TokenType._get;
    } else {
      state.tokens[state.tokens.length - 1].type = TokenType._set;
    }
    parseClassPropertyName(classContextId);
    parseClassMethod(
      memberStart,
      /* isConstructor */
      false
    );
  } else if (token.contextualKeyword === ContextualKeyword._accessor && !isLineTerminator()) {
    parseClassPropertyName(classContextId);
    parseClassProperty();
  } else if (isLineTerminator()) {
    parseClassProperty();
  } else {
    unexpected();
  }
}
function parseClassMethod(functionStart, isConstructor) {
  if (isTypeScriptEnabled) {
    tsTryParseTypeParameters();
  } else if (isFlowEnabled) {
    if (match2(TokenType.lessThan)) {
      flowParseTypeParameterDeclaration();
    }
  }
  parseMethod(functionStart, isConstructor);
}
function parseClassPropertyName(classContextId) {
  parsePropertyName(classContextId);
}
function parsePostMemberNameModifiers() {
  if (isTypeScriptEnabled) {
    const oldIsType = pushTypeContext(0);
    eat(TokenType.question);
    popTypeContext(oldIsType);
  }
}
function parseClassProperty() {
  if (isTypeScriptEnabled) {
    eatTypeToken(TokenType.bang);
    tsTryParseTypeAnnotation();
  } else if (isFlowEnabled) {
    if (match2(TokenType.colon)) {
      flowParseTypeAnnotation();
    }
  }
  if (match2(TokenType.eq)) {
    const equalsTokenIndex = state.tokens.length;
    next();
    parseMaybeAssign();
    state.tokens[equalsTokenIndex].rhsEndIndex = state.tokens.length;
  }
  semicolon();
}
function parseClassId(isStatement, optionalId = false) {
  if (isTypeScriptEnabled && (!isStatement || optionalId) && isContextual(ContextualKeyword._implements)) {
    return;
  }
  if (match2(TokenType.name)) {
    parseBindingIdentifier(true);
  }
  if (isTypeScriptEnabled) {
    tsTryParseTypeParameters();
  } else if (isFlowEnabled) {
    if (match2(TokenType.lessThan)) {
      flowParseTypeParameterDeclaration();
    }
  }
}
function parseClassSuper() {
  let hasSuper = false;
  if (eat(TokenType._extends)) {
    parseExprSubscripts();
    hasSuper = true;
  } else {
    hasSuper = false;
  }
  if (isTypeScriptEnabled) {
    tsAfterParseClassSuper(hasSuper);
  } else if (isFlowEnabled) {
    flowAfterParseClassSuper(hasSuper);
  }
}
function parseExport() {
  const exportIndex = state.tokens.length - 1;
  if (isTypeScriptEnabled) {
    if (tsTryParseExport()) {
      return;
    }
  }
  if (shouldParseExportStar()) {
    parseExportStar();
  } else if (isExportDefaultSpecifier()) {
    parseIdentifier();
    if (match2(TokenType.comma) && lookaheadType() === TokenType.star) {
      expect(TokenType.comma);
      expect(TokenType.star);
      expectContextual(ContextualKeyword._as);
      parseIdentifier();
    } else {
      parseExportSpecifiersMaybe();
    }
    parseExportFrom();
  } else if (eat(TokenType._default)) {
    parseExportDefaultExpression();
  } else if (shouldParseExportDeclaration()) {
    parseExportDeclaration();
  } else {
    parseExportSpecifiers();
    parseExportFrom();
  }
  state.tokens[exportIndex].rhsEndIndex = state.tokens.length;
}
function parseExportDefaultExpression() {
  if (isTypeScriptEnabled) {
    if (tsTryParseExportDefaultExpression()) {
      return;
    }
  }
  if (isFlowEnabled) {
    if (flowTryParseExportDefaultExpression()) {
      return;
    }
  }
  const functionStart = state.start;
  if (eat(TokenType._function)) {
    parseFunction(functionStart, true, true);
  } else if (isContextual(ContextualKeyword._async) && lookaheadType() === TokenType._function) {
    eatContextual(ContextualKeyword._async);
    eat(TokenType._function);
    parseFunction(functionStart, true, true);
  } else if (match2(TokenType._class)) {
    parseClass(true, true);
  } else if (match2(TokenType.at)) {
    parseDecorators();
    parseClass(true, true);
  } else {
    parseMaybeAssign();
    semicolon();
  }
}
function parseExportDeclaration() {
  if (isTypeScriptEnabled) {
    tsParseExportDeclaration();
  } else if (isFlowEnabled) {
    flowParseExportDeclaration();
  } else {
    parseStatement(true);
  }
}
function isExportDefaultSpecifier() {
  if (isTypeScriptEnabled && tsIsDeclarationStart()) {
    return false;
  } else if (isFlowEnabled && flowShouldDisallowExportDefaultSpecifier()) {
    return false;
  }
  if (match2(TokenType.name)) {
    return state.contextualKeyword !== ContextualKeyword._async;
  }
  if (!match2(TokenType._default)) {
    return false;
  }
  const _next = nextTokenStart();
  const lookahead = lookaheadTypeAndKeyword();
  const hasFrom = lookahead.type === TokenType.name && lookahead.contextualKeyword === ContextualKeyword._from;
  if (lookahead.type === TokenType.comma) {
    return true;
  }
  if (hasFrom) {
    const nextAfterFrom = input.charCodeAt(nextTokenStartSince(_next + 4));
    return nextAfterFrom === charCodes.quotationMark || nextAfterFrom === charCodes.apostrophe;
  }
  return false;
}
function parseExportSpecifiersMaybe() {
  if (eat(TokenType.comma)) {
    parseExportSpecifiers();
  }
}
function parseExportFrom() {
  if (eatContextual(ContextualKeyword._from)) {
    parseExprAtom();
    maybeParseImportAttributes();
  }
  semicolon();
}
function shouldParseExportStar() {
  if (isFlowEnabled) {
    return flowShouldParseExportStar();
  } else {
    return match2(TokenType.star);
  }
}
function parseExportStar() {
  if (isFlowEnabled) {
    flowParseExportStar();
  } else {
    baseParseExportStar();
  }
}
function baseParseExportStar() {
  expect(TokenType.star);
  if (isContextual(ContextualKeyword._as)) {
    parseExportNamespace();
  } else {
    parseExportFrom();
  }
}
function parseExportNamespace() {
  next();
  state.tokens[state.tokens.length - 1].type = TokenType._as;
  parseIdentifier();
  parseExportSpecifiersMaybe();
  parseExportFrom();
}
function shouldParseExportDeclaration() {
  return isTypeScriptEnabled && tsIsDeclarationStart() || isFlowEnabled && flowShouldParseExportDeclaration() || state.type === TokenType._var || state.type === TokenType._const || state.type === TokenType._let || state.type === TokenType._function || state.type === TokenType._class || isContextual(ContextualKeyword._async) || match2(TokenType.at);
}
function parseExportSpecifiers() {
  let first = true;
  expect(TokenType.braceL);
  while (!eat(TokenType.braceR) && !state.error) {
    if (first) {
      first = false;
    } else {
      expect(TokenType.comma);
      if (eat(TokenType.braceR)) {
        break;
      }
    }
    parseExportSpecifier();
  }
}
function parseExportSpecifier() {
  if (isTypeScriptEnabled) {
    tsParseExportSpecifier();
    return;
  }
  parseIdentifier();
  state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.ExportAccess;
  if (eatContextual(ContextualKeyword._as)) {
    parseIdentifier();
  }
}
function isImportReflection() {
  const snapshot = state.snapshot();
  expectContextual(ContextualKeyword._module);
  if (eatContextual(ContextualKeyword._from)) {
    if (isContextual(ContextualKeyword._from)) {
      state.restoreFromSnapshot(snapshot);
      return true;
    } else {
      state.restoreFromSnapshot(snapshot);
      return false;
    }
  } else if (match2(TokenType.comma)) {
    state.restoreFromSnapshot(snapshot);
    return false;
  } else {
    state.restoreFromSnapshot(snapshot);
    return true;
  }
}
function parseMaybeImportReflection() {
  if (isContextual(ContextualKeyword._module) && isImportReflection()) {
    next();
  }
}
function parseImport() {
  if (isTypeScriptEnabled && match2(TokenType.name) && lookaheadType() === TokenType.eq) {
    tsParseImportEqualsDeclaration();
    return;
  }
  if (isTypeScriptEnabled && isContextual(ContextualKeyword._type)) {
    const lookahead = lookaheadTypeAndKeyword();
    if (lookahead.type === TokenType.name && lookahead.contextualKeyword !== ContextualKeyword._from) {
      expectContextual(ContextualKeyword._type);
      if (lookaheadType() === TokenType.eq) {
        tsParseImportEqualsDeclaration();
        return;
      }
    } else if (lookahead.type === TokenType.star || lookahead.type === TokenType.braceL) {
      expectContextual(ContextualKeyword._type);
    }
  }
  if (match2(TokenType.string)) {
    parseExprAtom();
  } else {
    parseMaybeImportReflection();
    parseImportSpecifiers();
    expectContextual(ContextualKeyword._from);
    parseExprAtom();
  }
  maybeParseImportAttributes();
  semicolon();
}
function shouldParseDefaultImport() {
  return match2(TokenType.name);
}
function parseImportSpecifierLocal() {
  parseImportedIdentifier();
}
function parseImportSpecifiers() {
  if (isFlowEnabled) {
    flowStartParseImportSpecifiers();
  }
  let first = true;
  if (shouldParseDefaultImport()) {
    parseImportSpecifierLocal();
    if (!eat(TokenType.comma))
      return;
  }
  if (match2(TokenType.star)) {
    next();
    expectContextual(ContextualKeyword._as);
    parseImportSpecifierLocal();
    return;
  }
  expect(TokenType.braceL);
  while (!eat(TokenType.braceR) && !state.error) {
    if (first) {
      first = false;
    } else {
      if (eat(TokenType.colon)) {
        unexpected(
          "ES2015 named imports do not destructure. Use another statement for destructuring after the import."
        );
      }
      expect(TokenType.comma);
      if (eat(TokenType.braceR)) {
        break;
      }
    }
    parseImportSpecifier();
  }
}
function parseImportSpecifier() {
  if (isTypeScriptEnabled) {
    tsParseImportSpecifier();
    return;
  }
  if (isFlowEnabled) {
    flowParseImportSpecifier();
    return;
  }
  parseImportedIdentifier();
  if (isContextual(ContextualKeyword._as)) {
    state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.ImportAccess;
    next();
    parseImportedIdentifier();
  }
}
function maybeParseImportAttributes() {
  if (match2(TokenType._with) || isContextual(ContextualKeyword._assert) && !hasPrecedingLineBreak()) {
    next();
    parseObj(false, false);
  }
}

// node_modules/sucrase/dist/esm/parser/traverser/index.js
function parseFile() {
  if (state.pos === 0 && input.charCodeAt(0) === charCodes.numberSign && input.charCodeAt(1) === charCodes.exclamationMark) {
    skipLineComment(2);
  }
  nextToken();
  return parseTopLevel();
}

// node_modules/sucrase/dist/esm/parser/index.js
var File = class {
  constructor(tokens, scopes) {
    this.tokens = tokens;
    this.scopes = scopes;
  }
};
function parse2(input2, isJSXEnabled2, isTypeScriptEnabled2, isFlowEnabled2) {
  if (isFlowEnabled2 && isTypeScriptEnabled2) {
    throw new Error("Cannot combine flow and typescript plugins.");
  }
  initParser(input2, isJSXEnabled2, isTypeScriptEnabled2, isFlowEnabled2);
  const result = parseFile();
  if (state.error) {
    throw augmentError(state.error);
  }
  return result;
}

// node_modules/sucrase/dist/esm/util/isAsyncOperation.js
function isAsyncOperation(tokens) {
  let index = tokens.currentIndex();
  let depth = 0;
  const startToken = tokens.currentToken();
  do {
    const token = tokens.tokens[index];
    if (token.isOptionalChainStart) {
      depth++;
    }
    if (token.isOptionalChainEnd) {
      depth--;
    }
    depth += token.numNullishCoalesceStarts;
    depth -= token.numNullishCoalesceEnds;
    if (token.contextualKeyword === ContextualKeyword._await && token.identifierRole == null && token.scopeDepth === startToken.scopeDepth) {
      return true;
    }
    index += 1;
  } while (depth > 0 && index < tokens.tokens.length);
  return false;
}

// node_modules/sucrase/dist/esm/TokenProcessor.js
var TokenProcessor = class {
  __init() {
    this.resultCode = "";
  }
  // Array mapping input token index to optional string index position in the
  // output code.
  __init2() {
    this.resultMappings = new Array(this.tokens.length);
  }
  __init3() {
    this.tokenIndex = 0;
  }
  constructor(code, tokens, isFlowEnabled2, disableESTransforms, helperManager) {
    ;
    this.code = code;
    this.tokens = tokens;
    this.isFlowEnabled = isFlowEnabled2;
    this.disableESTransforms = disableESTransforms;
    this.helperManager = helperManager;
    TokenProcessor.prototype.__init.call(this);
    TokenProcessor.prototype.__init2.call(this);
    TokenProcessor.prototype.__init3.call(this);
  }
  /**
   * Snapshot the token state in a way that can be restored later, useful for
   * things like lookahead.
   *
   * resultMappings do not need to be copied since in all use cases, they will
   * be overwritten anyway after restore.
   */
  snapshot() {
    return {
      resultCode: this.resultCode,
      tokenIndex: this.tokenIndex
    };
  }
  restoreToSnapshot(snapshot) {
    this.resultCode = snapshot.resultCode;
    this.tokenIndex = snapshot.tokenIndex;
  }
  /**
   * Remove and return the code generated since the snapshot, leaving the
   * current token position in-place. Unlike most TokenProcessor operations,
   * this operation can result in input/output line number mismatches because
   * the removed code may contain newlines, so this operation should be used
   * sparingly.
   */
  dangerouslyGetAndRemoveCodeSinceSnapshot(snapshot) {
    const result = this.resultCode.slice(snapshot.resultCode.length);
    this.resultCode = snapshot.resultCode;
    return result;
  }
  reset() {
    this.resultCode = "";
    this.resultMappings = new Array(this.tokens.length);
    this.tokenIndex = 0;
  }
  matchesContextualAtIndex(index, contextualKeyword) {
    return this.matches1AtIndex(index, TokenType.name) && this.tokens[index].contextualKeyword === contextualKeyword;
  }
  identifierNameAtIndex(index) {
    return this.identifierNameForToken(this.tokens[index]);
  }
  identifierNameAtRelativeIndex(relativeIndex) {
    return this.identifierNameForToken(this.tokenAtRelativeIndex(relativeIndex));
  }
  identifierName() {
    return this.identifierNameForToken(this.currentToken());
  }
  identifierNameForToken(token) {
    return this.code.slice(token.start, token.end);
  }
  rawCodeForToken(token) {
    return this.code.slice(token.start, token.end);
  }
  stringValueAtIndex(index) {
    return this.stringValueForToken(this.tokens[index]);
  }
  stringValue() {
    return this.stringValueForToken(this.currentToken());
  }
  stringValueForToken(token) {
    return this.code.slice(token.start + 1, token.end - 1);
  }
  matches1AtIndex(index, t1) {
    return this.tokens[index].type === t1;
  }
  matches2AtIndex(index, t1, t22) {
    return this.tokens[index].type === t1 && this.tokens[index + 1].type === t22;
  }
  matches3AtIndex(index, t1, t22, t32) {
    return this.tokens[index].type === t1 && this.tokens[index + 1].type === t22 && this.tokens[index + 2].type === t32;
  }
  matches1(t1) {
    return this.tokens[this.tokenIndex].type === t1;
  }
  matches2(t1, t22) {
    return this.tokens[this.tokenIndex].type === t1 && this.tokens[this.tokenIndex + 1].type === t22;
  }
  matches3(t1, t22, t32) {
    return this.tokens[this.tokenIndex].type === t1 && this.tokens[this.tokenIndex + 1].type === t22 && this.tokens[this.tokenIndex + 2].type === t32;
  }
  matches4(t1, t22, t32, t4) {
    return this.tokens[this.tokenIndex].type === t1 && this.tokens[this.tokenIndex + 1].type === t22 && this.tokens[this.tokenIndex + 2].type === t32 && this.tokens[this.tokenIndex + 3].type === t4;
  }
  matches5(t1, t22, t32, t4, t5) {
    return this.tokens[this.tokenIndex].type === t1 && this.tokens[this.tokenIndex + 1].type === t22 && this.tokens[this.tokenIndex + 2].type === t32 && this.tokens[this.tokenIndex + 3].type === t4 && this.tokens[this.tokenIndex + 4].type === t5;
  }
  matchesContextual(contextualKeyword) {
    return this.matchesContextualAtIndex(this.tokenIndex, contextualKeyword);
  }
  matchesContextIdAndLabel(type, contextId) {
    return this.matches1(type) && this.currentToken().contextId === contextId;
  }
  previousWhitespaceAndComments() {
    let whitespaceAndComments = this.code.slice(
      this.tokenIndex > 0 ? this.tokens[this.tokenIndex - 1].end : 0,
      this.tokenIndex < this.tokens.length ? this.tokens[this.tokenIndex].start : this.code.length
    );
    if (this.isFlowEnabled) {
      whitespaceAndComments = whitespaceAndComments.replace(/@flow/g, "");
    }
    return whitespaceAndComments;
  }
  replaceToken(newCode) {
    this.resultCode += this.previousWhitespaceAndComments();
    this.appendTokenPrefix();
    this.resultMappings[this.tokenIndex] = this.resultCode.length;
    this.resultCode += newCode;
    this.appendTokenSuffix();
    this.tokenIndex++;
  }
  replaceTokenTrimmingLeftWhitespace(newCode) {
    this.resultCode += this.previousWhitespaceAndComments().replace(/[^\r\n]/g, "");
    this.appendTokenPrefix();
    this.resultMappings[this.tokenIndex] = this.resultCode.length;
    this.resultCode += newCode;
    this.appendTokenSuffix();
    this.tokenIndex++;
  }
  removeInitialToken() {
    this.replaceToken("");
  }
  removeToken() {
    this.replaceTokenTrimmingLeftWhitespace("");
  }
  /**
   * Remove all code until the next }, accounting for balanced braces.
   */
  removeBalancedCode() {
    let braceDepth = 0;
    while (!this.isAtEnd()) {
      if (this.matches1(TokenType.braceL)) {
        braceDepth++;
      } else if (this.matches1(TokenType.braceR)) {
        if (braceDepth === 0) {
          return;
        }
        braceDepth--;
      }
      this.removeToken();
    }
  }
  copyExpectedToken(tokenType) {
    if (this.tokens[this.tokenIndex].type !== tokenType) {
      throw new Error(`Expected token ${tokenType}`);
    }
    this.copyToken();
  }
  copyToken() {
    this.resultCode += this.previousWhitespaceAndComments();
    this.appendTokenPrefix();
    this.resultMappings[this.tokenIndex] = this.resultCode.length;
    this.resultCode += this.code.slice(
      this.tokens[this.tokenIndex].start,
      this.tokens[this.tokenIndex].end
    );
    this.appendTokenSuffix();
    this.tokenIndex++;
  }
  copyTokenWithPrefix(prefix) {
    this.resultCode += this.previousWhitespaceAndComments();
    this.appendTokenPrefix();
    this.resultCode += prefix;
    this.resultMappings[this.tokenIndex] = this.resultCode.length;
    this.resultCode += this.code.slice(
      this.tokens[this.tokenIndex].start,
      this.tokens[this.tokenIndex].end
    );
    this.appendTokenSuffix();
    this.tokenIndex++;
  }
  appendTokenPrefix() {
    const token = this.currentToken();
    if (token.numNullishCoalesceStarts || token.isOptionalChainStart) {
      token.isAsyncOperation = isAsyncOperation(this);
    }
    if (this.disableESTransforms) {
      return;
    }
    if (token.numNullishCoalesceStarts) {
      for (let i4 = 0; i4 < token.numNullishCoalesceStarts; i4++) {
        if (token.isAsyncOperation) {
          this.resultCode += "await ";
          this.resultCode += this.helperManager.getHelperName("asyncNullishCoalesce");
        } else {
          this.resultCode += this.helperManager.getHelperName("nullishCoalesce");
        }
        this.resultCode += "(";
      }
    }
    if (token.isOptionalChainStart) {
      if (token.isAsyncOperation) {
        this.resultCode += "await ";
      }
      if (this.tokenIndex > 0 && this.tokenAtRelativeIndex(-1).type === TokenType._delete) {
        if (token.isAsyncOperation) {
          this.resultCode += this.helperManager.getHelperName("asyncOptionalChainDelete");
        } else {
          this.resultCode += this.helperManager.getHelperName("optionalChainDelete");
        }
      } else if (token.isAsyncOperation) {
        this.resultCode += this.helperManager.getHelperName("asyncOptionalChain");
      } else {
        this.resultCode += this.helperManager.getHelperName("optionalChain");
      }
      this.resultCode += "([";
    }
  }
  appendTokenSuffix() {
    const token = this.currentToken();
    if (token.isOptionalChainEnd && !this.disableESTransforms) {
      this.resultCode += "])";
    }
    if (token.numNullishCoalesceEnds && !this.disableESTransforms) {
      for (let i4 = 0; i4 < token.numNullishCoalesceEnds; i4++) {
        this.resultCode += "))";
      }
    }
  }
  appendCode(code) {
    this.resultCode += code;
  }
  currentToken() {
    return this.tokens[this.tokenIndex];
  }
  currentTokenCode() {
    const token = this.currentToken();
    return this.code.slice(token.start, token.end);
  }
  tokenAtRelativeIndex(relativeIndex) {
    return this.tokens[this.tokenIndex + relativeIndex];
  }
  currentIndex() {
    return this.tokenIndex;
  }
  /**
   * Move to the next token. Only suitable in preprocessing steps. When
   * generating new code, you should use copyToken or removeToken.
   */
  nextToken() {
    if (this.tokenIndex === this.tokens.length) {
      throw new Error("Unexpectedly reached end of input.");
    }
    this.tokenIndex++;
  }
  previousToken() {
    this.tokenIndex--;
  }
  finish() {
    if (this.tokenIndex !== this.tokens.length) {
      throw new Error("Tried to finish processing tokens before reaching the end.");
    }
    this.resultCode += this.previousWhitespaceAndComments();
    return { code: this.resultCode, mappings: this.resultMappings };
  }
  isAtEnd() {
    return this.tokenIndex === this.tokens.length;
  }
};

// node_modules/sucrase/dist/esm/util/getClassInfo.js
function getClassInfo(rootTransformer, tokens, nameManager, disableESTransforms) {
  const snapshot = tokens.snapshot();
  const headerInfo = processClassHeader(tokens);
  let constructorInitializerStatements = [];
  const instanceInitializerNames = [];
  const staticInitializerNames = [];
  let constructorInsertPos = null;
  const fields = [];
  const rangesToRemove = [];
  const classContextId = tokens.currentToken().contextId;
  if (classContextId == null) {
    throw new Error("Expected non-null class context ID on class open-brace.");
  }
  tokens.nextToken();
  while (!tokens.matchesContextIdAndLabel(TokenType.braceR, classContextId)) {
    if (tokens.matchesContextual(ContextualKeyword._constructor) && !tokens.currentToken().isType) {
      ({ constructorInitializerStatements, constructorInsertPos } = processConstructor(tokens));
    } else if (tokens.matches1(TokenType.semi)) {
      if (!disableESTransforms) {
        rangesToRemove.push({ start: tokens.currentIndex(), end: tokens.currentIndex() + 1 });
      }
      tokens.nextToken();
    } else if (tokens.currentToken().isType) {
      tokens.nextToken();
    } else {
      const statementStartIndex = tokens.currentIndex();
      let isStatic = false;
      let isESPrivate = false;
      let isDeclareOrAbstract = false;
      while (isAccessModifier(tokens.currentToken())) {
        if (tokens.matches1(TokenType._static)) {
          isStatic = true;
        }
        if (tokens.matches1(TokenType.hash)) {
          isESPrivate = true;
        }
        if (tokens.matches1(TokenType._declare) || tokens.matches1(TokenType._abstract)) {
          isDeclareOrAbstract = true;
        }
        tokens.nextToken();
      }
      if (isStatic && tokens.matches1(TokenType.braceL)) {
        skipToNextClassElement(tokens, classContextId);
        continue;
      }
      if (isESPrivate) {
        skipToNextClassElement(tokens, classContextId);
        continue;
      }
      if (tokens.matchesContextual(ContextualKeyword._constructor) && !tokens.currentToken().isType) {
        ({ constructorInitializerStatements, constructorInsertPos } = processConstructor(tokens));
        continue;
      }
      const nameStartIndex = tokens.currentIndex();
      skipFieldName(tokens);
      if (tokens.matches1(TokenType.lessThan) || tokens.matches1(TokenType.parenL)) {
        skipToNextClassElement(tokens, classContextId);
        continue;
      }
      while (tokens.currentToken().isType) {
        tokens.nextToken();
      }
      if (tokens.matches1(TokenType.eq)) {
        const equalsIndex = tokens.currentIndex();
        const valueEnd = tokens.currentToken().rhsEndIndex;
        if (valueEnd == null) {
          throw new Error("Expected rhsEndIndex on class field assignment.");
        }
        tokens.nextToken();
        while (tokens.currentIndex() < valueEnd) {
          rootTransformer.processToken();
        }
        let initializerName;
        if (isStatic) {
          initializerName = nameManager.claimFreeName("__initStatic");
          staticInitializerNames.push(initializerName);
        } else {
          initializerName = nameManager.claimFreeName("__init");
          instanceInitializerNames.push(initializerName);
        }
        fields.push({
          initializerName,
          equalsIndex,
          start: nameStartIndex,
          end: tokens.currentIndex()
        });
      } else if (!disableESTransforms || isDeclareOrAbstract) {
        rangesToRemove.push({ start: statementStartIndex, end: tokens.currentIndex() });
      }
    }
  }
  tokens.restoreToSnapshot(snapshot);
  if (disableESTransforms) {
    return {
      headerInfo,
      constructorInitializerStatements,
      instanceInitializerNames: [],
      staticInitializerNames: [],
      constructorInsertPos,
      fields: [],
      rangesToRemove
    };
  } else {
    return {
      headerInfo,
      constructorInitializerStatements,
      instanceInitializerNames,
      staticInitializerNames,
      constructorInsertPos,
      fields,
      rangesToRemove
    };
  }
}
function skipToNextClassElement(tokens, classContextId) {
  tokens.nextToken();
  while (tokens.currentToken().contextId !== classContextId) {
    tokens.nextToken();
  }
  while (isAccessModifier(tokens.tokenAtRelativeIndex(-1))) {
    tokens.previousToken();
  }
}
function processClassHeader(tokens) {
  const classToken = tokens.currentToken();
  const contextId = classToken.contextId;
  if (contextId == null) {
    throw new Error("Expected context ID on class token.");
  }
  const isExpression = classToken.isExpression;
  if (isExpression == null) {
    throw new Error("Expected isExpression on class token.");
  }
  let className = null;
  let hasSuperclass = false;
  tokens.nextToken();
  if (tokens.matches1(TokenType.name)) {
    className = tokens.identifierName();
  }
  while (!tokens.matchesContextIdAndLabel(TokenType.braceL, contextId)) {
    if (tokens.matches1(TokenType._extends) && !tokens.currentToken().isType) {
      hasSuperclass = true;
    }
    tokens.nextToken();
  }
  return { isExpression, className, hasSuperclass };
}
function processConstructor(tokens) {
  const constructorInitializerStatements = [];
  tokens.nextToken();
  const constructorContextId = tokens.currentToken().contextId;
  if (constructorContextId == null) {
    throw new Error("Expected context ID on open-paren starting constructor params.");
  }
  while (!tokens.matchesContextIdAndLabel(TokenType.parenR, constructorContextId)) {
    if (tokens.currentToken().contextId === constructorContextId) {
      tokens.nextToken();
      if (isAccessModifier(tokens.currentToken())) {
        tokens.nextToken();
        while (isAccessModifier(tokens.currentToken())) {
          tokens.nextToken();
        }
        const token = tokens.currentToken();
        if (token.type !== TokenType.name) {
          throw new Error("Expected identifier after access modifiers in constructor arg.");
        }
        const name = tokens.identifierNameForToken(token);
        constructorInitializerStatements.push(`this.${name} = ${name}`);
      }
    } else {
      tokens.nextToken();
    }
  }
  tokens.nextToken();
  while (tokens.currentToken().isType) {
    tokens.nextToken();
  }
  let constructorInsertPos = tokens.currentIndex();
  let foundSuperCall = false;
  while (!tokens.matchesContextIdAndLabel(TokenType.braceR, constructorContextId)) {
    if (!foundSuperCall && tokens.matches2(TokenType._super, TokenType.parenL)) {
      tokens.nextToken();
      const superCallContextId = tokens.currentToken().contextId;
      if (superCallContextId == null) {
        throw new Error("Expected a context ID on the super call");
      }
      while (!tokens.matchesContextIdAndLabel(TokenType.parenR, superCallContextId)) {
        tokens.nextToken();
      }
      constructorInsertPos = tokens.currentIndex();
      foundSuperCall = true;
    }
    tokens.nextToken();
  }
  tokens.nextToken();
  return { constructorInitializerStatements, constructorInsertPos };
}
function isAccessModifier(token) {
  return [
    TokenType._async,
    TokenType._get,
    TokenType._set,
    TokenType.plus,
    TokenType.minus,
    TokenType._readonly,
    TokenType._static,
    TokenType._public,
    TokenType._private,
    TokenType._protected,
    TokenType._override,
    TokenType._abstract,
    TokenType.star,
    TokenType._declare,
    TokenType.hash
  ].includes(token.type);
}
function skipFieldName(tokens) {
  if (tokens.matches1(TokenType.bracketL)) {
    const startToken = tokens.currentToken();
    const classContextId = startToken.contextId;
    if (classContextId == null) {
      throw new Error("Expected class context ID on computed name open bracket.");
    }
    while (!tokens.matchesContextIdAndLabel(TokenType.bracketR, classContextId)) {
      tokens.nextToken();
    }
    tokens.nextToken();
  } else {
    tokens.nextToken();
  }
}

// node_modules/sucrase/dist/esm/util/elideImportEquals.js
function elideImportEquals(tokens) {
  tokens.removeInitialToken();
  tokens.removeToken();
  tokens.removeToken();
  tokens.removeToken();
  if (tokens.matches1(TokenType.parenL)) {
    tokens.removeToken();
    tokens.removeToken();
    tokens.removeToken();
  } else {
    while (tokens.matches1(TokenType.dot)) {
      tokens.removeToken();
      tokens.removeToken();
    }
  }
}

// node_modules/sucrase/dist/esm/util/getDeclarationInfo.js
var EMPTY_DECLARATION_INFO = {
  typeDeclarations: /* @__PURE__ */ new Set(),
  valueDeclarations: /* @__PURE__ */ new Set()
};
function getDeclarationInfo(tokens) {
  const typeDeclarations = /* @__PURE__ */ new Set();
  const valueDeclarations = /* @__PURE__ */ new Set();
  for (let i4 = 0; i4 < tokens.tokens.length; i4++) {
    const token = tokens.tokens[i4];
    if (token.type === TokenType.name && isTopLevelDeclaration(token)) {
      if (token.isType) {
        typeDeclarations.add(tokens.identifierNameForToken(token));
      } else {
        valueDeclarations.add(tokens.identifierNameForToken(token));
      }
    }
  }
  return { typeDeclarations, valueDeclarations };
}

// node_modules/sucrase/dist/esm/util/isExportFrom.js
function isExportFrom(tokens) {
  let closeBraceIndex = tokens.currentIndex();
  while (!tokens.matches1AtIndex(closeBraceIndex, TokenType.braceR)) {
    closeBraceIndex++;
  }
  return tokens.matchesContextualAtIndex(closeBraceIndex + 1, ContextualKeyword._from) && tokens.matches1AtIndex(closeBraceIndex + 2, TokenType.string);
}

// node_modules/sucrase/dist/esm/util/removeMaybeImportAttributes.js
function removeMaybeImportAttributes(tokens) {
  if (tokens.matches2(TokenType._with, TokenType.braceL) || tokens.matches2(TokenType.name, TokenType.braceL) && tokens.matchesContextual(ContextualKeyword._assert)) {
    tokens.removeToken();
    tokens.removeToken();
    tokens.removeBalancedCode();
    tokens.removeToken();
  }
}

// node_modules/sucrase/dist/esm/util/shouldElideDefaultExport.js
function shouldElideDefaultExport(isTypeScriptTransformEnabled, keepUnusedImports, tokens, declarationInfo) {
  if (!isTypeScriptTransformEnabled || keepUnusedImports) {
    return false;
  }
  const exportToken = tokens.currentToken();
  if (exportToken.rhsEndIndex == null) {
    throw new Error("Expected non-null rhsEndIndex on export token.");
  }
  const numTokens = exportToken.rhsEndIndex - tokens.currentIndex();
  if (numTokens !== 3 && !(numTokens === 4 && tokens.matches1AtIndex(exportToken.rhsEndIndex - 1, TokenType.semi))) {
    return false;
  }
  const identifierToken = tokens.tokenAtRelativeIndex(2);
  if (identifierToken.type !== TokenType.name) {
    return false;
  }
  const exportedName = tokens.identifierNameForToken(identifierToken);
  return declarationInfo.typeDeclarations.has(exportedName) && !declarationInfo.valueDeclarations.has(exportedName);
}

// node_modules/sucrase/dist/esm/transformers/CJSImportTransformer.js
var CJSImportTransformer = class extends Transformer {
  __init() {
    this.hadExport = false;
  }
  __init2() {
    this.hadNamedExport = false;
  }
  __init3() {
    this.hadDefaultExport = false;
  }
  constructor(rootTransformer, tokens, importProcessor, nameManager, helperManager, reactHotLoaderTransformer, enableLegacyBabel5ModuleInterop, enableLegacyTypeScriptModuleInterop, isTypeScriptTransformEnabled, isFlowTransformEnabled, preserveDynamicImport, keepUnusedImports) {
    super();
    this.rootTransformer = rootTransformer;
    this.tokens = tokens;
    this.importProcessor = importProcessor;
    this.nameManager = nameManager;
    this.helperManager = helperManager;
    this.reactHotLoaderTransformer = reactHotLoaderTransformer;
    this.enableLegacyBabel5ModuleInterop = enableLegacyBabel5ModuleInterop;
    this.enableLegacyTypeScriptModuleInterop = enableLegacyTypeScriptModuleInterop;
    this.isTypeScriptTransformEnabled = isTypeScriptTransformEnabled;
    this.isFlowTransformEnabled = isFlowTransformEnabled;
    this.preserveDynamicImport = preserveDynamicImport;
    this.keepUnusedImports = keepUnusedImports;
    CJSImportTransformer.prototype.__init.call(this);
    CJSImportTransformer.prototype.__init2.call(this);
    CJSImportTransformer.prototype.__init3.call(this);
    ;
    this.declarationInfo = isTypeScriptTransformEnabled ? getDeclarationInfo(tokens) : EMPTY_DECLARATION_INFO;
  }
  getPrefixCode() {
    let prefix = "";
    if (this.hadExport) {
      prefix += 'Object.defineProperty(exports, "__esModule", {value: true});';
    }
    return prefix;
  }
  getSuffixCode() {
    if (this.enableLegacyBabel5ModuleInterop && this.hadDefaultExport && !this.hadNamedExport) {
      return "\nmodule.exports = exports.default;\n";
    }
    return "";
  }
  process() {
    if (this.tokens.matches3(TokenType._import, TokenType.name, TokenType.eq)) {
      return this.processImportEquals();
    }
    if (this.tokens.matches1(TokenType._import)) {
      this.processImport();
      return true;
    }
    if (this.tokens.matches2(TokenType._export, TokenType.eq)) {
      this.tokens.replaceToken("module.exports");
      return true;
    }
    if (this.tokens.matches1(TokenType._export) && !this.tokens.currentToken().isType) {
      this.hadExport = true;
      return this.processExport();
    }
    if (this.tokens.matches2(TokenType.name, TokenType.postIncDec)) {
      if (this.processPostIncDec()) {
        return true;
      }
    }
    if (this.tokens.matches1(TokenType.name) || this.tokens.matches1(TokenType.jsxName)) {
      return this.processIdentifier();
    }
    if (this.tokens.matches1(TokenType.eq)) {
      return this.processAssignment();
    }
    if (this.tokens.matches1(TokenType.assign)) {
      return this.processComplexAssignment();
    }
    if (this.tokens.matches1(TokenType.preIncDec)) {
      return this.processPreIncDec();
    }
    return false;
  }
  processImportEquals() {
    const importName = this.tokens.identifierNameAtIndex(this.tokens.currentIndex() + 1);
    if (this.importProcessor.shouldAutomaticallyElideImportedName(importName)) {
      elideImportEquals(this.tokens);
    } else {
      this.tokens.replaceToken("const");
    }
    return true;
  }
  /**
   * Transform this:
   * import foo, {bar} from 'baz';
   * into
   * var _baz = require('baz'); var _baz2 = _interopRequireDefault(_baz);
   *
   * The import code was already generated in the import preprocessing step, so
   * we just need to look it up.
   */
  processImport() {
    if (this.tokens.matches2(TokenType._import, TokenType.parenL)) {
      if (this.preserveDynamicImport) {
        this.tokens.copyToken();
        return;
      }
      const requireWrapper = this.enableLegacyTypeScriptModuleInterop ? "" : `${this.helperManager.getHelperName("interopRequireWildcard")}(`;
      this.tokens.replaceToken(`Promise.resolve().then(() => ${requireWrapper}require`);
      const contextId = this.tokens.currentToken().contextId;
      if (contextId == null) {
        throw new Error("Expected context ID on dynamic import invocation.");
      }
      this.tokens.copyToken();
      while (!this.tokens.matchesContextIdAndLabel(TokenType.parenR, contextId)) {
        this.rootTransformer.processToken();
      }
      this.tokens.replaceToken(requireWrapper ? ")))" : "))");
      return;
    }
    const shouldElideImport = this.removeImportAndDetectIfShouldElide();
    if (shouldElideImport) {
      this.tokens.removeToken();
    } else {
      const path = this.tokens.stringValue();
      this.tokens.replaceTokenTrimmingLeftWhitespace(this.importProcessor.claimImportCode(path));
      this.tokens.appendCode(this.importProcessor.claimImportCode(path));
    }
    removeMaybeImportAttributes(this.tokens);
    if (this.tokens.matches1(TokenType.semi)) {
      this.tokens.removeToken();
    }
  }
  /**
   * Erase this import (since any CJS output would be completely different), and
   * return true if this import is should be elided due to being a type-only
   * import. Such imports will not be emitted at all to avoid side effects.
   *
   * Import elision only happens with the TypeScript or Flow transforms enabled.
   *
   * TODO: This function has some awkward overlap with
   *  CJSImportProcessor.pruneTypeOnlyImports , and the two should be unified.
   *  That function handles TypeScript implicit import name elision, and removes
   *  an import if all typical imported names (without `type`) are removed due
   *  to being type-only imports. This function handles Flow import removal and
   *  properly distinguishes `import 'foo'` from `import {} from 'foo'` for TS
   *  purposes.
   *
   * The position should end at the import string.
   */
  removeImportAndDetectIfShouldElide() {
    this.tokens.removeInitialToken();
    if (this.tokens.matchesContextual(ContextualKeyword._type) && !this.tokens.matches1AtIndex(this.tokens.currentIndex() + 1, TokenType.comma) && !this.tokens.matchesContextualAtIndex(this.tokens.currentIndex() + 1, ContextualKeyword._from)) {
      this.removeRemainingImport();
      return true;
    }
    if (this.tokens.matches1(TokenType.name) || this.tokens.matches1(TokenType.star)) {
      this.removeRemainingImport();
      return false;
    }
    if (this.tokens.matches1(TokenType.string)) {
      return false;
    }
    let foundNonTypeImport = false;
    let foundAnyNamedImport = false;
    while (!this.tokens.matches1(TokenType.string)) {
      if (!foundNonTypeImport && this.tokens.matches1(TokenType.braceL) || this.tokens.matches1(TokenType.comma)) {
        this.tokens.removeToken();
        if (!this.tokens.matches1(TokenType.braceR)) {
          foundAnyNamedImport = true;
        }
        if (this.tokens.matches2(TokenType.name, TokenType.comma) || this.tokens.matches2(TokenType.name, TokenType.braceR) || this.tokens.matches4(TokenType.name, TokenType.name, TokenType.name, TokenType.comma) || this.tokens.matches4(TokenType.name, TokenType.name, TokenType.name, TokenType.braceR)) {
          foundNonTypeImport = true;
        }
      }
      this.tokens.removeToken();
    }
    if (this.keepUnusedImports) {
      return false;
    }
    if (this.isTypeScriptTransformEnabled) {
      return !foundNonTypeImport;
    } else if (this.isFlowTransformEnabled) {
      return foundAnyNamedImport && !foundNonTypeImport;
    } else {
      return false;
    }
  }
  removeRemainingImport() {
    while (!this.tokens.matches1(TokenType.string)) {
      this.tokens.removeToken();
    }
  }
  processIdentifier() {
    const token = this.tokens.currentToken();
    if (token.shadowsGlobal) {
      return false;
    }
    if (token.identifierRole === IdentifierRole.ObjectShorthand) {
      return this.processObjectShorthand();
    }
    if (token.identifierRole !== IdentifierRole.Access) {
      return false;
    }
    const replacement = this.importProcessor.getIdentifierReplacement(
      this.tokens.identifierNameForToken(token)
    );
    if (!replacement) {
      return false;
    }
    let possibleOpenParenIndex = this.tokens.currentIndex() + 1;
    while (possibleOpenParenIndex < this.tokens.tokens.length && this.tokens.tokens[possibleOpenParenIndex].type === TokenType.parenR) {
      possibleOpenParenIndex++;
    }
    if (this.tokens.tokens[possibleOpenParenIndex].type === TokenType.parenL) {
      if (this.tokens.tokenAtRelativeIndex(1).type === TokenType.parenL && this.tokens.tokenAtRelativeIndex(-1).type !== TokenType._new) {
        this.tokens.replaceToken(`${replacement}.call(void 0, `);
        this.tokens.removeToken();
        this.rootTransformer.processBalancedCode();
        this.tokens.copyExpectedToken(TokenType.parenR);
      } else {
        this.tokens.replaceToken(`(0, ${replacement})`);
      }
    } else {
      this.tokens.replaceToken(replacement);
    }
    return true;
  }
  processObjectShorthand() {
    const identifier = this.tokens.identifierName();
    const replacement = this.importProcessor.getIdentifierReplacement(identifier);
    if (!replacement) {
      return false;
    }
    this.tokens.replaceToken(`${identifier}: ${replacement}`);
    return true;
  }
  processExport() {
    if (this.tokens.matches2(TokenType._export, TokenType._enum) || this.tokens.matches3(TokenType._export, TokenType._const, TokenType._enum)) {
      this.hadNamedExport = true;
      return false;
    }
    if (this.tokens.matches2(TokenType._export, TokenType._default)) {
      if (this.tokens.matches3(TokenType._export, TokenType._default, TokenType._enum)) {
        this.hadDefaultExport = true;
        return false;
      }
      this.processExportDefault();
      return true;
    } else if (this.tokens.matches2(TokenType._export, TokenType.braceL)) {
      this.processExportBindings();
      return true;
    } else if (this.tokens.matches2(TokenType._export, TokenType.name) && this.tokens.matchesContextualAtIndex(this.tokens.currentIndex() + 1, ContextualKeyword._type)) {
      this.tokens.removeInitialToken();
      this.tokens.removeToken();
      if (this.tokens.matches1(TokenType.braceL)) {
        while (!this.tokens.matches1(TokenType.braceR)) {
          this.tokens.removeToken();
        }
        this.tokens.removeToken();
      } else {
        this.tokens.removeToken();
        if (this.tokens.matches1(TokenType._as)) {
          this.tokens.removeToken();
          this.tokens.removeToken();
        }
      }
      if (this.tokens.matchesContextual(ContextualKeyword._from) && this.tokens.matches1AtIndex(this.tokens.currentIndex() + 1, TokenType.string)) {
        this.tokens.removeToken();
        this.tokens.removeToken();
        removeMaybeImportAttributes(this.tokens);
      }
      return true;
    }
    this.hadNamedExport = true;
    if (this.tokens.matches2(TokenType._export, TokenType._var) || this.tokens.matches2(TokenType._export, TokenType._let) || this.tokens.matches2(TokenType._export, TokenType._const)) {
      this.processExportVar();
      return true;
    } else if (this.tokens.matches2(TokenType._export, TokenType._function) || // export async function
    this.tokens.matches3(TokenType._export, TokenType.name, TokenType._function)) {
      this.processExportFunction();
      return true;
    } else if (this.tokens.matches2(TokenType._export, TokenType._class) || this.tokens.matches3(TokenType._export, TokenType._abstract, TokenType._class) || this.tokens.matches2(TokenType._export, TokenType.at)) {
      this.processExportClass();
      return true;
    } else if (this.tokens.matches2(TokenType._export, TokenType.star)) {
      this.processExportStar();
      return true;
    } else {
      throw new Error("Unrecognized export syntax.");
    }
  }
  processAssignment() {
    const index = this.tokens.currentIndex();
    const identifierToken = this.tokens.tokens[index - 1];
    if (identifierToken.isType || identifierToken.type !== TokenType.name) {
      return false;
    }
    if (identifierToken.shadowsGlobal) {
      return false;
    }
    if (index >= 2 && this.tokens.matches1AtIndex(index - 2, TokenType.dot)) {
      return false;
    }
    if (index >= 2 && [TokenType._var, TokenType._let, TokenType._const].includes(this.tokens.tokens[index - 2].type)) {
      return false;
    }
    const assignmentSnippet = this.importProcessor.resolveExportBinding(
      this.tokens.identifierNameForToken(identifierToken)
    );
    if (!assignmentSnippet) {
      return false;
    }
    this.tokens.copyToken();
    this.tokens.appendCode(` ${assignmentSnippet} =`);
    return true;
  }
  /**
   * Process something like `a += 3`, where `a` might be an exported value.
   */
  processComplexAssignment() {
    const index = this.tokens.currentIndex();
    const identifierToken = this.tokens.tokens[index - 1];
    if (identifierToken.type !== TokenType.name) {
      return false;
    }
    if (identifierToken.shadowsGlobal) {
      return false;
    }
    if (index >= 2 && this.tokens.matches1AtIndex(index - 2, TokenType.dot)) {
      return false;
    }
    const assignmentSnippet = this.importProcessor.resolveExportBinding(
      this.tokens.identifierNameForToken(identifierToken)
    );
    if (!assignmentSnippet) {
      return false;
    }
    this.tokens.appendCode(` = ${assignmentSnippet}`);
    this.tokens.copyToken();
    return true;
  }
  /**
   * Process something like `++a`, where `a` might be an exported value.
   */
  processPreIncDec() {
    const index = this.tokens.currentIndex();
    const identifierToken = this.tokens.tokens[index + 1];
    if (identifierToken.type !== TokenType.name) {
      return false;
    }
    if (identifierToken.shadowsGlobal) {
      return false;
    }
    if (index + 2 < this.tokens.tokens.length && (this.tokens.matches1AtIndex(index + 2, TokenType.dot) || this.tokens.matches1AtIndex(index + 2, TokenType.bracketL) || this.tokens.matches1AtIndex(index + 2, TokenType.parenL))) {
      return false;
    }
    const identifierName = this.tokens.identifierNameForToken(identifierToken);
    const assignmentSnippet = this.importProcessor.resolveExportBinding(identifierName);
    if (!assignmentSnippet) {
      return false;
    }
    this.tokens.appendCode(`${assignmentSnippet} = `);
    this.tokens.copyToken();
    return true;
  }
  /**
   * Process something like `a++`, where `a` might be an exported value.
   * This starts at the `a`, not at the `++`.
   */
  processPostIncDec() {
    const index = this.tokens.currentIndex();
    const identifierToken = this.tokens.tokens[index];
    const operatorToken = this.tokens.tokens[index + 1];
    if (identifierToken.type !== TokenType.name) {
      return false;
    }
    if (identifierToken.shadowsGlobal) {
      return false;
    }
    if (index >= 1 && this.tokens.matches1AtIndex(index - 1, TokenType.dot)) {
      return false;
    }
    const identifierName = this.tokens.identifierNameForToken(identifierToken);
    const assignmentSnippet = this.importProcessor.resolveExportBinding(identifierName);
    if (!assignmentSnippet) {
      return false;
    }
    const operatorCode = this.tokens.rawCodeForToken(operatorToken);
    const base = this.importProcessor.getIdentifierReplacement(identifierName) || identifierName;
    if (operatorCode === "++") {
      this.tokens.replaceToken(`(${base} = ${assignmentSnippet} = ${base} + 1, ${base} - 1)`);
    } else if (operatorCode === "--") {
      this.tokens.replaceToken(`(${base} = ${assignmentSnippet} = ${base} - 1, ${base} + 1)`);
    } else {
      throw new Error(`Unexpected operator: ${operatorCode}`);
    }
    this.tokens.removeToken();
    return true;
  }
  processExportDefault() {
    let exportedRuntimeValue = true;
    if (this.tokens.matches4(TokenType._export, TokenType._default, TokenType._function, TokenType.name) || // export default async function
    this.tokens.matches5(TokenType._export, TokenType._default, TokenType.name, TokenType._function, TokenType.name) && this.tokens.matchesContextualAtIndex(
      this.tokens.currentIndex() + 2,
      ContextualKeyword._async
    )) {
      this.tokens.removeInitialToken();
      this.tokens.removeToken();
      const name = this.processNamedFunction();
      this.tokens.appendCode(` exports.default = ${name};`);
    } else if (this.tokens.matches4(TokenType._export, TokenType._default, TokenType._class, TokenType.name) || this.tokens.matches5(TokenType._export, TokenType._default, TokenType._abstract, TokenType._class, TokenType.name) || this.tokens.matches3(TokenType._export, TokenType._default, TokenType.at)) {
      this.tokens.removeInitialToken();
      this.tokens.removeToken();
      this.copyDecorators();
      if (this.tokens.matches1(TokenType._abstract)) {
        this.tokens.removeToken();
      }
      const name = this.rootTransformer.processNamedClass();
      this.tokens.appendCode(` exports.default = ${name};`);
    } else if (shouldElideDefaultExport(
      this.isTypeScriptTransformEnabled,
      this.keepUnusedImports,
      this.tokens,
      this.declarationInfo
    )) {
      exportedRuntimeValue = false;
      this.tokens.removeInitialToken();
      this.tokens.removeToken();
      this.tokens.removeToken();
    } else if (this.reactHotLoaderTransformer) {
      const defaultVarName = this.nameManager.claimFreeName("_default");
      this.tokens.replaceToken(`let ${defaultVarName}; exports.`);
      this.tokens.copyToken();
      this.tokens.appendCode(` = ${defaultVarName} =`);
      this.reactHotLoaderTransformer.setExtractedDefaultExportName(defaultVarName);
    } else {
      this.tokens.replaceToken("exports.");
      this.tokens.copyToken();
      this.tokens.appendCode(" =");
    }
    if (exportedRuntimeValue) {
      this.hadDefaultExport = true;
    }
  }
  copyDecorators() {
    while (this.tokens.matches1(TokenType.at)) {
      this.tokens.copyToken();
      if (this.tokens.matches1(TokenType.parenL)) {
        this.tokens.copyExpectedToken(TokenType.parenL);
        this.rootTransformer.processBalancedCode();
        this.tokens.copyExpectedToken(TokenType.parenR);
      } else {
        this.tokens.copyExpectedToken(TokenType.name);
        while (this.tokens.matches1(TokenType.dot)) {
          this.tokens.copyExpectedToken(TokenType.dot);
          this.tokens.copyExpectedToken(TokenType.name);
        }
        if (this.tokens.matches1(TokenType.parenL)) {
          this.tokens.copyExpectedToken(TokenType.parenL);
          this.rootTransformer.processBalancedCode();
          this.tokens.copyExpectedToken(TokenType.parenR);
        }
      }
    }
  }
  /**
   * Transform a declaration like `export var`, `export let`, or `export const`.
   */
  processExportVar() {
    if (this.isSimpleExportVar()) {
      this.processSimpleExportVar();
    } else {
      this.processComplexExportVar();
    }
  }
  /**
   * Determine if the export is of the form:
   * export var/let/const [varName] = [expr];
   * In other words, determine if function name inference might apply.
   */
  isSimpleExportVar() {
    let tokenIndex = this.tokens.currentIndex();
    tokenIndex++;
    tokenIndex++;
    if (!this.tokens.matches1AtIndex(tokenIndex, TokenType.name)) {
      return false;
    }
    tokenIndex++;
    while (tokenIndex < this.tokens.tokens.length && this.tokens.tokens[tokenIndex].isType) {
      tokenIndex++;
    }
    if (!this.tokens.matches1AtIndex(tokenIndex, TokenType.eq)) {
      return false;
    }
    return true;
  }
  /**
   * Transform an `export var` declaration initializing a single variable.
   *
   * For example, this:
   * export const f = () => {};
   * becomes this:
   * const f = () => {}; exports.f = f;
   *
   * The variable is unused (e.g. exports.f has the true value of the export).
   * We need to produce an assignment of this form so that the function will
   * have an inferred name of "f", which wouldn't happen in the more general
   * case below.
   */
  processSimpleExportVar() {
    this.tokens.removeInitialToken();
    this.tokens.copyToken();
    const varName = this.tokens.identifierName();
    while (!this.tokens.matches1(TokenType.eq)) {
      this.rootTransformer.processToken();
    }
    const endIndex = this.tokens.currentToken().rhsEndIndex;
    if (endIndex == null) {
      throw new Error("Expected = token with an end index.");
    }
    while (this.tokens.currentIndex() < endIndex) {
      this.rootTransformer.processToken();
    }
    this.tokens.appendCode(`; exports.${varName} = ${varName}`);
  }
  /**
   * Transform normal declaration exports, including handling destructuring.
   * For example, this:
   * export const {x: [a = 2, b], c} = d;
   * becomes this:
   * ({x: [exports.a = 2, exports.b], c: exports.c} = d;)
   */
  processComplexExportVar() {
    this.tokens.removeInitialToken();
    this.tokens.removeToken();
    const needsParens = this.tokens.matches1(TokenType.braceL);
    if (needsParens) {
      this.tokens.appendCode("(");
    }
    let depth = 0;
    while (true) {
      if (this.tokens.matches1(TokenType.braceL) || this.tokens.matches1(TokenType.dollarBraceL) || this.tokens.matches1(TokenType.bracketL)) {
        depth++;
        this.tokens.copyToken();
      } else if (this.tokens.matches1(TokenType.braceR) || this.tokens.matches1(TokenType.bracketR)) {
        depth--;
        this.tokens.copyToken();
      } else if (depth === 0 && !this.tokens.matches1(TokenType.name) && !this.tokens.currentToken().isType) {
        break;
      } else if (this.tokens.matches1(TokenType.eq)) {
        const endIndex = this.tokens.currentToken().rhsEndIndex;
        if (endIndex == null) {
          throw new Error("Expected = token with an end index.");
        }
        while (this.tokens.currentIndex() < endIndex) {
          this.rootTransformer.processToken();
        }
      } else {
        const token = this.tokens.currentToken();
        if (isDeclaration(token)) {
          const name = this.tokens.identifierName();
          let replacement = this.importProcessor.getIdentifierReplacement(name);
          if (replacement === null) {
            throw new Error(`Expected a replacement for ${name} in \`export var\` syntax.`);
          }
          if (isObjectShorthandDeclaration(token)) {
            replacement = `${name}: ${replacement}`;
          }
          this.tokens.replaceToken(replacement);
        } else {
          this.rootTransformer.processToken();
        }
      }
    }
    if (needsParens) {
      const endIndex = this.tokens.currentToken().rhsEndIndex;
      if (endIndex == null) {
        throw new Error("Expected = token with an end index.");
      }
      while (this.tokens.currentIndex() < endIndex) {
        this.rootTransformer.processToken();
      }
      this.tokens.appendCode(")");
    }
  }
  /**
   * Transform this:
   * export function foo() {}
   * into this:
   * function foo() {} exports.foo = foo;
   */
  processExportFunction() {
    this.tokens.replaceToken("");
    const name = this.processNamedFunction();
    this.tokens.appendCode(` exports.${name} = ${name};`);
  }
  /**
   * Skip past a function with a name and return that name.
   */
  processNamedFunction() {
    if (this.tokens.matches1(TokenType._function)) {
      this.tokens.copyToken();
    } else if (this.tokens.matches2(TokenType.name, TokenType._function)) {
      if (!this.tokens.matchesContextual(ContextualKeyword._async)) {
        throw new Error("Expected async keyword in function export.");
      }
      this.tokens.copyToken();
      this.tokens.copyToken();
    }
    if (this.tokens.matches1(TokenType.star)) {
      this.tokens.copyToken();
    }
    if (!this.tokens.matches1(TokenType.name)) {
      throw new Error("Expected identifier for exported function name.");
    }
    const name = this.tokens.identifierName();
    this.tokens.copyToken();
    if (this.tokens.currentToken().isType) {
      this.tokens.removeInitialToken();
      while (this.tokens.currentToken().isType) {
        this.tokens.removeToken();
      }
    }
    this.tokens.copyExpectedToken(TokenType.parenL);
    this.rootTransformer.processBalancedCode();
    this.tokens.copyExpectedToken(TokenType.parenR);
    this.rootTransformer.processPossibleTypeRange();
    this.tokens.copyExpectedToken(TokenType.braceL);
    this.rootTransformer.processBalancedCode();
    this.tokens.copyExpectedToken(TokenType.braceR);
    return name;
  }
  /**
   * Transform this:
   * export class A {}
   * into this:
   * class A {} exports.A = A;
   */
  processExportClass() {
    this.tokens.removeInitialToken();
    this.copyDecorators();
    if (this.tokens.matches1(TokenType._abstract)) {
      this.tokens.removeToken();
    }
    const name = this.rootTransformer.processNamedClass();
    this.tokens.appendCode(` exports.${name} = ${name};`);
  }
  /**
   * Transform this:
   * export {a, b as c};
   * into this:
   * exports.a = a; exports.c = b;
   *
   * OR
   *
   * Transform this:
   * export {a, b as c} from './foo';
   * into the pre-generated Object.defineProperty code from the ImportProcessor.
   *
   * For the first case, if the TypeScript transform is enabled, we need to skip
   * exports that are only defined as types.
   */
  processExportBindings() {
    this.tokens.removeInitialToken();
    this.tokens.removeToken();
    const isReExport = isExportFrom(this.tokens);
    const exportStatements = [];
    while (true) {
      if (this.tokens.matches1(TokenType.braceR)) {
        this.tokens.removeToken();
        break;
      }
      const specifierInfo = getImportExportSpecifierInfo(this.tokens);
      while (this.tokens.currentIndex() < specifierInfo.endIndex) {
        this.tokens.removeToken();
      }
      const shouldRemoveExport = specifierInfo.isType || !isReExport && this.shouldElideExportedIdentifier(specifierInfo.leftName);
      if (!shouldRemoveExport) {
        const exportedName = specifierInfo.rightName;
        if (exportedName === "default") {
          this.hadDefaultExport = true;
        } else {
          this.hadNamedExport = true;
        }
        const localName = specifierInfo.leftName;
        const newLocalName = this.importProcessor.getIdentifierReplacement(localName);
        exportStatements.push(`exports.${exportedName} = ${newLocalName || localName};`);
      }
      if (this.tokens.matches1(TokenType.braceR)) {
        this.tokens.removeToken();
        break;
      }
      if (this.tokens.matches2(TokenType.comma, TokenType.braceR)) {
        this.tokens.removeToken();
        this.tokens.removeToken();
        break;
      } else if (this.tokens.matches1(TokenType.comma)) {
        this.tokens.removeToken();
      } else {
        throw new Error(`Unexpected token: ${JSON.stringify(this.tokens.currentToken())}`);
      }
    }
    if (this.tokens.matchesContextual(ContextualKeyword._from)) {
      this.tokens.removeToken();
      const path = this.tokens.stringValue();
      this.tokens.replaceTokenTrimmingLeftWhitespace(this.importProcessor.claimImportCode(path));
      removeMaybeImportAttributes(this.tokens);
    } else {
      this.tokens.appendCode(exportStatements.join(" "));
    }
    if (this.tokens.matches1(TokenType.semi)) {
      this.tokens.removeToken();
    }
  }
  processExportStar() {
    this.tokens.removeInitialToken();
    while (!this.tokens.matches1(TokenType.string)) {
      this.tokens.removeToken();
    }
    const path = this.tokens.stringValue();
    this.tokens.replaceTokenTrimmingLeftWhitespace(this.importProcessor.claimImportCode(path));
    removeMaybeImportAttributes(this.tokens);
    if (this.tokens.matches1(TokenType.semi)) {
      this.tokens.removeToken();
    }
  }
  shouldElideExportedIdentifier(name) {
    return this.isTypeScriptTransformEnabled && !this.keepUnusedImports && !this.declarationInfo.valueDeclarations.has(name);
  }
};

// node_modules/sucrase/dist/esm/transformers/ESMImportTransformer.js
var ESMImportTransformer = class extends Transformer {
  constructor(tokens, nameManager, helperManager, reactHotLoaderTransformer, isTypeScriptTransformEnabled, isFlowTransformEnabled, keepUnusedImports, options) {
    super();
    this.tokens = tokens;
    this.nameManager = nameManager;
    this.helperManager = helperManager;
    this.reactHotLoaderTransformer = reactHotLoaderTransformer;
    this.isTypeScriptTransformEnabled = isTypeScriptTransformEnabled;
    this.isFlowTransformEnabled = isFlowTransformEnabled;
    this.keepUnusedImports = keepUnusedImports;
    ;
    this.nonTypeIdentifiers = isTypeScriptTransformEnabled && !keepUnusedImports ? getNonTypeIdentifiers(tokens, options) : /* @__PURE__ */ new Set();
    this.declarationInfo = isTypeScriptTransformEnabled && !keepUnusedImports ? getDeclarationInfo(tokens) : EMPTY_DECLARATION_INFO;
    this.injectCreateRequireForImportRequire = Boolean(options.injectCreateRequireForImportRequire);
  }
  process() {
    if (this.tokens.matches3(TokenType._import, TokenType.name, TokenType.eq)) {
      return this.processImportEquals();
    }
    if (this.tokens.matches4(TokenType._import, TokenType.name, TokenType.name, TokenType.eq) && this.tokens.matchesContextualAtIndex(this.tokens.currentIndex() + 1, ContextualKeyword._type)) {
      this.tokens.removeInitialToken();
      for (let i4 = 0; i4 < 7; i4++) {
        this.tokens.removeToken();
      }
      return true;
    }
    if (this.tokens.matches2(TokenType._export, TokenType.eq)) {
      this.tokens.replaceToken("module.exports");
      return true;
    }
    if (this.tokens.matches5(TokenType._export, TokenType._import, TokenType.name, TokenType.name, TokenType.eq) && this.tokens.matchesContextualAtIndex(this.tokens.currentIndex() + 2, ContextualKeyword._type)) {
      this.tokens.removeInitialToken();
      for (let i4 = 0; i4 < 8; i4++) {
        this.tokens.removeToken();
      }
      return true;
    }
    if (this.tokens.matches1(TokenType._import)) {
      return this.processImport();
    }
    if (this.tokens.matches2(TokenType._export, TokenType._default)) {
      return this.processExportDefault();
    }
    if (this.tokens.matches2(TokenType._export, TokenType.braceL)) {
      return this.processNamedExports();
    }
    if (this.tokens.matches2(TokenType._export, TokenType.name) && this.tokens.matchesContextualAtIndex(this.tokens.currentIndex() + 1, ContextualKeyword._type)) {
      this.tokens.removeInitialToken();
      this.tokens.removeToken();
      if (this.tokens.matches1(TokenType.braceL)) {
        while (!this.tokens.matches1(TokenType.braceR)) {
          this.tokens.removeToken();
        }
        this.tokens.removeToken();
      } else {
        this.tokens.removeToken();
        if (this.tokens.matches1(TokenType._as)) {
          this.tokens.removeToken();
          this.tokens.removeToken();
        }
      }
      if (this.tokens.matchesContextual(ContextualKeyword._from) && this.tokens.matches1AtIndex(this.tokens.currentIndex() + 1, TokenType.string)) {
        this.tokens.removeToken();
        this.tokens.removeToken();
        removeMaybeImportAttributes(this.tokens);
      }
      return true;
    }
    return false;
  }
  processImportEquals() {
    const importName = this.tokens.identifierNameAtIndex(this.tokens.currentIndex() + 1);
    if (this.shouldAutomaticallyElideImportedName(importName)) {
      elideImportEquals(this.tokens);
    } else if (this.injectCreateRequireForImportRequire) {
      this.tokens.replaceToken("const");
      this.tokens.copyToken();
      this.tokens.copyToken();
      this.tokens.replaceToken(this.helperManager.getHelperName("require"));
    } else {
      this.tokens.replaceToken("const");
    }
    return true;
  }
  processImport() {
    if (this.tokens.matches2(TokenType._import, TokenType.parenL)) {
      return false;
    }
    const snapshot = this.tokens.snapshot();
    const allImportsRemoved = this.removeImportTypeBindings();
    if (allImportsRemoved) {
      this.tokens.restoreToSnapshot(snapshot);
      while (!this.tokens.matches1(TokenType.string)) {
        this.tokens.removeToken();
      }
      this.tokens.removeToken();
      removeMaybeImportAttributes(this.tokens);
      if (this.tokens.matches1(TokenType.semi)) {
        this.tokens.removeToken();
      }
    }
    return true;
  }
  /**
   * Remove type bindings from this import, leaving the rest of the import intact.
   *
   * Return true if this import was ONLY types, and thus is eligible for removal. This will bail out
   * of the replacement operation, so we can return early here.
   */
  removeImportTypeBindings() {
    this.tokens.copyExpectedToken(TokenType._import);
    if (this.tokens.matchesContextual(ContextualKeyword._type) && !this.tokens.matches1AtIndex(this.tokens.currentIndex() + 1, TokenType.comma) && !this.tokens.matchesContextualAtIndex(this.tokens.currentIndex() + 1, ContextualKeyword._from)) {
      return true;
    }
    if (this.tokens.matches1(TokenType.string)) {
      this.tokens.copyToken();
      return false;
    }
    if (this.tokens.matchesContextual(ContextualKeyword._module) && this.tokens.matchesContextualAtIndex(this.tokens.currentIndex() + 2, ContextualKeyword._from)) {
      this.tokens.copyToken();
    }
    let foundNonTypeImport = false;
    let foundAnyNamedImport = false;
    let needsComma = false;
    if (this.tokens.matches1(TokenType.name)) {
      if (this.shouldAutomaticallyElideImportedName(this.tokens.identifierName())) {
        this.tokens.removeToken();
        if (this.tokens.matches1(TokenType.comma)) {
          this.tokens.removeToken();
        }
      } else {
        foundNonTypeImport = true;
        this.tokens.copyToken();
        if (this.tokens.matches1(TokenType.comma)) {
          needsComma = true;
          this.tokens.removeToken();
        }
      }
    }
    if (this.tokens.matches1(TokenType.star)) {
      if (this.shouldAutomaticallyElideImportedName(this.tokens.identifierNameAtRelativeIndex(2))) {
        this.tokens.removeToken();
        this.tokens.removeToken();
        this.tokens.removeToken();
      } else {
        if (needsComma) {
          this.tokens.appendCode(",");
        }
        foundNonTypeImport = true;
        this.tokens.copyExpectedToken(TokenType.star);
        this.tokens.copyExpectedToken(TokenType.name);
        this.tokens.copyExpectedToken(TokenType.name);
      }
    } else if (this.tokens.matches1(TokenType.braceL)) {
      if (needsComma) {
        this.tokens.appendCode(",");
      }
      this.tokens.copyToken();
      while (!this.tokens.matches1(TokenType.braceR)) {
        foundAnyNamedImport = true;
        const specifierInfo = getImportExportSpecifierInfo(this.tokens);
        if (specifierInfo.isType || this.shouldAutomaticallyElideImportedName(specifierInfo.rightName)) {
          while (this.tokens.currentIndex() < specifierInfo.endIndex) {
            this.tokens.removeToken();
          }
          if (this.tokens.matches1(TokenType.comma)) {
            this.tokens.removeToken();
          }
        } else {
          foundNonTypeImport = true;
          while (this.tokens.currentIndex() < specifierInfo.endIndex) {
            this.tokens.copyToken();
          }
          if (this.tokens.matches1(TokenType.comma)) {
            this.tokens.copyToken();
          }
        }
      }
      this.tokens.copyExpectedToken(TokenType.braceR);
    }
    if (this.keepUnusedImports) {
      return false;
    }
    if (this.isTypeScriptTransformEnabled) {
      return !foundNonTypeImport;
    } else if (this.isFlowTransformEnabled) {
      return foundAnyNamedImport && !foundNonTypeImport;
    } else {
      return false;
    }
  }
  shouldAutomaticallyElideImportedName(name) {
    return this.isTypeScriptTransformEnabled && !this.keepUnusedImports && !this.nonTypeIdentifiers.has(name);
  }
  processExportDefault() {
    if (shouldElideDefaultExport(
      this.isTypeScriptTransformEnabled,
      this.keepUnusedImports,
      this.tokens,
      this.declarationInfo
    )) {
      this.tokens.removeInitialToken();
      this.tokens.removeToken();
      this.tokens.removeToken();
      return true;
    }
    const alreadyHasName = this.tokens.matches4(TokenType._export, TokenType._default, TokenType._function, TokenType.name) || // export default async function
    this.tokens.matches5(TokenType._export, TokenType._default, TokenType.name, TokenType._function, TokenType.name) && this.tokens.matchesContextualAtIndex(
      this.tokens.currentIndex() + 2,
      ContextualKeyword._async
    ) || this.tokens.matches4(TokenType._export, TokenType._default, TokenType._class, TokenType.name) || this.tokens.matches5(TokenType._export, TokenType._default, TokenType._abstract, TokenType._class, TokenType.name);
    if (!alreadyHasName && this.reactHotLoaderTransformer) {
      const defaultVarName = this.nameManager.claimFreeName("_default");
      this.tokens.replaceToken(`let ${defaultVarName}; export`);
      this.tokens.copyToken();
      this.tokens.appendCode(` ${defaultVarName} =`);
      this.reactHotLoaderTransformer.setExtractedDefaultExportName(defaultVarName);
      return true;
    }
    return false;
  }
  /**
   * Handle a statement with one of these forms:
   * export {a, type b};
   * export {c, type d} from 'foo';
   *
   * In both cases, any explicit type exports should be removed. In the first
   * case, we also need to handle implicit export elision for names declared as
   * types. In the second case, we must NOT do implicit named export elision,
   * but we must remove the runtime import if all exports are type exports.
   */
  processNamedExports() {
    if (!this.isTypeScriptTransformEnabled) {
      return false;
    }
    this.tokens.copyExpectedToken(TokenType._export);
    this.tokens.copyExpectedToken(TokenType.braceL);
    const isReExport = isExportFrom(this.tokens);
    let foundNonTypeExport = false;
    while (!this.tokens.matches1(TokenType.braceR)) {
      const specifierInfo = getImportExportSpecifierInfo(this.tokens);
      if (specifierInfo.isType || !isReExport && this.shouldElideExportedName(specifierInfo.leftName)) {
        while (this.tokens.currentIndex() < specifierInfo.endIndex) {
          this.tokens.removeToken();
        }
        if (this.tokens.matches1(TokenType.comma)) {
          this.tokens.removeToken();
        }
      } else {
        foundNonTypeExport = true;
        while (this.tokens.currentIndex() < specifierInfo.endIndex) {
          this.tokens.copyToken();
        }
        if (this.tokens.matches1(TokenType.comma)) {
          this.tokens.copyToken();
        }
      }
    }
    this.tokens.copyExpectedToken(TokenType.braceR);
    if (!this.keepUnusedImports && isReExport && !foundNonTypeExport) {
      this.tokens.removeToken();
      this.tokens.removeToken();
      removeMaybeImportAttributes(this.tokens);
    }
    return true;
  }
  /**
   * ESM elides all imports with the rule that we only elide if we see that it's
   * a type and never see it as a value. This is in contrast to CJS, which
   * elides imports that are completely unknown.
   */
  shouldElideExportedName(name) {
    return this.isTypeScriptTransformEnabled && !this.keepUnusedImports && this.declarationInfo.typeDeclarations.has(name) && !this.declarationInfo.valueDeclarations.has(name);
  }
};

// node_modules/sucrase/dist/esm/transformers/FlowTransformer.js
var FlowTransformer = class extends Transformer {
  constructor(rootTransformer, tokens, isImportsTransformEnabled) {
    super();
    this.rootTransformer = rootTransformer;
    this.tokens = tokens;
    this.isImportsTransformEnabled = isImportsTransformEnabled;
    ;
  }
  process() {
    if (this.rootTransformer.processPossibleArrowParamEnd() || this.rootTransformer.processPossibleAsyncArrowWithTypeParams() || this.rootTransformer.processPossibleTypeRange()) {
      return true;
    }
    if (this.tokens.matches1(TokenType._enum)) {
      this.processEnum();
      return true;
    }
    if (this.tokens.matches2(TokenType._export, TokenType._enum)) {
      this.processNamedExportEnum();
      return true;
    }
    if (this.tokens.matches3(TokenType._export, TokenType._default, TokenType._enum)) {
      this.processDefaultExportEnum();
      return true;
    }
    return false;
  }
  /**
   * Handle a declaration like:
   * export enum E ...
   *
   * With this imports transform, this becomes:
   * const E = [[enum]]; exports.E = E;
   *
   * otherwise, it becomes:
   * export const E = [[enum]];
   */
  processNamedExportEnum() {
    if (this.isImportsTransformEnabled) {
      this.tokens.removeInitialToken();
      const enumName = this.tokens.identifierNameAtRelativeIndex(1);
      this.processEnum();
      this.tokens.appendCode(` exports.${enumName} = ${enumName};`);
    } else {
      this.tokens.copyToken();
      this.processEnum();
    }
  }
  /**
   * Handle a declaration like:
   * export default enum E
   *
   * With the imports transform, this becomes:
   * const E = [[enum]]; exports.default = E;
   *
   * otherwise, it becomes:
   * const E = [[enum]]; export default E;
   */
  processDefaultExportEnum() {
    this.tokens.removeInitialToken();
    this.tokens.removeToken();
    const enumName = this.tokens.identifierNameAtRelativeIndex(1);
    this.processEnum();
    if (this.isImportsTransformEnabled) {
      this.tokens.appendCode(` exports.default = ${enumName};`);
    } else {
      this.tokens.appendCode(` export default ${enumName};`);
    }
  }
  /**
   * Transpile flow enums to invoke the "flow-enums-runtime" library.
   *
   * Currently, the transpiled code always uses `require("flow-enums-runtime")`,
   * but if future flexibility is needed, we could expose a config option for
   * this string (similar to configurable JSX). Even when targeting ESM, the
   * default behavior of babel-plugin-transform-flow-enums is to use require
   * rather than injecting an import.
   *
   * Flow enums are quite a bit simpler than TS enums and have some convenient
   * constraints:
   * - Element initializers must be either always present or always absent. That
   *   means that we can use fixed lookahead on the first element (if any) and
   *   assume that all elements are like that.
   * - The right-hand side of an element initializer must be a literal value,
   *   not a complex expression and not referencing other elements. That means
   *   we can simply copy a single token.
   *
   * Enums can be broken up into three basic cases:
   *
   * Mirrored enums:
   * enum E {A, B}
   *   ->
   * const E = require("flow-enums-runtime").Mirrored(["A", "B"]);
   *
   * Initializer enums:
   * enum E {A = 1, B = 2}
   *   ->
   * const E = require("flow-enums-runtime")({A: 1, B: 2});
   *
   * Symbol enums:
   * enum E of symbol {A, B}
   *   ->
   * const E = require("flow-enums-runtime")({A: Symbol("A"), B: Symbol("B")});
   *
   * We can statically detect which of the three cases this is by looking at the
   * "of" declaration (if any) and seeing if the first element has an initializer.
   * Since the other transform details are so similar between the three cases, we
   * use a single implementation and vary the transform within processEnumElement
   * based on case.
   */
  processEnum() {
    this.tokens.replaceToken("const");
    this.tokens.copyExpectedToken(TokenType.name);
    let isSymbolEnum = false;
    if (this.tokens.matchesContextual(ContextualKeyword._of)) {
      this.tokens.removeToken();
      isSymbolEnum = this.tokens.matchesContextual(ContextualKeyword._symbol);
      this.tokens.removeToken();
    }
    const hasInitializers = this.tokens.matches3(TokenType.braceL, TokenType.name, TokenType.eq);
    this.tokens.appendCode(' = require("flow-enums-runtime")');
    const isMirrored = !isSymbolEnum && !hasInitializers;
    this.tokens.replaceTokenTrimmingLeftWhitespace(isMirrored ? ".Mirrored([" : "({");
    while (!this.tokens.matches1(TokenType.braceR)) {
      if (this.tokens.matches1(TokenType.ellipsis)) {
        this.tokens.removeToken();
        break;
      }
      this.processEnumElement(isSymbolEnum, hasInitializers);
      if (this.tokens.matches1(TokenType.comma)) {
        this.tokens.copyToken();
      }
    }
    this.tokens.replaceToken(isMirrored ? "]);" : "});");
  }
  /**
   * Process an individual enum element, producing either an array element or an
   * object element based on what type of enum this is.
   */
  processEnumElement(isSymbolEnum, hasInitializers) {
    if (isSymbolEnum) {
      const elementName = this.tokens.identifierName();
      this.tokens.copyToken();
      this.tokens.appendCode(`: Symbol("${elementName}")`);
    } else if (hasInitializers) {
      this.tokens.copyToken();
      this.tokens.replaceTokenTrimmingLeftWhitespace(":");
      this.tokens.copyToken();
    } else {
      this.tokens.replaceToken(`"${this.tokens.identifierName()}"`);
    }
  }
};

// node_modules/sucrase/dist/esm/transformers/JestHoistTransformer.js
function _optionalChain(ops) {
  let lastAccessLHS = void 0;
  let value = ops[0];
  let i4 = 1;
  while (i4 < ops.length) {
    const op = ops[i4];
    const fn2 = ops[i4 + 1];
    i4 += 2;
    if ((op === "optionalAccess" || op === "optionalCall") && value == null) {
      return void 0;
    }
    if (op === "access" || op === "optionalAccess") {
      lastAccessLHS = value;
      value = fn2(value);
    } else if (op === "call" || op === "optionalCall") {
      value = fn2((...args) => value.call(lastAccessLHS, ...args));
      lastAccessLHS = void 0;
    }
  }
  return value;
}
var JEST_GLOBAL_NAME = "jest";
var HOISTED_METHODS = ["mock", "unmock", "enableAutomock", "disableAutomock"];
var JestHoistTransformer = class extends Transformer {
  __init() {
    this.hoistedFunctionNames = [];
  }
  constructor(rootTransformer, tokens, nameManager, importProcessor) {
    super();
    this.rootTransformer = rootTransformer;
    this.tokens = tokens;
    this.nameManager = nameManager;
    this.importProcessor = importProcessor;
    JestHoistTransformer.prototype.__init.call(this);
    ;
  }
  process() {
    if (this.tokens.currentToken().scopeDepth === 0 && this.tokens.matches4(TokenType.name, TokenType.dot, TokenType.name, TokenType.parenL) && this.tokens.identifierName() === JEST_GLOBAL_NAME) {
      if (_optionalChain([this, "access", (_3) => _3.importProcessor, "optionalAccess", (_22) => _22.getGlobalNames, "call", (_3) => _3(), "optionalAccess", (_4) => _4.has, "call", (_5) => _5(JEST_GLOBAL_NAME)])) {
        return false;
      }
      return this.extractHoistedCalls();
    }
    return false;
  }
  getHoistedCode() {
    if (this.hoistedFunctionNames.length > 0) {
      return this.hoistedFunctionNames.map((name) => `${name}();`).join("");
    }
    return "";
  }
  /**
   * Extracts any methods calls on the jest-object that should be hoisted.
   *
   * According to the jest docs, https://jestjs.io/docs/en/jest-object#jestmockmodulename-factory-options,
   * mock, unmock, enableAutomock, disableAutomock, are the methods that should be hoisted.
   *
   * We do not apply the same checks of the arguments as babel-plugin-jest-hoist does.
   */
  extractHoistedCalls() {
    this.tokens.removeToken();
    let followsNonHoistedJestCall = false;
    while (this.tokens.matches3(TokenType.dot, TokenType.name, TokenType.parenL)) {
      const methodName = this.tokens.identifierNameAtIndex(this.tokens.currentIndex() + 1);
      const shouldHoist = HOISTED_METHODS.includes(methodName);
      if (shouldHoist) {
        const hoistedFunctionName = this.nameManager.claimFreeName("__jestHoist");
        this.hoistedFunctionNames.push(hoistedFunctionName);
        this.tokens.replaceToken(`function ${hoistedFunctionName}(){${JEST_GLOBAL_NAME}.`);
        this.tokens.copyToken();
        this.tokens.copyToken();
        this.rootTransformer.processBalancedCode();
        this.tokens.copyExpectedToken(TokenType.parenR);
        this.tokens.appendCode(";}");
        followsNonHoistedJestCall = false;
      } else {
        if (followsNonHoistedJestCall) {
          this.tokens.copyToken();
        } else {
          this.tokens.replaceToken(`${JEST_GLOBAL_NAME}.`);
        }
        this.tokens.copyToken();
        this.tokens.copyToken();
        this.rootTransformer.processBalancedCode();
        this.tokens.copyExpectedToken(TokenType.parenR);
        followsNonHoistedJestCall = true;
      }
    }
    return true;
  }
};

// node_modules/sucrase/dist/esm/transformers/NumericSeparatorTransformer.js
var NumericSeparatorTransformer = class extends Transformer {
  constructor(tokens) {
    super();
    this.tokens = tokens;
    ;
  }
  process() {
    if (this.tokens.matches1(TokenType.num)) {
      const code = this.tokens.currentTokenCode();
      if (code.includes("_")) {
        this.tokens.replaceToken(code.replace(/_/g, ""));
        return true;
      }
    }
    return false;
  }
};

// node_modules/sucrase/dist/esm/transformers/OptionalCatchBindingTransformer.js
var OptionalCatchBindingTransformer = class extends Transformer {
  constructor(tokens, nameManager) {
    super();
    this.tokens = tokens;
    this.nameManager = nameManager;
    ;
  }
  process() {
    if (this.tokens.matches2(TokenType._catch, TokenType.braceL)) {
      this.tokens.copyToken();
      this.tokens.appendCode(` (${this.nameManager.claimFreeName("e")})`);
      return true;
    }
    return false;
  }
};

// node_modules/sucrase/dist/esm/transformers/OptionalChainingNullishTransformer.js
var OptionalChainingNullishTransformer = class extends Transformer {
  constructor(tokens, nameManager) {
    super();
    this.tokens = tokens;
    this.nameManager = nameManager;
    ;
  }
  process() {
    if (this.tokens.matches1(TokenType.nullishCoalescing)) {
      const token2 = this.tokens.currentToken();
      if (this.tokens.tokens[token2.nullishStartIndex].isAsyncOperation) {
        this.tokens.replaceTokenTrimmingLeftWhitespace(", async () => (");
      } else {
        this.tokens.replaceTokenTrimmingLeftWhitespace(", () => (");
      }
      return true;
    }
    if (this.tokens.matches1(TokenType._delete)) {
      const nextToken2 = this.tokens.tokenAtRelativeIndex(1);
      if (nextToken2.isOptionalChainStart) {
        this.tokens.removeInitialToken();
        return true;
      }
    }
    const token = this.tokens.currentToken();
    const chainStart = token.subscriptStartIndex;
    if (chainStart != null && this.tokens.tokens[chainStart].isOptionalChainStart && // Super subscripts can't be optional (since super is never null/undefined), and the syntax
    // relies on the subscript being intact, so leave this token alone.
    this.tokens.tokenAtRelativeIndex(-1).type !== TokenType._super) {
      const param = this.nameManager.claimFreeName("_");
      let arrowStartSnippet;
      if (chainStart > 0 && this.tokens.matches1AtIndex(chainStart - 1, TokenType._delete) && this.isLastSubscriptInChain()) {
        arrowStartSnippet = `${param} => delete ${param}`;
      } else {
        arrowStartSnippet = `${param} => ${param}`;
      }
      if (this.tokens.tokens[chainStart].isAsyncOperation) {
        arrowStartSnippet = `async ${arrowStartSnippet}`;
      }
      if (this.tokens.matches2(TokenType.questionDot, TokenType.parenL) || this.tokens.matches2(TokenType.questionDot, TokenType.lessThan)) {
        if (this.justSkippedSuper()) {
          this.tokens.appendCode(".bind(this)");
        }
        this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalCall', ${arrowStartSnippet}`);
      } else if (this.tokens.matches2(TokenType.questionDot, TokenType.bracketL)) {
        this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalAccess', ${arrowStartSnippet}`);
      } else if (this.tokens.matches1(TokenType.questionDot)) {
        this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalAccess', ${arrowStartSnippet}.`);
      } else if (this.tokens.matches1(TokenType.dot)) {
        this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'access', ${arrowStartSnippet}.`);
      } else if (this.tokens.matches1(TokenType.bracketL)) {
        this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'access', ${arrowStartSnippet}[`);
      } else if (this.tokens.matches1(TokenType.parenL)) {
        if (this.justSkippedSuper()) {
          this.tokens.appendCode(".bind(this)");
        }
        this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'call', ${arrowStartSnippet}(`);
      } else {
        throw new Error("Unexpected subscript operator in optional chain.");
      }
      return true;
    }
    return false;
  }
  /**
   * Determine if the current token is the last of its chain, so that we know whether it's eligible
   * to have a delete op inserted.
   *
   * We can do this by walking forward until we determine one way or another. Each
   * isOptionalChainStart token must be paired with exactly one isOptionalChainEnd token after it in
   * a nesting way, so we can track depth and walk to the end of the chain (the point where the
   * depth goes negative) and see if any other subscript token is after us in the chain.
   */
  isLastSubscriptInChain() {
    let depth = 0;
    for (let i4 = this.tokens.currentIndex() + 1; ; i4++) {
      if (i4 >= this.tokens.tokens.length) {
        throw new Error("Reached the end of the code while finding the end of the access chain.");
      }
      if (this.tokens.tokens[i4].isOptionalChainStart) {
        depth++;
      } else if (this.tokens.tokens[i4].isOptionalChainEnd) {
        depth--;
      }
      if (depth < 0) {
        return true;
      }
      if (depth === 0 && this.tokens.tokens[i4].subscriptStartIndex != null) {
        return false;
      }
    }
  }
  /**
   * Determine if we are the open-paren in an expression like super.a()?.b.
   *
   * We can do this by walking backward to find the previous subscript. If that subscript was
   * preceded by a super, then we must be the subscript after it, so if this is a call expression,
   * we'll need to attach the right context.
   */
  justSkippedSuper() {
    let depth = 0;
    let index = this.tokens.currentIndex() - 1;
    while (true) {
      if (index < 0) {
        throw new Error(
          "Reached the start of the code while finding the start of the access chain."
        );
      }
      if (this.tokens.tokens[index].isOptionalChainStart) {
        depth--;
      } else if (this.tokens.tokens[index].isOptionalChainEnd) {
        depth++;
      }
      if (depth < 0) {
        return false;
      }
      if (depth === 0 && this.tokens.tokens[index].subscriptStartIndex != null) {
        return this.tokens.tokens[index - 1].type === TokenType._super;
      }
      index--;
    }
  }
};

// node_modules/sucrase/dist/esm/transformers/ReactDisplayNameTransformer.js
var ReactDisplayNameTransformer = class extends Transformer {
  constructor(rootTransformer, tokens, importProcessor, options) {
    super();
    this.rootTransformer = rootTransformer;
    this.tokens = tokens;
    this.importProcessor = importProcessor;
    this.options = options;
    ;
  }
  process() {
    const startIndex = this.tokens.currentIndex();
    if (this.tokens.identifierName() === "createReactClass") {
      const newName = this.importProcessor && this.importProcessor.getIdentifierReplacement("createReactClass");
      if (newName) {
        this.tokens.replaceToken(`(0, ${newName})`);
      } else {
        this.tokens.copyToken();
      }
      this.tryProcessCreateClassCall(startIndex);
      return true;
    }
    if (this.tokens.matches3(TokenType.name, TokenType.dot, TokenType.name) && this.tokens.identifierName() === "React" && this.tokens.identifierNameAtIndex(this.tokens.currentIndex() + 2) === "createClass") {
      const newName = this.importProcessor ? this.importProcessor.getIdentifierReplacement("React") || "React" : "React";
      if (newName) {
        this.tokens.replaceToken(newName);
        this.tokens.copyToken();
        this.tokens.copyToken();
      } else {
        this.tokens.copyToken();
        this.tokens.copyToken();
        this.tokens.copyToken();
      }
      this.tryProcessCreateClassCall(startIndex);
      return true;
    }
    return false;
  }
  /**
   * This is called with the token position at the open-paren.
   */
  tryProcessCreateClassCall(startIndex) {
    const displayName = this.findDisplayName(startIndex);
    if (!displayName) {
      return;
    }
    if (this.classNeedsDisplayName()) {
      this.tokens.copyExpectedToken(TokenType.parenL);
      this.tokens.copyExpectedToken(TokenType.braceL);
      this.tokens.appendCode(`displayName: '${displayName}',`);
      this.rootTransformer.processBalancedCode();
      this.tokens.copyExpectedToken(TokenType.braceR);
      this.tokens.copyExpectedToken(TokenType.parenR);
    }
  }
  findDisplayName(startIndex) {
    if (startIndex < 2) {
      return null;
    }
    if (this.tokens.matches2AtIndex(startIndex - 2, TokenType.name, TokenType.eq)) {
      return this.tokens.identifierNameAtIndex(startIndex - 2);
    }
    if (startIndex >= 2 && this.tokens.tokens[startIndex - 2].identifierRole === IdentifierRole.ObjectKey) {
      return this.tokens.identifierNameAtIndex(startIndex - 2);
    }
    if (this.tokens.matches2AtIndex(startIndex - 2, TokenType._export, TokenType._default)) {
      return this.getDisplayNameFromFilename();
    }
    return null;
  }
  getDisplayNameFromFilename() {
    const filePath = this.options.filePath || "unknown";
    const pathSegments = filePath.split("/");
    const filename = pathSegments[pathSegments.length - 1];
    const dotIndex = filename.lastIndexOf(".");
    const baseFilename = dotIndex === -1 ? filename : filename.slice(0, dotIndex);
    if (baseFilename === "index" && pathSegments[pathSegments.length - 2]) {
      return pathSegments[pathSegments.length - 2];
    } else {
      return baseFilename;
    }
  }
  /**
   * We only want to add a display name when this is a function call containing
   * one argument, which is an object literal without `displayName` as an
   * existing key.
   */
  classNeedsDisplayName() {
    let index = this.tokens.currentIndex();
    if (!this.tokens.matches2(TokenType.parenL, TokenType.braceL)) {
      return false;
    }
    const objectStartIndex = index + 1;
    const objectContextId = this.tokens.tokens[objectStartIndex].contextId;
    if (objectContextId == null) {
      throw new Error("Expected non-null context ID on object open-brace.");
    }
    for (; index < this.tokens.tokens.length; index++) {
      const token = this.tokens.tokens[index];
      if (token.type === TokenType.braceR && token.contextId === objectContextId) {
        index++;
        break;
      }
      if (this.tokens.identifierNameAtIndex(index) === "displayName" && this.tokens.tokens[index].identifierRole === IdentifierRole.ObjectKey && token.contextId === objectContextId) {
        return false;
      }
    }
    if (index === this.tokens.tokens.length) {
      throw new Error("Unexpected end of input when processing React class.");
    }
    return this.tokens.matches1AtIndex(index, TokenType.parenR) || this.tokens.matches2AtIndex(index, TokenType.comma, TokenType.parenR);
  }
};

// node_modules/sucrase/dist/esm/transformers/ReactHotLoaderTransformer.js
var ReactHotLoaderTransformer = class extends Transformer {
  __init() {
    this.extractedDefaultExportName = null;
  }
  constructor(tokens, filePath) {
    super();
    this.tokens = tokens;
    this.filePath = filePath;
    ReactHotLoaderTransformer.prototype.__init.call(this);
    ;
  }
  setExtractedDefaultExportName(extractedDefaultExportName) {
    this.extractedDefaultExportName = extractedDefaultExportName;
  }
  getPrefixCode() {
    return `
      (function () {
        var enterModule = require('react-hot-loader').enterModule;
        enterModule && enterModule(module);
      })();`.replace(/\s+/g, " ").trim();
  }
  getSuffixCode() {
    const topLevelNames = /* @__PURE__ */ new Set();
    for (const token of this.tokens.tokens) {
      if (!token.isType && isTopLevelDeclaration(token) && token.identifierRole !== IdentifierRole.ImportDeclaration) {
        topLevelNames.add(this.tokens.identifierNameForToken(token));
      }
    }
    const namesToRegister = Array.from(topLevelNames).map((name) => ({
      variableName: name,
      uniqueLocalName: name
    }));
    if (this.extractedDefaultExportName) {
      namesToRegister.push({
        variableName: this.extractedDefaultExportName,
        uniqueLocalName: "default"
      });
    }
    return `
;(function () {
  var reactHotLoader = require('react-hot-loader').default;
  var leaveModule = require('react-hot-loader').leaveModule;
  if (!reactHotLoader) {
    return;
  }
${namesToRegister.map(
      ({ variableName, uniqueLocalName }) => `  reactHotLoader.register(${variableName}, "${uniqueLocalName}", ${JSON.stringify(
        this.filePath || ""
      )});`
    ).join("\n")}
  leaveModule(module);
})();`;
  }
  process() {
    return false;
  }
};

// node_modules/sucrase/dist/esm/util/isIdentifier.js
var RESERVED_WORDS = /* @__PURE__ */ new Set([
  // Reserved keywords as of ECMAScript 2015
  "break",
  "case",
  "catch",
  "class",
  "const",
  "continue",
  "debugger",
  "default",
  "delete",
  "do",
  "else",
  "export",
  "extends",
  "finally",
  "for",
  "function",
  "if",
  "import",
  "in",
  "instanceof",
  "new",
  "return",
  "super",
  "switch",
  "this",
  "throw",
  "try",
  "typeof",
  "var",
  "void",
  "while",
  "with",
  "yield",
  // Future reserved keywords
  "enum",
  "implements",
  "interface",
  "let",
  "package",
  "private",
  "protected",
  "public",
  "static",
  "await",
  // Literals that cannot be used as identifiers
  "false",
  "null",
  "true"
]);
function isIdentifier(name) {
  if (name.length === 0) {
    return false;
  }
  if (!IS_IDENTIFIER_START[name.charCodeAt(0)]) {
    return false;
  }
  for (let i4 = 1; i4 < name.length; i4++) {
    if (!IS_IDENTIFIER_CHAR[name.charCodeAt(i4)]) {
      return false;
    }
  }
  return !RESERVED_WORDS.has(name);
}

// node_modules/sucrase/dist/esm/transformers/TypeScriptTransformer.js
var TypeScriptTransformer = class extends Transformer {
  constructor(rootTransformer, tokens, isImportsTransformEnabled) {
    super();
    this.rootTransformer = rootTransformer;
    this.tokens = tokens;
    this.isImportsTransformEnabled = isImportsTransformEnabled;
    ;
  }
  process() {
    if (this.rootTransformer.processPossibleArrowParamEnd() || this.rootTransformer.processPossibleAsyncArrowWithTypeParams() || this.rootTransformer.processPossibleTypeRange()) {
      return true;
    }
    if (this.tokens.matches1(TokenType._public) || this.tokens.matches1(TokenType._protected) || this.tokens.matches1(TokenType._private) || this.tokens.matches1(TokenType._abstract) || this.tokens.matches1(TokenType._readonly) || this.tokens.matches1(TokenType._override) || this.tokens.matches1(TokenType.nonNullAssertion)) {
      this.tokens.removeInitialToken();
      return true;
    }
    if (this.tokens.matches1(TokenType._enum) || this.tokens.matches2(TokenType._const, TokenType._enum)) {
      this.processEnum();
      return true;
    }
    if (this.tokens.matches2(TokenType._export, TokenType._enum) || this.tokens.matches3(TokenType._export, TokenType._const, TokenType._enum)) {
      this.processEnum(true);
      return true;
    }
    return false;
  }
  processEnum(isExport = false) {
    this.tokens.removeInitialToken();
    while (this.tokens.matches1(TokenType._const) || this.tokens.matches1(TokenType._enum)) {
      this.tokens.removeToken();
    }
    const enumName = this.tokens.identifierName();
    this.tokens.removeToken();
    if (isExport && !this.isImportsTransformEnabled) {
      this.tokens.appendCode("export ");
    }
    this.tokens.appendCode(`var ${enumName}; (function (${enumName})`);
    this.tokens.copyExpectedToken(TokenType.braceL);
    this.processEnumBody(enumName);
    this.tokens.copyExpectedToken(TokenType.braceR);
    if (isExport && this.isImportsTransformEnabled) {
      this.tokens.appendCode(`)(${enumName} || (exports.${enumName} = ${enumName} = {}));`);
    } else {
      this.tokens.appendCode(`)(${enumName} || (${enumName} = {}));`);
    }
  }
  /**
   * Transform an enum into equivalent JS. This has complexity in a few places:
   * - TS allows string enums, numeric enums, and a mix of the two styles within an enum.
   * - Enum keys are allowed to be referenced in later enum values.
   * - Enum keys are allowed to be strings.
   * - When enum values are omitted, they should follow an auto-increment behavior.
   */
  processEnumBody(enumName) {
    let previousValueCode = null;
    while (true) {
      if (this.tokens.matches1(TokenType.braceR)) {
        break;
      }
      const { nameStringCode, variableName } = this.extractEnumKeyInfo(this.tokens.currentToken());
      this.tokens.removeInitialToken();
      if (this.tokens.matches3(TokenType.eq, TokenType.string, TokenType.comma) || this.tokens.matches3(TokenType.eq, TokenType.string, TokenType.braceR)) {
        this.processStringLiteralEnumMember(enumName, nameStringCode, variableName);
      } else if (this.tokens.matches1(TokenType.eq)) {
        this.processExplicitValueEnumMember(enumName, nameStringCode, variableName);
      } else {
        this.processImplicitValueEnumMember(
          enumName,
          nameStringCode,
          variableName,
          previousValueCode
        );
      }
      if (this.tokens.matches1(TokenType.comma)) {
        this.tokens.removeToken();
      }
      if (variableName != null) {
        previousValueCode = variableName;
      } else {
        previousValueCode = `${enumName}[${nameStringCode}]`;
      }
    }
  }
  /**
   * Detect name information about this enum key, which will be used to determine which code to emit
   * and whether we should declare a variable as part of this declaration.
   *
   * Some cases to keep in mind:
   * - Enum keys can be implicitly referenced later, e.g. `X = 1, Y = X`. In Sucrase, we implement
   *   this by declaring a variable `X` so that later expressions can use it.
   * - In addition to the usual identifier key syntax, enum keys are allowed to be string literals,
   *   e.g. `"hello world" = 3,`. Template literal syntax is NOT allowed.
   * - Even if the enum key is defined as a string literal, it may still be referenced by identifier
   *   later, e.g. `"X" = 1, Y = X`. That means that we need to detect whether or not a string
   *   literal is identifier-like and emit a variable if so, even if the declaration did not use an
   *   identifier.
   * - Reserved keywords like `break` are valid enum keys, but are not valid to be referenced later
   *   and would be a syntax error if we emitted a variable, so we need to skip the variable
   *   declaration in those cases.
   *
   * The variableName return value captures these nuances: if non-null, we can and must emit a
   * variable declaration, and if null, we can't and shouldn't.
   */
  extractEnumKeyInfo(nameToken) {
    if (nameToken.type === TokenType.name) {
      const name = this.tokens.identifierNameForToken(nameToken);
      return {
        nameStringCode: `"${name}"`,
        variableName: isIdentifier(name) ? name : null
      };
    } else if (nameToken.type === TokenType.string) {
      const name = this.tokens.stringValueForToken(nameToken);
      return {
        nameStringCode: this.tokens.code.slice(nameToken.start, nameToken.end),
        variableName: isIdentifier(name) ? name : null
      };
    } else {
      throw new Error("Expected name or string at beginning of enum element.");
    }
  }
  /**
   * Handle an enum member where the RHS is just a string literal (not omitted, not a number, and
   * not a complex expression). This is the typical form for TS string enums, and in this case, we
   * do *not* create a reverse mapping.
   *
   * This is called after deleting the key token, when the token processor is at the equals sign.
   *
   * Example 1:
   * someKey = "some value"
   * ->
   * const someKey = "some value"; MyEnum["someKey"] = someKey;
   *
   * Example 2:
   * "some key" = "some value"
   * ->
   * MyEnum["some key"] = "some value";
   */
  processStringLiteralEnumMember(enumName, nameStringCode, variableName) {
    if (variableName != null) {
      this.tokens.appendCode(`const ${variableName}`);
      this.tokens.copyToken();
      this.tokens.copyToken();
      this.tokens.appendCode(`; ${enumName}[${nameStringCode}] = ${variableName};`);
    } else {
      this.tokens.appendCode(`${enumName}[${nameStringCode}]`);
      this.tokens.copyToken();
      this.tokens.copyToken();
      this.tokens.appendCode(";");
    }
  }
  /**
   * Handle an enum member initialized with an expression on the right-hand side (other than a
   * string literal). In these cases, we should transform the expression and emit code that sets up
   * a reverse mapping.
   *
   * The TypeScript implementation of this operation distinguishes between expressions that can be
   * "constant folded" at compile time (i.e. consist of number literals and simple math operations
   * on those numbers) and ones that are dynamic. For constant expressions, it emits the resolved
   * numeric value, and auto-incrementing is only allowed in that case. Evaluating expressions at
   * compile time would add significant complexity to Sucrase, so Sucrase instead leaves the
   * expression as-is, and will later emit something like `MyEnum["previousKey"] + 1` to implement
   * auto-incrementing.
   *
   * This is called after deleting the key token, when the token processor is at the equals sign.
   *
   * Example 1:
   * someKey = 1 + 1
   * ->
   * const someKey = 1 + 1; MyEnum[MyEnum["someKey"] = someKey] = "someKey";
   *
   * Example 2:
   * "some key" = 1 + 1
   * ->
   * MyEnum[MyEnum["some key"] = 1 + 1] = "some key";
   */
  processExplicitValueEnumMember(enumName, nameStringCode, variableName) {
    const rhsEndIndex = this.tokens.currentToken().rhsEndIndex;
    if (rhsEndIndex == null) {
      throw new Error("Expected rhsEndIndex on enum assign.");
    }
    if (variableName != null) {
      this.tokens.appendCode(`const ${variableName}`);
      this.tokens.copyToken();
      while (this.tokens.currentIndex() < rhsEndIndex) {
        this.rootTransformer.processToken();
      }
      this.tokens.appendCode(
        `; ${enumName}[${enumName}[${nameStringCode}] = ${variableName}] = ${nameStringCode};`
      );
    } else {
      this.tokens.appendCode(`${enumName}[${enumName}[${nameStringCode}]`);
      this.tokens.copyToken();
      while (this.tokens.currentIndex() < rhsEndIndex) {
        this.rootTransformer.processToken();
      }
      this.tokens.appendCode(`] = ${nameStringCode};`);
    }
  }
  /**
   * Handle an enum member with no right-hand side expression. In this case, the value is the
   * previous value plus 1, or 0 if there was no previous value. We should also always emit a
   * reverse mapping.
   *
   * Example 1:
   * someKey2
   * ->
   * const someKey2 = someKey1 + 1; MyEnum[MyEnum["someKey2"] = someKey2] = "someKey2";
   *
   * Example 2:
   * "some key 2"
   * ->
   * MyEnum[MyEnum["some key 2"] = someKey1 + 1] = "some key 2";
   */
  processImplicitValueEnumMember(enumName, nameStringCode, variableName, previousValueCode) {
    let valueCode = previousValueCode != null ? `${previousValueCode} + 1` : "0";
    if (variableName != null) {
      this.tokens.appendCode(`const ${variableName} = ${valueCode}; `);
      valueCode = variableName;
    }
    this.tokens.appendCode(
      `${enumName}[${enumName}[${nameStringCode}] = ${valueCode}] = ${nameStringCode};`
    );
  }
};

// node_modules/sucrase/dist/esm/transformers/RootTransformer.js
var RootTransformer = class {
  __init() {
    this.transformers = [];
  }
  __init2() {
    this.generatedVariables = [];
  }
  constructor(sucraseContext, transforms, enableLegacyBabel5ModuleInterop, options) {
    ;
    RootTransformer.prototype.__init.call(this);
    RootTransformer.prototype.__init2.call(this);
    this.nameManager = sucraseContext.nameManager;
    this.helperManager = sucraseContext.helperManager;
    const { tokenProcessor, importProcessor } = sucraseContext;
    this.tokens = tokenProcessor;
    this.isImportsTransformEnabled = transforms.includes("imports");
    this.isReactHotLoaderTransformEnabled = transforms.includes("react-hot-loader");
    this.disableESTransforms = Boolean(options.disableESTransforms);
    if (!options.disableESTransforms) {
      this.transformers.push(
        new OptionalChainingNullishTransformer(tokenProcessor, this.nameManager)
      );
      this.transformers.push(new NumericSeparatorTransformer(tokenProcessor));
      this.transformers.push(new OptionalCatchBindingTransformer(tokenProcessor, this.nameManager));
    }
    if (transforms.includes("jsx")) {
      if (options.jsxRuntime !== "preserve") {
        this.transformers.push(
          new JSXTransformer(this, tokenProcessor, importProcessor, this.nameManager, options)
        );
      }
      this.transformers.push(
        new ReactDisplayNameTransformer(this, tokenProcessor, importProcessor, options)
      );
    }
    let reactHotLoaderTransformer = null;
    if (transforms.includes("react-hot-loader")) {
      if (!options.filePath) {
        throw new Error("filePath is required when using the react-hot-loader transform.");
      }
      reactHotLoaderTransformer = new ReactHotLoaderTransformer(tokenProcessor, options.filePath);
      this.transformers.push(reactHotLoaderTransformer);
    }
    if (transforms.includes("imports")) {
      if (importProcessor === null) {
        throw new Error("Expected non-null importProcessor with imports transform enabled.");
      }
      this.transformers.push(
        new CJSImportTransformer(
          this,
          tokenProcessor,
          importProcessor,
          this.nameManager,
          this.helperManager,
          reactHotLoaderTransformer,
          enableLegacyBabel5ModuleInterop,
          Boolean(options.enableLegacyTypeScriptModuleInterop),
          transforms.includes("typescript"),
          transforms.includes("flow"),
          Boolean(options.preserveDynamicImport),
          Boolean(options.keepUnusedImports)
        )
      );
    } else {
      this.transformers.push(
        new ESMImportTransformer(
          tokenProcessor,
          this.nameManager,
          this.helperManager,
          reactHotLoaderTransformer,
          transforms.includes("typescript"),
          transforms.includes("flow"),
          Boolean(options.keepUnusedImports),
          options
        )
      );
    }
    if (transforms.includes("flow")) {
      this.transformers.push(
        new FlowTransformer(this, tokenProcessor, transforms.includes("imports"))
      );
    }
    if (transforms.includes("typescript")) {
      this.transformers.push(
        new TypeScriptTransformer(this, tokenProcessor, transforms.includes("imports"))
      );
    }
    if (transforms.includes("jest")) {
      this.transformers.push(
        new JestHoistTransformer(this, tokenProcessor, this.nameManager, importProcessor)
      );
    }
  }
  transform() {
    this.tokens.reset();
    this.processBalancedCode();
    const shouldAddUseStrict = this.isImportsTransformEnabled;
    let prefix = shouldAddUseStrict ? '"use strict";' : "";
    for (const transformer of this.transformers) {
      prefix += transformer.getPrefixCode();
    }
    prefix += this.helperManager.emitHelpers();
    prefix += this.generatedVariables.map((v3) => ` var ${v3};`).join("");
    for (const transformer of this.transformers) {
      prefix += transformer.getHoistedCode();
    }
    let suffix = "";
    for (const transformer of this.transformers) {
      suffix += transformer.getSuffixCode();
    }
    const result = this.tokens.finish();
    let { code } = result;
    if (code.startsWith("#!")) {
      let newlineIndex = code.indexOf("\n");
      if (newlineIndex === -1) {
        newlineIndex = code.length;
        code += "\n";
      }
      return {
        code: code.slice(0, newlineIndex + 1) + prefix + code.slice(newlineIndex + 1) + suffix,
        // The hashbang line has no tokens, so shifting the tokens to account
        // for prefix can happen normally.
        mappings: this.shiftMappings(result.mappings, prefix.length)
      };
    } else {
      return {
        code: prefix + code + suffix,
        mappings: this.shiftMappings(result.mappings, prefix.length)
      };
    }
  }
  processBalancedCode() {
    let braceDepth = 0;
    let parenDepth = 0;
    while (!this.tokens.isAtEnd()) {
      if (this.tokens.matches1(TokenType.braceL) || this.tokens.matches1(TokenType.dollarBraceL)) {
        braceDepth++;
      } else if (this.tokens.matches1(TokenType.braceR)) {
        if (braceDepth === 0) {
          return;
        }
        braceDepth--;
      }
      if (this.tokens.matches1(TokenType.parenL)) {
        parenDepth++;
      } else if (this.tokens.matches1(TokenType.parenR)) {
        if (parenDepth === 0) {
          return;
        }
        parenDepth--;
      }
      this.processToken();
    }
  }
  processToken() {
    if (this.tokens.matches1(TokenType._class)) {
      this.processClass();
      return;
    }
    for (const transformer of this.transformers) {
      const wasProcessed = transformer.process();
      if (wasProcessed) {
        return;
      }
    }
    this.tokens.copyToken();
  }
  /**
   * Skip past a class with a name and return that name.
   */
  processNamedClass() {
    if (!this.tokens.matches2(TokenType._class, TokenType.name)) {
      throw new Error("Expected identifier for exported class name.");
    }
    const name = this.tokens.identifierNameAtIndex(this.tokens.currentIndex() + 1);
    this.processClass();
    return name;
  }
  processClass() {
    const classInfo = getClassInfo(this, this.tokens, this.nameManager, this.disableESTransforms);
    const needsCommaExpression = (classInfo.headerInfo.isExpression || !classInfo.headerInfo.className) && classInfo.staticInitializerNames.length + classInfo.instanceInitializerNames.length > 0;
    let className = classInfo.headerInfo.className;
    if (needsCommaExpression) {
      className = this.nameManager.claimFreeName("_class");
      this.generatedVariables.push(className);
      this.tokens.appendCode(` (${className} =`);
    }
    const classToken = this.tokens.currentToken();
    const contextId = classToken.contextId;
    if (contextId == null) {
      throw new Error("Expected class to have a context ID.");
    }
    this.tokens.copyExpectedToken(TokenType._class);
    while (!this.tokens.matchesContextIdAndLabel(TokenType.braceL, contextId)) {
      this.processToken();
    }
    this.processClassBody(classInfo, className);
    const staticInitializerStatements = classInfo.staticInitializerNames.map(
      (name) => `${className}.${name}()`
    );
    if (needsCommaExpression) {
      this.tokens.appendCode(
        `, ${staticInitializerStatements.map((s4) => `${s4}, `).join("")}${className})`
      );
    } else if (classInfo.staticInitializerNames.length > 0) {
      this.tokens.appendCode(` ${staticInitializerStatements.map((s4) => `${s4};`).join(" ")}`);
    }
  }
  /**
   * We want to just handle class fields in all contexts, since TypeScript supports them. Later,
   * when some JS implementations support class fields, this should be made optional.
   */
  processClassBody(classInfo, className) {
    const {
      headerInfo,
      constructorInsertPos,
      constructorInitializerStatements,
      fields,
      instanceInitializerNames,
      rangesToRemove
    } = classInfo;
    let fieldIndex = 0;
    let rangeToRemoveIndex = 0;
    const classContextId = this.tokens.currentToken().contextId;
    if (classContextId == null) {
      throw new Error("Expected non-null context ID on class.");
    }
    this.tokens.copyExpectedToken(TokenType.braceL);
    if (this.isReactHotLoaderTransformEnabled) {
      this.tokens.appendCode(
        "__reactstandin__regenerateByEval(key, code) {this[key] = eval(code);}"
      );
    }
    const needsConstructorInit = constructorInitializerStatements.length + instanceInitializerNames.length > 0;
    if (constructorInsertPos === null && needsConstructorInit) {
      const constructorInitializersCode = this.makeConstructorInitCode(
        constructorInitializerStatements,
        instanceInitializerNames,
        className
      );
      if (headerInfo.hasSuperclass) {
        const argsName = this.nameManager.claimFreeName("args");
        this.tokens.appendCode(
          `constructor(...${argsName}) { super(...${argsName}); ${constructorInitializersCode}; }`
        );
      } else {
        this.tokens.appendCode(`constructor() { ${constructorInitializersCode}; }`);
      }
    }
    while (!this.tokens.matchesContextIdAndLabel(TokenType.braceR, classContextId)) {
      if (fieldIndex < fields.length && this.tokens.currentIndex() === fields[fieldIndex].start) {
        let needsCloseBrace = false;
        if (this.tokens.matches1(TokenType.bracketL)) {
          this.tokens.copyTokenWithPrefix(`${fields[fieldIndex].initializerName}() {this`);
        } else if (this.tokens.matches1(TokenType.string) || this.tokens.matches1(TokenType.num)) {
          this.tokens.copyTokenWithPrefix(`${fields[fieldIndex].initializerName}() {this[`);
          needsCloseBrace = true;
        } else {
          this.tokens.copyTokenWithPrefix(`${fields[fieldIndex].initializerName}() {this.`);
        }
        while (this.tokens.currentIndex() < fields[fieldIndex].end) {
          if (needsCloseBrace && this.tokens.currentIndex() === fields[fieldIndex].equalsIndex) {
            this.tokens.appendCode("]");
          }
          this.processToken();
        }
        this.tokens.appendCode("}");
        fieldIndex++;
      } else if (rangeToRemoveIndex < rangesToRemove.length && this.tokens.currentIndex() >= rangesToRemove[rangeToRemoveIndex].start) {
        if (this.tokens.currentIndex() < rangesToRemove[rangeToRemoveIndex].end) {
          this.tokens.removeInitialToken();
        }
        while (this.tokens.currentIndex() < rangesToRemove[rangeToRemoveIndex].end) {
          this.tokens.removeToken();
        }
        rangeToRemoveIndex++;
      } else if (this.tokens.currentIndex() === constructorInsertPos) {
        this.tokens.copyToken();
        if (needsConstructorInit) {
          this.tokens.appendCode(
            `;${this.makeConstructorInitCode(
              constructorInitializerStatements,
              instanceInitializerNames,
              className
            )};`
          );
        }
        this.processToken();
      } else {
        this.processToken();
      }
    }
    this.tokens.copyExpectedToken(TokenType.braceR);
  }
  makeConstructorInitCode(constructorInitializerStatements, instanceInitializerNames, className) {
    return [
      ...constructorInitializerStatements,
      ...instanceInitializerNames.map((name) => `${className}.prototype.${name}.call(this)`)
    ].join(";");
  }
  /**
   * Normally it's ok to simply remove type tokens, but we need to be more careful when dealing with
   * arrow function return types since they can confuse the parser. In that case, we want to move
   * the close-paren to the same line as the arrow.
   *
   * See https://github.com/alangpierce/sucrase/issues/391 for more details.
   */
  processPossibleArrowParamEnd() {
    if (this.tokens.matches2(TokenType.parenR, TokenType.colon) && this.tokens.tokenAtRelativeIndex(1).isType) {
      let nextNonTypeIndex = this.tokens.currentIndex() + 1;
      while (this.tokens.tokens[nextNonTypeIndex].isType) {
        nextNonTypeIndex++;
      }
      if (this.tokens.matches1AtIndex(nextNonTypeIndex, TokenType.arrow)) {
        this.tokens.removeInitialToken();
        while (this.tokens.currentIndex() < nextNonTypeIndex) {
          this.tokens.removeToken();
        }
        this.tokens.replaceTokenTrimmingLeftWhitespace(") =>");
        return true;
      }
    }
    return false;
  }
  /**
   * An async arrow function might be of the form:
   *
   * async <
   *   T
   * >() => {}
   *
   * in which case, removing the type parameters will cause a syntax error. Detect this case and
   * move the open-paren earlier.
   */
  processPossibleAsyncArrowWithTypeParams() {
    if (!this.tokens.matchesContextual(ContextualKeyword._async) && !this.tokens.matches1(TokenType._async)) {
      return false;
    }
    const nextToken2 = this.tokens.tokenAtRelativeIndex(1);
    if (nextToken2.type !== TokenType.lessThan || !nextToken2.isType) {
      return false;
    }
    let nextNonTypeIndex = this.tokens.currentIndex() + 1;
    while (this.tokens.tokens[nextNonTypeIndex].isType) {
      nextNonTypeIndex++;
    }
    if (this.tokens.matches1AtIndex(nextNonTypeIndex, TokenType.parenL)) {
      this.tokens.replaceToken("async (");
      this.tokens.removeInitialToken();
      while (this.tokens.currentIndex() < nextNonTypeIndex) {
        this.tokens.removeToken();
      }
      this.tokens.removeToken();
      this.processBalancedCode();
      this.processToken();
      return true;
    }
    return false;
  }
  processPossibleTypeRange() {
    if (this.tokens.currentToken().isType) {
      this.tokens.removeInitialToken();
      while (this.tokens.currentToken().isType) {
        this.tokens.removeToken();
      }
      return true;
    }
    return false;
  }
  shiftMappings(mappings, prefixLength) {
    for (let i4 = 0; i4 < mappings.length; i4++) {
      const mapping = mappings[i4];
      if (mapping !== void 0) {
        mappings[i4] = mapping + prefixLength;
      }
    }
    return mappings;
  }
};

// node_modules/sucrase/dist/esm/util/formatTokens.js
var import_lines_and_columns = __toESM(require_build());

// node_modules/sucrase/dist/esm/util/getTSImportedNames.js
function getTSImportedNames(tokens) {
  const importedNames = /* @__PURE__ */ new Set();
  for (let i4 = 0; i4 < tokens.tokens.length; i4++) {
    if (tokens.matches1AtIndex(i4, TokenType._import) && !tokens.matches3AtIndex(i4, TokenType._import, TokenType.name, TokenType.eq)) {
      collectNamesForImport(tokens, i4, importedNames);
    }
  }
  return importedNames;
}
function collectNamesForImport(tokens, index, importedNames) {
  index++;
  if (tokens.matches1AtIndex(index, TokenType.parenL)) {
    return;
  }
  if (tokens.matches1AtIndex(index, TokenType.name)) {
    importedNames.add(tokens.identifierNameAtIndex(index));
    index++;
    if (tokens.matches1AtIndex(index, TokenType.comma)) {
      index++;
    }
  }
  if (tokens.matches1AtIndex(index, TokenType.star)) {
    index += 2;
    importedNames.add(tokens.identifierNameAtIndex(index));
    index++;
  }
  if (tokens.matches1AtIndex(index, TokenType.braceL)) {
    index++;
    collectNamesForNamedImport(tokens, index, importedNames);
  }
}
function collectNamesForNamedImport(tokens, index, importedNames) {
  while (true) {
    if (tokens.matches1AtIndex(index, TokenType.braceR)) {
      return;
    }
    const specifierInfo = getImportExportSpecifierInfo(tokens, index);
    index = specifierInfo.endIndex;
    if (!specifierInfo.isType) {
      importedNames.add(specifierInfo.rightName);
    }
    if (tokens.matches2AtIndex(index, TokenType.comma, TokenType.braceR)) {
      return;
    } else if (tokens.matches1AtIndex(index, TokenType.braceR)) {
      return;
    } else if (tokens.matches1AtIndex(index, TokenType.comma)) {
      index++;
    } else {
      throw new Error(`Unexpected token: ${JSON.stringify(tokens.tokens[index])}`);
    }
  }
}

// node_modules/sucrase/dist/esm/index.js
function transform(code, options) {
  validateOptions(options);
  try {
    const sucraseContext = getSucraseContext(code, options);
    const transformer = new RootTransformer(
      sucraseContext,
      options.transforms,
      Boolean(options.enableLegacyBabel5ModuleInterop),
      options
    );
    const transformerResult = transformer.transform();
    let result = { code: transformerResult.code };
    if (options.sourceMapOptions) {
      if (!options.filePath) {
        throw new Error("filePath must be specified when generating a source map.");
      }
      result = {
        ...result,
        sourceMap: computeSourceMap(
          transformerResult,
          options.filePath,
          options.sourceMapOptions,
          code,
          sucraseContext.tokenProcessor.tokens
        )
      };
    }
    return result;
  } catch (e3) {
    if (options.filePath) {
      e3.message = `Error transforming ${options.filePath}: ${e3.message}`;
    }
    throw e3;
  }
}
function getSucraseContext(code, options) {
  const isJSXEnabled2 = options.transforms.includes("jsx");
  const isTypeScriptEnabled2 = options.transforms.includes("typescript");
  const isFlowEnabled2 = options.transforms.includes("flow");
  const disableESTransforms = options.disableESTransforms === true;
  const file = parse2(code, isJSXEnabled2, isTypeScriptEnabled2, isFlowEnabled2);
  const tokens = file.tokens;
  const scopes = file.scopes;
  const nameManager = new NameManager(code, tokens);
  const helperManager = new HelperManager(nameManager);
  const tokenProcessor = new TokenProcessor(
    code,
    tokens,
    isFlowEnabled2,
    disableESTransforms,
    helperManager
  );
  const enableLegacyTypeScriptModuleInterop = Boolean(options.enableLegacyTypeScriptModuleInterop);
  let importProcessor = null;
  if (options.transforms.includes("imports")) {
    importProcessor = new CJSImportProcessor(
      nameManager,
      tokenProcessor,
      enableLegacyTypeScriptModuleInterop,
      options,
      options.transforms.includes("typescript"),
      Boolean(options.keepUnusedImports),
      helperManager
    );
    importProcessor.preprocessTokens();
    identifyShadowedGlobals(tokenProcessor, scopes, importProcessor.getGlobalNames());
    if (options.transforms.includes("typescript") && !options.keepUnusedImports) {
      importProcessor.pruneTypeOnlyImports();
    }
  } else if (options.transforms.includes("typescript") && !options.keepUnusedImports) {
    identifyShadowedGlobals(tokenProcessor, scopes, getTSImportedNames(tokenProcessor));
  }
  return { tokenProcessor, scopes, nameManager, importProcessor, helperManager };
}

// src/utils/javascript.ts
function transpile(script, language) {
  switch (language) {
    case "js":
      return script;
    case "jsx":
      return transform(script, { transforms: ["jsx"], jsxPragma: "h", jsxFragmentPragma: "Fragment" }).code;
    case "ts":
      return transform(script, { transforms: ["typescript"] }).code;
    case "tsx":
      return transform(script, {
        transforms: ["typescript", "jsx"],
        jsxPragma: "h",
        jsxFragmentPragma: "Fragment"
      }).code;
  }
}
function evalInContext(script, variables) {
  const pairs = Object.entries(variables);
  const keys = pairs.map(([key, _3]) => key);
  const values = pairs.map(([_3, value]) => value);
  return new Function(...keys, script)(...values);
}
async function asyncEvalInContext(script, variables) {
  if (script.includes("await")) {
    return evalInContext("return (async () => { " + script + " })()", variables);
  } else {
    return Promise.resolve(evalInContext(script, variables));
  }
}

// src/ui/hooks.tsx
var import_obsidian2 = require("obsidian");
function useIndexUpdates(datacore, settings) {
  const [revision, setRevision] = d2(datacore.datastore.revision);
  const debouncedRevision = T2(() => {
    var _a;
    if ((settings == null ? void 0 : settings.debounce) && settings.debounce == 0)
      return setRevision;
    else
      return (0, import_obsidian2.debounce)(setRevision, (_a = settings == null ? void 0 : settings.debounce) != null ? _a : 500);
  }, [setRevision, settings == null ? void 0 : settings.debounce]);
  y2(() => {
    const ref = datacore.on("update", debouncedRevision);
    return () => datacore.offref(ref);
  }, []);
  return revision;
}
function useFileMetadata(datacore, path, settings) {
  const indexRevision = useIndexUpdates(datacore, settings);
  return T2(() => datacore.datastore.load(path), [indexRevision, path]);
}
function tryUseFullQuery(datacore, query, settings) {
  const indexRevision = useIndexUpdates(datacore, settings);
  const internedQuery = useInterning(
    query,
    (first, second) => Literals.equals(first, second)
  );
  const internedResult = A2(void 0);
  return T2(() => {
    const newResult = datacore.datastore.search(query);
    if (!newResult.successful) {
      internedResult.current = Result.failure(newResult.error);
      return internedResult.current;
    }
    if (internedResult.current === void 0) {
      internedResult.current = Result.success(newResult.value);
      return internedResult.current;
    }
    const oldResult = internedResult.current;
    if (!oldResult.successful) {
      internedResult.current = Result.success(newResult.value);
      return internedResult.current;
    }
    if (oldResult.value.revision != newResult.value.revision || !sameObjects(oldResult.value.results, newResult.value.results)) {
      return internedResult.current = Result.success(newResult.value);
    }
    return internedResult.current;
  }, [internedQuery, indexRevision]);
}
function useFullQuery(datacore, query, settings) {
  return tryUseFullQuery(datacore, query, settings).orElseThrow((e3) => "Failed to search: " + e3);
}
function useQuery(datacore, query, settings) {
  return useFullQuery(datacore, query, settings).results;
}
function sameObjects(old, incoming) {
  if (old.length != incoming.length)
    return false;
  const olds = {};
  for (const indexable of old) {
    olds[indexable.$id] = indexable.$revision;
  }
  for (const indexable of incoming) {
    const value = olds[indexable.$id];
    if (value == void 0)
      return false;
    if (value != indexable.$revision)
      return false;
  }
  return true;
}
function useInterning(value, equality) {
  const ref = A2();
  if (ref.current === void 0 || !equality(ref.current, value)) {
    ref.current = value;
  }
  return ref.current;
}
var NO_OP_UPDATE = (x4) => {
};
function useControlledState(initialState, override, update) {
  const [state2, setState] = d2(override != null ? override : initialState);
  if (override !== void 0) {
    if (state2 != override)
      setState(override);
    return [override, update != null ? update : NO_OP_UPDATE];
  }
  const setStateWithUpdate = q2(
    (value) => {
      setState(value);
      if (update)
        update(value);
    },
    [setState, update]
  );
  return [state2, setStateWithUpdate];
}
function useAsElement(element) {
  const sourcePath = x2(CURRENT_FILE_CONTEXT);
  return T2(() => {
    if (t(element)) {
      return element;
    } else {
      return /* @__PURE__ */ u3(Lit, { sourcePath, inline: true, value: element });
    }
  }, [element]);
}

// src/ui/loading-boundary.tsx
function LoadingProgress({ datacore }) {
  var _a, _b, _c, _d;
  useIndexUpdates(datacore, { debounce: 250 });
  return /* @__PURE__ */ u3("p", { children: [
    (_b = (_a = datacore.initializer) == null ? void 0 : _a.initialized) != null ? _b : 0,
    " / ",
    (_d = (_c = datacore.initializer) == null ? void 0 : _c.targetTotal) != null ? _d : 0
  ] });
}
function LoadingBoundary({ children, datacore }) {
  const [initialized, setInitialized] = d2(datacore.initialized);
  y2(() => {
    if (initialized)
      return;
    const ref = datacore.on("initialized", () => setInitialized(true));
    return () => datacore.offref(ref);
  }, [initialized, datacore]);
  if (initialized) {
    return /* @__PURE__ */ u3(k, { children });
  } else {
    return /* @__PURE__ */ u3("div", { className: "datacore-loading-boundary", children: [
      /* @__PURE__ */ u3("h4", { className: "datacore-loading-title", children: "Datacore is getting ready..." }),
      /* @__PURE__ */ u3("div", { className: "datacore-loading-content", children: /* @__PURE__ */ u3(LoadingProgress, { datacore }) })
    ] });
  }
}
function ScriptContainer({
  executor,
  sourcePath
}) {
  const [element, setElement] = d2(void 0);
  const [error, setError] = d2(void 0);
  y2(() => {
    setElement(void 0);
    setError(void 0);
    (async () => {
      try {
        const result = await executor();
        setElement(makeRenderableElement(result, sourcePath));
      } catch (error2) {
        setError(error2 instanceof Error ? error2 : new Error(String(error2)));
      }
    })();
  }, [executor, sourcePath]);
  if (error) {
    throw error;
  }
  return /* @__PURE__ */ u3(k, { children: element != null ? element : /* @__PURE__ */ u3(ErrorMessage, { message: "< View is rendering >" }) });
}
function makeRenderableElement(object, sourcePath) {
  if (typeof object === "function") {
    return _(object, {});
  } else if (Array.isArray(object)) {
    return _(
      "div",
      {},
      object.map((x4) => makeRenderableElement(x4, sourcePath))
    );
  } else if (t(object)) {
    return object;
  } else {
    return /* @__PURE__ */ u3(Lit, { value: object, sourcePath });
  }
}

// src/ui/javascript.tsx
var DatacoreJSRenderer = class extends import_obsidian3.MarkdownRenderChild {
  constructor(api, container, path, script, language) {
    super(container);
    this.api = api;
    this.container = container;
    this.path = path;
    this.script = script;
    this.language = language;
    this.loaded = false;
  }
  async onload() {
    this.loaded = true;
    try {
      const primitiveScript = transpile(this.script, this.language);
      const renderer = async () => {
        return await asyncEvalInContext(primitiveScript, {
          dc: this.api,
          h: _,
          Fragment: k
        });
      };
      this.renderScript(renderer);
      this.registerEvent(
        this.api.core.on("rename", (newPath, oldPath) => {
          if (oldPath === this.path) {
            this.path = this.api.path = newPath;
            this.renderScript(renderer);
          }
        })
      );
    } catch (ex) {
      E(
        /* @__PURE__ */ u3(ErrorMessage, { message: "Datacore failed to render the code block.", error: "" + ex }),
        this.container
      );
    }
  }
  /** Lazily renders a script, catching errors automatically. */
  renderScript(renderer) {
    E(
      /* @__PURE__ */ u3(
        DatacoreContextProvider,
        {
          app: this.api.app,
          component: this,
          datacore: this.api.core,
          settings: this.api.core.settings,
          children: /* @__PURE__ */ u3(CURRENT_FILE_CONTEXT.Provider, { value: this.path, children: /* @__PURE__ */ u3(SimpleErrorBoundary, { message: "The datacore script failed to execute.", children: /* @__PURE__ */ u3(LoadingBoundary, { datacore: this.api.core, children: /* @__PURE__ */ u3(ScriptContainer, { executor: renderer, sourcePath: this.path }) }) }) })
        }
      ),
      this.container
    );
  }
  onunload() {
    if (this.loaded)
      bn(this.container);
    this.loaded = false;
  }
};

// src/api/ui/layout.tsx
function Stack(props) {
  const { className, justify, align, style, children, ...rest } = props;
  const extraStyle = T2(() => {
    let style2 = "";
    if (justify)
      style2 += `justify-content: ${justify};`;
    if (align)
      style2 += `align-items: ${align};`;
    return style2.length == 0 ? void 0 : style2;
  }, [justify, align]);
  return /* @__PURE__ */ u3(
    "div",
    {
      className: className ? className + " dc-stack" : "dc-stack",
      style: style ? extraStyle + style : extraStyle,
      ...rest,
      children
    }
  );
}
function Group(props) {
  const { className, justify, align, style, children, ...rest } = props;
  const extraStyle = T2(() => {
    let style2 = "";
    if (justify)
      style2 += `justify-content: ${justify};`;
    if (align)
      style2 += `align-items: ${align};`;
    return style2.length == 0 ? void 0 : style2;
  }, [justify, align]);
  return /* @__PURE__ */ u3(
    "div",
    {
      className: className ? className + " dc-group" : "dc-group",
      style: style ? extraStyle + style : extraStyle,
      ...rest,
      children
    }
  );
}

// src/api/ui/basics.tsx
var import_obsidian4 = require("obsidian");
var INTENT_CLASSES = {
  error: "dc-intent-error",
  warn: "dc-intent-warn",
  info: "dc-intent-info",
  success: "dc-intent-success"
};
function Button(props) {
  const { className, intent, children, ...forwardingProps } = props;
  return /* @__PURE__ */ u3(
    "button",
    {
      className: combineClasses("dc-button", intent ? INTENT_CLASSES[intent] : void 0, className),
      ...forwardingProps,
      children
    }
  );
}
function Textbox(props) {
  var _a;
  const { className, children, ...forwardingProps } = props;
  return /* @__PURE__ */ u3("input", { type: (_a = props.type) != null ? _a : "text", className: combineClasses("dc-textbox", className), ...forwardingProps });
}
function Checkbox(props) {
  const {
    className,
    disabled,
    defaultChecked,
    checked: isChecked,
    onCheckChange,
    children,
    ...forwardingProps
  } = props;
  const [checked, setChecked] = useControlledState(defaultChecked != null ? defaultChecked : false, isChecked, onCheckChange);
  const onChange = q2(
    (event) => setChecked(event.currentTarget.checked),
    [setChecked]
  );
  return /* @__PURE__ */ u3("label", { className: combineClasses("dc-checkbox", disabled ? "dc-checkbox-disabled" : void 0, className), children: [
    /* @__PURE__ */ u3(
      "input",
      {
        type: "checkbox",
        defaultChecked,
        checked,
        disabled,
        onChange,
        ...forwardingProps
      }
    ),
    children
  ] });
}
function Slider(props) {
  const { className, min = 0, max = 10, step = 1, value, defaultValue, onValueChange, ...forwardingProps } = props;
  const [slider, setSlider] = useControlledState(defaultValue != null ? defaultValue : 0, value, onValueChange);
  const onChange = q2(
    (event) => setSlider(parseInt(event.currentTarget.value)),
    [setSlider]
  );
  return /* @__PURE__ */ u3(
    "input",
    {
      type: "range",
      "aria-label": slider.toString(),
      className: combineClasses("dc-slider", className),
      min,
      max,
      step,
      value: slider,
      onChange,
      ...forwardingProps
    }
  );
}
function Switch(props) {
  const { className, disabled, defaultChecked, checked, onToggleChange, ...forwardingProps } = props;
  const [toggled, setToggled] = useControlledState(defaultChecked != null ? defaultChecked : false, checked, onToggleChange);
  const onChange = q2(
    (event) => setToggled(event.currentTarget.checked),
    [setToggled]
  );
  return /* @__PURE__ */ u3(
    "label",
    {
      className: combineClasses(
        "dc-switch checkbox-container",
        toggled ? "is-enabled" : void 0,
        disabled ? "dc-switch-disabled" : void 0,
        className
      ),
      children: /* @__PURE__ */ u3(
        "input",
        {
          type: "checkbox",
          className: "dc-switch-input",
          defaultChecked,
          checked: toggled,
          disabled,
          onChange,
          ...forwardingProps
        }
      )
    }
  );
}
function VanillaSelect(props) {
  const { className, options = [], value, defaultValue, onValueChange, ...forwardingProps } = props;
  const [selectedValue, setSelectedValue] = useControlledState(defaultValue != null ? defaultValue : "", value, onValueChange);
  return /* @__PURE__ */ u3(
    "select",
    {
      className: combineClasses("dc-select dropdown", className),
      value: selectedValue,
      onChange: (e3) => {
        setSelectedValue(e3.currentTarget.value);
      },
      ...forwardingProps,
      children: options.map((option) => /* @__PURE__ */ u3("option", { value: option.value, children: option.label }, option.value))
    }
  );
}
function Icon(props) {
  const { className, icon } = props;
  const ref = Rn.createRef();
  Rn.useEffect(() => {
    if (ref.current) {
      (0, import_obsidian4.setIcon)(ref.current, icon);
    }
  }, [ref]);
  return /* @__PURE__ */ u3("span", { ref, className: combineClasses("dc-icon", className), "data-icon": icon });
}
function combineClasses(fixed, ...rest) {
  const nonempty = rest.filter((c3) => c3 !== void 0);
  if (nonempty.length === 0)
    return fixed;
  return [fixed, ...nonempty].join(" ");
}

// src/api/ui/views/paging.tsx
function RawControlledPager({
  page,
  setPage,
  totalPages
}) {
  totalPages = Math.max(1, totalPages);
  const realPage = clamp(page, 0, totalPages - 1);
  const visiblePages = T2(() => splitPages(realPage, totalPages), [realPage, totalPages]);
  return /* @__PURE__ */ u3("div", { className: "dc-paging-control", children: [
    /* @__PURE__ */ u3(
      "button",
      {
        className: "dc-paging-control-page",
        onClick: () => page != 0 && setPage(page - 1),
        disabled: page == 0,
        children: /* @__PURE__ */ u3(
          "svg",
          {
            "aria-hidden": "true",
            fill: "none",
            focusable: "false",
            height: "1em",
            role: "presentation",
            viewBox: "0 0 24 24",
            width: "1em",
            children: /* @__PURE__ */ u3(
              "path",
              {
                d: "M15.5 19l-7-7 7-7",
                stroke: "currentColor",
                "stroke-linecap": "round",
                "stroke-linejoin": "round",
                "stroke-width": "1.5"
              }
            )
          }
        )
      }
    ),
    visiblePages.map((pages, i4) => /* @__PURE__ */ u3(k, { children: [
      i4 > 0 && /* @__PURE__ */ u3(
        "button",
        {
          className: "dc-paging-control-page dc-paging-control-separator",
          onClick: () => setPage(realPage + (isLeftSeperator(realPage, visiblePages.length, i4) ? -5 : 5)),
          children: [
            /* @__PURE__ */ u3(
              "svg",
              {
                "aria-hidden": "true",
                fill: "none",
                height: "1em",
                "shape-rendering": "geometricPrecision",
                "stroke-linecap": "round",
                "stroke-linejoin": "round",
                "stroke-width": "1.5",
                viewBox: "0 0 24 24",
                width: "1em",
                class: "dc-paging-control-ellipsis",
                children: [
                  /* @__PURE__ */ u3("circle", { cx: "12", cy: "12", fill: "currentColor", r: "1" }),
                  /* @__PURE__ */ u3("circle", { cx: "19", cy: "12", fill: "currentColor", r: "1" }),
                  /* @__PURE__ */ u3("circle", { cx: "5", cy: "12", fill: "currentColor", r: "1" })
                ]
              }
            ),
            /* @__PURE__ */ u3(
              "svg",
              {
                "aria-hidden": "true",
                fill: "none",
                focusable: "false",
                height: "1em",
                role: "presentation",
                "shape-rendering": "geometricPrecision",
                stroke: "currentColor",
                "stroke-linecap": "round",
                "stroke-linejoin": "round",
                "stroke-width": "1.5",
                viewBox: "0 0 24 24",
                width: "1em",
                class: `dc-paging-control-leap-${isLeftSeperator(realPage, visiblePages.length, i4) ? "left" : "right"}`,
                children: [
                  /* @__PURE__ */ u3("path", { d: "M13 17l5-5-5-5" }),
                  /* @__PURE__ */ u3("path", { d: "M6 17l5-5-5-5" })
                ]
              }
            )
          ]
        }
      ),
      pages.map((p3) => /* @__PURE__ */ u3(
        "button",
        {
          className: `dc-paging-control-page ${p3 === realPage ? " dc-paging-control-page-active" : ""}`,
          onClick: () => setPage(p3),
          children: p3 + 1
        }
      ))
    ] })),
    /* @__PURE__ */ u3(
      "button",
      {
        className: "dc-paging-control-page",
        onClick: () => page !== totalPages - 1 && setPage(page + 1),
        disabled: page === totalPages - 1,
        children: /* @__PURE__ */ u3(
          "svg",
          {
            "aria-hidden": "true",
            fill: "none",
            focusable: "false",
            height: "1em",
            role: "presentation",
            viewBox: "0 0 24 24",
            width: "1em",
            children: /* @__PURE__ */ u3(
              "path",
              {
                d: "M8.5 5l7 7-7 7",
                stroke: "currentColor",
                "stroke-linecap": "round",
                "stroke-linejoin": "round",
                "stroke-width": "1.5"
              }
            )
          }
        )
      }
    )
  ] });
}
var ControlledPager = Rn.memo(RawControlledPager);
function usePaging({
  initialPage = 0,
  pageSize,
  elements
}) {
  const totalPages = Math.max(1, Math.ceil(elements / pageSize));
  const [pageStart, setPageStart] = d2(() => clamp(initialPage, 0, totalPages - 1));
  const setBoundedPage = q2(
    (page2) => setPageStart(clamp(page2, 0, totalPages - 1) * pageSize),
    [pageSize, totalPages]
  );
  const page = clamp(Math.floor(pageStart / pageSize), 0, totalPages - 1);
  return [page, totalPages, setBoundedPage];
}
function useDatacorePaging({
  initialPage = 0,
  paging,
  scrollOnPageChange,
  elements,
  container
}) {
  const settings = x2(SETTINGS_CONTEXT);
  const pageSize = typeof paging === "number" ? paging : settings.defaultPageSize;
  const pagingEnabled = typeof paging === "number" || paging === true;
  const shouldScroll = typeof scrollOnPageChange === "number" && scrollOnPageChange >= pageSize || !!(scrollOnPageChange != null ? scrollOnPageChange : settings.scrollOnPageChange);
  const [page, totalPages, rawSetPage] = usePaging({ initialPage, pageSize, elements });
  const setPage = q2(
    (newPage) => {
      var _a;
      if (page != newPage && container && shouldScroll) {
        (_a = container.current) == null ? void 0 : _a.scrollIntoView({
          behavior: "smooth",
          block: "start",
          inline: "nearest"
        });
      }
      rawSetPage(newPage);
    },
    [page, container, shouldScroll, rawSetPage]
  );
  return { enabled: pagingEnabled, scroll: shouldScroll, page, pageSize, totalPages, setPage };
}
function clamp(input2, min, max) {
  if (input2 < min)
    return min;
  if (input2 > max)
    return max;
  return input2;
}
function splitPages(page, totalPages) {
  if (totalPages < 12)
    return [Array.from({ length: totalPages }, (_3, i4) => i4)];
  if (page < 5)
    return [
      [0, 1, 2, 3, 4, 5, 6, 7],
      [totalPages - 2, totalPages - 1]
    ];
  else if (page > totalPages - 6)
    return [
      [0, 1],
      [
        totalPages - 8,
        totalPages - 7,
        totalPages - 6,
        totalPages - 5,
        totalPages - 4,
        totalPages - 3,
        totalPages - 2,
        totalPages - 1
      ]
    ];
  else
    return [
      [0, 1],
      [page - 2, page - 1, page, page + 1, page + 2],
      [totalPages - 2, totalPages - 1]
    ];
}
function isLeftSeperator(realPage, visiblePagesLength, seperatorIndex) {
  if (visiblePagesLength === 2) {
    if (realPage < 5) {
      return false;
    } else {
      return true;
    }
  } else {
    if (seperatorIndex === 1) {
      return true;
    } else {
      return false;
    }
  }
}

// src/api/ui/views/table.tsx
function TableView(props) {
  const columns = useInterning(props.columns, (a3, b3) => {
    if (a3.length != b3.length)
      return false;
    return a3.every((value, index) => value == b3[index]);
  });
  const tableRef = A2(null);
  const totalElements = T2(() => Groupings.count(props.rows), [props.rows]);
  const paging = useDatacorePaging({
    initialPage: 0,
    paging: props.paging,
    scrollOnPageChange: props.scrollOnPaging,
    elements: totalElements,
    container: tableRef
  });
  const pagedRows = T2(() => {
    if (paging.enabled)
      return Groupings.slice(props.rows, paging.page * paging.pageSize, (paging.page + 1) * paging.pageSize);
    else
      return props.rows;
  }, [paging.page, paging.pageSize, paging.enabled, props.rows]);
  const groupings = T2(() => {
    if (!props.groupings)
      return void 0;
    if (Array.isArray(props.groupings))
      return props.groupings;
    if (Literals.isFunction(props.groupings))
      return [{ render: props.groupings }];
    else
      return [props.groupings];
  }, [props.groupings]);
  return /* @__PURE__ */ u3("div", { ref: tableRef, children: [
    /* @__PURE__ */ u3("table", { className: "datacore-table", children: [
      /* @__PURE__ */ u3("thead", { children: /* @__PURE__ */ u3("tr", { className: "datacore-table-header-row", children: columns.map((col) => /* @__PURE__ */ u3(TableViewHeaderCell, { column: col })) }) }),
      /* @__PURE__ */ u3("tbody", { children: pagedRows.map((row) => /* @__PURE__ */ u3(VanillaRowGroup, { level: 0, groupings, columns, element: row })) })
    ] }),
    paging.enabled && /* @__PURE__ */ u3(ControlledPager, { page: paging.page, totalPages: paging.totalPages, setPage: paging.setPage })
  ] });
}
function TableViewHeaderCell({ column }) {
  const header = T2(() => {
    if (!column.title) {
      return column.id;
    } else if (typeof column.title === "function") {
      return column.title();
    } else {
      return column.title;
    }
  }, [column.id, column.title]);
  const realWidth = T2(
    () => column.width === "minimum" ? "1px" : column.width === "maximum" ? "auto" : column.width,
    [column.width]
  );
  return /* @__PURE__ */ u3("th", { style: { width: realWidth }, className: "datacore-table-header-cell", children: /* @__PURE__ */ u3("div", { className: "datacore-table-header-title", children: header }) });
}
function VanillaRowGroup({
  level,
  columns,
  element,
  groupings
}) {
  if (Groupings.isElementGroup(element)) {
    const groupingConfig = groupings == null ? void 0 : groupings[Math.min(groupings.length - 1, level)];
    return /* @__PURE__ */ u3(k, { children: [
      /* @__PURE__ */ u3(TableGroupHeader, { level, value: element, width: columns.length, config: groupingConfig }),
      element.rows.map((row) => /* @__PURE__ */ u3(VanillaRowGroup, { level: level + 1, columns, element: row }))
    ] });
  } else {
    return /* @__PURE__ */ u3(TableRow, { level, row: element, columns });
  }
}
function TableGroupHeader({
  level,
  value,
  width,
  config
}) {
  const sourcePath = x2(CURRENT_FILE_CONTEXT);
  const rawRenderable = T2(() => {
    if (config == null ? void 0 : config.render)
      return config.render(value.key, value.rows);
    else
      return /* @__PURE__ */ u3("h2", { children: /* @__PURE__ */ u3(Lit, { sourcePath, inline: true, value: value.key }) });
  }, [config == null ? void 0 : config.render, value.key, value.rows]);
  const renderable = useAsElement(rawRenderable);
  return /* @__PURE__ */ u3("tr", { className: "datacore-table-group-header", children: /* @__PURE__ */ u3("td", { colSpan: width, children: renderable }) });
}
function TableRow({ level, row, columns }) {
  return /* @__PURE__ */ u3("tr", { className: "datacore-table-row", style: level ? `padding-left: ${level * 5}px` : void 0, children: columns.map((col) => /* @__PURE__ */ u3(TableRowCell, { row, column: col })) });
}
function TableRowCell({ row, column }) {
  const value = T2(() => column.value(row), [row, column.value]);
  const renderable = T2(() => {
    if (column.render)
      return column.render(value, row);
    else
      return value;
  }, [row, column.render, value]);
  const rendered = useAsElement(renderable);
  return /* @__PURE__ */ u3("td", { className: "datacore-table-cell", children: rendered });
}

// src/api/ui/views/callout.tsx
var METADATA_SPLIT_REGEX = /\|(.*)/s;
function Callout({
  collapsible = true,
  open: openProp,
  initialOpen,
  onOpenChange,
  title,
  icon,
  children,
  type
}) {
  var _a, _b;
  const [open, setOpen] = useControlledState(initialOpen != null ? initialOpen : true, openProp, onOpenChange);
  return /* @__PURE__ */ u3(
    "div",
    {
      "data-callout-metadata": (_a = type == null ? void 0 : type.split(METADATA_SPLIT_REGEX)) == null ? void 0 : _a[1],
      "data-callout": (_b = type == null ? void 0 : type.split(METADATA_SPLIT_REGEX)) == null ? void 0 : _b[0],
      "data-callout-fold": open ? "+" : "-",
      className: combineClasses("datacore", "callout", collapsible ? "is-collapsible" : void 0),
      children: [
        /* @__PURE__ */ u3("div", { className: "callout-title", onClick: () => collapsible && setOpen(!open), children: [
          icon && /* @__PURE__ */ u3("div", { className: "callout-icon", children: icon }),
          /* @__PURE__ */ u3("div", { className: "callout-title-inner", children: title }),
          collapsible && /* @__PURE__ */ u3("div", { className: combineClasses("callout-fold", !open ? "is-collapsed" : void 0), children: /* @__PURE__ */ u3(
            "svg",
            {
              xmlns: "http://www.w3.org/2000/svg",
              width: "24",
              height: "24",
              viewBox: "0 0 24 24",
              fill: "none",
              stroke: "currentColor",
              "stroke-width": "2",
              "stroke-linecap": "round",
              "stroke-linejoin": "round",
              class: "svg-icon lucide-chevron-down",
              children: /* @__PURE__ */ u3("path", { d: "m6 9 6 6 6-6" })
            }
          ) })
        ] }),
        open && /* @__PURE__ */ u3("div", { className: "callout-content", children })
      ]
    }
  );
}

// src/api/data-array.ts
var _DataArrayImpl = class {
  constructor(values, defaultComparator = DataArray.defaultComparator) {
    this.values = values;
    this.defaultComparator = defaultComparator;
    this.length = values.length;
  }
  static wrap(arr, defaultComparator = DataArray.defaultComparator) {
    return new Proxy(
      new _DataArrayImpl(arr, defaultComparator),
      _DataArrayImpl.ARRAY_PROXY
    );
  }
  /** Wraps the array into a data array with the current comparator. */
  lwrap(values) {
    return _DataArrayImpl.wrap(values, this.defaultComparator);
  }
  chain(op) {
    return op(this);
  }
  where(predicate) {
    return this.lwrap(this.values.filter(predicate));
  }
  filter(predicate) {
    return this.where(predicate);
  }
  map(f4) {
    return this.lwrap(this.values.map(f4));
  }
  flatMap(f4) {
    let result = [];
    for (let index = 0; index < this.length; index++) {
      let value = f4(this.values[index], index, this.values);
      if (!value || value.length == 0)
        continue;
      for (let r3 of value)
        result.push(r3);
    }
    return this.lwrap(result);
  }
  mutate(f4) {
    for (let index = 0; index < this.values.length; index++) {
      f4(this.values[index], index, this.values);
    }
    return this;
  }
  limit(count) {
    return this.lwrap(this.values.slice(0, count));
  }
  slice(start, end) {
    return this.lwrap(this.values.slice(start, end));
  }
  concat(other) {
    return this.lwrap(this.values.concat(other.values));
  }
  /** Return the first index of the given (optionally starting the search) */
  indexOf(element, fromIndex) {
    return this.findIndex((e3) => this.defaultComparator(e3, element) == 0, fromIndex);
  }
  /** Return the first element that satisfies the given predicate. */
  find(pred) {
    let index = this.findIndex(pred);
    if (index == -1)
      return void 0;
    else
      return this.values[index];
  }
  findIndex(pred, fromIndex) {
    for (let index = fromIndex != null ? fromIndex : 0; index < this.length; index++) {
      if (pred(this.values[index], index, this.values))
        return index;
    }
    return -1;
  }
  includes(element) {
    return this.indexOf(element, 0) != -1;
  }
  join(sep) {
    return this.map((s4) => Literals.toString(s4)).array().join(sep != null ? sep : ", ");
  }
  sort(key, direction, comparator) {
    if (this.values.length == 0)
      return this;
    let realComparator = comparator != null ? comparator : this.defaultComparator;
    let realKey = key != null ? key : (l4) => l4;
    let copy = [].concat(this.array()).map((elem, index) => {
      return { index, value: elem };
    });
    copy.sort((a3, b3) => {
      let aKey = realKey(a3.value, a3.index, this.values);
      let bKey = realKey(b3.value, b3.index, this.values);
      return direction === "desc" ? -realComparator(aKey, bKey) : realComparator(aKey, bKey);
    });
    return this.lwrap(copy.map((e3) => e3.value));
  }
  sortInPlace(key, direction, comparator) {
    if (this.values.length == 0)
      return this;
    let realComparator = comparator != null ? comparator : this.defaultComparator;
    let realKey = key != null ? key : (l4) => l4;
    this.values.sort((a3, b3) => {
      let aKey = realKey(a3);
      let bKey = realKey(b3);
      return direction == "desc" ? -realComparator(aKey, bKey) : realComparator(aKey, bKey);
    });
    return this;
  }
  groupBy(key, comparator) {
    if (this.values.length == 0)
      return this.lwrap([]);
    let intermediate = this.sort(key, "asc", comparator);
    comparator = comparator != null ? comparator : this.defaultComparator;
    let result = [];
    let currentRow = [intermediate[0]];
    let current = key(intermediate[0], 0, intermediate.values);
    for (let index = 1; index < intermediate.length; index++) {
      let newKey = key(intermediate[index], index, intermediate.values);
      if (comparator(current, newKey) != 0) {
        result.push({ key: current, rows: currentRow });
        current = newKey;
        currentRow = [intermediate[index]];
      } else {
        currentRow.push(intermediate[index]);
      }
    }
    result.push({ key: current, rows: currentRow });
    return this.lwrap(result);
  }
  groupIn(key, comparator) {
    if (Groupings.isGrouping(this.values)) {
      return this.map((v3) => {
        return {
          key: v3.key,
          rows: this.lwrap(v3.rows).groupIn(key).array()
        };
      });
    } else {
      return this.groupBy(key, comparator);
    }
  }
  distinct(key, comparator) {
    if (this.values.length == 0)
      return this;
    let realKey = key != null ? key : (x4) => x4;
    let intermediate = this.map((x4, index) => {
      return { key: realKey(x4, index, this.values), value: x4 };
    }).sort((x4) => x4.key, "asc", comparator);
    comparator = comparator != null ? comparator : this.defaultComparator;
    let result = [intermediate[0].value];
    for (let index = 1; index < intermediate.length; index++) {
      if (comparator(intermediate[index - 1].key, intermediate[index].key) != 0) {
        result.push(intermediate[index].value);
      }
    }
    return this.lwrap(result);
  }
  every(f4) {
    return this.values.every(f4);
  }
  some(f4) {
    return this.values.some(f4);
  }
  none(f4) {
    return this.values.every((v3, i4, a3) => !f4(v3, i4, a3));
  }
  first() {
    return this.values.length > 0 ? this.values[0] : void 0;
  }
  last() {
    return this.values.length > 0 ? this.values[this.values.length - 1] : void 0;
  }
  to(key) {
    let result = [];
    for (let child of this.values) {
      let value = child[key];
      if (value === void 0 || value === null)
        continue;
      if (Array.isArray(value) || DataArray.isDataArray(value))
        value.forEach((v3) => result.push(v3));
      else
        result.push(value);
    }
    return this.lwrap(result);
  }
  into(key) {
    let result = [];
    for (let child of this.values) {
      let value = child[key];
      if (value === void 0 || value === null)
        continue;
      result.push(value);
    }
    return this.lwrap(result);
  }
  expand(key) {
    let result = [];
    let queue = [].concat(this.values);
    while (queue.length > 0) {
      let next2 = queue.pop();
      let value = next2[key];
      if (value === void 0 || value === null)
        continue;
      if (Array.isArray(value))
        value.forEach((v3) => queue.push(v3));
      else if (value instanceof _DataArrayImpl)
        value.forEach((v3) => queue.push(v3));
      else
        queue.push(value);
      result.push(next2);
    }
    return this.lwrap(result);
  }
  forEach(f4) {
    for (let index = 0; index < this.values.length; index++) {
      f4(this.values[index], index, this.values);
    }
  }
  array() {
    return [].concat(this.values);
  }
  [Symbol.iterator]() {
    return this.values[Symbol.iterator]();
  }
  toString() {
    return "[" + this.values.join(", ") + "]";
  }
};
var DataArrayImpl = _DataArrayImpl;
DataArrayImpl.ARRAY_FUNCTIONS = /* @__PURE__ */ new Set([
  "chain",
  "where",
  "filter",
  "map",
  "flatMap",
  "mutate",
  "slice",
  "concat",
  "indexOf",
  "limit",
  "find",
  "findIndex",
  "includes",
  "join",
  "sort",
  "sortInPlace",
  "groupBy",
  "groupIn",
  "distinct",
  "every",
  "some",
  "none",
  "first",
  "last",
  "to",
  "into",
  "lwrap",
  "expand",
  "forEach",
  "length",
  "values",
  "array",
  "defaultComparator",
  "toString",
  "settings"
]);
DataArrayImpl.ARRAY_PROXY = {
  get: function(target, prop, reciever) {
    if (typeof prop === "symbol")
      return target[prop];
    else if (typeof prop === "number")
      return target.values[prop];
    else if (prop === "constructor")
      return target.values.constructor;
    else if (!isNaN(parseInt(prop)))
      return target.values[parseInt(prop)];
    else if (_DataArrayImpl.ARRAY_FUNCTIONS.has(prop.toString()))
      return target[prop.toString()];
    return target.to(prop);
  }
};
var DataArray;
((DataArray2) => {
  function wrap(raw) {
    if (isDataArray(raw))
      return raw;
    return DataArrayImpl.wrap(raw);
  }
  DataArray2.wrap = wrap;
  function from(raw) {
    if (isDataArray(raw))
      return raw;
    let data = [];
    for (let elem of raw)
      data.push(elem);
    return DataArrayImpl.wrap(data);
  }
  DataArray2.from = from;
  function isDataArray(obj) {
    return obj instanceof DataArrayImpl;
  }
  DataArray2.isDataArray = isDataArray;
  function defaultComparator(first, second) {
    return Literals.compare(first, second);
  }
  DataArray2.defaultComparator = defaultComparator;
})(DataArray || (DataArray = {}));
var oldArrayIsArray = Array.isArray;
Array.isArray = (arg) => {
  return oldArrayIsArray(arg) || DataArray.isDataArray(arg);
};

// src/api/coerce.ts
var Coerce;
((Coerce2) => {
  function string2(value) {
    const wrapped = Literals.wrapValue(value);
    if (!wrapped)
      return void 0;
    switch (wrapped.type) {
      case "string":
        return wrapped.value;
      case "number":
        return "" + wrapped.value;
      case "date":
        return renderMinimalDate(wrapped.value, "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss");
      case "link":
        return wrapped.value.markdown();
      case "boolean":
        return "" + wrapped.value;
      default:
        return void 0;
    }
  }
  Coerce2.string = string2;
  function boolean(value) {
    if (typeof value === "boolean")
      return value;
    else if (typeof value === "string" && value.toLowerCase() === "true")
      return true;
    else if (typeof value === "string" && value.toLowerCase() === "false")
      return false;
    else
      return void 0;
  }
  Coerce2.boolean = boolean;
  function number(value) {
    if (typeof value === "number")
      return value;
    else if (typeof value === "string") {
      const parsed = parseFloat(value);
      if (!isNaN(parsed))
        return parsed;
      else
        return void 0;
    } else
      return void 0;
  }
  Coerce2.number = number;
  function date(value) {
    if (value instanceof DateTime)
      return value;
    else if (typeof value === "string") {
      const parsed = PRIMITIVES.datePlus.parse(value);
      if (parsed.status)
        return parsed.value;
      else
        return void 0;
    } else
      return void 0;
  }
  Coerce2.date = date;
  function duration(value) {
    if (value instanceof Duration)
      return value;
    else if (typeof value === "string") {
      const parsed = PRIMITIVES.duration.parse(value);
      if (parsed.status)
        return parsed.value;
      else
        return void 0;
    } else
      return void 0;
  }
  Coerce2.duration = duration;
  function link(value) {
    if (value instanceof Link)
      return value;
    else if (typeof value === "string") {
      const parsed = PRIMITIVES.embedLink.parse(value);
      if (parsed.status)
        return parsed.value;
      else
        return void 0;
    } else
      return void 0;
  }
  Coerce2.link = link;
  function array2(value) {
    if (Array.isArray(value))
      return value;
    else
      return [value];
  }
  Coerce2.array = array2;
})(Coerce || (Coerce = {}));

// src/index/types/indexable.ts
var LINKABLE_TYPE = "linkable";
var FILE_TYPE = "file";
var TAGGABLE_TYPE = "taggable";
var LINKBEARING_TYPE = "links";
var INDEXABLE_EXTENSIONS = /* @__PURE__ */ new Set(["md", "markdown", "canvas"]);

// src/expression/field.ts
var FIELDBEARING_TYPE = "fields";
var Fieldbearings;
((Fieldbearings2) => {
  function isFieldbearing(object) {
    return object != null && typeof object === "object" && "field" in object && typeof object["field"] == "function";
  }
  Fieldbearings2.isFieldbearing = isFieldbearing;
  function get2(object, key) {
    var _a;
    if (isFieldbearing(object))
      return (_a = object.field(key)) == null ? void 0 : _a.value;
    else
      return object[key];
  }
  Fieldbearings2.get = get2;
})(Fieldbearings || (Fieldbearings = {}));
var Extractors;
((Extractors2) => {
  function isValidIntrinsic(object, key, exclude) {
    if ((exclude == null ? void 0 : exclude.has(key)) || !key.startsWith("$"))
      return false;
    const value = object[key];
    if (Literals.isFunction(value))
      return false;
    return true;
  }
  function* prototypeKeys(object) {
    for (const key of Object.keys(object))
      yield key;
    let proto = Object.getPrototypeOf(object);
    while (proto) {
      for (const key of Object.getOwnPropertyNames(proto))
        yield key;
      proto = Object.getPrototypeOf(proto);
    }
  }
  function intrinsics(except) {
    return (maybeObject, key) => {
      var _a, _b;
      const object = maybeObject;
      if (key == null) {
        const fields = [];
        for (const key2 of prototypeKeys(object)) {
          if (!isValidIntrinsic(object, key2, except))
            continue;
          fields.push({
            key: key2,
            value: object[key2],
            provenance: { type: "intrinsic", file: object.$file, revision: (_a = object.$revision) != null ? _a : 0 }
          });
        }
        return fields;
      } else {
        if (key in object && isValidIntrinsic(object, key, except)) {
          const entry = {
            key,
            value: object[key],
            provenance: { type: "intrinsic", file: object.$file, revision: (_b = object.$revision) != null ? _b : 0 }
          };
          return [entry];
        }
        return [];
      }
    };
  }
  Extractors2.intrinsics = intrinsics;
  function frontmatter(front) {
    return (object, key) => {
      var _a, _b;
      const frontmatter2 = front(object);
      if (!frontmatter2)
        return [];
      if (key == null) {
        const fields = [];
        for (const key2 of Object.keys(frontmatter2)) {
          const entry = frontmatter2[key2];
          fields.push({
            key: entry.key.toLowerCase(),
            value: entry.value,
            raw: entry.raw,
            provenance: {
              type: "frontmatter",
              file: object.$file,
              key: entry.key,
              revision: (_a = object.$revision) != null ? _a : 0
            }
          });
        }
        return fields;
      } else {
        key = key.toLowerCase();
        if (!(key in frontmatter2))
          return [];
        const entry = frontmatter2[key];
        return [
          {
            key,
            value: entry.value,
            raw: entry.raw,
            provenance: { type: "frontmatter", file: object.$file, key, revision: (_b = object.$revision) != null ? _b : 0 }
          }
        ];
      }
    };
  }
  Extractors2.frontmatter = frontmatter;
  function inlineFields(inlineMap) {
    return (object, key) => {
      var _a, _b;
      const map = inlineMap(object);
      if (!map)
        return [];
      if (key == null) {
        const fields = [];
        for (const field of Object.values(map)) {
          const provenance = {
            type: "inline-field",
            file: object.$file,
            line: field.position.line,
            key: field.key,
            revision: (_a = object.$revision) != null ? _a : 0
          };
          fields.push({
            key: field.key.toLowerCase(),
            value: field.value,
            raw: field.raw,
            provenance
          });
        }
        return fields;
      } else {
        key = key.toLowerCase();
        if (!(key in map))
          return [];
        const field = map[key];
        const provenance = {
          type: "inline-field",
          file: object.$file,
          line: field.position.line,
          key: field.key,
          revision: (_b = object.$revision) != null ? _b : 0
        };
        return [
          {
            key,
            value: field.value,
            raw: field.raw,
            provenance
          }
        ];
      }
    };
  }
  Extractors2.inlineFields = inlineFields;
  function merge(...extractors) {
    return (object, key) => {
      if (key == null) {
        const used = /* @__PURE__ */ new Set();
        const fields = [];
        for (const extractor of extractors) {
          for (const field of extractor(object, void 0)) {
            if (used.has(field.key.toLowerCase()))
              continue;
            used.add(field.key.toLowerCase());
            fields.push(field);
          }
        }
        return fields;
      } else {
        for (const extractor of extractors) {
          const field = extractor(object, key);
          if (field && field.length > 0)
            return field;
        }
        return [];
      }
    };
  }
  Extractors2.merge = merge;
})(Extractors || (Extractors = {}));

// src/index/import/inline-field.ts
var P6 = __toESM(require_parsimmon_umd_min());

// src/utils/data.ts
function mapObjectValues(object, func) {
  const result = {};
  for (const [key, value] of Object.entries(object)) {
    result[key] = func(value);
  }
  return result;
}

// src/index/types/json/common.ts
var JsonConversion;
((JsonConversion2) => {
  JsonConversion2.NOOP_NORMALIZER = (input2) => input2;
  function json(literal) {
    const wrapped = Literals.wrapValue(literal);
    if (!wrapped)
      return null;
    switch (wrapped == null ? void 0 : wrapped.type) {
      case "array":
        return wrapped.value.map(JsonConversion2.json);
      case "object":
        return mapObjectValues(wrapped.value, JsonConversion2.json);
      case "date":
        return { $_type: "date", value: wrapped.value.toISO({ extendedZone: true, includeOffset: true }) };
      case "link":
        return { $_type: "link", value: wrapped.value.toObject() };
      case "duration":
        return { $_type: "duration", value: wrapped.value.toISO() };
      case "boolean":
      case "number":
      case "string":
        return wrapped.value;
      case "function":
      case "null":
        return null;
    }
  }
  JsonConversion2.json = json;
  function value(json2, normalizer = JsonConversion2.NOOP_NORMALIZER) {
    if (json2 === null || json2 === void 0)
      return null;
    if (Array.isArray(json2)) {
      return normalizer(json2.map((input2) => JsonConversion2.value(input2, normalizer)));
    } else if (typeof json2 === "object") {
      if (!("$_type" in json2))
        return mapObjectValues(json2, (v3) => JsonConversion2.value(v3, normalizer));
      switch (json2["$_type"]) {
        case "date":
          return normalizer(DateTime.fromISO(json2.value, { setZone: true }));
        case "duration":
          return normalizer(Duration.fromISO(json2.value));
        case "link":
          return normalizer(Link.fromObject(json2.value));
        default:
          throw new Error(`Unrecognized serialized type '${json2["$_type"]}'!`);
      }
    }
    return normalizer(json2);
  }
  JsonConversion2.value = value;
})(JsonConversion || (JsonConversion = {}));

// src/index/import/inline-field.ts
function jsonInlineField(field) {
  return Object.assign({}, field, { value: JsonConversion.json(field.value) });
}
function valueInlineField(field) {
  return Object.assign({}, field, { value: JsonConversion.value(field.value) });
}
var INLINE_FIELD_WRAPPERS = Object.freeze({
  "[": "]",
  "(": ")"
});
var FULL_LINE_KEY_PART = P6.alt(
  P6.regexp(new RegExp(emoji_regex_default(), "u")),
  P6.regexp(/[0-9\p{Letter}\w\s_/-]+/u)
).many().map((parts) => parts.join(""));
var FULL_LINE_KEY_PARSER = P6.regexp(/[^0-9\w\p{Letter}]*/u).then(FULL_LINE_KEY_PART).skip(P6.regexp(/[_\*~`]*/u));

// src/index/types/markdown.ts
var _MarkdownPage = class {
  constructor(init) {
    // Use static types for all markdown files.
    this.$types = _MarkdownPage.TYPES;
    this.$typename = "Page";
    /** Obsidian-provided size of this page in bytes. */
    this.$size = 0;
    /**
     * All child markdown sections of this markdown file. The initial section before any content is special and is
     * named with the title of the file.
     */
    this.$sections = [];
    Object.assign(this, init);
  }
  // Markdown file IDs are always just the full path.
  get $id() {
    return this.$path;
  }
  // The file of a file is... it's file.
  get $file() {
    return this.$path;
  }
  /** @internal Create a markdown file from the given raw values. */
  static from(raw, normalizer = NOOP_NORMALIZER) {
    const sections = raw.$sections.map((sect) => MarkdownSection.from(sect, raw.$path, normalizer));
    return new _MarkdownPage({
      $path: raw.$path,
      $frontmatter: raw.$frontmatter ? mapObjectValues(raw.$frontmatter, (fm) => normalizeLinks(valueFrontmatterEntry(fm), normalizer)) : void 0,
      $infields: mapObjectValues(raw.$infields, (field) => normalizeLinks(valueInlineField(field), normalizer)),
      $ctime: DateTime.fromMillis(raw.$ctime),
      $mtime: DateTime.fromMillis(raw.$mtime),
      $extension: raw.$extension,
      $size: raw.$size,
      $position: raw.$position,
      $tags: raw.$tags,
      $links: raw.$links.map((link) => normalizer(Link.fromObject(link))),
      $sections: sections
    });
  }
  /** Return the number of lines in the document. */
  get $lineCount() {
    return this.$position.end;
  }
  /** The name of the file. */
  get $name() {
    return getFileTitle(this.$path);
  }
  /** A link to this file. */
  get $link() {
    return Link.file(this.$path);
  }
  /** All of the indexed fields in this object. */
  get fields() {
    return _MarkdownPage.FIELD_DEF(this);
  }
  /** Get the full field definition for the given field. */
  field(key) {
    var _a;
    return (_a = _MarkdownPage.FIELD_DEF(this, key)) == null ? void 0 : _a[0];
  }
  /** Get the value for the given field. */
  value(key) {
    var _a;
    return (_a = this.field(key)) == null ? void 0 : _a.value;
  }
  /** @internal Convert this page into it's partial representation for saving. */
  json() {
    return {
      $path: this.$path,
      $frontmatter: this.$frontmatter ? mapObjectValues(this.$frontmatter, jsonFrontmatterEntry) : void 0,
      $infields: mapObjectValues(this.$infields, jsonInlineField),
      $ctime: this.$ctime.toMillis(),
      $mtime: this.$mtime.toMillis(),
      $extension: this.$extension,
      $size: this.$size,
      $position: this.$position,
      $tags: this.$tags,
      $links: this.$links.map((link) => link.toObject()),
      $sections: this.$sections.map((sect) => sect.json())
    };
  }
};
var MarkdownPage = _MarkdownPage;
/** All of the types that a markdown file is. */
MarkdownPage.TYPES = [FILE_TYPE, "markdown", "page", TAGGABLE_TYPE, LINKABLE_TYPE, LINKBEARING_TYPE, FIELDBEARING_TYPE];
MarkdownPage.FIELD_DEF = Extractors.merge(
  Extractors.intrinsics(),
  Extractors.frontmatter((f4) => f4.$frontmatter),
  Extractors.inlineFields((f4) => f4.$infields)
);
var _MarkdownSection = class {
  constructor(init) {
    /** Path of the file that this section is in. */
    this.$types = _MarkdownSection.TYPES;
    this.$typename = "Section";
    Object.assign(this, init);
  }
  /** @internal Convert raw markdown section data to the appropriate class. */
  static from(raw, file, normalizer = NOOP_NORMALIZER) {
    const blocks = raw.$blocks.map((block) => MarkdownBlock.from(block, file, normalizer));
    return new _MarkdownSection({
      $file: file,
      $id: _MarkdownSection.readableId(file, raw.$title, raw.$ordinal),
      $ordinal: raw.$ordinal,
      $title: raw.$title,
      $level: raw.$level,
      $position: raw.$position,
      $tags: raw.$tags,
      $links: raw.$links.map((l4) => normalizer(Link.fromObject(l4))),
      $blocks: blocks,
      $infields: mapObjectValues(raw.$infields, (i4) => normalizeLinks(valueInlineField(i4), normalizer))
    });
  }
  /** Obtain the number of lines in the section. */
  get $lineCount() {
    return this.$position.end - this.$position.start;
  }
  /** Alias for title which allows searching over pages and sections by 'name'. */
  get $name() {
    return this.$title;
  }
  /** Return a link to this section. */
  get $link() {
    return Link.header(this.$file, this.$title);
  }
  /** All of the indexed fields in this object. */
  get fields() {
    return _MarkdownSection.FIELD_DEF(this);
  }
  /** Fetch a specific field by key. */
  field(key) {
    var _a;
    return (_a = _MarkdownSection.FIELD_DEF(this, key)) == null ? void 0 : _a[0];
  }
  value(key) {
    var _a;
    return (_a = this.field(key)) == null ? void 0 : _a.value;
  }
  /** @internal */
  json() {
    return {
      $ordinal: this.$ordinal,
      $title: this.$title,
      $level: this.$level,
      $position: this.$position,
      $tags: this.$tags,
      $links: this.$links.map((link) => link.toObject()),
      $blocks: this.$blocks.map((block) => block.json()),
      $infields: mapObjectValues(this.$infields, jsonInlineField)
    };
  }
  /** Generate a readable ID for this section using the first 8 characters of the string and the ordinal. */
  static readableId(file, title, ordinal) {
    const first8 = title.substring(0, Math.min(title.length, 8)).replace(/[^A-Za-z0-9-_]+/gi, "-");
    return `${file}/section${ordinal}/${first8}`;
  }
};
var MarkdownSection = _MarkdownSection;
/** All of the types that a markdown section is. */
MarkdownSection.TYPES = ["markdown", "section", TAGGABLE_TYPE, LINKABLE_TYPE, LINKBEARING_TYPE, FIELDBEARING_TYPE];
MarkdownSection.FIELD_DEF = Extractors.merge(
  Extractors.intrinsics(),
  Extractors.inlineFields((f4) => f4.$infields)
);
var _MarkdownBlock = class {
  constructor(init) {
    this.$types = _MarkdownBlock.TYPES;
    this.$typename = "Block";
    Object.assign(this, init);
  }
  /** @internal */
  static from(object, file, normalizer = NOOP_NORMALIZER) {
    if (object.$type === "list") {
      return MarkdownListBlock.from(object, file, normalizer);
    } else if (object.$type === "datablock") {
      return MarkdownDatablock.from(object, file, normalizer);
    } else if (object.$type === "codeblock") {
      return MarkdownCodeblock.from(object, file, normalizer);
    }
    return new _MarkdownBlock({
      $file: file,
      $id: _MarkdownBlock.readableId(file, object.$ordinal),
      $ordinal: object.$ordinal,
      $position: object.$position,
      $tags: object.$tags,
      $links: object.$links.map((l4) => normalizer(Link.fromObject(l4))),
      $infields: mapObjectValues(object.$infields, (i4) => normalizeLinks(valueInlineField(i4), normalizer)),
      $blockId: object.$blockId,
      $type: object.$type
    });
  }
  /** If this block has a block ID, the link to this block. */
  get $link() {
    if (this.$blockId)
      return Link.block(this.$file, this.$blockId);
    else
      return void 0;
  }
  /** All of the indexed fields in this object. */
  get fields() {
    return _MarkdownBlock.FIELD_DEF(this);
  }
  /** Fetch a specific field by key. */
  field(key) {
    var _a;
    return (_a = _MarkdownBlock.FIELD_DEF(this, key)) == null ? void 0 : _a[0];
  }
  value(key) {
    var _a;
    return (_a = this.field(key)) == null ? void 0 : _a.value;
  }
  /** @internal */
  json() {
    return {
      $ordinal: this.$ordinal,
      $position: this.$position,
      $tags: this.$tags,
      $links: this.$links.map((l4) => l4.toObject()),
      $infields: mapObjectValues(this.$infields, jsonInlineField),
      $blockId: this.$blockId,
      $type: this.$type
    };
  }
  /** Generate a readable ID for this block using the ordinal of the block. */
  static readableId(file, ordinal) {
    return `${file}/block${ordinal}`;
  }
};
var MarkdownBlock = _MarkdownBlock;
MarkdownBlock.TYPES = ["markdown", "block", LINKBEARING_TYPE, TAGGABLE_TYPE, FIELDBEARING_TYPE];
MarkdownBlock.FIELD_DEF = Extractors.merge(
  Extractors.intrinsics(),
  Extractors.inlineFields((f4) => f4.$infields)
);
var _MarkdownListBlock = class extends MarkdownBlock {
  constructor(init) {
    super(init);
    this.$types = _MarkdownListBlock.TYPES;
    this.$typename = "List Block";
  }
  /** @internal Create a list block from a serialized value. */
  static from(object, file, normalizer = NOOP_NORMALIZER) {
    const elements = object.$elements.map((elem) => MarkdownListItem.from(elem, file, normalizer));
    return new _MarkdownListBlock({
      // TODO: This is shared with other blocks, should probably be fixed.
      $file: file,
      $id: MarkdownBlock.readableId(file, object.$ordinal),
      $ordinal: object.$ordinal,
      $position: object.$position,
      $tags: object.$tags,
      $links: object.$links.map((l4) => normalizer(Link.fromObject(l4))),
      $infields: mapObjectValues(object.$infields, (i4) => normalizeLinks(valueInlineField(i4), normalizer)),
      $blockId: object.$blockId,
      $elements: elements,
      $type: "list"
    });
  }
  /** @internal */
  json() {
    return Object.assign(super.json(), {
      $elements: this.$elements.map((elem) => elem.json())
    });
  }
};
var MarkdownListBlock = _MarkdownListBlock;
MarkdownListBlock.TYPES = ["markdown", "block", "block-list", TAGGABLE_TYPE, LINKBEARING_TYPE, FIELDBEARING_TYPE];
var _MarkdownCodeblock = class extends MarkdownBlock {
  constructor(init) {
    super(init);
    this.$types = _MarkdownCodeblock.TYPES;
  }
  /** @internal */
  static from(object, file, normalizer = NOOP_NORMALIZER) {
    return new _MarkdownCodeblock({
      $file: file,
      $id: _MarkdownCodeblock.readableId(file, object.$position.start),
      $position: object.$position,
      $ordinal: object.$ordinal,
      $typename: "Codeblock",
      $type: "codeblock",
      $blockId: object.$blockId,
      $languages: object.$languages,
      $links: object.$links.map((link) => normalizer(Link.fromObject(link))),
      $tags: object.$tags,
      $infields: mapObjectValues(object.$infields, valueInlineField),
      $contentPosition: object.$contentPosition,
      $style: object.$style
    });
  }
  /** All of the indexed fields in this object. */
  get fields() {
    return _MarkdownCodeblock.SUB_FIELD_DEF(this);
  }
  /** Fetch a specific field by key. */
  field(key) {
    var _a;
    return (_a = _MarkdownCodeblock.SUB_FIELD_DEF(this, key)) == null ? void 0 : _a[0];
  }
  /** Fetch the value of a specific field. */
  value(key) {
    var _a;
    return (_a = this.field(key)) == null ? void 0 : _a.value;
  }
  /** @internal */
  json() {
    return Object.assign(super.json(), {
      $languages: this.$languages,
      $contentPosition: this.$contentPosition,
      $style: this.$style
    });
  }
  static readableId(file, line) {
    return `${file}/codeblock${line}`;
  }
};
var MarkdownCodeblock = _MarkdownCodeblock;
MarkdownCodeblock.TYPES = ["markdown", "block", "codeblock", TAGGABLE_TYPE, LINKBEARING_TYPE, FIELDBEARING_TYPE];
MarkdownCodeblock.SUB_FIELD_DEF = Extractors.merge(
  MarkdownBlock.FIELD_DEF
);
var _MarkdownDatablock = class extends MarkdownBlock {
  constructor(init) {
    super(init);
    this.$types = _MarkdownDatablock.TYPES;
  }
  /** @internal */
  static from(object, file, normalizer = NOOP_NORMALIZER) {
    const normdata = normalizeLinks(mapObjectValues(object.$data, valueFrontmatterEntry), normalizer);
    const links = gatherLinks(normdata);
    const tags = gatherTags(normdata);
    return new _MarkdownDatablock({
      $file: file,
      $id: _MarkdownDatablock.readableId(file, object.$position.start),
      $position: object.$position,
      $infields: {},
      $ordinal: object.$ordinal,
      $data: normdata,
      $links: links,
      $typename: "Datablock",
      $tags: tags,
      $type: "datablock",
      $blockId: object.$blockId
    });
  }
  /** All of the indexed fields in this object. */
  get fields() {
    return _MarkdownDatablock.SUB_FIELD_DEF(this);
  }
  /** Fetch a specific field by key. */
  field(key) {
    var _a;
    return (_a = _MarkdownDatablock.SUB_FIELD_DEF(this, key)) == null ? void 0 : _a[0];
  }
  value(key) {
    var _a;
    return (_a = this.field(key)) == null ? void 0 : _a.value;
  }
  /** @internal */
  json() {
    return Object.assign(super.json(), {
      $data: mapObjectValues(this.$data, jsonFrontmatterEntry)
    });
  }
  static readableId(file, line) {
    return `${file}/datablock${line}`;
  }
};
var MarkdownDatablock = _MarkdownDatablock;
MarkdownDatablock.TYPES = ["markdown", "block", "datablock", TAGGABLE_TYPE, LINKBEARING_TYPE, FIELDBEARING_TYPE];
MarkdownDatablock.SUB_FIELD_DEF = Extractors.merge(
  MarkdownBlock.FIELD_DEF,
  Extractors.frontmatter((f4) => f4.$data)
);
var _MarkdownListItem = class {
  constructor(init) {
    this.$types = _MarkdownListItem.TYPES;
    this.$typename = "List item";
    Object.assign(this, init);
  }
  /** @internal Create a list item from a serialized object. */
  static from(object, file, normalizer = NOOP_NORMALIZER) {
    if (object.$type === "task")
      return MarkdownTaskItem.from(object, file, normalizer);
    const elements = object.$elements.map((elem) => _MarkdownListItem.from(elem, file, normalizer));
    return new _MarkdownListItem({
      $file: file,
      $id: _MarkdownListItem.readableId(file, object.$position.start),
      $position: object.$position,
      $elements: elements,
      $type: object.$type,
      $tags: object.$tags,
      $infields: mapObjectValues(object.$infields, (i4) => normalizeLinks(valueInlineField(i4), normalizer)),
      $links: object.$links.map((l4) => normalizer(Link.fromObject(l4))),
      $blockId: object.$blockId,
      $parentLine: object.$parentLine,
      $text: object.$text,
      $symbol: object.$symbol
    });
  }
  /** Get the line that this list item starts on. */
  get $line() {
    return this.$position.start;
  }
  /** The number of lines in this list item. */
  get $lineCount() {
    return this.$position.end - this.$position.start + 1;
  }
  /** Cleaned text that is guaranteed to be non-null and has indentation, inline fields, and id removed. */
  get $cleantext() {
    if (!this.$text)
      return "";
    return this.$text.replace(/(.*?)([\[\(][^:(\[]+::\s*.*?[\]\)]\s*)*(\^.+){0,1}$/gm, "$1").trim();
  }
  /** All of the indexed fields in this object. */
  get fields() {
    return _MarkdownListItem.FIELD_DEF(this);
  }
  /** Fetch a specific field by key. */
  field(key) {
    var _a;
    return (_a = _MarkdownListItem.FIELD_DEF(this, key)) == null ? void 0 : _a[0];
  }
  value(key) {
    var _a;
    return (_a = this.field(key)) == null ? void 0 : _a.value;
  }
  /** @internal */
  json() {
    return {
      $position: this.$position,
      $elements: this.$elements.map((elem) => elem.json()),
      $type: this.$type,
      $tags: this.$tags,
      $infields: mapObjectValues(this.$infields, jsonInlineField),
      $links: this.$links,
      $blockId: this.$blockId,
      $parentLine: this.$parentLine,
      $symbol: this.$symbol,
      $text: this.$text
    };
  }
  /** Generate a readable ID for this item using the line number. */
  static readableId(file, line) {
    return `${file}/list${line}`;
  }
};
var MarkdownListItem = _MarkdownListItem;
MarkdownListItem.TYPES = ["markdown", "list-item", LINKBEARING_TYPE, TAGGABLE_TYPE, FIELDBEARING_TYPE];
MarkdownListItem.FIELD_DEF = Extractors.merge(
  Extractors.intrinsics(),
  Extractors.inlineFields((f4) => f4.$infields)
);
var _MarkdownTaskItem = class extends MarkdownListItem {
  constructor(init) {
    super(init);
    this.$types = _MarkdownTaskItem.TYPES;
    this.$typename = "Task";
  }
  /** @internal */
  static from(object, file, normalizer) {
    const elements = object.$elements.map((elem) => MarkdownListItem.from(elem, file, normalizer));
    return new _MarkdownTaskItem({
      $file: file,
      $id: MarkdownListItem.readableId(file, object.$position.start),
      $position: object.$position,
      $elements: elements,
      $type: object.$type,
      $tags: object.$tags,
      $infields: mapObjectValues(object.$infields, (i4) => normalizeLinks(valueInlineField(i4), normalizer)),
      $links: object.$links.map((l4) => normalizer(Link.fromObject(l4))),
      $blockId: object.$blockId,
      $parentLine: object.$parentLine,
      $status: object.$status,
      $symbol: object.$symbol,
      $text: object.$text
    });
  }
  /** @internal */
  json() {
    return Object.assign(super.json(), {
      $status: this.$status
    });
  }
  /** Determine if the given task is completed. */
  get $completed() {
    return this.$status === "x" || this.$status === "X";
  }
};
var MarkdownTaskItem = _MarkdownTaskItem;
MarkdownTaskItem.TYPES = ["markdown", "list-item", "task", LINKBEARING_TYPE, TAGGABLE_TYPE, FIELDBEARING_TYPE];
function jsonFrontmatterEntry(raw) {
  return {
    key: raw.key,
    value: JsonConversion.json(raw.value),
    raw: raw.raw
  };
}
function valueFrontmatterEntry(raw) {
  return {
    key: raw.key,
    value: JsonConversion.value(raw.value),
    raw: raw.raw
  };
}
function normalizeLinks(input2, normalizer) {
  return Literals.mapLeaves(input2, (value) => {
    if (Literals.isLink(value))
      return normalizer(value);
    else
      return value;
  });
}
function gatherLinks(input2) {
  const result = [];
  Literals.mapLeaves(input2, (value) => {
    if (Literals.isLink(value))
      result.push(value);
    return null;
  });
  return result;
}
function gatherTags(data) {
  function recurse(input2) {
    if (Literals.isString(input2))
      return [input2.startsWith("#") ? input2 : "#" + input2];
    else if (Literals.isArray(input2))
      return input2.flatMap(recurse);
    else
      return [];
  }
  let tags = [];
  if ("tag" in data)
    tags = tags.concat(recurse(data["tags"]));
  if ("tags" in data)
    tags = tags.concat(recurse(data["tags"]));
  return tags;
}
var NOOP_NORMALIZER = (x4) => x4;

// src/utils/deferred.ts
function deferred() {
  let resolve;
  let reject;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  const deferred2 = promise;
  deferred2.resolve = resolve;
  deferred2.reject = reject;
  return deferred2;
}

// src/api/script-cache.ts
var _ScriptCache = class {
  constructor(store) {
    this.store = store;
    /** Caches scripts by fully qualified path. */
    this.scripts = /* @__PURE__ */ new Map();
  }
  /** Load the given script at the given path, recursively loading any subscripts as well.  */
  async load(path, context) {
    const key = this.pathkey(path);
    const currentScript = this.scripts.get(key);
    if (currentScript) {
      if (currentScript.type === "loaded")
        return Result.success(currentScript.object);
      return Result.failure(
        `Failed to import script "${path.toString()}", as it is in the middle of being loaded. Do you have
                 a circular dependency in your require() calls? The currently loaded or loading scripts are: 
                 ${Array.from(this.scripts.values()).map((sc) => "	" + sc.path).join("\n")}`
      );
    }
    const deferral = deferred();
    this.scripts.set(key, { type: "loading", promise: deferral, path: key });
    const result = await this.loadUncached(path, context);
    deferral.resolve(result);
    if (result.successful) {
      this.scripts.set(key, { type: "loaded", path: key, object: result.value });
    } else {
      this.scripts.delete(key);
    }
    return result;
  }
  /** Load a script, directly bypassing the cache. */
  async loadUncached(path, context) {
    const maybeSource = await this.resolveSource(path);
    if (!maybeSource.successful)
      return maybeSource;
    const { code, language } = maybeSource.value;
    let basic;
    try {
      basic = transpile(code, language);
    } catch (error) {
      return Result.failure(`Failed to import ${path.toString()} while transpiling from ${language}: ${error}`);
    }
    const finalContext = Object.assign({ h: _, Fragment: k }, context);
    try {
      return Result.success(await asyncEvalInContext(basic, finalContext));
    } catch (error) {
      return Result.failure(`Failed to execute script '${path.toString()}': ${error}`);
    }
  }
  /** Normalize a path or link to a textual path. */
  pathkey(path) {
    if (path instanceof Link)
      return path.obsidianLink();
    else
      return path;
  }
  /** Attempts to resolve the source to load given a path or link to a markdown section. */
  async resolveSource(path) {
    const object = this.store.resolveLink(path);
    if (!object)
      return Result.failure("Could not find a script at the given path: " + path.toString());
    const tfile = this.store.vault.getFileByPath(object.$file);
    if (!tfile)
      return Result.failure(`File "${object.$file}" not found.`);
    if (tfile.extension.toLocaleLowerCase() in _ScriptCache.FILE_EXTENSIONS) {
      const language = _ScriptCache.FILE_EXTENSIONS[tfile.extension.toLocaleLowerCase()];
      try {
        const code = await this.store.vault.cachedRead(tfile);
        return Result.success({ code, language });
      } catch (error) {
        return Result.failure("Failed to load javascript/typescript source file: " + error);
      }
    }
    if (object instanceof MarkdownSection) {
      const maybeBlock = object.$blocks.filter((b3) => b3.$type === "codeblock").find(
        (cb) => cb.$languages.some((language2) => language2.toLocaleLowerCase() in _ScriptCache.SCRIPT_LANGUAGES)
      );
      if (!maybeBlock)
        return Result.failure("Could not find a script in the given markdown section: " + path.toString());
      const language = _ScriptCache.SCRIPT_LANGUAGES[maybeBlock.$languages.find((lang) => lang.toLocaleLowerCase() in _ScriptCache.SCRIPT_LANGUAGES)];
      return (await this.readCodeblock(tfile, maybeBlock)).map((code) => ({ code, language }));
    } else if (object instanceof MarkdownCodeblock) {
      const maybeLanguage = object.$languages.find(
        (lang) => lang.toLocaleLowerCase() in _ScriptCache.SCRIPT_LANGUAGES
      );
      if (!maybeLanguage)
        return Result.failure(`The codeblock referenced by '${path}' is not a JS/TS codeblock.`);
      const language = _ScriptCache.SCRIPT_LANGUAGES[maybeLanguage];
      return (await this.readCodeblock(tfile, object)).map((code) => ({ code, language }));
    }
    return Result.failure(`Cannot import '${path.toString()}: not a JS/TS file or codeblock reference.`);
  }
  /** Read the contents of a codeblock from a file. */
  async readCodeblock(file, block) {
    try {
      const raw = lineRange(
        await this.store.vault.cachedRead(file),
        block.$contentPosition.start,
        block.$contentPosition.end
      );
      if (block.$style === "fenced")
        return Result.success(raw);
      else
        return Result.success(
          raw.split("\n").map((line) => line.trimStart()).join("\n")
        );
    } catch (error) {
      return Result.failure(`Failed to read a codeblock from ${file.path}: ${error}`);
    }
  }
};
var ScriptCache = _ScriptCache;
/** All of the tags we recognize for scripts. */
ScriptCache.SCRIPT_LANGUAGES = {
  js: "js",
  javascript: "js",
  datacorejs: "js",
  typescript: "ts",
  ts: "ts",
  datacorets: "ts",
  jsx: "jsx",
  datacorejsx: "jsx",
  tsx: "tsx",
  datacoretsx: "tsx"
};
/** All of the direct file extensions we can load. */
ScriptCache.FILE_EXTENSIONS = {
  tsx: "tsx",
  jsx: "jsx",
  js: "js",
  ts: "ts"
};

// src/api/ui/views/cards.tsx
function Card(props) {
  const cardTitle = T2(() => {
    if (typeof props.title === "function") {
      return props.title(props.value);
    } else {
      return props.title;
    }
  }, [props.value, props.title]);
  const innerContent = T2(() => {
    if (typeof props.content === "function")
      return props.content(props.value);
    else
      return props.content;
  }, [props.value, props.content]);
  const footerContent = T2(() => {
    if (props.footer !== void 0) {
      if (typeof props.footer === "function") {
        return props.footer(props.value);
      } else {
        return props.footer;
      }
    }
    return null;
  }, [props.footer, props.value]);
  const titleClasses = T2(() => {
    let base = ["datacore-card-title"];
    if (props.centerTitle)
      base = base.concat("centered");
    return base;
  }, [props.centerTitle, props.title, props.content, props.value]);
  return /* @__PURE__ */ u3("div", { className: "datacore-card", children: [
    /* @__PURE__ */ u3("div", { className: titleClasses.join(" "), children: cardTitle }),
    /* @__PURE__ */ u3("div", { className: "datacore-card-inner", children: [
      /* @__PURE__ */ u3("div", { className: "datacore-card-content", children: innerContent }),
      /* @__PURE__ */ u3("div", { className: "datacore-card-footer", children: footerContent })
    ] })
  ] });
}

// src/api/ui/views/list.tsx
function ListView(props) {
  var _a, _b;
  const type = (_a = props.type) != null ? _a : "unordered";
  const renderer = (_b = props.renderer) != null ? _b : (x4) => x4;
  const containerRef = A2(null);
  const totalElements = T2(() => Groupings.count(props.rows), [props.rows]);
  const paging = useDatacorePaging({
    initialPage: 0,
    paging: props.paging,
    scrollOnPageChange: props.scrollOnPaging,
    elements: totalElements,
    container: containerRef
  });
  const pagedRows = T2(() => {
    if (paging.enabled)
      return Groupings.slice(props.rows, paging.page * paging.pageSize, (paging.page + 1) * paging.pageSize);
    else
      return props.rows;
  }, [paging.page, paging.pageSize, paging.enabled, props.rows]);
  const groupings = T2(() => {
    if (!props.groupings)
      return void 0;
    if (Array.isArray(props.groupings))
      return props.groupings;
    if (Literals.isFunction(props.groupings))
      return [{ render: props.groupings }];
    else
      return [props.groupings];
  }, [props.groupings]);
  const maxChildDepth = T2(() => {
    var _a2;
    return (_a2 = props.maxChildDepth) != null ? _a2 : 12;
  }, [props.maxChildDepth]);
  const childFunc = T2(() => ensureChildrenFunc(props.childSource), [props.childSource]);
  return /* @__PURE__ */ u3("div", { ref: containerRef, className: "datacore-list", children: [
    /* @__PURE__ */ u3(
      ListGroup,
      {
        level: 0,
        type,
        rows: pagedRows,
        renderer,
        groupings,
        maxChildDepth,
        childFunc
      }
    ),
    paging.enabled && /* @__PURE__ */ u3(ControlledPager, { page: paging.page, totalPages: paging.totalPages, setPage: paging.setPage })
  ] });
}
function ListGroup({
  level,
  type,
  rows,
  renderer,
  groupings,
  maxChildDepth,
  childFunc
}) {
  const groupingConfig = groupings == null ? void 0 : groupings[Math.min(groupings.length - 1, level)];
  if (Groupings.isGrouping(rows)) {
    return /* @__PURE__ */ u3(k, { children: rows.map((group) => /* @__PURE__ */ u3(k, { children: [
      /* @__PURE__ */ u3(ListGroupHeader, { level, value: group, config: groupingConfig }),
      /* @__PURE__ */ u3(
        ListGroup,
        {
          level: level + 1,
          type,
          rows: group.rows,
          renderer,
          groupings,
          maxChildDepth,
          childFunc
        }
      )
    ] })) });
  } else {
    if (type === "ordered" || type === "unordered") {
      return /* @__PURE__ */ u3(
        HtmlList,
        {
          type,
          rows,
          renderer,
          maxDepth: maxChildDepth,
          depth: 0,
          childFunc
        }
      );
    } else {
      return /* @__PURE__ */ u3(BlockList, { rows, renderer, maxChildDepth, childFunc });
    }
  }
}
function ListGroupHeader({
  level,
  value,
  config
}) {
  const sourcePath = x2(CURRENT_FILE_CONTEXT);
  const rawRenderable = T2(() => {
    if (config == null ? void 0 : config.render)
      return config.render(value.key, value.rows);
    else
      return /* @__PURE__ */ u3("h2", { children: /* @__PURE__ */ u3(Lit, { sourcePath, inline: true, value: value.key }) });
  }, [config == null ? void 0 : config.render, value.key, value.rows]);
  const renderable = useAsElement(rawRenderable);
  return /* @__PURE__ */ u3("span", { className: "datacore-list-group-header", children: renderable });
}
function HtmlList({
  type,
  rows,
  renderer,
  maxDepth,
  depth,
  childFunc
}) {
  if (type === "ordered") {
    return /* @__PURE__ */ u3("ol", { className: "datacore-list datacore-list-ordered", children: rows.map((element, index) => /* @__PURE__ */ u3(
      HtmlListItem,
      {
        type,
        element,
        renderer,
        maxDepth,
        depth,
        childFunc
      },
      index
    )) });
  } else {
    return /* @__PURE__ */ u3("ul", { className: "datacore-list datacore-list-unordered", children: rows.map((element, index) => /* @__PURE__ */ u3(
      HtmlListItem,
      {
        type,
        element,
        renderer,
        maxDepth,
        depth,
        childFunc
      },
      index
    )) });
  }
}
function HtmlListItem({
  type,
  element,
  renderer,
  maxDepth,
  depth,
  childFunc
}) {
  const children = T2(() => {
    if (depth >= maxDepth)
      return [];
    else
      return childFunc(element);
  }, [element, childFunc, depth, maxDepth]);
  return /* @__PURE__ */ u3("li", { className: "datacore-list-item", children: [
    ensureListElement(renderer(element)),
    children && /* @__PURE__ */ u3(
      HtmlList,
      {
        type,
        rows: children,
        maxDepth,
        depth: depth + 1,
        renderer,
        childFunc
      }
    )
  ] });
}
function BlockList({
  rows,
  renderer,
  maxChildDepth,
  childFunc
}) {
  return /* @__PURE__ */ u3("div", { className: "datacore-list datacore-list-block", children: rows.map((element, index) => /* @__PURE__ */ u3(
    BlockListItem,
    {
      element,
      renderer,
      maxDepth: maxChildDepth,
      depth: 0,
      childFunc
    },
    index
  )) });
}
function BlockListItem({
  element,
  renderer,
  maxDepth,
  depth,
  childFunc
}) {
  const children = T2(() => {
    if (depth >= maxDepth)
      return [];
    else
      return childFunc(element);
  }, [element, childFunc, depth, maxDepth]);
  const style = T2(() => {
    return {
      paddingLeft: depth * 4
    };
  }, [depth]);
  return /* @__PURE__ */ u3("div", { className: "datacore-block-list-item", style, children: [
    ensureListElement(renderer(element)),
    children == null ? void 0 : children.map((child, index) => /* @__PURE__ */ u3(
      BlockListItem,
      {
        element: child,
        maxDepth,
        depth: depth + 1,
        renderer,
        childFunc
      },
      index
    ))
  ] });
}
function ensureListElement(element) {
  if (t(element)) {
    return element;
  } else {
    return /* @__PURE__ */ u3(DefaultListElement, { element });
  }
}
function DefaultListElement({ element }) {
  const sourcePath = x2(CURRENT_FILE_CONTEXT);
  if (element instanceof MarkdownListItem) {
    return /* @__PURE__ */ u3(Lit, { inline: true, value: element.$text, sourcePath: element.$file });
  }
  return /* @__PURE__ */ u3(Lit, { inline: true, value: element, sourcePath });
}
function ensureChildrenFunc(childProp) {
  if (childProp === void 0) {
    return defaultChildren;
  } else if (childProp === null) {
    return (element) => [];
  } else if (Literals.isString(childProp)) {
    return (element) => fetchProps(element, [childProp]);
  } else if (Literals.isArray(childProp)) {
    return (element) => fetchProps(element, childProp);
  } else {
    return childProp;
  }
}
function defaultChildren(element) {
  return fetchProps(element, ["$children", "children"]);
}
function fetchProps(element, props) {
  const result = [];
  for (const prop of props) {
    const items = element[prop];
    if (!items)
      continue;
    if (Literals.isArray(items))
      result.push(...items);
    else
      result.push(items);
  }
  return result;
}

// src/api/local-api.tsx
var DatacoreLocalApi = class {
  constructor(api, path) {
    this.api = api;
    this.path = path;
    ///////////////////////
    // General utilities //
    ///////////////////////
    /** Utilities for coercing types into one specific type for easier programming. */
    this.coerce = Coerce;
    /////////////
    //  Hooks  //
    /////////////
    // Export the common preact hooks for people to use via `dc.`:
    /** See the preact or react 'useState' hook. */
    this.useState = d2;
    /** See the preact or react 'useCallback' hook. */
    this.useCallback = q2;
    /** Se the preact or react 'useReducer' hook. */
    this.useReducer = h2;
    /** See the preact or react 'useMemo' hook. */
    this.useMemo = T2;
    /** See the preact or react 'useEffect' hook. */
    this.useEffect = y2;
    /** See the preact or react 'createContext' function. */
    this.createContext = K;
    /** See the preact or react 'useContext' function. */
    this.useContext = x2;
    /** See the preact or react 'useRef' function. */
    this.useRef = A2;
    /**
     * Calls a function to obtain a value; returns the same exact _instance_ of that value as long
     * as calls to the function return an equivalent value. Interning is a useful performance concept
     * for reducing the total number of unique objects in memory and for making better use of
     * React's reference-equality-based caching.
     */
    this.useInterning = useInterning;
    /////////////////////
    // Visual Elements //
    /////////////////////
    /** Vertical flexbox container; good for putting items together in a column. */
    this.Stack = Stack;
    /** Horizontal flexbox container; good for putting items together in a row. */
    this.Group = Group;
    /** Renders a literal value in a pretty way that respects settings. */
    this.Literal = (({ value, sourcePath, inline }) => {
      var _a;
      const implicitSourcePath = x2(CURRENT_FILE_CONTEXT);
      return /* @__PURE__ */ u3(Lit, { value, sourcePath: (_a = sourcePath != null ? sourcePath : implicitSourcePath) != null ? _a : this.path, inline });
    }).bind(this);
    /** Renders markdown using the Obsidian markdown renderer, optionally attaching additional styles. */
    this.Markdown = (({
      content,
      sourcePath,
      inline,
      style,
      className
    }) => {
      var _a;
      const implicitSourcePath = x2(CURRENT_FILE_CONTEXT);
      return /* @__PURE__ */ u3(
        Markdown,
        {
          content,
          sourcePath: (_a = sourcePath != null ? sourcePath : implicitSourcePath) != null ? _a : this.path,
          inline,
          style,
          cls: className
        }
      );
    }).bind(this);
    /** Renders an obsidian-style link directly and more efficiently than rendering markdown. */
    this.Link = ObsidianLink;
    /** Create a vanilla Obsidian embed for the given link. */
    this.LinkEmbed = (({
      link,
      inline,
      sourcePath
    }) => {
      var _a;
      const realLink = T2(() => typeof link === "string" ? Link.file(link) : link, [link]);
      const implicitSourcePath = x2(CURRENT_FILE_CONTEXT);
      return /* @__PURE__ */ u3(
        Embed,
        {
          link: realLink,
          inline: inline != null ? inline : false,
          sourcePath: (_a = sourcePath != null ? sourcePath : implicitSourcePath) != null ? _a : this.path
        }
      );
    }).bind(this);
    /** Create an explicit 'span' embed which extracts a span of lines from a markdown file. */
    this.SpanEmbed = (({
      path,
      start,
      end,
      explain,
      showExplain,
      sourcePath: maybeSourcePath
    }) => {
      const sourcePath = maybeSourcePath != null ? maybeSourcePath : this.path;
      const resolvedPath = T2(() => this.resolvePath(path, sourcePath), [path, sourcePath]);
      return /* @__PURE__ */ u3(LineSpanEmbed, { path: resolvedPath, start, end, explain, showExplain });
    }).bind(this);
    /** Renders an obsidian lucide icon. */
    this.Icon = Icon;
    /**
     * Generate an embed of the given markdown element. Useful to pass to the 'renderer' prop of various views
     * to efficiently render embeds of various elements.
     *
     * For example, `dc.embed(<file>)` will produce a file embedding, and `dc.embed(<section>)` will produce a section embedding.
     */
    this.embed = ((element) => {
      if (element.$types.contains("markdown") && element.$file && "$position" in element) {
        const { start, end } = element.$position;
        if (!Literals.isNumber(start) || !Literals.isNumber(end))
          return /* @__PURE__ */ u3(
            ErrorMessage,
            {
              message: `Invalid $position field '${JSON.stringify(element.$position)}' for element '${element.$id}' from '${element.$file}'`
            }
          );
        return /* @__PURE__ */ u3(this.SpanEmbed, { path: element.$file, start, end });
      }
      return /* @__PURE__ */ u3(ErrorMessage, { message: `No valid embedding for element '${element.$id}' from '${element.$file}'` });
    }).bind(this);
    ///////////
    // Views //
    ///////////
    /** @deprecated - Use just `Table` instead. */
    this.VanillaTable = TableView;
    /** A simple and configurable table view that supports rendering paged and grouped data. */
    this.Table = TableView;
    /** A simple and configurable list view that supports rendering paged and grouped data. */
    this.List = ListView;
    /** A single card which can be composed into a grid view. */
    this.Card = Card;
    /////////////////////////
    // Interative elements //
    /////////////////////////
    this.Button = Button;
    this.Textbox = Textbox;
    this.Callout = Callout;
    this.Checkbox = Checkbox;
    this.Slider = Slider;
    this.Switch = Switch;
    this.VanillaSelect = VanillaSelect;
    this.scriptCache = new ScriptCache(this.core.datastore);
  }
  /** The current file path for the local API. */
  currentPath() {
    return this.path;
  }
  currentFile() {
    return this.api.page(this.path);
  }
  /** Get acess to luxon functions. */
  get luxon() {
    return luxon_exports;
  }
  /** Get access to preact functions. */
  get preact() {
    return preact_module_exports;
  }
  /** Central Obsidian app object. */
  get app() {
    return this.core.app;
  }
  /** The internal plugin central datastructure. */
  get core() {
    return this.api.core;
  }
  //////////////////////////////
  // Script loading utilities //
  //////////////////////////////
  /**
   * Asynchronously load a javascript block from the given path or link; you can either load from JS/TS/JSX/TSX files
   * directly, or from codeblocks by loading from the section the codeblock is inside of. There are a few stipulations
   * to loading:
   * - You cannot load cyclical dependencies.
   * - This is similar to vanilla js `require()`, not `import ... `. Your scripts you are requiring need to explicitly
   *   return the things they are exporting, like the example below. The `export` keyword does not work.
   *
   * ```js
   * function MyElement() {
   *  ...
   * }
   *
   * return { MyElement };
   * ```
   */
  async require(path) {
    const result = await this.scriptCache.load(path, { dc: this });
    return result.orElseThrow();
  }
  /** Resolve a local or absolute path or link to an absolute path. */
  resolvePath(path, sourcePath) {
    return this.api.resolvePath(path, sourcePath != null ? sourcePath : this.path);
  }
  /** Try to parse the given query, returning a monadic success/failure result. */
  tryParseQuery(query) {
    return this.api.tryParseQuery(query);
  }
  /** Try to parse the given query, throwing an error if it is invalid. */
  parseQuery(query) {
    return this.tryParseQuery(query).orElseThrow((e3) => "Failed to parse query: " + e3);
  }
  /** Create a file link pointing to the given path. */
  fileLink(path) {
    return Link.file(path);
  }
  /** Create a link to a header with the given name. */
  headerLink(path, header) {
    return Link.header(path, header);
  }
  /** Create a link to a block with the given path and block ID. */
  blockLink(path, block) {
    return Link.block(path, block);
  }
  /** Try to parse the given link, throwing an error if it is invalid. */
  parseLink(linktext) {
    return this.api.parseLink(linktext);
  }
  /** Try to parse a link, returning a monadic success/failure result. */
  tryParseLink(linktext) {
    return this.api.tryParseLink(linktext);
  }
  /** Create a data array from a regular array. */
  array(input2) {
    return DataArray.wrap(input2);
  }
  /** Evaluate an expression and return it's evaluated value. */
  evaluate(expression, variables, sourcePath) {
    return this.api.evaluate(expression, variables, sourcePath != null ? sourcePath : this.path);
  }
  /** Evaluate an expression and return it's evaluated value, throwing an exception on failure. */
  tryEvaluate(expression, variables, sourcePath) {
    return this.api.tryEvaluate(expression, variables, sourcePath != null ? sourcePath : this.path);
  }
  query(query) {
    return this.api.query(query);
  }
  tryQuery(query) {
    return this.api.tryQuery(query);
  }
  fullquery(query) {
    return this.api.fullquery(query);
  }
  tryFullQuery(query) {
    return this.api.tryFullQuery(query);
  }
  /** Memoize the input automatically and process it using a DataArray; returns a vanilla array back. */
  useArray(input2, process, deps) {
    return T2(() => process(DataArray.wrap(input2)).array(), [input2, ...deps != null ? deps : []]);
  }
  useCurrentFile(settings) {
    return useFileMetadata(this.core, this.path, settings);
  }
  /** Use the current path. Automatically updates the view if the path changes (though that would be weird). */
  useCurrentPath(settings) {
    return this.path;
  }
  useFile(path, settings) {
    return useFileMetadata(this.core, path, settings);
  }
  /** Automatically refresh the view whenever the index updates; returns the latest index revision ID. */
  useIndexUpdates(settings) {
    return useIndexUpdates(this.core, settings);
  }
  useFullQuery(query, settings) {
    return useFullQuery(this.core, this.parseQuery(query), settings);
  }
  useQuery(query, settings) {
    return useQuery(this.core, this.parseQuery(query), settings);
  }
};

// src/api/api.ts
var import_parsimmon = __toESM(require_parsimmon_umd_min());

// src/expression/binaryop.ts
var BinaryOpHandler = class {
  static create() {
    return new BinaryOpHandler();
  }
  constructor() {
    this.map = /* @__PURE__ */ new Map();
    this.handleDefaultNulls = false;
  }
  register(left, op, right, func) {
    this.map.set(
      BinaryOpHandler.repr(op, left, right),
      (a3, b3, c3) => Result.success(func(a3, b3, c3))
    );
    return this;
  }
  registerResult(left, op, right, func) {
    this.map.set(BinaryOpHandler.repr(op, left, right), func);
    return this;
  }
  registerComm(left, op, right, func) {
    return this.register(left, op, right, func).register(right, op, left, (a3, b3, ctx) => func(b3, a3, ctx));
  }
  /** If enabled, all null (op) null operations produce null. */
  withDefaultNullHandling() {
    this.handleDefaultNulls = true;
    return this;
  }
  /** Implement a comparison function. */
  compare(type, compare) {
    return this.register(type, "<", type, (a3, b3, ctx) => compare(a3, b3, ctx) < 0).register(type, "<=", type, (a3, b3, ctx) => compare(a3, b3, ctx) <= 0).register(type, ">", type, (a3, b3, ctx) => compare(a3, b3, ctx) > 0).register(type, ">=", type, (a3, b3, ctx) => compare(a3, b3, ctx) >= 0).register(type, "=", type, (a3, b3, ctx) => compare(a3, b3, ctx) == 0).register(type, "!=", type, (a3, b3, ctx) => compare(a3, b3, ctx) != 0);
  }
  /** Attempt to evaluate the given binary operator on the two literal fields. */
  evaluate(op, left, right, ctx) {
    let leftType = Literals.typeOf(left);
    let rightType = Literals.typeOf(right);
    if (!leftType)
      return Result.failure(`Unrecognized value '${left}'`);
    else if (!rightType)
      return Result.failure(`Unrecognized value '${right}'`);
    if (this.handleDefaultNulls && leftType === "null" && rightType === "null")
      return Result.success(null);
    let handler = this.map.get(BinaryOpHandler.repr(op, leftType, rightType));
    if (handler)
      return handler(left, right, ctx);
    let handler2 = this.map.get(BinaryOpHandler.repr(op, leftType, "*"));
    if (handler2)
      return handler2(left, right, ctx);
    let handler3 = this.map.get(BinaryOpHandler.repr(op, "*", rightType));
    if (handler3)
      return handler3(left, right, ctx);
    let handler4 = this.map.get(BinaryOpHandler.repr(op, "*", "*"));
    if (handler4)
      return handler4(left, right, ctx);
    return Result.failure(`No implementation found for '${leftType} ${op} ${rightType}'`);
  }
  /** Create a string representation of the given triplet for unique lookup in the map. */
  static repr(op, left, right) {
    return `${left},${op},${right}`;
  }
};
function createBinaryOps(linkNormalizer) {
  return BinaryOpHandler.create().compare("*", (a3, b3) => Literals.compare(a3, b3, linkNormalizer)).register("*", "&", "*", (a3, b3) => Literals.isTruthy(a3) && Literals.isTruthy(b3)).register("*", "|", "*", (a3, b3) => Literals.isTruthy(a3) || Literals.isTruthy(b3)).register("number", "+", "number", (a3, b3) => a3 + b3).register("number", "-", "number", (a3, b3) => a3 - b3).register("number", "*", "number", (a3, b3) => a3 * b3).register("number", "/", "number", (a3, b3) => a3 / b3).register("number", "%", "number", (a3, b3) => a3 % b3).register("string", "+", "*", (a3, b3, ctx) => a3 + Literals.toString(b3, stringSettings(ctx.settings))).register("*", "+", "string", (a3, b3, ctx) => Literals.toString(a3, stringSettings(ctx.settings)) + b3).registerComm("string", "*", "number", (a3, b3) => b3 < 0 ? "" : a3.repeat(b3)).register("date", "-", "date", (a3, b3) => {
    return normalizeDuration(
      a3.diff(b3, ["years", "months", "days", "hours", "minutes", "seconds", "milliseconds"])
    );
  }).register("date", "-", "duration", (a3, b3) => a3.minus(b3)).registerComm("date", "+", "duration", (a3, b3) => a3.plus(b3)).register("duration", "+", "duration", (a3, b3) => normalizeDuration(a3.plus(b3))).register("duration", "-", "duration", (a3, b3) => normalizeDuration(a3.minus(b3))).register("duration", "/", "number", (a3, b3) => normalizeDuration(a3.mapUnits((x4) => x4 / b3))).registerComm("duration", "*", "number", (a3, b3) => normalizeDuration(a3.mapUnits((x4) => x4 * b3))).register("array", "+", "array", (a3, b3) => [].concat(a3).concat(b3)).register("object", "+", "object", (a3, b3) => Object.assign({}, a3, b3)).register("array", "index", "number", (arr, idx) => {
    if (idx < 0 || idx >= arr.length)
      return null;
    return arr[idx];
  }).registerResult("array", "index", "string", (arr, key, context) => {
    if (arr.length == 0)
      return Result.success([]);
    const result = [];
    for (const element of arr) {
      const resolved = context.evaluate(
        Expressions.index(Expressions.literal(element), Expressions.literal(key))
      );
      if (!resolved.successful)
        return Result.failure(resolved.error);
      result.push(resolved.value);
    }
    return Result.success(result);
  }).register("object", "index", "string", (obj, key) => {
    var _a;
    return (_a = Fieldbearings.get(obj, key)) != null ? _a : null;
  }).registerResult("link", "index", "string", indexLink).registerResult("link", "index", "number", indexLink).register("object", "index", "number", (obj, key) => {
    var _a;
    return (_a = obj[key]) != null ? _a : null;
  }).register("string", "index", "number", (str, idx) => idx < 0 || idx >= str.length ? null : str[idx]).register("date", "index", "string", indexDate).register("duration", "index", "string", indexDuration).withDefaultNullHandling();
}
function stringSettings(settings) {
  return {
    dateFormat: settings.defaultDateFormat,
    dateTimeFormat: settings.defaultDateTimeFormat,
    nullRepresentation: settings.renderNullAs
  };
}
function indexLink(link, key, context) {
  const object = context.linkHandler.resolve(link);
  if (!object)
    return Result.success(null);
  return context.evaluate(Expressions.index(Expressions.literal(object), Expressions.literal(key)));
}
function indexDate(date, key) {
  switch (key) {
    case "year":
      return date.year;
    case "month":
      return date.month;
    case "day":
      return date.day;
    case "hour":
      return date.hour;
    case "minute":
      return date.minute;
    case "second":
      return date.second;
    case "millisecond":
      return date.millisecond;
    case "week":
      return date.weekNumber;
    default:
      return null;
  }
}
function indexDuration(dur, key) {
  switch (key) {
    case "years":
      return dur.years;
    case "months":
      return dur.months;
    case "days":
      return dur.days;
    case "hours":
      return dur.hours;
    case "minutes":
      return dur.minutes;
    case "seconds":
      return dur.seconds;
    case "milliseconds":
      return dur.milliseconds;
    default:
      return null;
  }
}

// src/expression/functions.ts
var FunctionBuilder = class {
  constructor(name) {
    this.name = name;
    this.variants = [];
    this.vectorized = {};
  }
  /** Add a general function variant which accepts any number of arguments of any type. */
  vararg(impl) {
    this.variants.push({ args: [], varargs: true, impl });
    return this;
  }
  /** Add a function variant which takes in a single argument. */
  add1(argType, impl) {
    this.variants.push({
      args: [argType],
      varargs: false,
      impl: (c3, ...rest) => impl(rest[0], c3)
    });
    return this;
  }
  /** Add a function variant which takes in two typed arguments. */
  add2(arg1, arg2, impl) {
    this.variants.push({
      args: [arg1, arg2],
      varargs: false,
      impl: (c3, ...rest) => impl(rest[0], rest[1], c3)
    });
    return this;
  }
  /** Add a function variant which takes in three typed arguments. */
  add3(arg1, arg2, arg3, impl) {
    this.variants.push({
      args: [arg1, arg2, arg3],
      varargs: false,
      impl: (c3, ...rest) => impl(rest[0], rest[1], rest[2], c3)
    });
    return this;
  }
  /** Add vectorized variants which accept the given number of arguments and delegate. */
  vectorize(numArgs, positions) {
    this.vectorized[numArgs] = positions;
    return this;
  }
  /** Return a function which checks the number and type of arguments, passing them on to the first matching variant. */
  build() {
    let self2 = (context, ...args) => {
      let types = [];
      for (let arg of args) {
        let argType = Literals.typeOf(arg);
        if (!argType)
          throw Error(`Unrecognized argument type for argument '${arg}'`);
        types.push(argType);
      }
      if (this.vectorized[types.length]) {
        let vectorizedPositions = this.vectorized[types.length].filter((k4) => types[k4] == "array");
        if (vectorizedPositions.length > 0) {
          let minLength = vectorizedPositions.map((p3) => args[p3].length).reduce((p3, c3) => Math.min(p3, c3));
          let result = [];
          for (let vpos = 0; vpos < minLength; vpos++) {
            let subargs = [];
            for (let index = 0; index < args.length; index++) {
              if (vectorizedPositions.includes(index)) {
                let arr = args[index];
                subargs.push(arr[vpos]);
              } else {
                subargs.push(args[index]);
              }
            }
            result.push(self2(context, ...subargs));
          }
          return result;
        }
      }
      outer:
        for (let variant of this.variants) {
          if (variant.varargs)
            return variant.impl(context, ...args);
          if (variant.args.length != types.length)
            continue;
          for (let index = 0; index < variant.args.length; index++) {
            if (variant.args[index] != "*" && variant.args[index] != types[index])
              continue outer;
          }
          return variant.impl(context, ...args);
        }
      throw Error(`No implementation of '${this.name}' found for arguments: ${types.join(", ")}`);
    };
    return self2;
  }
};
var Functions;
((Functions2) => {
  function bind(func, context) {
    return (...args) => func(context, ...args);
  }
  Functions2.bind = bind;
  function bindAll(funcs, context) {
    let result = {};
    for (let [key, func] of Object.entries(funcs)) {
      result[key] = Functions2.bind(func, context);
    }
    return result;
  }
  Functions2.bindAll = bindAll;
})(Functions || (Functions = {}));
var DefaultFunctions;
((DefaultFunctions2) => {
  DefaultFunctions2.typeOf = new FunctionBuilder("type").add1("array", (_3) => "array").add1("boolean", (_3) => "boolean").add1("date", (_3) => "date").add1("duration", (_3) => "duration").add1("function", (_3) => "function").add1("link", (_3) => "link").add1("null", (_3) => "null").add1("number", (_3) => "number").add1("object", (_3) => "object").add1("string", (_3) => "string").add1("*", (_3) => "unknown").build();
  DefaultFunctions2.length = new FunctionBuilder("length").add1("array", (a3) => a3.length).add1("object", (a3) => Object.keys(a3).length).add1("string", (a3) => a3.length).add1("null", (_a) => 0).build();
  DefaultFunctions2.list = (_context, ...args) => args;
  DefaultFunctions2.object = (_context, ...args) => {
    if (args.length % 2 != 0)
      throw Error("object() requires an even number of arguments");
    let result = {};
    for (let index = 0; index < args.length; index += 2) {
      let key = args[index];
      if (!Literals.isString(key))
        throw Error("keys should be of type string for object(key1, value1, ...)");
      result[key] = args[index + 1];
    }
    return result;
  };
  DefaultFunctions2.link = new FunctionBuilder("link").add1("string", (a3, c3) => Link.file(c3.linkHandler.normalize(a3), false)).add1("link", (a3) => a3).add1("null", (_a) => null).vectorize(1, [0]).add2("string", "string", (t4, d3, c3) => Link.file(c3.linkHandler.normalize(t4), false, d3)).add3("string", "string", "boolean", (t4, d3, e3, c3) => Link.file(c3.linkHandler.normalize(t4), e3, d3)).add2("link", "string", (t4, d3) => t4.withDisplay(d3)).add2("null", "*", () => null).add2("*", "null", (t4, _n2, c3) => (0, DefaultFunctions2.link)(c3, t4)).vectorize(2, [0, 1]).build();
  DefaultFunctions2.embed = new FunctionBuilder("embed").add1("link", (l4) => l4.toEmbed()).vectorize(1, [0]).add2("link", "boolean", (l4, e3, c3) => e3 ? l4.toEmbed() : l4.fromEmbed()).add1("null", () => null).add2("null", "*", () => null).add2("*", "null", () => null).vectorize(2, [0, 1]).build();
  DefaultFunctions2.date = new FunctionBuilder("date").add1("string", (str) => {
    let parsedDate = PRIMITIVES.datePlus.parse(str);
    if (parsedDate.status)
      return parsedDate.value;
    else
      return null;
  }).add1("date", (d3) => d3).add1("link", (link2, c3) => {
    var _a, _b;
    if (link2.display) {
      let parsedDate2 = PRIMITIVES.date.parse(link2.display);
      if (parsedDate2.status)
        return parsedDate2.value;
    }
    let parsedDate = PRIMITIVES.date.parse(link2.path);
    if (parsedDate.status)
      return parsedDate.value;
    let resolved = c3.linkHandler.resolve(link2.path);
    if (resolved && ((_a = resolved == null ? void 0 : resolved.file) == null ? void 0 : _a.day)) {
      return (_b = resolved == null ? void 0 : resolved.file) == null ? void 0 : _b.day;
    }
    return null;
  }).add2("string", "string", (d3, f4) => {
    if (f4 === "x" || f4 === "X") {
      let match3 = NUMBER_REGEX.exec(d3);
      if (match3)
        return DateTime.fromMillis(Number.parseInt(match3[0]) * (f4 === "X" ? 1e3 : 1));
      else {
        throw Error("Not a number for format( (${ f }): ${ d }");
      }
    } else {
      let parsedDate = DateTime.fromFormat(d3, f4);
      if (parsedDate.isValid)
        return parsedDate;
      else {
        throw Error(`Can't handle format (${f4}) on date string (${d3})`);
      }
    }
  }).add1("null", () => null).vectorize(1, [0]).build();
  DefaultFunctions2.dur = new FunctionBuilder("dur").add1("string", (str) => {
    let parsedDur = PRIMITIVES.duration.parse(str.trim());
    if (parsedDur.status)
      return parsedDur.value;
    else
      return null;
  }).add1("duration", (d3) => d3).add1("null", (d3) => d3).vectorize(1, [0]).build();
  DefaultFunctions2.dateformat = new FunctionBuilder("dateformat").add2("date", "string", (date2, format) => date2.toFormat(format, { locale: currentLocale() })).add2("null", "string", (_nul, _format) => null).vectorize(2, [0]).build();
  DefaultFunctions2.localtime = new FunctionBuilder("localtime").add1("date", (d3) => d3.toLocal()).add1("null", () => null).vectorize(1, [0]).build();
  const NUMBER_REGEX = /-?[0-9]+(\.[0-9]+)?/;
  DefaultFunctions2.number = new FunctionBuilder("number").add1("number", (a3) => a3).add1("string", (str) => {
    let match3 = NUMBER_REGEX.exec(str);
    if (match3)
      return Number.parseFloat(match3[0]);
    else
      return null;
  }).add1("null", () => null).vectorize(1, [0]).build();
  DefaultFunctions2.string = new FunctionBuilder("string").add1("*", (a3, ctx) => Literals.toString(a3, stringSettings(ctx.settings))).build();
  DefaultFunctions2.round = new FunctionBuilder("round").add1("number", (n3) => Math.round(n3)).add1("null", () => null).vectorize(1, [0]).add2("number", "number", (n3, p3) => {
    if (p3 <= 0)
      return Math.round(n3);
    return parseFloat(n3.toFixed(p3));
  }).add2("number", "null", (n3) => Math.round(n3)).add2("null", "*", () => null).vectorize(2, [0]).build();
  DefaultFunctions2.min = new FunctionBuilder("min").add2("*", "null", (a3, _n2) => a3).add2("null", "*", (_n2, a3) => a3).add2("*", "*", (a3, b3, ctx) => Literals.compare(a3, b3, ctx.linkHandler.normalize) <= 0 ? a3 : b3).add1("array", (a3, ctx) => (0, DefaultFunctions2.min)(ctx, ...a3)).vararg((ctx, ...args) => args.length == 0 ? null : args.reduce((p3, c3) => (0, DefaultFunctions2.min)(ctx, p3, c3))).build();
  DefaultFunctions2.max = new FunctionBuilder("max").add2("*", "null", (a3, _n2) => a3).add2("null", "*", (_n2, a3) => a3).add2("*", "*", (a3, b3, ctx) => Literals.compare(a3, b3, ctx.linkHandler.normalize) > 0 ? a3 : b3).add1("array", (a3, ctx) => (0, DefaultFunctions2.max)(ctx, ...a3)).vararg((ctx, ...args) => args.length == 0 ? null : args.reduce((p3, c3) => (0, DefaultFunctions2.max)(ctx, p3, c3))).build();
  DefaultFunctions2.minby = new FunctionBuilder("minby").add2("array", "function", (arr, func, ctx) => {
    if (arr.length == 0)
      return null;
    let values = arr.map((v3) => {
      return { value: v3, mapped: func(ctx, v3) };
    });
    let filtered = values.filter((v3) => !Literals.isNull(v3.mapped));
    if (filtered.length == 0)
      return arr[0];
    return filtered.reduce((p3, c3) => {
      if (Literals.compare(p3.mapped, c3.mapped, ctx.linkHandler.normalize) <= 0)
        return p3;
      else
        return c3;
    }).value;
  }).add2("null", "function", (_arr, _func, _ctx) => null).build();
  DefaultFunctions2.maxby = new FunctionBuilder("maxby").add2("array", "function", (arr, func, ctx) => {
    if (arr.length == 0)
      return null;
    let values = arr.map((v3) => {
      return { value: v3, mapped: func(ctx, v3) };
    });
    let filtered = values.filter((v3) => !Literals.isNull(v3.mapped));
    if (filtered.length == 0)
      return arr[0];
    return filtered.reduce((p3, c3) => {
      if (Literals.compare(p3.mapped, c3.mapped, ctx.linkHandler.normalize) > 0)
        return p3;
      else
        return c3;
    }).value;
  }).add2("null", "function", (_arr, _func, _ctx) => null).build();
  DefaultFunctions2.striptime = new FunctionBuilder("striptime").add1("date", (d3) => DateTime.fromObject({ year: d3.year, month: d3.month, day: d3.day })).add1("null", (_n2) => null).vectorize(1, [0]).build();
  DefaultFunctions2.contains = new FunctionBuilder("contains").add2("array", "*", (l4, elem, context) => l4.some((e3) => (0, DefaultFunctions2.contains)(context, e3, elem))).add2("string", "string", (haystack, needle) => haystack.includes(needle)).add2("object", "string", (obj, key) => key in obj).add2(
    "*",
    "*",
    (elem1, elem2, context) => context.evaluate(Expressions.binaryOp(Expressions.literal(elem1), "=", Expressions.literal(elem2))).orElseThrow()
  ).vectorize(2, [1]).build();
  DefaultFunctions2.icontains = new FunctionBuilder("icontains").add2("array", "*", (l4, elem, context) => l4.some((e3) => (0, DefaultFunctions2.icontains)(context, e3, elem))).add2(
    "string",
    "string",
    (haystack, needle) => haystack.toLocaleLowerCase().includes(needle.toLocaleLowerCase())
  ).add2("object", "string", (obj, key) => key in obj).add2(
    "*",
    "*",
    (elem1, elem2, context) => context.evaluate(Expressions.binaryOp(Expressions.literal(elem1), "=", Expressions.literal(elem2))).orElseThrow()
  ).vectorize(2, [1]).build();
  DefaultFunctions2.econtains = new FunctionBuilder("econtains").add2(
    "array",
    "*",
    (l4, elem, context) => l4.some(
      (e3) => context.evaluate(Expressions.binaryOp(Expressions.literal(elem), "=", Expressions.literal(e3))).orElseThrow()
    )
  ).add2("string", "string", (haystack, needle) => haystack.includes(needle)).add2("object", "string", (obj, key) => key in obj).add2(
    "*",
    "*",
    (elem1, elem2, context) => context.evaluate(Expressions.binaryOp(Expressions.literal(elem1), "=", Expressions.literal(elem2))).orElseThrow()
  ).vectorize(2, [1]).build();
  DefaultFunctions2.containsword = new FunctionBuilder("containsword").add2(
    "string",
    "string",
    (hay, needle) => !!hay.match(new RegExp(".*\\b" + escapeRegex(needle) + "\\b.*", "i"))
  ).add2("null", "*", (_a, _b) => null).add2("*", "null", (_a, _b) => null).vectorize(2, [0, 1]).build();
  DefaultFunctions2.extract = (context, ...args) => {
    if (args.length == 0)
      return "extract(object, key1, ...) requires at least 1 argument";
    let object2 = args[0];
    if (Literals.isArray(object2))
      return object2.map((v3) => (0, DefaultFunctions2.extract)(context, v3, ...args.slice(1)));
    let result = {};
    for (let index = 1; index < args.length; index++) {
      let key = args[index];
      if (!Literals.isString(key))
        throw Error("extract(object, key1, ...) must be called with string keys");
      result[key] = context.evaluate(Expressions.index(Expressions.literal(object2), Expressions.literal(key))).orElseThrow();
    }
    return result;
  };
  DefaultFunctions2.reverse = new FunctionBuilder("reverse").add1("array", (l4) => {
    let result = [];
    for (let index = l4.length - 1; index >= 0; index--)
      result.push(l4[index]);
    return result;
  }).add1("string", (l4) => {
    let result = "";
    for (let c3 = 0; c3 < l4.length; c3++)
      result += l4[l4.length - c3 - 1];
    return result;
  }).add1("*", (e3) => e3).build();
  DefaultFunctions2.sort = new FunctionBuilder("sort").add1("array", (list2, context) => (0, DefaultFunctions2.sort)(context, list2, (_ctx, a3) => a3)).add2("array", "function", (list2, key, context) => {
    let result = [].concat(list2);
    result.sort((a3, b3) => {
      let akey = key(context, a3);
      let bkey = key(context, b3);
      let le = context.evaluate(Expressions.binaryOp(Expressions.literal(akey), "<", Expressions.literal(bkey))).orElseThrow();
      if (Literals.isTruthy(le))
        return -1;
      let eq = context.evaluate(Expressions.binaryOp(Expressions.literal(akey), "=", Expressions.literal(bkey))).orElseThrow();
      if (Literals.isTruthy(eq))
        return 0;
      return 1;
    });
    return result;
  }).add1("*", (e3) => e3).build();
  DefaultFunctions2.regextest = new FunctionBuilder("regextest").add2("string", "string", (pattern, field) => RegExp(pattern).test(field)).add2("null", "*", (_n2, _a) => false).add2("*", "null", (_a, _n2) => false).vectorize(2, [0, 1]).build();
  DefaultFunctions2.regexmatch = new FunctionBuilder("regexmatch").add2("string", "string", (pattern, field) => {
    if (!pattern.startsWith("^") && !pattern.endsWith("$"))
      pattern = "^" + pattern + "$";
    return !!field.match(pattern);
  }).add2("null", "*", (_n2, _a) => false).add2("*", "null", (_a, _n2) => false).vectorize(2, [0, 1]).build();
  DefaultFunctions2.regexreplace = new FunctionBuilder("regexreplace").add3("string", "string", "string", (field, pat, rep) => {
    try {
      let reg = new RegExp(pat, "g");
      return field.replace(reg, rep);
    } catch (ex) {
      throw Error(`Invalid regexp '${pat}' in regexreplace`);
    }
  }).add3("null", "*", "*", () => null).add3("*", "null", "*", () => null).add3("*", "*", "null", () => null).vectorize(3, [0, 1, 2]).build();
  DefaultFunctions2.lower = new FunctionBuilder("lower").add1("string", (s4) => s4.toLocaleLowerCase()).add1("null", () => null).vectorize(1, [0]).build();
  DefaultFunctions2.upper = new FunctionBuilder("upper").add1("string", (s4) => s4.toLocaleUpperCase()).add1("null", () => null).vectorize(1, [0]).build();
  DefaultFunctions2.replace = new FunctionBuilder("replace").add3("string", "string", "string", (str, pat, repr) => str.split(pat).join(repr)).add3("null", "*", "*", () => null).add3("*", "null", "*", () => null).add3("*", "*", "null", () => null).vectorize(3, [0, 1, 2]).build();
  const splitImpl = (str, delim, limit) => str.split(new RegExp(delim), limit).map((str2) => str2 || "");
  DefaultFunctions2.split = new FunctionBuilder("split").add2("string", "string", (string3, splitter) => splitImpl(string3, splitter)).add3("string", "string", "number", (string3, splitter, limit) => splitImpl(string3, splitter, limit)).add2("null", "*", () => null).add2("*", "null", () => null).add3("*", "*", "null", () => null).add3("*", "null", "*", () => null).add3("null", "*", "*", () => null).build();
  DefaultFunctions2.startswith = new FunctionBuilder("startswith").add2("string", "string", (str, starting) => str.startsWith(starting)).add2("null", "*", () => null).add2("*", "null", () => null).vectorize(2, [0, 1]).build();
  DefaultFunctions2.endswith = new FunctionBuilder("endswith").add2("string", "string", (str, ending) => str.endsWith(ending)).add2("null", "*", () => null).add2("*", "null", () => null).vectorize(2, [0, 1]).build();
  DefaultFunctions2.padleft = new FunctionBuilder("padleft").add2("string", "number", (str, len) => str.padStart(len, " ")).add3("string", "number", "string", (str, len, padding) => str.padStart(len, padding)).add2("null", "*", () => null).add2("*", "null", () => null).add3("null", "*", "*", () => null).add3("*", "null", "*", () => null).add3("*", "*", "null", () => null).vectorize(2, [0, 1]).vectorize(3, [0, 1, 2]).build();
  DefaultFunctions2.padright = new FunctionBuilder("padright").add2("string", "number", (str, len) => str.padEnd(len, " ")).add3("string", "number", "string", (str, len, padding) => str.padEnd(len, padding)).add2("null", "*", () => null).add2("*", "null", () => null).add3("null", "*", "*", () => null).add3("*", "null", "*", () => null).add3("*", "*", "null", () => null).vectorize(2, [0, 1]).vectorize(3, [0, 1, 2]).build();
  DefaultFunctions2.substring = new FunctionBuilder("substring").add2("string", "number", (str, start) => str.substring(start)).add3("string", "number", "number", (str, start, end) => str.substring(start, end)).add2("null", "*", () => null).add2("*", "null", () => null).add3("null", "*", "*", () => null).add3("*", "null", "*", () => null).add3("*", "*", "null", () => null).vectorize(2, [0, 1]).vectorize(3, [0, 1, 2]).build();
  DefaultFunctions2.truncate = new FunctionBuilder("truncate").add3("string", "number", "string", (str, length2, suffix) => {
    if (str.length > length2 - suffix.length) {
      return str.substring(0, Math.max(0, length2 - suffix.length)) + suffix;
    } else {
      return str;
    }
  }).add2("string", "number", (str, length2, ctx) => (0, DefaultFunctions2.truncate)(ctx, str, length2, "...")).add2("null", "*", () => null).add2("*", "null", () => null).add3("null", "*", "*", () => null).add3("*", "null", "*", () => null).add3("*", "*", "null", () => null).vectorize(2, [0, 1]).vectorize(3, [0, 1, 2]).build();
  DefaultFunctions2.fdefault = new FunctionBuilder("default").add2("*", "*", (v3, bk) => Literals.isNull(v3) ? bk : v3).vectorize(2, [0, 1]).build();
  DefaultFunctions2.ldefault = new FunctionBuilder("ldefault").add2("*", "*", (v3, bk) => Literals.isNull(v3) ? bk : v3).build();
  DefaultFunctions2.choice = new FunctionBuilder("choice").add3("*", "*", "*", (b3, left, right) => Literals.isTruthy(b3) ? left : right).vectorize(3, [0]).build();
  DefaultFunctions2.reduce = new FunctionBuilder("reduce").add2("array", "string", (lis, op, context) => {
    if (lis.length == 0)
      return null;
    if (op != "+" && op != "-" && op != "*" && op != "/" && op != "&" && op != "|")
      throw Error("reduce(array, op) supports '+', '-', '/', '*', '&', and '|'");
    let value = lis[0];
    for (let index = 1; index < lis.length; index++) {
      value = context.evaluate(Expressions.binaryOp(Expressions.literal(value), op, Expressions.literal(lis[index]))).orElseThrow();
    }
    return value;
  }).add2("array", "function", (lis, op, context) => {
    if (lis.length == 0)
      return null;
    let value = lis[0];
    for (let index = 1; index < lis.length; index++) {
      if (Literals.isNull(lis[index]))
        continue;
      value = op(context, value, lis[index]);
    }
    return value;
  }).add2("null", "*", () => null).add2("*", "null", () => null).vectorize(2, [1]).build();
  DefaultFunctions2.sum = new FunctionBuilder("sum").add1("array", (arr, c3) => (0, DefaultFunctions2.reduce)(c3, arr, "+")).add1("*", (e3) => e3).build();
  DefaultFunctions2.average = new FunctionBuilder("average").add1("array", (array2, context) => {
    if (array2.length == 0)
      return null;
    const add = (0, DefaultFunctions2.sum)(context, array2);
    if (add == null || add == void 0)
      return null;
    return context.evaluate(Expressions.binaryOp(Expressions.literal(add), "/", Expressions.literal(array2.length))).orElseThrow();
  }).add1("*", (e3) => e3).build();
  DefaultFunctions2.product = new FunctionBuilder("product").add1("array", (arr, c3) => (0, DefaultFunctions2.reduce)(c3, arr, "*")).add1("*", (e3) => e3).build();
  DefaultFunctions2.join = new FunctionBuilder("join").add2(
    "array",
    "string",
    (arr, sep, ctx) => arr.map((e3) => Literals.toString(e3, stringSettings(ctx.settings))).join(sep)
  ).add2("array", "null", (arr, _s, context) => (0, DefaultFunctions2.join)(context, arr, ", ")).add2("*", "string", (elem, sep, ctx) => Literals.toString(elem, stringSettings(ctx.settings))).add1("array", (arr, context) => (0, DefaultFunctions2.join)(context, arr, ", ")).add1("*", (e3, ctx) => Literals.toString(e3, stringSettings(ctx.settings))).vectorize(2, [1]).build();
  DefaultFunctions2.any = new FunctionBuilder("any").add1("array", (arr) => arr.some((v3) => Literals.isTruthy(v3))).add2("array", "function", (arr, f4, ctx) => arr.some((v3) => Literals.isTruthy(f4(ctx, v3)))).vararg((_ctx, ...args) => args.some((v3) => Literals.isTruthy(v3))).build();
  DefaultFunctions2.all = new FunctionBuilder("all").add1("array", (arr) => arr.every((v3) => Literals.isTruthy(v3))).add2("array", "function", (arr, f4, ctx) => arr.every((v3) => Literals.isTruthy(f4(ctx, v3)))).vararg((_ctx, ...args) => args.every((v3) => Literals.isTruthy(v3))).build();
  DefaultFunctions2.none = new FunctionBuilder("all").add1("array", (arr) => !arr.some((v3) => Literals.isTruthy(v3))).add2("array", "function", (arr, f4, ctx) => !arr.some((v3) => Literals.isTruthy(f4(ctx, v3)))).vararg((_ctx, ...args) => !args.some((v3) => Literals.isTruthy(v3))).build();
  DefaultFunctions2.filter = new FunctionBuilder("filter").add2("array", "function", (arr, f4, ctx) => arr.filter((v3) => Literals.isTruthy(f4(ctx, v3)))).add2("null", "*", () => null).build();
  DefaultFunctions2.map = new FunctionBuilder("map").add2("array", "function", (arr, f4, ctx) => arr.map((v3) => f4(ctx, v3))).add2("null", "*", () => null).build();
  DefaultFunctions2.nonnull = new FunctionBuilder("nonnull").add1("array", (arr) => arr.filter((v3) => Literals.typeOf(v3) != "null")).vararg((_ctx, ...args) => args.filter((v3) => Literals.typeOf(v3) != "null")).build();
  DefaultFunctions2.meta = new FunctionBuilder("meta").add1("link", (link2) => {
    var _a, _b;
    return {
      display: (_a = link2.display) != null ? _a : null,
      embed: link2.embed,
      path: link2.path,
      subpath: (_b = link2.subpath) != null ? _b : null,
      type: link2.type
    };
  }).build();
  DefaultFunctions2.flat = new FunctionBuilder("flat").add1("array", (a3) => {
    return a3.flat();
  }).add2("array", "number", (a3, n3) => a3.flat(n3)).add1("null", () => null).build();
})(DefaultFunctions || (DefaultFunctions = {}));
var DEFAULT_FUNCTIONS = {
  // Constructors.
  list: DefaultFunctions.list,
  array: DefaultFunctions.list,
  link: DefaultFunctions.link,
  embed: DefaultFunctions.embed,
  date: DefaultFunctions.date,
  dur: DefaultFunctions.dur,
  dateformat: DefaultFunctions.dateformat,
  localtime: DefaultFunctions.localtime,
  number: DefaultFunctions.number,
  string: DefaultFunctions.string,
  object: DefaultFunctions.object,
  typeof: DefaultFunctions.typeOf,
  // Math Operations.
  round: DefaultFunctions.round,
  min: DefaultFunctions.min,
  max: DefaultFunctions.max,
  minby: DefaultFunctions.minby,
  maxby: DefaultFunctions.maxby,
  // String operations.
  regexreplace: DefaultFunctions.regexreplace,
  regextest: DefaultFunctions.regextest,
  regexmatch: DefaultFunctions.regexmatch,
  replace: DefaultFunctions.replace,
  lower: DefaultFunctions.lower,
  upper: DefaultFunctions.upper,
  split: DefaultFunctions.split,
  startswith: DefaultFunctions.startswith,
  endswith: DefaultFunctions.endswith,
  padleft: DefaultFunctions.padleft,
  padright: DefaultFunctions.padright,
  substring: DefaultFunctions.substring,
  truncate: DefaultFunctions.truncate,
  // Date Operations.
  striptime: DefaultFunctions.striptime,
  // List operations.
  length: DefaultFunctions.length,
  contains: DefaultFunctions.contains,
  icontains: DefaultFunctions.icontains,
  econtains: DefaultFunctions.econtains,
  containsword: DefaultFunctions.containsword,
  reverse: DefaultFunctions.reverse,
  sort: DefaultFunctions.sort,
  flat: DefaultFunctions.flat,
  // Aggregation operations like reduce.
  reduce: DefaultFunctions.reduce,
  join: DefaultFunctions.join,
  sum: DefaultFunctions.sum,
  product: DefaultFunctions.product,
  average: DefaultFunctions.average,
  all: DefaultFunctions.all,
  any: DefaultFunctions.any,
  none: DefaultFunctions.none,
  filter: DefaultFunctions.filter,
  map: DefaultFunctions.map,
  nonnull: DefaultFunctions.nonnull,
  // Object/Utility operations.
  extract: DefaultFunctions.extract,
  default: DefaultFunctions.fdefault,
  ldefault: DefaultFunctions.ldefault,
  choice: DefaultFunctions.choice,
  meta: DefaultFunctions.meta
};

// src/expression/evaluator.ts
var Evaluator = class {
  /**
   * Create a new context with the given namespace of globals, as well as optionally with custom binary operator, function,
   * and link handlers.
   */
  constructor(linkHandler, settings, globals = {}, binaryOps = createBinaryOps(linkHandler.normalize), functions = DEFAULT_FUNCTIONS) {
    this.linkHandler = linkHandler;
    this.settings = settings;
    this.globals = globals;
    this.binaryOps = binaryOps;
    this.functions = functions;
  }
  /** Set a global value in this context. */
  set(name, value) {
    this.globals[name] = value;
    return this;
  }
  /** Get the value of a global variable by name. Returns null if not present. */
  get(name) {
    var _a;
    return (_a = this.globals[name]) != null ? _a : null;
  }
  /** Try to evaluate an arbitrary expression in this context, raising an exception on failure. */
  tryEvaluate(expr, variables = Variables.empty()) {
    return this.evaluate(expr, variables).orElseThrow();
  }
  /** Evaluate an arbitrary expression in this context. */
  evaluate(expr, variables = Variables.empty()) {
    switch (expr.type) {
      case "literal":
        return Result.success(expr.value);
      case "variable":
        if (expr.name === Expressions.ROW)
          return Result.success(variables.all());
        const resolved = variables.resolve(expr.name);
        if (resolved !== void 0)
          return Result.success(resolved);
        if (expr.name in this.globals)
          return Result.success(this.globals[expr.name]);
        return Result.success(null);
      case "negated":
        return this.evaluate(expr.child, variables).map((s4) => !Literals.isTruthy(s4));
      case "binaryop":
        return Result.flatMap2(
          this.evaluate(expr.left, variables),
          this.evaluate(expr.right, variables),
          (a3, b3) => this.binaryOps.evaluate(expr.op, a3, b3, this)
        );
      case "list":
        let result = [];
        for (let child of expr.values) {
          let subeval = this.evaluate(child, variables);
          if (!subeval.successful)
            return subeval;
          result.push(subeval.value);
        }
        return Result.success(result);
      case "object":
        let objResult = {};
        for (let [key, child] of Object.entries(expr.values)) {
          let subeval = this.evaluate(child, variables);
          if (!subeval.successful)
            return subeval;
          objResult[key] = subeval.value;
        }
        return Result.success(objResult);
      case "lambda":
        return Result.success((ctx, ...args) => {
          let locals = {};
          for (let arg = 0; arg < Math.min(args.length, expr.arguments.length); arg++) {
            locals[expr.arguments[arg]] = args[arg];
          }
          return ctx.evaluate(expr.value, Variables.lambda(variables, locals)).orElseThrow();
        });
      case "method":
        const maybeTarget = this.evaluate(expr.target, variables);
        if (!maybeTarget.successful)
          return maybeTarget;
        const target = maybeTarget.value;
        if (Literals.isObject(target)) {
          const method = target[expr.func];
          if (method && Literals.isFunction(method)) {
            return this.evaluateFunctionCall(method, expr.arguments, variables);
          }
        }
        return this.evaluateFunctionCall(expr.func, [expr.target, ...expr.arguments], variables);
      case "function":
        let rawFunc = expr.func.type == "variable" ? Result.success(expr.func.name) : this.evaluate(expr.func, variables);
        if (!rawFunc.successful)
          return rawFunc;
        return this.evaluateFunctionCall(rawFunc.value, expr.arguments, variables);
    }
  }
  /** General logic for making a function call. */
  evaluateFunctionCall(func, incomingArgs, variables) {
    const args = [];
    for (const arg of incomingArgs) {
      const resolved = this.evaluate(arg, variables);
      if (!resolved.successful)
        return resolved;
      args.push(resolved.value);
    }
    let call;
    if (Literals.isFunction(func))
      call = func;
    else if (Literals.isString(func) && func in this.functions)
      call = this.functions[func];
    else if (Literals.isString(func))
      return Result.failure(`Unrecognized function name '${func}'`);
    else
      return Result.failure(`Cannot call type '${Literals.typeOf(func)}' as a function`);
    try {
      return Result.success(call(this, ...args));
    } catch (e3) {
      return Result.failure(e3.message);
    }
  }
};
var ObjectVariables = class {
  constructor(object) {
    this.object = object;
  }
  all() {
    return this.object;
  }
  resolve(name) {
    return this.object[name];
  }
};
var FieldbearingVariables = class {
  constructor(object) {
    this.object = object;
  }
  all() {
    const object = {};
    for (const field of this.object.fields) {
      object[field.key] = field.value;
    }
    return object;
  }
  resolve(name) {
    var _a;
    return (_a = this.object.field(name)) == null ? void 0 : _a.value;
  }
};
var LambdaVariables = class {
  constructor(parent, locals) {
    this.parent = parent;
    this.locals = locals;
  }
  all() {
    return { ...this.parent.all(), ...this.locals };
  }
  resolve(name) {
    var _a;
    return (_a = this.locals[name]) != null ? _a : this.parent.resolve(name);
  }
};
var Variables;
((Variables2) => {
  function empty() {
    return new ObjectVariables({});
  }
  Variables2.empty = empty;
  function infer(object) {
    if (Fieldbearings.isFieldbearing(object)) {
      return new FieldbearingVariables(object);
    } else {
      return new ObjectVariables(object);
    }
  }
  Variables2.infer = infer;
  function lambda(parent, locals) {
    return new LambdaVariables(parent, locals);
  }
  Variables2.lambda = lambda;
})(Variables || (Variables = {}));

// src/api/api.ts
var DatacoreApi = class {
  constructor(core) {
    this.core = core;
    ///////////////////////
    // General utilities //
    ///////////////////////
    /** Utilities for coercing types into one specific type for easier programming. */
    this.coerce = Coerce;
  }
  /** Get access to luxon functions. */
  get luxon() {
    return luxon_exports;
  }
  /** Get access to preact functions. */
  get preact() {
    return preact_module_exports;
  }
  /** Central Obsidian app object. */
  get app() {
    return this.core.app;
  }
  ///////////////
  // Local API //
  ///////////////
  /** Construct a local API for the file at the given path. */
  local(path) {
    return new DatacoreLocalApi(this, path);
  }
  page(path) {
    const realPath = path instanceof Link ? path.path : path;
    return this.core.datastore.load(realPath);
  }
  query(query) {
    return this.tryQuery(query).orElseThrow();
  }
  tryQuery(query) {
    return this.tryFullQuery(query).map((result) => result.results);
  }
  fullquery(query) {
    return this.tryFullQuery(query).orElseThrow();
  }
  tryFullQuery(query) {
    const parsedQuery = typeof query === "string" ? QUERY.query.tryParse(query) : query;
    return this.core.datastore.search(parsedQuery);
  }
  /** Resolve a local or absolute path or link to an absolute path. */
  resolvePath(path, sourcePath) {
    const rawpath = path instanceof Link ? path.path : path;
    if (rawpath.startsWith("/"))
      return rawpath.substring(1);
    const absolute = this.core.metadataCache.getFirstLinkpathDest(rawpath, sourcePath != null ? sourcePath : "");
    if (absolute)
      return absolute.path;
    return rawpath;
  }
  /** Try to parse the given query, returning a monadic success/failure result. */
  tryParseQuery(query) {
    if (!(typeof query === "string"))
      return Result.success(query);
    const result = QUERY.query.parse(query);
    if (result.status)
      return Result.success(result.value);
    else
      return Result.failure(import_parsimmon.default.formatError(query, result));
  }
  /** Try to parse the given query, throwing an error if it is invalid. */
  parseQuery(query) {
    return this.tryParseQuery(query).orElseThrow((e3) => "Failed to parse query: " + e3);
  }
  /** Create a file link pointing to the given path. */
  fileLink(path) {
    return Link.file(path);
  }
  /** Create a link to a header with the given name. */
  headerLink(path, header) {
    return Link.header(path, header);
  }
  /** Create a link to a block with the given path and block ID. */
  blockLink(path, block) {
    return Link.block(path, block);
  }
  /** Try to parse the given link, throwing an error if it is invalid. */
  parseLink(linktext) {
    return this.tryParseLink(linktext).orElseThrow((e3) => "Failed to parse link: " + e3);
  }
  /** Try to parse a link, returning a monadic success/failure result. */
  tryParseLink(linktext) {
    const parsed = PRIMITIVES.embedLink.parse(linktext);
    if (!parsed.status)
      return Result.failure(import_parsimmon.default.formatError(linktext, parsed));
    return Result.success(parsed.value);
  }
  /** Create a data array from a regular array. */
  array(input2) {
    return DataArray.wrap(input2);
  }
  /** Evaluate an expression and return it's evaluated value, throwing an exception on failure. */
  evaluate(expression, variables, sourcePath) {
    return this.tryEvaluate(expression, variables, sourcePath).orElseThrow();
  }
  /** Evaluate an expression and return it's evaluated value. */
  tryEvaluate(expression, variables, sourcePath) {
    if (typeof expression === "string") {
      const parsed = EXPRESSION.expression.parse(expression);
      if (!parsed.status)
        return Result.failure(import_parsimmon.default.formatError(expression, parsed));
      expression = parsed.value;
    }
    return this.core.datastore.evaluator(sourcePath).evaluate(expression, Variables.infer(variables));
  }
  /////////////////////
  // Visual Elements //
  /////////////////////
  /**
   * Run the given DatacoreJS script, rendering it into the given container. This function
   * will return quickly; actual rendering is done asynchronously in the background.
   *
   * Returns a markdown render child representing the rendered object.
   */
  executeJs(source, container, component, sourcePath) {
    return this._renderJavascript(source, container, component, sourcePath, "js");
  }
  /**
   * Similar to `executeJs`, but for JSX scripts. If you are unsure if your input will be JS
   * or JSX, use this one, as it also supports regular javascript (albeit at at a mild performance
   * hit to rendering).
   */
  executeJsx(source, container, component, sourcePath) {
    return this._renderJavascript(source, container, component, sourcePath, "jsx");
  }
  /**
   * Similar to `executeJs`, but for TypeScript scripts. Use the TSX variant for TSX supprot.
   */
  executeTs(source, container, component, sourcePath) {
    return this._renderJavascript(source, container, component, sourcePath, "ts");
  }
  /**
   * Similar to `executeTs`, but for TSX scripts. If you are unsure if your input will be TS
   * or TSX, use this one, as it also supports regular javascript (albeit at at a mild performance
   * hit to rendering).
   *
   * This generally will also work if you are unsure if your input is javascript or typescript,
   * though beware there are a few niche cases where javascript and typescript diverge in syntax.
   */
  executeTsx(source, container, component, sourcePath) {
    return this._renderJavascript(source, container, component, sourcePath, "tsx");
  }
  /** Shared logic for rendering any JS/TS script. */
  _renderJavascript(source, container, component, sourcePath, language) {
    let local = new DatacoreLocalApi(this, sourcePath);
    const renderer = new DatacoreJSRenderer(local, container, sourcePath, source, language);
    component.addChild(renderer);
    return renderer;
  }
};

// src/index/storage/folder.ts
var import_obsidian5 = require("obsidian");
var _FolderIndex = class {
  constructor(vault) {
    this.vault = vault;
  }
  /** Get the list of all files under the given path. */
  get(prefix, filter) {
    let folder = this.vault.getAbstractFileByPath(prefix || "/");
    if (!folder) {
      return _FolderIndex.EMPTY_SET;
    } else if (folder instanceof import_obsidian5.TFolder) {
      return new Set(this.walk(folder, filter));
    } else {
      if (!filter || filter(prefix)) {
        return new Set(prefix);
      } else {
        return _FolderIndex.EMPTY_SET;
      }
    }
  }
  /** Get the list of files specifically under the given path. */
  getExact(prefix, filter) {
    let folder = this.vault.getAbstractFileByPath(prefix || "/");
    if (!folder) {
      return _FolderIndex.EMPTY_SET;
    } else if (folder instanceof import_obsidian5.TFolder) {
      const elements = /* @__PURE__ */ new Set();
      for (const file of folder.children) {
        if (!(file instanceof import_obsidian5.TFile))
          continue;
        if (filter && !filter(file.path))
          continue;
        elements.add(file.path);
      }
      return elements;
    } else {
      if (!filter || filter(prefix)) {
        return new Set(prefix);
      } else {
        return _FolderIndex.EMPTY_SET;
      }
    }
  }
  /** Determines if the given path exists in the index. */
  pathExists(path) {
    return this.vault.getAbstractFileByPath(path || "/") != null;
  }
  /** Determines if the given folder exists in the index. */
  folderExists(folder) {
    return this.vault.getAbstractFileByPath(folder || "/") instanceof import_obsidian5.TFolder;
  }
  /**
   * Use the in-memory prefix index to convert a relative path to an absolute one.
   */
  resolveRelative(path, origin) {
    if (!origin)
      return path;
    else if (path.startsWith("/"))
      return path.substring(1);
    let relativePath = getParentFolder(origin) + "/" + path;
    if (this.pathExists(relativePath))
      return relativePath;
    else
      return path;
  }
  *walk(folder, filter) {
    for (const file of folder.children) {
      if (file instanceof import_obsidian5.TFolder) {
        yield* this.walk(file, filter);
      } else if (filter ? filter(file.path) : true) {
        yield file.path;
      }
    }
  }
};
var FolderIndex = _FolderIndex;
/** Empty placeholder set. */
FolderIndex.EMPTY_SET = /* @__PURE__ */ new Set();

// src/index/storage/inverted.ts
var _InvertedIndex = class {
  constructor() {
    this.inverted = /* @__PURE__ */ new Map();
  }
  /** Set the key to the given values. */
  set(key, values) {
    for (let value of values) {
      if (!this.inverted.has(value))
        this.inverted.set(value, /* @__PURE__ */ new Set());
      this.inverted.get(value).add(key);
    }
  }
  /** Get all keys that map to the given value. */
  get(value) {
    var _a;
    return (_a = this.inverted.get(value)) != null ? _a : _InvertedIndex.EMPTY_SET;
  }
  /** Delete a key from the set of associated values. */
  delete(key, values) {
    for (let value of values) {
      const set = this.inverted.get(value);
      if (set) {
        set.delete(key);
      }
      if (set && set.size == 0) {
        this.inverted.delete(value);
      }
    }
  }
  clear() {
    this.inverted.clear();
  }
};
var InvertedIndex = _InvertedIndex;
InvertedIndex.EMPTY_SET = /* @__PURE__ */ new Set();

// node_modules/flatqueue/index.js
var FlatQueue = class {
  constructor() {
    this.ids = [];
    this.values = [];
    this.length = 0;
  }
  clear() {
    this.length = 0;
  }
  push(id, value) {
    let pos = this.length++;
    while (pos > 0) {
      const parent = pos - 1 >> 1;
      const parentValue = this.values[parent];
      if (value >= parentValue)
        break;
      this.ids[pos] = this.ids[parent];
      this.values[pos] = parentValue;
      pos = parent;
    }
    this.ids[pos] = id;
    this.values[pos] = value;
  }
  pop() {
    if (this.length === 0)
      return void 0;
    const top = this.ids[0];
    this.length--;
    if (this.length > 0) {
      const id = this.ids[0] = this.ids[this.length];
      const value = this.values[0] = this.values[this.length];
      const halfLength = this.length >> 1;
      let pos = 0;
      while (pos < halfLength) {
        let left = (pos << 1) + 1;
        const right = left + 1;
        let bestIndex = this.ids[left];
        let bestValue = this.values[left];
        const rightValue = this.values[right];
        if (right < this.length && rightValue < bestValue) {
          left = right;
          bestIndex = this.ids[right];
          bestValue = rightValue;
        }
        if (bestValue >= value)
          break;
        this.ids[pos] = bestIndex;
        this.values[pos] = bestValue;
        pos = left;
      }
      this.ids[pos] = id;
      this.values[pos] = value;
    }
    return top;
  }
  peek() {
    if (this.length === 0)
      return void 0;
    return this.ids[0];
  }
  peekValue() {
    if (this.length === 0)
      return void 0;
    return this.values[0];
  }
  shrink() {
    this.ids.length = this.values.length = this.length;
  }
};

// src/index/storage/fields.ts
var import_sorted_btree = __toESM(require_b_tree());
var EverythingFieldIndex = class {
  constructor(all) {
    this.all = all;
  }
  add(id, value) {
  }
  delete(id, value) {
  }
  equals(value) {
    return void 0;
  }
};
var IdFieldIndex = class {
  constructor(all, lookup) {
    this.all = all;
    this.lookup = lookup;
  }
  add(id, value) {
  }
  delete(id, value) {
  }
  equals(value) {
    if (!Literals.isString(value))
      return void 0;
    if (this.lookup(value)) {
      return /* @__PURE__ */ new Set([value]);
    } else {
      return void 0;
    }
  }
};
var SetFieldIndex = class {
  constructor() {
    this.present = /* @__PURE__ */ new Set();
  }
  /** Add an (object, value) pairing to the collection. */
  add(id, value) {
    this.present.add(id);
  }
  /** Delete an (object, value) pairing from the collection. */
  delete(id, value) {
    this.present.delete(id);
  }
  /** Return a set of all pages in which the field exists at all (even if undefined). */
  all() {
    return this.present;
  }
  /** Return all pages with a value exactly equal to the given value. */
  equals(value) {
    return void 0;
  }
};
var _BTreeFieldIndex = class {
  constructor() {
    this.present = /* @__PURE__ */ new Set();
    this.values = new import_sorted_btree.default([], (a3, b3) => Literals.compare(a3, b3));
  }
  /** Add an (object, value) pairing to the collection. */
  add(id, value) {
    this.present.add(id);
    this.values.setIfNotPresent(value, /* @__PURE__ */ new Set());
    this.values.get(value).add(id);
  }
  /** Delete an (object, value) pairing from the collection. */
  delete(id, value) {
    this.present.delete(id);
    const set = this.values.get(value);
    set == null ? void 0 : set.delete(id);
    if (set == null || set.size == 0) {
      this.values.delete(value);
    }
  }
  /** Return a set of all pages in which the field exists at all (even if undefined). */
  all() {
    return this.present;
  }
  /** Return all pages with a value exactly equal to the given value. */
  equals(value) {
    return this.values.get(value, _BTreeFieldIndex.EMPTY_SET);
  }
};
var BTreeFieldIndex = _BTreeFieldIndex;
/** Placeholder empty set. */
BTreeFieldIndex.EMPTY_SET = /* @__PURE__ */ new Set();

// src/index/storage/query-executor.ts
function optimizeQuery(query) {
  query = denest(query);
  query = constantfold(query);
  return query;
}
function denest(query) {
  switch (query.type) {
    case "and":
      const ands = query.elements.flatMap((element) => {
        const fixed = denest(element);
        if (fixed.type === "and")
          return fixed.elements;
        else
          return [fixed];
      });
      return { type: "and", elements: ands };
    case "or":
      const ors = query.elements.flatMap((element) => {
        const fixed = denest(element);
        if (fixed.type === "or")
          return fixed.elements;
        else
          return [fixed];
      });
      return { type: "or", elements: ors };
    case "not":
      return { type: "not", element: denest(query.element) };
    case "child-of":
      return Object.assign({}, query, { parents: denest(query.parents) });
    case "parent-of":
      return Object.assign({}, query, { children: denest(query.children) });
    case "linked":
      return Object.assign({}, query, { source: denest(query.source) });
    default:
      return query;
  }
}
function constantfold(query) {
  switch (query.type) {
    case "and":
      const achildren = [];
      for (const child of query.elements) {
        const folded2 = constantfold(child);
        if (folded2.type === "constant") {
          if (folded2.constant)
            continue;
          else
            return { type: "constant", constant: false };
        }
        achildren.push(folded2);
      }
      return { type: "and", elements: achildren };
    case "or":
      const ochildren = [];
      for (const child of query.elements) {
        const folded2 = constantfold(child);
        if (folded2.type === "constant") {
          if (!folded2.constant)
            continue;
          else
            return { type: "constant", constant: true };
        }
        ochildren.push(folded2);
      }
      return { type: "or", elements: ochildren };
    case "not":
      const folded = constantfold(query.element);
      if (folded.type === "constant") {
        return { type: "constant", constant: !folded.constant };
      }
      return { type: "not", element: folded };
    case "child-of":
      const parents = constantfold(query.parents);
      if (parents.type === "constant") {
        if (!parents.constant)
          return { type: "constant", constant: false };
        else if (parents.constant && query.inclusive)
          return { type: "constant", constant: true };
      }
      return Object.assign({}, query, { parents });
    case "parent-of":
      const children = constantfold(query.children);
      if (children.type === "constant") {
        if (!children.constant)
          return { type: "constant", constant: false };
        else if (children.constant && query.inclusive)
          return { type: "constant", constant: true };
      }
      return Object.assign({}, query, { children });
    case "linked":
      const source = constantfold(query.source);
      if (source.type === "constant") {
        if (!source.constant)
          return { type: "constant", constant: false };
        else if (source.constant && query.inclusive)
          return { type: "constant", constant: true };
      }
      return Object.assign({}, query, { source });
    default:
      return query;
  }
}
function execute(query, resolver, evaluator) {
  return simplify(query, resolver).flatMap((tree) => collapse(tree, resolver, evaluator));
}
function simplify(query, resolver) {
  switch (query.type) {
    case "and":
      return Result.mapAll(query.elements, (child) => simplify(child, resolver)).map((elements) => {
        const flattened = elements.flatMap(
          (element) => element.type === "and" ? element.elements : [element]
        );
        const other = [];
        const primitive = Filters.lazyIntersect(flattened, (element) => {
          if (element.type === "filter")
            return element.filter;
          else {
            other.push(element);
            return void 0;
          }
        });
        if (primitive.type === "nothing")
          return { type: "filter", filter: Filters.NOTHING };
        else if (primitive.type != "everything")
          other.push(FilterTrees.filter(primitive));
        return FilterTrees.and(other);
      });
    case "or":
      return Result.mapAll(query.elements, (child) => simplify(child, resolver)).map((elements) => {
        const flattened = elements.flatMap((element) => element.type === "or" ? element.elements : [element]);
        const other = [];
        const primitive = Filters.lazyUnion(flattened, (element) => {
          if (element.type === "filter")
            return element.filter;
          else {
            other.push(element);
            return void 0;
          }
        });
        if (primitive.type === "everything")
          return { type: "filter", filter: Filters.EVERYTHING };
        else if (primitive.type != "nothing")
          other.push(FilterTrees.filter(primitive));
        return FilterTrees.or(other);
      });
    case "not":
      return simplify(query.element, resolver).map(FilterTrees.not);
    case "expression":
      const candidates = hasVariables(query.expression, resolver);
      return Result.success({ type: "scan", candidates, expression: query.expression });
    default:
      return resolver.resolve(query).map((filter) => ({ type: "filter", filter }));
  }
}
function collapse(tree, resolver, evaluator, limit = Filters.EVERYTHING) {
  switch (tree.type) {
    case "or":
      return Filters.lazyFailableUnion(tree.elements, (element) => collapse(element, resolver, evaluator, limit));
    case "and":
      const primitives = tree.elements.filter((elem) => elem.type === "filter").map((f4) => f4.filter);
      let restrictedLimit = Filters.intersect([limit, ...primitives]);
      for (const element of tree.elements) {
        if (element.type === "filter")
          continue;
        const maybeEvaluated = collapse(element, resolver, evaluator, restrictedLimit);
        if (!maybeEvaluated.successful)
          return maybeEvaluated.cast();
        const evaluated = maybeEvaluated.value;
        restrictedLimit = Filters.intersect([restrictedLimit, evaluated]);
        if (restrictedLimit.type === "nothing")
          return Result.success(Filters.NOTHING);
      }
      return Result.success(restrictedLimit);
    case "not":
      return collapse(tree.element, resolver, evaluator, limit).map(Filters.negate);
    case "filter":
      return Result.success(tree.filter);
    case "scan":
      const candidates = Filters.resolve(Filters.intersect([tree.candidates, limit]), resolver.universe);
      return filterScan(candidates, tree.expression, evaluator, resolver).map(Filters.atom);
  }
}
function filterScan(candidates, expr, evaluator, resolver) {
  const result = /* @__PURE__ */ new Set();
  for (const candidate of candidates) {
    const object = resolver.load(candidate);
    if (!object)
      continue;
    const value = evaluator.evaluate(expr, Variables.infer(object));
    if (!value.successful) {
      return Result.failure(`Error while evaluating expression "${Expressions.toString(expr)}": ${value.error}`);
    } else {
      if (Literals.isTruthy(value.value))
        result.add(candidate);
    }
  }
  return Result.success(result);
}
function hasVariables(expr, resolver) {
  const variables = Expressions.unboundVariables(expr, /* @__PURE__ */ new Set([Expressions.ROW, "this"]));
  if (variables.size == 0)
    return Filters.EVERYTHING;
  return Filters.lazyUnion(variables, (variable) => resolver.resolvePrimitive({ type: "field", value: variable }));
}
var FilterTrees;
((FilterTrees2) => {
  function filter(filter2) {
    return { type: "filter", filter: filter2 };
  }
  FilterTrees2.filter = filter;
  function and(children) {
    if (children.length == 0)
      return filter(Filters.EVERYTHING);
    else if (children.length == 1)
      return children[0];
    else
      return { type: "and", elements: children };
  }
  FilterTrees2.and = and;
  function or(children) {
    if (children.length == 0)
      return filter(Filters.NOTHING);
    else if (children.length == 1)
      return children[0];
    else
      return { type: "or", elements: children };
  }
  FilterTrees2.or = or;
  function not(child) {
    if (child.type === "filter")
      return { type: "filter", filter: Filters.negate(child.filter) };
    else
      return { type: "not", element: child };
  }
  FilterTrees2.not = not;
})(FilterTrees || (FilterTrees = {}));

// src/index/datastore.ts
var Datastore = class {
  constructor(vault, metadataCache, settings) {
    this.vault = vault;
    this.metadataCache = metadataCache;
    this.settings = settings;
    this.revision = 0;
    this.ids = /* @__PURE__ */ new Set();
    this.objects = /* @__PURE__ */ new Map();
    this.children = /* @__PURE__ */ new Map();
    this.types = new InvertedIndex();
    this.etags = new InvertedIndex();
    this.tags = new InvertedIndex();
    this.links = new InvertedIndex();
    this.fields = this._initializeFields();
    this.folder = new FolderIndex(vault);
  }
  /** Return the total number of objects in the store. */
  get size() {
    return this.objects.size;
  }
  /** Update the revision of the datastore due to an external update. */
  touch() {
    this.revision += 1;
  }
  /** Load an object by ID or list of IDs. */
  load(id) {
    if (Array.isArray(id)) {
      return id.map((a3) => this.load(a3)).filter((obj) => obj !== void 0);
    }
    return this.objects.get(id);
  }
  /** Sets up sane field defaults for several indexable fields. */
  _initializeFields() {
    const fields = /* @__PURE__ */ new Map();
    fields.set(
      "$id",
      new IdFieldIndex(
        () => this.ids,
        (id) => this.objects.has(id)
      )
    );
    fields.set("$types", new EverythingFieldIndex(() => this.ids));
    fields.set("$typename", new EverythingFieldIndex(() => this.ids));
    fields.set("$revision", new EverythingFieldIndex(() => this.ids));
    fields.set("$completed", new BTreeFieldIndex());
    fields.set("$status", new BTreeFieldIndex());
    return fields;
  }
  /**
   * Store the given object, making it immediately queryable. Storing an object
   * takes ownership over it, and index-specific variables (prefixed via '$') may be
   * added to the object.
   */
  store(object, substorer) {
    this._recursiveStore(object, this.revision++, substorer, void 0);
  }
  /** Recursively store objects using a potential subindexer. */
  _recursiveStore(object, revision, substorer, parent) {
    if (Literals.isArray(object)) {
      for (let element of object) {
        this._recursiveStore(element, revision, substorer, parent);
      }
      return;
    }
    this._deleteRecursive(object.$id);
    object.$revision = revision;
    object.$parent = parent;
    this.ids.add(object.$id);
    this.objects.set(object.$id, object);
    if (parent) {
      if (!this.children.has(parent.$id))
        this.children.set(parent.$id, /* @__PURE__ */ new Set());
      this.children.get(parent.$id).add(object.$id);
    }
    this._index(object);
    substorer == null ? void 0 : substorer(object, (incoming, subindex) => this._recursiveStore(incoming, revision, subindex, object));
  }
  /** Delete an object by ID from the index, recursively deleting any child objects as well. */
  delete(id) {
    if (this._deleteRecursive(id)) {
      this.revision++;
      return true;
    }
    return false;
  }
  /** Internal method that does not bump the revision. */
  _deleteRecursive(id) {
    const object = this.objects.get(id);
    if (!object) {
      return false;
    }
    const children = this.children.get(id);
    if (children) {
      for (let child of children) {
        this._deleteRecursive(child);
      }
      this.children.delete(id);
    }
    this._unindex(object);
    this.ids.delete(id);
    this.objects.delete(id);
    return true;
  }
  /** Add the given indexable to the appropriate indices. */
  _index(object) {
    this.types.set(object.$id, object.$types);
    if (object.$types.contains(TAGGABLE_TYPE) && iterableExists(object, "$tags")) {
      const tags = object.$tags;
      this.etags.set(object.$id, tags);
      this.tags.set(object.$id, extractSubtags(tags));
    }
    if (object.$types.contains(LINKBEARING_TYPE) && iterableExists(object, "$links")) {
      this.links.set(
        object.$id,
        object.$links.map((link) => link.obsidianLink())
      );
    }
    if (object.$types.contains(FIELDBEARING_TYPE) && "fields" in object) {
      for (const field of object.fields) {
        const norm = field.key.toLowerCase();
        if (!this.fields.has(norm))
          this.fields.set(norm, new SetFieldIndex());
        this.fields.get(norm).add(object.$id, field.value);
      }
    }
  }
  /** Remove the given indexable from all indices. */
  _unindex(object) {
    this.types.delete(object.$id, object.$types);
    if (object.$types.contains(TAGGABLE_TYPE) && iterableExists(object, "$tags")) {
      const tags = object.$tags;
      this.etags.delete(object.$id, tags);
      this.tags.delete(object.$id, extractSubtags(tags));
    }
    if (object.$types.contains(LINKBEARING_TYPE) && iterableExists(object, "$links")) {
      this.links.delete(
        object.$id,
        object.$links.map((link) => link.obsidianLink())
      );
    }
    if (object.$types.contains(FIELDBEARING_TYPE) && "fields" in object) {
      for (const field of object.fields) {
        const norm = field.key.toLowerCase();
        if (!this.fields.has(norm))
          continue;
        this.fields.get(norm).delete(object.$id, field.value);
      }
    }
  }
  /** Completely clear the datastore of all values. */
  clear() {
    this.ids.clear();
    this.objects.clear();
    this.children.clear();
    this.types.clear();
    this.tags.clear();
    this.etags.clear();
    this.links.clear();
    this.fields.clear();
    this.revision++;
  }
  /** Find the corresponding object for a given link. */
  resolveLink(rawLink, sourcePath) {
    let link = typeof rawLink === "string" ? Link.parseInner(rawLink) : rawLink;
    if (sourcePath) {
      const linkdest = this.metadataCache.getFirstLinkpathDest(link.path, sourcePath);
      if (linkdest)
        link = link.withPath(linkdest.path);
    }
    const file = this.objects.get(link.path);
    if (!file)
      return void 0;
    if (link.type === "file")
      return file;
    if (!(file instanceof MarkdownPage))
      return void 0;
    if (link.type === "header") {
      const section = file.$sections.find(
        (sec) => normalizeHeaderForLink(sec.$title) == link.subpath || sec.$title == link.subpath
      );
      if (section)
        return section;
      else
        return void 0;
    } else if (link.type === "block") {
      for (const section of file.$sections) {
        const block = section.$blocks.find((bl) => bl.$blockId === link.subpath);
        if (block)
          return block;
      }
      return void 0;
    } else {
      throw new Error(`Unrecognized link type: ${link.type}`);
    }
  }
  /**
   * Search the datastore for all documents matching the given query, returning them
   * as a list of indexed objects along with performance metadata.
   */
  search(query, settings) {
    var _a;
    const start = Date.now();
    const maybeFilter = this._search(query, settings);
    if (!maybeFilter.successful)
      return maybeFilter.cast();
    const result = Filters.resolve(maybeFilter.value, this.ids);
    const objects = [];
    let maxRevision = 0;
    for (let id of result) {
      const object = this.objects.get(id);
      if (object) {
        objects.push(object);
        maxRevision = Math.max(maxRevision, (_a = object.$revision) != null ? _a : 0);
      }
    }
    return Result.success({
      query,
      results: objects,
      duration: (Date.now() - start) / 1e3,
      revision: maxRevision
    });
  }
  /** Create an expression evaluator backed by this datastore. */
  evaluator(sourcePath, globals) {
    return new Evaluator(
      {
        exists: (path) => this.resolveLink(typeof path == "string" ? Link.file(path) : path, sourcePath) != null,
        resolve: (path) => {
          var _a;
          return (_a = this.resolveLink(typeof path == "string" ? Link.file(path) : path, sourcePath)) != null ? _a : null;
        },
        normalize: (path) => {
          var _a, _b;
          return (_b = (_a = this.metadataCache.getFirstLinkpathDest(path, sourcePath != null ? sourcePath : "")) == null ? void 0 : _a.path) != null ? _b : path;
        }
      },
      this.settings,
      globals
    );
  }
  /** Internal search which yields a filter of results. */
  _search(query, settings) {
    const sourcePath = settings == null ? void 0 : settings.sourcePath;
    const evaluator = this.evaluator(sourcePath);
    const file = sourcePath ? this.objects.get(sourcePath) : void 0;
    if (file)
      evaluator.set("this", file);
    const resolver = {
      universe: this.ids,
      resolve: (leaf) => this._resolveSource(leaf, settings),
      resolvePrimitive: (leaf) => this._resolvePrimitive(leaf, settings),
      load: (id) => this.load(id)
    };
    return execute(optimizeQuery(query), resolver, evaluator);
  }
  _resolveSource(query, settings) {
    var _a, _b;
    switch (query.type) {
      case "child-of":
        const maybeParents = this._search(query.parents, settings);
        if (!maybeParents.successful)
          return maybeParents.cast();
        const parents = maybeParents.value;
        if (Filters.empty(parents)) {
          return Result.success(Filters.NOTHING);
        } else if (parents.type === "everything") {
          if (query.inclusive)
            return Result.success(Filters.EVERYTHING);
          const allChildren = /* @__PURE__ */ new Set();
          for (const element of this.objects.values()) {
            if (element.$parent)
              allChildren.add(element.$id);
          }
          return Result.success(Filters.atom(allChildren));
        }
        const resolvedParents = Filters.resolve(parents, this.ids);
        const childResults = new Set(query.inclusive ? resolvedParents : []);
        for (const parent of resolvedParents) {
          for (const child of this._iterateChildren(parent)) {
            childResults.add(child);
          }
        }
        return Result.success(Filters.atom(childResults));
      case "parent-of":
        const maybeChildren = this._search(query.children, settings);
        if (!maybeChildren.successful)
          return maybeChildren.cast();
        const children = maybeChildren.value;
        if (Filters.empty(children)) {
          return Result.success(Filters.NOTHING);
        } else if (children.type === "everything") {
          if (query.inclusive)
            return Result.success(Filters.EVERYTHING);
          return Result.success(Filters.atom(new Set(this.children.keys())));
        }
        const resolvedChildren = Filters.resolve(children, this.ids);
        const parentResults = new Set(query.inclusive ? resolvedChildren : []);
        for (const child of resolvedChildren) {
          for (const parent of this._iterateParents(child)) {
            parentResults.add(parent);
          }
        }
        return Result.success(Filters.atom(parentResults));
      case "linked":
        if (query.distance && query.distance < 0)
          return Result.success(Filters.NOTHING);
        const maybeSources = this._search(query.source, settings);
        if (!maybeSources.successful)
          return maybeSources.cast();
        const sources = maybeSources.value;
        if (Filters.empty(sources))
          return Result.success(Filters.NOTHING);
        else if (sources.type === "everything") {
          if (query.inclusive)
            return Result.success(Filters.EVERYTHING);
          else
            return Result.success(Filters.NOTHING);
        }
        const resolvedSources = Filters.resolve(sources, this.ids);
        const direction = (_a = query.direction) != null ? _a : "both";
        const results = this._traverseLinked(
          resolvedSources,
          (_b = query.distance) != null ? _b : 1,
          (id) => this._iterateAdjacentLinked(id, direction)
        );
        if (!query.inclusive)
          return Result.success(Filters.atom(Filters.setIntersectNegation(results, resolvedSources)));
        else
          return Result.success(Filters.atom(results));
      default:
        return Result.success(this._resolvePrimitive(query, settings));
    }
  }
  /** Resolve leaf nodes in a search AST, yielding raw sets of results. */
  _resolvePrimitive(query, settings) {
    var _a, _b;
    switch (query.type) {
      case "constant":
        return Filters.constant(query.constant);
      case "id":
        const exactObject = this.objects.get(query.value);
        return exactObject ? Filters.atom(/* @__PURE__ */ new Set([exactObject.$id])) : Filters.NOTHING;
      case "link":
        const resolvedPath = (_b = this.metadataCache.getFirstLinkpathDest(
          query.value.path,
          (_a = settings == null ? void 0 : settings.sourcePath) != null ? _a : ""
        )) == null ? void 0 : _b.path;
        const resolved = resolvedPath ? query.value.withPath(resolvedPath) : query.value;
        const object = this.resolveLink(resolved);
        return object ? Filters.atom(/* @__PURE__ */ new Set([object.$id])) : Filters.NOTHING;
      case "typed":
        return Filters.nullableAtom(this.types.get(query.value));
      case "tagged":
        if (query.exact) {
          return Filters.nullableAtom(this.etags.get(query.value));
        } else {
          return Filters.nullableAtom(this.tags.get(query.value));
        }
      case "path":
        let toplevel;
        if (query.exact) {
          toplevel = this.folder.getExact(query.value);
        } else {
          if (query.value == "" || query.value == "/")
            return Filters.EVERYTHING;
          toplevel = this.folder.get(query.value);
        }
        if (toplevel.size == 0)
          return Filters.NOTHING;
        const result = new Set(toplevel);
        for (let top of toplevel) {
          for (let child of this._iterateChildren(top)) {
            result.add(child);
          }
        }
        return Filters.atom(result);
      case "field":
        const normkey = query.value.toLowerCase();
        const fieldIndex = this.fields.get(normkey);
        if (fieldIndex == null)
          return Filters.NOTHING;
        return Filters.atom(fieldIndex.all());
      case "equal-value":
        return Filters.lazyUnion(
          query.values,
          (value) => this._filterFields(
            query.field,
            (index) => index.equals(value),
            (field) => Literals.compare(value, field.value) == 0
          )
        );
    }
  }
  /** Filter documents by field values, using the fast lookup if it returns a result and otherwise filtering over every document using the slow predicate. */
  _filterFields(key, fast, slow) {
    const normkey = key.toLowerCase();
    const index = this.fields.get(normkey);
    if (index == null)
      return Filters.NOTHING;
    const fastlookup = fast(index);
    if (fastlookup != null)
      return Filters.atom(fastlookup);
    const matches = /* @__PURE__ */ new Set();
    for (const objectId of index.all()) {
      const object = this.objects.get(objectId);
      if (!object || !object.$types.contains(FIELDBEARING_TYPE))
        continue;
      const field = object.field(normkey);
      if (!field)
        continue;
      if (slow(field))
        matches.add(objectId);
    }
    return Filters.atom(matches);
  }
  /**
   * Does Breadth-first Search to find all linked files within distance <distance>. This includes all source nodes,
   * so remove them afterwards if you do not want them.
   */
  _traverseLinked(sourceIds, distance, adjacent) {
    if (distance < 0)
      return /* @__PURE__ */ new Set();
    if (sourceIds.size == 0)
      return /* @__PURE__ */ new Set();
    const visited = new Set(sourceIds);
    const queue = new FlatQueue();
    for (const element of sourceIds)
      queue.push(element, 0);
    while (queue.length > 0) {
      const dist = queue.peekValue();
      const element = queue.pop();
      for (const neighbor of adjacent(element)) {
        if (visited.has(neighbor))
          continue;
        visited.add(neighbor);
        if (dist + 1 < distance)
          queue.push(neighbor, dist + 1);
      }
    }
    return visited;
  }
  /** Iterate all linked objects for the given object. */
  *_iterateAdjacentLinked(id, direction) {
    const object = this.objects.get(id);
    if (!object)
      return;
    if ((direction === "both" || direction === "incoming") && "$link" in object && object["$link"]) {
      const incoming = this.links.get(object.$link.obsidianLink());
      if (incoming) {
        for (const id2 of incoming) {
          yield id2;
        }
      }
    }
    if ((direction === "both" || direction === "outgoing") && object.$types.contains(LINKABLE_TYPE) && iterableExists(object, "$links")) {
      for (const link of object.$links) {
        const resolved = this.resolveLink(link);
        if (resolved)
          yield resolved.$id;
      }
    }
  }
  /** Iterator which produces all parents of the given object. */
  *_iterateParents(child) {
    let object = this.objects.get(child);
    while (object && (object == null ? void 0 : object.$parent)) {
      yield object.$parent.$id;
      object = object.$parent;
    }
  }
  /** Iterative which produces all children (recursively) of the given object. */
  *_iterateChildren(parent) {
    const children = this.children.get(parent);
    if (children && children.size > 0) {
      for (let child of children) {
        yield child;
        yield* this._iterateChildren(child);
      }
    }
  }
};
function iterableExists(object, key) {
  if (!(key in object))
    return false;
  const castObject = object;
  if (castObject[key] == null)
    return false;
  const value = castObject[key];
  return (Array.isArray(value) || typeof value === "object") && Symbol.iterator in value;
}

// src/index/persister.ts
var import_localforage = __toESM(require_localforage());
var LocalStorageCache = class {
  constructor(appId, version) {
    this.appId = appId;
    this.version = version;
    this.persister = import_localforage.default.createInstance({
      name: "datacore/cache/" + appId,
      driver: [import_localforage.default.INDEXEDDB],
      description: "Cache metadata about files and sections in the datacore index."
    });
  }
  /** Drop the entire cache instance and re-create a new fresh instance. */
  async recreate() {
    await import_localforage.default.dropInstance({ name: "datacore/cache/" + this.appId });
    this.persister = import_localforage.default.createInstance({
      name: "datacore/cache/" + this.appId,
      driver: [import_localforage.default.INDEXEDDB],
      description: "Cache metadata about files and sections in the datacore index."
    });
  }
  /** Load file metadata by path. */
  async loadFile(path) {
    const raw = await this.persister.getItem(this.fileKey(path));
    return raw;
  }
  /** Store file metadata by path. */
  async storeFile(path, data) {
    await this.persister.setItem(this.fileKey(path), {
      version: this.version,
      time: Date.now(),
      data
    });
  }
  /** Drop old file keys that no longer exist. */
  async synchronize(existing) {
    let keys = new Set(await this.allFiles());
    for (let exist of existing)
      keys.delete(exist);
    for (let key of keys)
      await this.persister.removeItem(this.fileKey(key));
    return keys;
  }
  /** Obtain a list of all metadata keys. */
  async allKeys() {
    return this.persister.keys();
  }
  /** Obtain a list of all persisted files. */
  async allFiles() {
    let keys = await this.allKeys();
    return keys.filter((k4) => k4.startsWith("file:")).map((k4) => k4.substring(5));
  }
  /** Get a unique key for a given file path. */
  fileKey(path) {
    return "file:" + path;
  }
};

// inline-worker:__inline-worker
function inlineWorker(scriptText) {
  let blob = new Blob([scriptText], { type: "text/javascript" });
  let url = URL.createObjectURL(blob);
  let worker = new Worker(url, { "name": "Datacore Indexer" });
  URL.revokeObjectURL(url);
  return worker;
}

// src/index/web-worker/importer.worker.ts
function Worker2() {
  return inlineWorker('var ll=Object.create;var zs=Object.defineProperty,cl=Object.defineProperties,fl=Object.getOwnPropertyDescriptor,dl=Object.getOwnPropertyDescriptors,hl=Object.getOwnPropertyNames,Ur=Object.getOwnPropertySymbols,pl=Object.getPrototypeOf,Ys=Object.prototype.hasOwnProperty,Ao=Object.prototype.propertyIsEnumerable;var No=(n,e,t)=>e in n?zs(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,R=(n,e)=>{for(var t in e||(e={}))Ys.call(e,t)&&No(n,t,e[t]);if(Ur)for(var t of Ur(e))Ao.call(e,t)&&No(n,t,e[t]);return n},be=(n,e)=>cl(n,dl(e));var Gs=(n,e)=>{var t={};for(var r in n)Ys.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&Ur)for(var r of Ur(n))e.indexOf(r)<0&&Ao.call(n,r)&&(t[r]=n[r]);return t};var Mo=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ml=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of hl(e))!Ys.call(n,s)&&s!==t&&zs(n,s,{get:()=>e[s],enumerable:!(r=fl(e,s))||r.enumerable});return n};var Kr=(n,e,t)=>(t=n!=null?ll(pl(n)):{},ml(e||!n||!n.__esModule?zs(t,"default",{value:n,enumerable:!0}):t,n));var ss=Mo((pr,Mi)=>{(function(n,e){typeof pr=="object"&&typeof Mi=="object"?Mi.exports=e():typeof define=="function"&&define.amd?define([],e):typeof pr=="object"?pr.Parsimmon=e():n.Parsimmon=e()})(typeof self!="undefined"?self:pr,function(){return function(n){var e={};function t(r){if(e[r])return e[r].exports;var s=e[r]={i:r,l:!1,exports:{}};return n[r].call(s.exports,s,s.exports,t),s.l=!0,s.exports}return t.m=n,t.c=e,t.d=function(r,s,i){t.o(r,s)||Object.defineProperty(r,s,{configurable:!1,enumerable:!0,get:i})},t.r=function(r){Object.defineProperty(r,"__esModule",{value:!0})},t.n=function(r){var s=r&&r.__esModule?function(){return r.default}:function(){return r};return t.d(s,"a",s),s},t.o=function(r,s){return Object.prototype.hasOwnProperty.call(r,s)},t.p="",t(t.s=0)}([function(n,e,t){"use strict";function r(c){if(!(this instanceof r))return new r(c);this._=c}var s=r.prototype;function i(c,D){for(var w=0;w<c;w++)D(w)}function o(c,D,w){return function(C,I){i(I.length,function(N){C(I[N],N,I)})}(function(C,I,N){D=c(D,C,I,N)},w),D}function a(c,D){return o(function(w,C,I,N){return w.concat([c(C,I,N)])},[],D)}function u(c,D){var w={v:0,buf:D};return i(c,function(){var C;w={v:w.v<<1|(C=w.buf,C[0]>>7),buf:function(I){var N=o(function(M,q,re,Te){return M.concat(re===Te.length-1?Buffer.from([q,0]).readUInt16BE(0):Te.readUInt16BE(re))},[],I);return Buffer.from(a(function(M){return(M<<1&65535)>>8},N))}(w.buf)}}),w}function l(){return typeof Buffer!="undefined"}function f(){if(!l())throw new Error("Buffer global does not exist; please use webpack if you need to parse Buffers in the browser.")}function d(c){f();var D=o(function(N,M){return N+M},0,c);if(D%8!=0)throw new Error("The bits ["+c.join(", ")+"] add up to "+D+" which is not an even number of bytes; the total should be divisible by 8");var w,C=D/8,I=(w=function(N){return N>48},o(function(N,M){return N||(w(M)?M:N)},null,c));if(I)throw new Error(I+" bit range requested exceeds 48 bit (6 byte) Number max.");return new r(function(N,M){var q=C+M;return q>N.length?O(M,C.toString()+" bytes"):F(q,o(function(re,Te){var ye=u(Te,re.buf);return{coll:re.coll.concat(ye.v),buf:ye.buf}},{coll:[],buf:N.slice(M,q)},c).coll)})}function y(c,D){return new r(function(w,C){return f(),C+D>w.length?O(C,D+" bytes for "+c):F(C+D,w.slice(C,C+D))})}function h(c,D){if(typeof(w=D)!="number"||Math.floor(w)!==w||D<0||D>6)throw new Error(c+" requires integer length in range [0, 6].");var w}function E(c){return h("uintBE",c),y("uintBE("+c+")",c).map(function(D){return D.readUIntBE(0,c)})}function p(c){return h("uintLE",c),y("uintLE("+c+")",c).map(function(D){return D.readUIntLE(0,c)})}function T(c){return h("intBE",c),y("intBE("+c+")",c).map(function(D){return D.readIntBE(0,c)})}function g(c){return h("intLE",c),y("intLE("+c+")",c).map(function(D){return D.readIntLE(0,c)})}function k(c){return c instanceof r}function L(c){return{}.toString.call(c)==="[object Array]"}function m(c){return l()&&Buffer.isBuffer(c)}function F(c,D){return{status:!0,index:c,value:D,furthest:-1,expected:[]}}function O(c,D){return L(D)||(D=[D]),{status:!1,index:-1,value:null,furthest:c,expected:D}}function x(c,D){if(!D||c.furthest>D.furthest)return c;var w=c.furthest===D.furthest?function(C,I){if(function(){if(r._supportsSet!==void 0)return r._supportsSet;var pt=typeof Set!="undefined";return r._supportsSet=pt,pt}()&&Array.from){for(var N=new Set(C),M=0;M<I.length;M++)N.add(I[M]);var q=Array.from(N);return q.sort(),q}for(var re={},Te=0;Te<C.length;Te++)re[C[Te]]=!0;for(var ye=0;ye<I.length;ye++)re[I[ye]]=!0;var ht=[];for(var Oe in re)({}).hasOwnProperty.call(re,Oe)&&ht.push(Oe);return ht.sort(),ht}(c.expected,D.expected):D.expected;return{status:c.status,index:c.index,value:c.value,furthest:D.furthest,expected:w}}var S={};function V(c,D){if(m(c))return{offset:D,line:-1,column:-1};c in S||(S[c]={});for(var w=S[c],C=0,I=0,N=0,M=D;M>=0;){if(M in w){C=w[M].line,N===0&&(N=w[M].lineStart);break}(c.charAt(M)===`\n`||c.charAt(M)==="\\r"&&c.charAt(M+1)!==`\n`)&&(I++,N===0&&(N=M+1)),M--}var q=C+I,re=D-N;return w[D]={line:q,lineStart:N},{offset:D,line:q+1,column:re+1}}function j(c){if(!k(c))throw new Error("not a parser: "+c)}function Y(c,D){return typeof c=="string"?c.charAt(D):c[D]}function te(c){if(typeof c!="number")throw new Error("not a number: "+c)}function v(c){if(typeof c!="function")throw new Error("not a function: "+c)}function A(c){if(typeof c!="string")throw new Error("not a string: "+c)}var z=2,we=3,se=8,Xe=5*se,tn=4*se,et="  ";function $t(c,D){return new Array(D+1).join(c)}function Rt(c,D,w){var C=D-c.length;return C<=0?c:$t(w,C)+c}function Ae(c,D,w,C){return{from:c-D>0?c-D:0,to:c+w>C?C:c+w}}function jt(c,D){var w,C,I,N,M,q=D.index,re=q.offset,Te=1;if(re===c.length)return"Got the end of the input";if(m(c)){var ye=re-re%se,ht=re-ye,Oe=Ae(ye,Xe,tn+se,c.length),pt=a(function(fe){return a(function(rn){return Rt(rn.toString(16),2,"0")},fe)},function(fe,rn){var sn=fe.length,Ut=[],on=0;if(sn<=rn)return[fe.slice()];for(var an=0;an<sn;an++)Ut[on]||Ut.push([]),Ut[on].push(fe[an]),(an+1)%rn==0&&on++;return Ut}(c.slice(Oe.from,Oe.to).toJSON().data,se));N=function(fe){return fe.from===0&&fe.to===1?{from:fe.from,to:fe.to}:{from:fe.from/se,to:Math.floor(fe.to/se)}}(Oe),C=ye/se,w=3*ht,ht>=4&&(w+=1),Te=2,I=a(function(fe){return fe.length<=4?fe.join(" "):fe.slice(0,4).join(" ")+"  "+fe.slice(4).join(" ")},pt),(M=(8*(N.to>0?N.to-1:N.to)).toString(16).length)<2&&(M=2)}else{var nn=c.split(/\\r\\n|[\\n\\r\\u2028\\u2029]/);w=q.column-1,C=q.line-1,N=Ae(C,z,we,nn.length),I=nn.slice(N.from,N.to),M=N.to.toString().length}var ul=C-N.from;return m(c)&&(M=(8*(N.to>0?N.to-1:N.to)).toString(16).length)<2&&(M=2),o(function(fe,rn,sn){var Ut,on=sn===ul,an=on?"> ":et;return Ut=m(c)?Rt((8*(N.from+sn)).toString(16),M,"0"):Rt((N.from+sn+1).toString(),M," "),[].concat(fe,[an+Ut+" | "+rn],on?[et+$t(" ",M)+" | "+Rt("",w," ")+$t("^",Te)]:[])},[],I).join(`\n`)}function To(c,D){return[`\n`,"-- PARSING FAILED "+$t("-",50),`\n\n`,jt(c,D),`\n\n`,(w=D.expected,w.length===1?`Expected:\n\n`+w[0]:`Expected one of the following: \n\n`+w.join(", ")),`\n`].join("");var w}function So(c){return c.flags!==void 0?c.flags:[c.global?"g":"",c.ignoreCase?"i":"",c.multiline?"m":"",c.unicode?"u":"",c.sticky?"y":""].join("")}function $r(){for(var c=[].slice.call(arguments),D=c.length,w=0;w<D;w+=1)j(c[w]);return r(function(C,I){for(var N,M=new Array(D),q=0;q<D;q+=1){if(!(N=x(c[q]._(C,I),N)).status)return N;M[q]=N.value,I=N.index}return x(F(I,M),N)})}function Vt(){var c=[].slice.call(arguments);if(c.length===0)throw new Error("seqMap needs at least one argument");var D=c.pop();return v(D),$r.apply(null,c).map(function(w){return D.apply(null,w)})}function Rr(){var c=[].slice.call(arguments),D=c.length;if(D===0)return jr("zero alternates");for(var w=0;w<D;w+=1)j(c[w]);return r(function(C,I){for(var N,M=0;M<c.length;M+=1)if((N=x(c[M]._(C,I),N)).status)return N;return N})}function ko(c,D){return Ws(c,D).or(qt([]))}function Ws(c,D){return j(c),j(D),Vt(c,D.then(c).many(),function(w,C){return[w].concat(C)})}function Bn(c){A(c);var D="\'"+c+"\'";return r(function(w,C){var I=C+c.length,N=w.slice(C,I);return N===c?F(I,N):O(C,D)})}function dt(c,D){(function(I){if(!(I instanceof RegExp))throw new Error("not a regexp: "+I);for(var N=So(I),M=0;M<N.length;M++){var q=N.charAt(M);if(q!=="i"&&q!=="m"&&q!=="u"&&q!=="s")throw new Error(\'unsupported regexp flag "\'+q+\'": \'+I)}})(c),arguments.length>=2?te(D):D=0;var w=function(I){return RegExp("^(?:"+I.source+")",So(I))}(c),C=""+c;return r(function(I,N){var M=w.exec(I.slice(N));if(M){if(0<=D&&D<=M.length){var q=M[0],re=M[D];return F(N+q.length,re)}return O(N,"valid match group (0 to "+M.length+") in "+C)}return O(N,C)})}function qt(c){return r(function(D,w){return F(w,c)})}function jr(c){return r(function(D,w){return O(w,c)})}function Vr(c){if(k(c))return r(function(D,w){var C=c._(D,w);return C.index=w,C.value="",C});if(typeof c=="string")return Vr(Bn(c));if(c instanceof RegExp)return Vr(dt(c));throw new Error("not a string, regexp, or parser: "+c)}function Co(c){return j(c),r(function(D,w){var C=c._(D,w),I=D.slice(w,C.index);return C.status?O(w,\'not "\'+I+\'"\'):F(w,null)})}function qr(c){return v(c),r(function(D,w){var C=Y(D,w);return w<D.length&&c(C)?F(w+1,C):O(w,"a character/byte matching "+c)})}function xo(c,D){arguments.length<2&&(D=c,c=void 0);var w=r(function(C,I){return w._=D()._,w._(C,I)});return c?w.desc(c):w}function Hs(){return jr("fantasy-land/empty")}s.parse=function(c){if(typeof c!="string"&&!m(c))throw new Error(".parse must be called with a string or Buffer as its argument");var D,w=this.skip(Js)._(c,0);return D=w.status?{status:!0,value:w.value}:{status:!1,index:V(c,w.furthest),expected:w.expected},delete S[c],D},s.tryParse=function(c){var D=this.parse(c);if(D.status)return D.value;var w=To(c,D),C=new Error(w);throw C.type="ParsimmonError",C.result=D,C},s.assert=function(c,D){return this.chain(function(w){return c(w)?qt(w):jr(D)})},s.or=function(c){return Rr(this,c)},s.trim=function(c){return this.wrap(c,c)},s.wrap=function(c,D){return Vt(c,this,D,function(w,C){return C})},s.thru=function(c){return c(this)},s.then=function(c){return j(c),$r(this,c).map(function(D){return D[1]})},s.many=function(){var c=this;return r(function(D,w){for(var C=[],I=void 0;;){if(!(I=x(c._(D,w),I)).status)return x(F(w,C),I);if(w===I.index)throw new Error("infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause");w=I.index,C.push(I.value)}})},s.tieWith=function(c){return A(c),this.map(function(D){if(function(I){if(!L(I))throw new Error("not an array: "+I)}(D),D.length){A(D[0]);for(var w=D[0],C=1;C<D.length;C++)A(D[C]),w+=c+D[C];return w}return""})},s.tie=function(){return this.tieWith("")},s.times=function(c,D){var w=this;return arguments.length<2&&(D=c),te(c),te(D),r(function(C,I){for(var N=[],M=void 0,q=void 0,re=0;re<c;re+=1){if(q=x(M=w._(C,I),q),!M.status)return q;I=M.index,N.push(M.value)}for(;re<D&&(q=x(M=w._(C,I),q),M.status);re+=1)I=M.index,N.push(M.value);return x(F(I,N),q)})},s.result=function(c){return this.map(function(){return c})},s.atMost=function(c){return this.times(0,c)},s.atLeast=function(c){return Vt(this.times(c),this.many(),function(D,w){return D.concat(w)})},s.map=function(c){v(c);var D=this;return r(function(w,C){var I=D._(w,C);return I.status?x(F(I.index,c(I.value)),I):I})},s.contramap=function(c){v(c);var D=this;return r(function(w,C){var I=D.parse(c(w.slice(C)));return I.status?F(C+w.length,I.value):I})},s.promap=function(c,D){return v(c),v(D),this.contramap(c).map(D)},s.skip=function(c){return $r(this,c).map(function(D){return D[0]})},s.mark=function(){return Vt(Pn,this,Pn,function(c,D,w){return{start:c,value:D,end:w}})},s.node=function(c){return Vt(Pn,this,Pn,function(D,w,C){return{name:c,value:w,start:D,end:C}})},s.sepBy=function(c){return ko(this,c)},s.sepBy1=function(c){return Ws(this,c)},s.lookahead=function(c){return this.skip(Vr(c))},s.notFollowedBy=function(c){return this.skip(Co(c))},s.desc=function(c){L(c)||(c=[c]);var D=this;return r(function(w,C){var I=D._(w,C);return I.status||(I.expected=c),I})},s.fallback=function(c){return this.or(qt(c))},s.ap=function(c){return Vt(c,this,function(D,w){return D(w)})},s.chain=function(c){var D=this;return r(function(w,C){var I=D._(w,C);return I.status?x(c(I.value)._(w,I.index),I):I})},s.concat=s.or,s.empty=Hs,s.of=qt,s["fantasy-land/ap"]=s.ap,s["fantasy-land/chain"]=s.chain,s["fantasy-land/concat"]=s.concat,s["fantasy-land/empty"]=s.empty,s["fantasy-land/of"]=s.of,s["fantasy-land/map"]=s.map;var Pn=r(function(c,D){return F(D,V(c,D))}),Xu=r(function(c,D){return D>=c.length?O(D,"any character/byte"):F(D+1,Y(c,D))}),el=r(function(c,D){return F(c.length,c.slice(D))}),Js=r(function(c,D){return D<c.length?O(D,"EOF"):F(D,null)}),tl=dt(/[0-9]/).desc("a digit"),nl=dt(/[0-9]*/).desc("optional digits"),rl=dt(/[a-z]/i).desc("a letter"),sl=dt(/[a-z]*/i).desc("optional letters"),il=dt(/\\s*/).desc("optional whitespace"),ol=dt(/\\s+/).desc("whitespace"),Oo=Bn("\\r"),vo=Bn(`\n`),Io=Bn(`\\r\n`),Lo=Rr(Io,vo,Oo).desc("newline"),al=Rr(Lo,Js);r.all=el,r.alt=Rr,r.any=Xu,r.cr=Oo,r.createLanguage=function(c){var D={};for(var w in c)({}).hasOwnProperty.call(c,w)&&function(C){D[C]=xo(function(){return c[C](D)})}(w);return D},r.crlf=Io,r.custom=function(c){return r(c(F,O))},r.digit=tl,r.digits=nl,r.empty=Hs,r.end=al,r.eof=Js,r.fail=jr,r.formatError=To,r.index=Pn,r.isParser=k,r.lazy=xo,r.letter=rl,r.letters=sl,r.lf=vo,r.lookahead=Vr,r.makeFailure=O,r.makeSuccess=F,r.newline=Lo,r.noneOf=function(c){return qr(function(D){return c.indexOf(D)<0}).desc("none of \'"+c+"\'")},r.notFollowedBy=Co,r.of=qt,r.oneOf=function(c){for(var D=c.split(""),w=0;w<D.length;w++)D[w]="\'"+D[w]+"\'";return qr(function(C){return c.indexOf(C)>=0}).desc(D)},r.optWhitespace=il,r.Parser=r,r.range=function(c,D){return qr(function(w){return c<=w&&w<=D}).desc(c+"-"+D)},r.regex=dt,r.regexp=dt,r.sepBy=ko,r.sepBy1=Ws,r.seq=$r,r.seqMap=Vt,r.seqObj=function(){for(var c,D={},w=0,C=(c=arguments,Array.prototype.slice.call(c)),I=C.length,N=0;N<I;N+=1){var M=C[N];if(!k(M)){if(L(M)&&M.length===2&&typeof M[0]=="string"&&k(M[1])){var q=M[0];if(Object.prototype.hasOwnProperty.call(D,q))throw new Error("seqObj: duplicate key "+q);D[q]=!0,w++;continue}throw new Error("seqObj arguments must be parsers or [string, parser] array pairs.")}}if(w===0)throw new Error("seqObj expects at least one named parser, found zero");return r(function(re,Te){for(var ye,ht={},Oe=0;Oe<I;Oe+=1){var pt,nn;if(L(C[Oe])?(pt=C[Oe][0],nn=C[Oe][1]):(pt=null,nn=C[Oe]),!(ye=x(nn._(re,Te),ye)).status)return ye;pt&&(ht[pt]=ye.value),Te=ye.index}return x(F(Te,ht),ye)})},r.string=Bn,r.succeed=qt,r.takeWhile=function(c){return v(c),r(function(D,w){for(var C=w;C<D.length&&c(Y(D,C));)C++;return F(C,D.slice(w,C))})},r.test=qr,r.whitespace=ol,r["fantasy-land/empty"]=Hs,r["fantasy-land/of"]=qt,r.Binary={bitSeq:d,bitSeqObj:function(c){f();var D={},w=0,C=a(function(N){if(L(N)){var M=N;if(M.length!==2)throw new Error("["+M.join(", ")+"] should be length 2, got length "+M.length);if(A(M[0]),te(M[1]),Object.prototype.hasOwnProperty.call(D,M[0]))throw new Error("duplicate key in bitSeqObj: "+M[0]);return D[M[0]]=!0,w++,M}return te(N),[null,N]},c);if(w<1)throw new Error("bitSeqObj expects at least one named pair, got ["+c.join(", ")+"]");var I=a(function(N){return N[0]},C);return d(a(function(N){return N[1]},C)).map(function(N){return o(function(M,q){return q[0]!==null&&(M[q[0]]=q[1]),M},{},a(function(M,q){return[M,N[q]]},I))})},byte:function(c){if(f(),te(c),c>255)throw new Error("Value specified to byte constructor ("+c+"=0x"+c.toString(16)+") is larger in value than a single byte.");var D=(c>15?"0x":"0x0")+c.toString(16);return r(function(w,C){var I=Y(w,C);return I===c?F(C+1,I):O(C,D)})},buffer:function(c){return y("buffer",c).map(function(D){return Buffer.from(D)})},encodedString:function(c,D){return y("string",D).map(function(w){return w.toString(c)})},uintBE:E,uint8BE:E(1),uint16BE:E(2),uint32BE:E(4),uintLE:p,uint8LE:p(1),uint16LE:p(2),uint32LE:p(4),intBE:T,int8BE:T(1),int16BE:T(2),int32BE:T(4),intLE:g,int8LE:g(1),int16LE:g(2),int32LE:g(4),floatBE:y("floatBE",4).map(function(c){return c.readFloatBE(0)}),floatLE:y("floatLE",4).map(function(c){return c.readFloatLE(0)}),doubleBE:y("doubleBE",8).map(function(c){return c.readDoubleBE(0)}),doubleLE:y("doubleLE",8).map(function(c){return c.readDoubleLE(0)})},n.exports=r}])})});var Pu=Mo(Ne=>{"use strict";var Ff=Ne&&Ne.__extends||function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(r[i]=s[i])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}();Object.defineProperty(Ne,"__esModule",{value:!0});Ne.EmptyBTree=Ne.asSet=Ne.simpleComparator=Ne.defaultComparator=void 0;function Mu(n,e){if(Number.isFinite(n)&&Number.isFinite(e))return n-e;var t=typeof n,r=typeof e;if(t!==r)return t<r?-1:1;if(t==="object"){if(n===null)return e===null?0:-1;if(e===null)return 1;if(n=n.valueOf(),e=e.valueOf(),t=typeof n,r=typeof e,t!==r)return t<r?-1:1}return n<e?-1:n>e?1:n===e?0:Number.isNaN(n)?Number.isNaN(e)?0:-1:Number.isNaN(e)?1:Array.isArray(n)?0:Number.NaN}Ne.defaultComparator=Mu;function wf(n,e){return n>e?1:n<e?-1:0}Ne.simpleComparator=wf;var ct=function(){function n(e,t,r){this._root=ho,this._size=0,this._maxNodeSize=r>=4?Math.min(r,256):32,this._compare=t||Mu,e&&this.setPairs(e)}return Object.defineProperty(n.prototype,"size",{get:function(){return this._size},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"length",{get:function(){return this._size},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"isEmpty",{get:function(){return this._size===0},enumerable:!1,configurable:!0}),n.prototype.clear=function(){this._root=ho,this._size=0},n.prototype.forEach=function(e,t){var r=this;return t!==void 0&&(e=e.bind(t)),this.forEachPair(function(s,i){return e(i,s,r)})},n.prototype.forEachPair=function(e,t){var r=this.minKey(),s=this.maxKey();return this.forRange(r,s,!0,e,t)},n.prototype.get=function(e,t){return this._root.get(e,t,this)},n.prototype.set=function(e,t,r){this._root.isShared&&(this._root=this._root.clone());var s=this._root.set(e,t,r,this);return s===!0||s===!1?s:(this._root=new Sf([this._root,s]),!0)},n.prototype.has=function(e){return this.forRange(e,e,!0,void 0)!==0},n.prototype.delete=function(e){return this.editRange(e,e,!0,Nu)!==0},n.prototype.with=function(e,t,r){var s=this.clone();return s.set(e,t,r)||r?s:this},n.prototype.withPairs=function(e,t){var r=this.clone();return r.setPairs(e,t)!==0||t?r:this},n.prototype.withKeys=function(e,t){for(var r=this.clone(),s=!1,i=0;i<e.length;i++)s=r.set(e[i],void 0,!1)||s;return t&&!s?this:r},n.prototype.without=function(e,t){return this.withoutRange(e,e,!0,t)},n.prototype.withoutKeys=function(e,t){var r=this.clone();return r.deleteKeys(e)||!t?r:this},n.prototype.withoutRange=function(e,t,r,s){var i=this.clone();return i.deleteRange(e,t,r)===0&&s?this:i},n.prototype.filter=function(e,t){var r=this.greedyClone(),s;return r.editAll(function(i,o,a){if(!e(i,o,a))return s=Bu}),!s&&t?this:r},n.prototype.mapValues=function(e){var t={},r=this.greedyClone();return r.editAll(function(s,i,o){return t.value=e(i,s,o),t}),r},n.prototype.reduce=function(e,t){for(var r=0,s=t,i=this.entries(this.minKey(),Ar),o;!(o=i.next()).done;)s=e(s,o.value,r++,this);return s},n.prototype.entries=function(e,t){var r=this.findPath(e);if(r===void 0)return An();var s=r.nodequeue,i=r.nodeindex,o=r.leaf,a=t!==void 0?1:0,u=e===void 0?-1:o.indexOf(e,0,this._compare)-1;return An(function(){e:for(;;)switch(a){case 0:if(++u<o.keys.length)return{done:!1,value:[o.keys[u],o.values[u]]};a=2;continue;case 1:if(++u<o.keys.length)return t[0]=o.keys[u],t[1]=o.values[u],{done:!1,value:t};a=2;case 2:for(var l=-1;;){if(++l>=s.length){a=3;continue e}if(++i[l]<s[l].length)break}for(;l>0;l--)s[l-1]=s[l][i[l]].children,i[l-1]=0;o=s[0][i[0]],u=-1,a=t!==void 0?1:0;continue;case 3:return{done:!0,value:void 0}}})},n.prototype.entriesReversed=function(e,t,r){if(e===void 0&&(e=this.maxKey(),r=void 0,e===void 0))return An();var s=this.findPath(e)||this.findPath(this.maxKey()),i=s.nodequeue,o=s.nodeindex,a=s.leaf;Le(!i[0]||a===i[0][o[0]],"wat!");var u=a.indexOf(e,0,this._compare);!r&&u<a.keys.length&&this._compare(a.keys[u],e)<=0&&u++;var l=t!==void 0?1:0;return An(function(){e:for(;;)switch(l){case 0:if(--u>=0)return{done:!1,value:[a.keys[u],a.values[u]]};l=2;continue;case 1:if(--u>=0)return t[0]=a.keys[u],t[1]=a.values[u],{done:!1,value:t};l=2;case 2:for(var f=-1;;){if(++f>=i.length){l=3;continue e}if(--o[f]>=0)break}for(;f>0;f--)i[f-1]=i[f][o[f]].children,o[f-1]=i[f-1].length-1;a=i[0][o[0]],u=a.keys.length,l=t!==void 0?1:0;continue;case 3:return{done:!0,value:void 0}}})},n.prototype.findPath=function(e){var t=this._root,r,s;if(t.isLeaf)r=Au,s=Au;else{r=[],s=[];for(var i=0;!t.isLeaf;i++){if(r[i]=t.children,s[i]=e===void 0?0:t.indexOf(e,0,this._compare),s[i]>=r[i].length)return;t=r[i][s[i]]}r.reverse(),s.reverse()}return{nodequeue:r,nodeindex:s,leaf:t}},n.prototype.diffAgainst=function(e,t,r,s){if(e._compare!==this._compare)throw new Error("Tree comparators are not the same.");if(this.isEmpty||e.isEmpty)return this.isEmpty&&e.isEmpty?void 0:this.isEmpty?r===void 0?void 0:n.stepToEnd(n.makeDiffCursor(e),r):t===void 0?void 0:n.stepToEnd(n.makeDiffCursor(this),t);for(var i=this._compare,o=n.makeDiffCursor(this),a=n.makeDiffCursor(e),u=!0,l=!0,f=n.compare(o,a,i);u&&l;){var d=n.compare(o,a,i),y=o.leaf,h=o.internalSpine,E=o.levelIndices,p=a.leaf,T=a.internalSpine,g=a.levelIndices;if(y||p){if(f!==0){if(d===0){if(y&&p&&s){var k=y.values[E[E.length-1]],L=p.values[g[g.length-1]];if(!Object.is(k,L)){var m=s(o.currentKey,k,L);if(m&&m.break)return m.break}}}else if(d>0){if(p&&r){var F=p.values[g[g.length-1]],m=r(a.currentKey,F);if(m&&m.break)return m.break}}else if(t&&y&&f!==0){var k=y.values[E[E.length-1]],m=t(o.currentKey,k);if(m&&m.break)return m.break}}}else if(!y&&!p&&d===0){var O=h.length-1,x=T.length-1,S=h[O][E[O]],V=T[x][g[x]];if(V===S){f=0,u=n.step(o,!0),l=n.step(a,!0);continue}}f=d,d<0?u=n.step(o):l=n.step(a)}if(u&&t)return n.finishCursorWalk(o,a,i,t);if(l&&r)return n.finishCursorWalk(a,o,i,r)},n.finishCursorWalk=function(e,t,r,s){var i=n.compare(e,t,r);if(i===0){if(!n.step(e))return}else i<0&&Le(!1,"cursor walk terminated early");return n.stepToEnd(e,s)},n.stepToEnd=function(e,t){for(var r=!0;r;){var s=e.leaf,i=e.levelIndices,o=e.currentKey;if(s){var a=s.values[i[i.length-1]],u=t(o,a);if(u&&u.break)return u.break}r=n.step(e)}},n.makeDiffCursor=function(e){var t=e._root,r=e.height;return{height:r,internalSpine:[[t]],levelIndices:[0],leaf:void 0,currentKey:t.maxKey()}},n.step=function(e,t){var r=e.internalSpine,s=e.levelIndices,i=e.leaf;if(t===!0||i){var o=s.length;if(t===!0||s[o-1]===0){var a=r.length;if(a===0)return!1;for(var u=a-1,l=u;l>=0;){if(s[l]>0)return l<o-1&&(e.leaf=void 0,s.pop()),l<u&&(e.internalSpine=r.slice(0,l+1)),e.currentKey=r[l][--s[l]].maxKey(),!0;l--}return!1}else{var f=--s[o-1];return e.currentKey=i.keys[f],!0}}else{var d=r.length,y=d-1,h=r[y][s[y]];if(h.isLeaf){e.leaf=h;var f=s[d]=h.values.length-1;e.currentKey=h.keys[f]}else{var E=h.children;r[d]=E;var p=E.length-1;s[d]=p,e.currentKey=E[p].maxKey()}return!0}},n.compare=function(e,t,r){var s=e.height,i=e.currentKey,o=e.levelIndices,a=t.height,u=t.currentKey,l=t.levelIndices,f=r(u,i);if(f!==0)return f;var d=s<a?s:a,y=o.length-(s-d),h=l.length-(a-d);return y-h},n.prototype.keys=function(e){var t=this.entries(e,Ar);return An(function(){var r=t.next();return r.value&&(r.value=r.value[0]),r})},n.prototype.values=function(e){var t=this.entries(e,Ar);return An(function(){var r=t.next();return r.value&&(r.value=r.value[1]),r})},Object.defineProperty(n.prototype,"maxNodeSize",{get:function(){return this._maxNodeSize},enumerable:!1,configurable:!0}),n.prototype.minKey=function(){return this._root.minKey()},n.prototype.maxKey=function(){return this._root.maxKey()},n.prototype.clone=function(){this._root.isShared=!0;var e=new n(void 0,this._compare,this._maxNodeSize);return e._root=this._root,e._size=this._size,e},n.prototype.greedyClone=function(e){var t=new n(void 0,this._compare,this._maxNodeSize);return t._root=this._root.greedyClone(e),t._size=this._size,t},n.prototype.toArray=function(e){e===void 0&&(e=2147483647);var t=this.minKey(),r=this.maxKey();return t!==void 0?this.getRange(t,r,!0,e):[]},n.prototype.keysArray=function(){var e=[];return this._root.forRange(this.minKey(),this.maxKey(),!0,!1,this,0,function(t,r){e.push(t)}),e},n.prototype.valuesArray=function(){var e=[];return this._root.forRange(this.minKey(),this.maxKey(),!0,!1,this,0,function(t,r){e.push(r)}),e},n.prototype.toString=function(){return this.toArray().toString()},n.prototype.setIfNotPresent=function(e,t){return this.set(e,t,!1)},n.prototype.nextHigherPair=function(e,t){return t=t||[],e===void 0?this._root.minPair(t):this._root.getPairOrNextHigher(e,this._compare,!1,t)},n.prototype.nextHigherKey=function(e){var t=this.nextHigherPair(e,Ar);return t&&t[0]},n.prototype.nextLowerPair=function(e,t){return t=t||[],e===void 0?this._root.maxPair(t):this._root.getPairOrNextLower(e,this._compare,!1,t)},n.prototype.nextLowerKey=function(e){var t=this.nextLowerPair(e,Ar);return t&&t[0]},n.prototype.getPairOrNextLower=function(e,t){return this._root.getPairOrNextLower(e,this._compare,!0,t||[])},n.prototype.getPairOrNextHigher=function(e,t){return this._root.getPairOrNextHigher(e,this._compare,!0,t||[])},n.prototype.changeIfPresent=function(e,t){return this.editRange(e,e,!0,function(r,s){return{value:t}})!==0},n.prototype.getRange=function(e,t,r,s){s===void 0&&(s=67108863);var i=[];return this._root.forRange(e,t,r,!1,this,0,function(o,a){return i.push([o,a]),i.length>s?kf:void 0}),i},n.prototype.setPairs=function(e,t){for(var r=0,s=0;s<e.length;s++)this.set(e[s][0],e[s][1],t)&&r++;return r},n.prototype.forRange=function(e,t,r,s,i){var o=this._root.forRange(e,t,r,!1,this,i||0,s);return typeof o=="number"?o:o.break},n.prototype.editRange=function(e,t,r,s,i){var o=this._root;o.isShared&&(this._root=o=o.clone());try{var a=o.forRange(e,t,r,!0,this,i||0,s);return typeof a=="number"?a:a.break}finally{for(var u=void 0;o.keys.length<=1&&!o.isLeaf;)u||(u=o.isShared),this._root=o=o.keys.length===0?ho:o.children[0];u&&(o.isShared=!0)}},n.prototype.editAll=function(e,t){return this.editRange(this.minKey(),this.maxKey(),!0,e,t)},n.prototype.deleteRange=function(e,t,r){return this.editRange(e,t,r,Nu)},n.prototype.deleteKeys=function(e){for(var t=0,r=0;t<e.length;t++)this.delete(e[t])&&r++;return r},Object.defineProperty(n.prototype,"height",{get:function(){for(var e=this._root,t=-1;e;)t++,e=e.isLeaf?void 0:e.children[0];return t},enumerable:!1,configurable:!0}),n.prototype.freeze=function(){var e=this;e.clear=e.set=e.editRange=function(){throw new Error("Attempted to modify a frozen BTree")}},n.prototype.unfreeze=function(){delete this.clear,delete this.set,delete this.editRange},Object.defineProperty(n.prototype,"isFrozen",{get:function(){return this.hasOwnProperty("editRange")},enumerable:!1,configurable:!0}),n.prototype.checkValid=function(){var e=this._root.checkValid(0,this,0);Le(e===this.size,"size mismatch: counted ",e,"but stored",this.size)},n}();Ne.default=ct;function Tf(n){return n}Ne.asSet=Tf;Symbol&&Symbol.iterator&&(ct.prototype[Symbol.iterator]=ct.prototype.entries);ct.prototype.where=ct.prototype.filter;ct.prototype.setRange=ct.prototype.setPairs;ct.prototype.add=ct.prototype.set;function An(n){n===void 0&&(n=function(){return{done:!0,value:void 0}});var e={next:n};return Symbol&&Symbol.iterator&&(e[Symbol.iterator]=function(){return this}),e}var _u=function(){function n(e,t){e===void 0&&(e=[]),this.keys=e,this.values=t||ge,this.isShared=void 0}return Object.defineProperty(n.prototype,"isLeaf",{get:function(){return this.children===void 0},enumerable:!1,configurable:!0}),n.prototype.maxKey=function(){return this.keys[this.keys.length-1]},n.prototype.indexOf=function(e,t,r){for(var s=this.keys,i=0,o=s.length,a=o>>1;i<o;){var u=r(s[a],e);if(u<0)i=a+1;else if(u>0)o=a;else{if(u===0)return a;if(e===e)return s.length;throw new Error("BTree: NaN was used as a key")}a=i+o>>1}return a^t},n.prototype.minKey=function(){return this.keys[0]},n.prototype.minPair=function(e){if(this.keys.length!==0)return e[0]=this.keys[0],e[1]=this.values[0],e},n.prototype.maxPair=function(e){if(this.keys.length!==0){var t=this.keys.length-1;return e[0]=this.keys[t],e[1]=this.values[t],e}},n.prototype.clone=function(){var e=this.values;return new n(this.keys.slice(0),e===ge?e:e.slice(0))},n.prototype.greedyClone=function(e){return this.isShared&&!e?this:this.clone()},n.prototype.get=function(e,t,r){var s=this.indexOf(e,-1,r._compare);return s<0?t:this.values[s]},n.prototype.getPairOrNextLower=function(e,t,r,s){var i=this.indexOf(e,-1,t),o=i<0?~i-1:r?i:i-1;if(o>=0)return s[0]=this.keys[o],s[1]=this.values[o],s},n.prototype.getPairOrNextHigher=function(e,t,r,s){var i=this.indexOf(e,-1,t),o=i<0?~i:r?i:i+1,a=this.keys;if(o<a.length)return s[0]=a[o],s[1]=this.values[o],s},n.prototype.checkValid=function(e,t,r){var s=this.keys.length,i=this.values.length;return Le(this.values===ge?s<=i:s===i,"keys/values length mismatch: depth",e,"with lengths",s,i,"and baseIndex",r),Le(e==0||s>0,"empty leaf at depth",e,"and baseIndex",r),s},n.prototype.set=function(e,t,r,s){var i=this.indexOf(e,-1,s._compare);if(i<0){if(i=~i,s._size++,this.keys.length<s._maxNodeSize)return this.insertInLeaf(i,e,t,s);var o=this.splitOffRightSide(),a=this;return i>this.keys.length&&(i-=this.keys.length,a=o),a.insertInLeaf(i,e,t,s),o}else return r!==!1&&(t!==void 0&&this.reifyValues(),this.keys[i]=e,this.values[i]=t),!1},n.prototype.reifyValues=function(){return this.values===ge?this.values=this.values.slice(0,this.keys.length):this.values},n.prototype.insertInLeaf=function(e,t,r,s){if(this.keys.splice(e,0,t),this.values===ge){for(;ge.length<s._maxNodeSize;)ge.push(void 0);if(r===void 0)return!0;this.values=ge.slice(0,this.keys.length-1)}return this.values.splice(e,0,r),!0},n.prototype.takeFromRight=function(e){var t=this.values;e.values===ge?t!==ge&&t.push(void 0):(t=this.reifyValues(),t.push(e.values.shift())),this.keys.push(e.keys.shift())},n.prototype.takeFromLeft=function(e){var t=this.values;e.values===ge?t!==ge&&t.unshift(void 0):(t=this.reifyValues(),t.unshift(e.values.pop())),this.keys.unshift(e.keys.pop())},n.prototype.splitOffRightSide=function(){var e=this.keys.length>>1,t=this.keys.splice(e),r=this.values===ge?ge:this.values.splice(e);return new n(t,r)},n.prototype.forRange=function(e,t,r,s,i,o,a){var u=i._compare,l,f;if(t===e){if(!r||(f=(l=this.indexOf(e,-1,u))+1,l<0))return o}else l=this.indexOf(e,0,u),f=this.indexOf(t,-1,u),f<0?f=~f:r===!0&&f++;var d=this.keys,y=this.values;if(a!==void 0)for(var h=l;h<f;h++){var E=d[h],p=a(E,y[h],o++);if(p!==void 0){if(s===!0){if(E!==d[h]||this.isShared===!0)throw new Error("BTree illegally changed or cloned in editRange");p.delete?(this.keys.splice(h,1),this.values!==ge&&this.values.splice(h,1),i._size--,h--,f--):p.hasOwnProperty("value")&&(y[h]=p.value)}if(p.break!==void 0)return p}}else o+=f-l;return o},n.prototype.mergeSibling=function(e,t){if(this.keys.push.apply(this.keys,e.keys),this.values===ge){if(e.values===ge)return;this.values=this.values.slice(0,this.keys.length)}this.values.push.apply(this.values,e.reifyValues())},n}(),Sf=function(n){Ff(e,n);function e(t,r){var s=this;if(!r){r=[];for(var i=0;i<t.length;i++)r[i]=t[i].maxKey()}return s=n.call(this,r)||this,s.children=t,s}return e.prototype.clone=function(){for(var t=this.children.slice(0),r=0;r<t.length;r++)t[r].isShared=!0;return new e(t,this.keys.slice(0))},e.prototype.greedyClone=function(t){if(this.isShared&&!t)return this;for(var r=new e(this.children.slice(0),this.keys.slice(0)),s=0;s<r.children.length;s++)r.children[s]=r.children[s].greedyClone(t);return r},e.prototype.minKey=function(){return this.children[0].minKey()},e.prototype.minPair=function(t){return this.children[0].minPair(t)},e.prototype.maxPair=function(t){return this.children[this.children.length-1].maxPair(t)},e.prototype.get=function(t,r,s){var i=this.indexOf(t,0,s._compare),o=this.children;return i<o.length?o[i].get(t,r,s):void 0},e.prototype.getPairOrNextLower=function(t,r,s,i){var o=this.indexOf(t,0,r),a=this.children;if(o>=a.length)return this.maxPair(i);var u=a[o].getPairOrNextLower(t,r,s,i);return u===void 0&&o>0?a[o-1].maxPair(i):u},e.prototype.getPairOrNextHigher=function(t,r,s,i){var o=this.indexOf(t,0,r),a=this.children,u=a.length;if(!(o>=u)){var l=a[o].getPairOrNextHigher(t,r,s,i);return l===void 0&&o<u-1?a[o+1].minPair(i):l}},e.prototype.checkValid=function(t,r,s){var i=this.keys.length,o=this.children.length;Le(i===o,"keys/children length mismatch: depth",t,"lengths",i,o,"baseIndex",s),Le(i>1||t>0,"internal node has length",i,"at depth",t,"baseIndex",s);for(var a=0,u=this.children,l=this.keys,f=0,d=0;d<o;d++)a+=u[d].checkValid(t+1,r,s+a),f+=u[d].keys.length,Le(a>=f,"wtf",s),Le(d===0||u[d-1].constructor===u[d].constructor,"type mismatch, baseIndex:",s),u[d].maxKey()!=l[d]&&Le(!1,"keys[",d,"] =",l[d],"is wrong, should be ",u[d].maxKey(),"at depth",t,"baseIndex",s),d===0||r._compare(l[d-1],l[d])<0||Le(!1,"sort violation at depth",t,"index",d,"keys",l[d-1],l[d]);var y=f===0;return(y||f>r.maxNodeSize*o)&&Le(!1,y?"too few":"too many","children (",f,a,") at depth",t,"maxNodeSize:",r.maxNodeSize,"children.length:",o,"baseIndex:",s),a},e.prototype.set=function(t,r,s,i){var o=this.children,a=i._maxNodeSize,u=i._compare,l=Math.min(this.indexOf(t,0,u),o.length-1),f=o[l];if(f.isShared&&(o[l]=f=f.clone()),f.keys.length>=a){var d;l>0&&(d=o[l-1]).keys.length<a&&u(f.keys[0],t)<0?(d.isShared&&(o[l-1]=d=d.clone()),d.takeFromRight(f),this.keys[l-1]=d.maxKey()):(d=o[l+1])!==void 0&&d.keys.length<a&&u(f.maxKey(),t)<0&&(d.isShared&&(o[l+1]=d=d.clone()),d.takeFromLeft(f),this.keys[l]=o[l].maxKey())}var y=f.set(t,r,s,i);if(y===!1)return!1;if(this.keys[l]=f.maxKey(),y===!0)return!0;if(this.keys.length<a)return this.insert(l+1,y),!0;var h=this.splitOffRightSide(),E=this;return u(y.maxKey(),this.maxKey())>0&&(E=h,l-=this.keys.length),E.insert(l+1,y),h},e.prototype.insert=function(t,r){this.children.splice(t,0,r),this.keys.splice(t,0,r.maxKey())},e.prototype.splitOffRightSide=function(){var t=this.children.length>>1;return new e(this.children.splice(t),this.keys.splice(t))},e.prototype.takeFromRight=function(t){this.keys.push(t.keys.shift()),this.children.push(t.children.shift())},e.prototype.takeFromLeft=function(t){this.keys.unshift(t.keys.pop()),this.children.unshift(t.children.pop())},e.prototype.forRange=function(t,r,s,i,o,a,u){var l=o._compare,f=this.keys,d=this.children,y=this.indexOf(t,0,l),h=y,E=Math.min(r===t?y:this.indexOf(r,0,l),f.length-1);if(i){if(h<=E)try{for(;h<=E;h++){d[h].isShared&&(d[h]=d[h].clone());var p=d[h].forRange(t,r,s,i,o,a,u);if(f[h]=d[h].maxKey(),typeof p!="number")return p;a=p}}finally{var T=o._maxNodeSize>>1;for(y>0&&y--,h=E;h>=y;h--)d[h].keys.length<=T&&(d[h].keys.length!==0?this.tryMerge(h,o._maxNodeSize):(f.splice(h,1),d.splice(h,1)));d.length!==0&&d[0].keys.length===0&&Le(!1,"emptiness bug")}}else for(;h<=E;h++){var p=d[h].forRange(t,r,s,i,o,a,u);if(typeof p!="number")return p;a=p}return a},e.prototype.tryMerge=function(t,r){var s=this.children;return t>=0&&t+1<s.length&&s[t].keys.length+s[t+1].keys.length<=r?(s[t].isShared&&(s[t]=s[t].clone()),s[t].mergeSibling(s[t+1],r),s.splice(t+1,1),this.keys.splice(t+1,1),this.keys[t]=s[t].maxKey(),!0):!1},e.prototype.mergeSibling=function(t,r){var s=this.keys.length;this.keys.push.apply(this.keys,t.keys);var i=t.children;if(this.children.push.apply(this.children,i),t.isShared&&!this.isShared)for(var o=0;o<i.length;o++)i[o].isShared=!0;this.tryMerge(s-1,r)},e}(_u),ge=[],Bu={delete:!0},Nu=function(){return Bu},kf={break:!0},ho=function(){var n=new _u;return n.isShared=!0,n}(),Au=[],Ar=[];function Le(n){for(var e=[],t=1;t<arguments.length;t++)e[t-1]=arguments[t];if(!n)throw e.unshift("B+ tree"),new Error(e.join(" "))}Ne.EmptyBTree=function(){var n=new ct;return n.freeze(),n}()});var mt=class extends Error{},Wr=class extends mt{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},Hr=class extends mt{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},Jr=class extends mt{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},Dt=class extends mt{},un=class extends mt{constructor(e){super(`Invalid unit ${e}`)}},me=class extends mt{},je=class extends mt{constructor(){super("Zone is an abstract class")}};var B="numeric",Ve="short",ve="long",ln={year:B,month:B,day:B},$n={year:B,month:Ve,day:B},Zs={year:B,month:Ve,day:B,weekday:Ve},Rn={year:B,month:ve,day:B},jn={year:B,month:ve,day:B,weekday:ve},Vn={hour:B,minute:B},qn={hour:B,minute:B,second:B},Un={hour:B,minute:B,second:B,timeZoneName:Ve},Kn={hour:B,minute:B,second:B,timeZoneName:ve},Wn={hour:B,minute:B,hourCycle:"h23"},Hn={hour:B,minute:B,second:B,hourCycle:"h23"},Jn={hour:B,minute:B,second:B,hourCycle:"h23",timeZoneName:Ve},zn={hour:B,minute:B,second:B,hourCycle:"h23",timeZoneName:ve},Yn={year:B,month:B,day:B,hour:B,minute:B},Gn={year:B,month:B,day:B,hour:B,minute:B,second:B},Zn={year:B,month:Ve,day:B,hour:B,minute:B},Qn={year:B,month:Ve,day:B,hour:B,minute:B,second:B},Qs={year:B,month:Ve,day:B,weekday:Ve,hour:B,minute:B},Xn={year:B,month:ve,day:B,hour:B,minute:B,timeZoneName:Ve},er={year:B,month:ve,day:B,hour:B,minute:B,second:B,timeZoneName:Ve},tr={year:B,month:ve,day:B,weekday:ve,hour:B,minute:B,timeZoneName:ve},nr={year:B,month:ve,day:B,weekday:ve,hour:B,minute:B,second:B,timeZoneName:ve};function K(n){return typeof n=="undefined"}function tt(n){return typeof n=="number"}function rr(n){return typeof n=="number"&&n%1===0}function _o(n){return typeof n=="string"}function Bo(n){return Object.prototype.toString.call(n)==="[object Date]"}function zr(){try{return typeof Intl!="undefined"&&!!Intl.RelativeTimeFormat}catch(n){return!1}}function Po(n){return Array.isArray(n)?n:[n]}function ei(n,e,t){if(n.length!==0)return n.reduce((r,s)=>{let i=[e(s),s];return r&&t(r[0],i[0])===r[0]?r:i},null)[1]}function $o(n,e){return e.reduce((t,r)=>(t[r]=n[r],t),{})}function kt(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function nt(n,e,t){return rr(n)&&n>=e&&n<=t}function Dl(n,e){return n-e*Math.floor(n/e)}function ae(n,e=2){let t=n<0,r;return t?r="-"+(""+-n).padStart(e,"0"):r=(""+n).padStart(e,"0"),r}function yt(n){if(!(K(n)||n===null||n===""))return parseInt(n,10)}function Ct(n){if(!(K(n)||n===null||n===""))return parseFloat(n)}function sr(n){if(!(K(n)||n===null||n==="")){let e=parseFloat("0."+n)*1e3;return Math.floor(e)}}function cn(n,e,t=!1){let r=10**e;return(t?Math.trunc:Math.round)(n*r)/r}function Kt(n){return n%4===0&&(n%100!==0||n%400===0)}function Wt(n){return Kt(n)?366:365}function fn(n,e){let t=Dl(e-1,12)+1,r=n+(e-t)/12;return t===2?Kt(r)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][t-1]}function ir(n){let e=Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second,n.millisecond);return n.year<100&&n.year>=0&&(e=new Date(e),e.setUTCFullYear(e.getUTCFullYear()-1900)),+e}function dn(n){let e=(n+Math.floor(n/4)-Math.floor(n/100)+Math.floor(n/400))%7,t=n-1,r=(t+Math.floor(t/4)-Math.floor(t/100)+Math.floor(t/400))%7;return e===4||r===3?53:52}function or(n){return n>99?n:n>60?1900+n:2e3+n}function Yr(n,e,t,r=null){let s=new Date(n),i={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};r&&(i.timeZone=r);let o=R({timeZoneName:e},i),a=new Intl.DateTimeFormat(t,o).formatToParts(s).find(u=>u.type.toLowerCase()==="timezonename");return a?a.value:null}function Ht(n,e){let t=parseInt(n,10);Number.isNaN(t)&&(t=0);let r=parseInt(e,10)||0,s=t<0||Object.is(t,-0)?-r:r;return t*60+s}function ti(n){let e=Number(n);if(typeof n=="boolean"||n===""||Number.isNaN(e))throw new me(`Invalid unit value ${n}`);return e}function hn(n,e){let t={};for(let r in n)if(kt(n,r)){let s=n[r];if(s==null)continue;t[e(r)]=ti(s)}return t}function xt(n,e){let t=Math.trunc(Math.abs(n/60)),r=Math.trunc(Math.abs(n%60)),s=n>=0?"+":"-";switch(e){case"short":return`${s}${ae(t,2)}:${ae(r,2)}`;case"narrow":return`${s}${t}${r>0?`:${r}`:""}`;case"techie":return`${s}${ae(t,2)}${ae(r,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function ar(n){return $o(n,["hour","minute","second","millisecond"])}var ni=/[A-Za-z_+-]{1,256}(?::?\\/[A-Za-z0-9_+-]{1,256}(?:\\/[A-Za-z0-9_+-]{1,256})?)?/;var yl=["January","February","March","April","May","June","July","August","September","October","November","December"],ri=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],gl=["J","F","M","A","M","J","J","A","S","O","N","D"];function si(n){switch(n){case"narrow":return[...gl];case"short":return[...ri];case"long":return[...yl];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var ii=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],oi=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],bl=["M","T","W","T","F","S","S"];function ai(n){switch(n){case"narrow":return[...bl];case"short":return[...oi];case"long":return[...ii];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var ui=["AM","PM"],El=["Before Christ","Anno Domini"],Fl=["BC","AD"],wl=["B","A"];function li(n){switch(n){case"narrow":return[...wl];case"short":return[...Fl];case"long":return[...El];default:return null}}function Ro(n){return ui[n.hour<12?0:1]}function jo(n,e){return ai(e)[n.weekday-1]}function Vo(n,e){return si(e)[n.month-1]}function qo(n,e){return li(e)[n.year<0?0:1]}function Uo(n,e,t="always",r=!1){let s={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},i=["hours","minutes","seconds"].indexOf(n)===-1;if(t==="auto"&&i){let d=n==="days";switch(e){case 1:return d?"tomorrow":`next ${s[n][0]}`;case-1:return d?"yesterday":`last ${s[n][0]}`;case 0:return d?"today":`this ${s[n][0]}`;default:}}let o=Object.is(e,-0)||e<0,a=Math.abs(e),u=a===1,l=s[n],f=r?u?l[1]:l[2]||l[1]:u?s[n][0]:n;return o?`${a} ${f} ago`:`in ${a} ${f}`}function Ko(n,e){let t="";for(let r of n)r.literal?t+=r.val:t+=e(r.val);return t}var Tl={D:ln,DD:$n,DDD:Rn,DDDD:jn,t:Vn,tt:qn,ttt:Un,tttt:Kn,T:Wn,TT:Hn,TTT:Jn,TTTT:zn,f:Yn,ff:Zn,fff:Xn,ffff:tr,F:Gn,FF:Qn,FFF:er,FFFF:nr},ce=class{static create(e,t={}){return new ce(e,t)}static parseFormat(e){let t=null,r="",s=!1,i=[];for(let o=0;o<e.length;o++){let a=e.charAt(o);a==="\'"?(r.length>0&&i.push({literal:s,val:r}),t=null,r="",s=!s):s||a===t?r+=a:(r.length>0&&i.push({literal:!1,val:r}),r=a,t=a)}return r.length>0&&i.push({literal:s,val:r}),i}static macroTokenToFormatOpts(e){return Tl[e]}constructor(e,t){this.opts=t,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,t){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,R(R({},this.opts),t)).format()}formatDateTime(e,t={}){return this.loc.dtFormatter(e,R(R({},this.opts),t)).format()}formatDateTimeParts(e,t={}){return this.loc.dtFormatter(e,R(R({},this.opts),t)).formatToParts()}resolvedOptions(e,t={}){return this.loc.dtFormatter(e,R(R({},this.opts),t)).resolvedOptions()}num(e,t=0){if(this.opts.forceSimple)return ae(e,t);let r=R({},this.opts);return t>0&&(r.padTo=t),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,t){let r=this.loc.listingMode()==="en",s=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",i=(h,E)=>this.loc.extract(e,h,E),o=h=>e.isOffsetFixed&&e.offset===0&&h.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,h.format):"",a=()=>r?Ro(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),u=(h,E)=>r?Vo(e,h):i(E?{month:h}:{month:h,day:"numeric"},"month"),l=(h,E)=>r?jo(e,h):i(E?{weekday:h}:{weekday:h,month:"long",day:"numeric"},"weekday"),f=h=>{let E=ce.macroTokenToFormatOpts(h);return E?this.formatWithSystemDefault(e,E):h},d=h=>r?qo(e,h):i({era:h},"era"),y=h=>{switch(h){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return o({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return o({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return o({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return s?i({day:"numeric"},"day"):this.num(e.day);case"dd":return s?i({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return l("short",!0);case"cccc":return l("long",!0);case"ccccc":return l("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return l("short",!1);case"EEEE":return l("long",!1);case"EEEEE":return l("narrow",!1);case"L":return s?i({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return s?i({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return u("short",!0);case"LLLL":return u("long",!0);case"LLLLL":return u("narrow",!0);case"M":return s?i({month:"numeric"},"month"):this.num(e.month);case"MM":return s?i({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return u("short",!1);case"MMMM":return u("long",!1);case"MMMMM":return u("narrow",!1);case"y":return s?i({year:"numeric"},"year"):this.num(e.year);case"yy":return s?i({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return s?i({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return s?i({year:"numeric"},"year"):this.num(e.year,6);case"G":return d("short");case"GG":return d("long");case"GGGGG":return d("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return f(h)}};return Ko(ce.parseFormat(t),y)}formatDurationFromString(e,t){let r=u=>{switch(u[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},s=u=>l=>{let f=r(l);return f?this.num(u.get(f),l.length):l},i=ce.parseFormat(t),o=i.reduce((u,{literal:l,val:f})=>l?u:u.concat(f),[]),a=e.shiftTo(...o.map(r).filter(u=>u));return Ko(i,s(a))}};var De=class{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};var Ce=class{get type(){throw new je}get name(){throw new je}get ianaName(){return this.name}get isUniversal(){throw new je}offsetName(e,t){throw new je}formatOffset(e,t){throw new je}offset(e){throw new je}equals(e){throw new je}get isValid(){throw new je}};var fi=null,Ot=class extends Ce{static get instance(){return fi===null&&(fi=new Ot),fi}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:r}){return Yr(e,t,r)}formatOffset(e,t){return xt(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}};var Zr={};function Sl(n){return Zr[n]||(Zr[n]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:n,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),Zr[n]}var kl={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function Cl(n,e){let t=n.format(e).replace(/\\u200E/g,""),r=/(\\d+)\\/(\\d+)\\/(\\d+) (AD|BC),? (\\d+):(\\d+):(\\d+)/.exec(t),[,s,i,o,a,u,l,f]=r;return[o,s,i,a,u,l,f]}function xl(n,e){let t=n.formatToParts(e),r=[];for(let s=0;s<t.length;s++){let{type:i,value:o}=t[s],a=kl[i];i==="era"?r[a]=o:K(a)||(r[a]=parseInt(o,10))}return r}var Gr={},de=class extends Ce{static create(e){return Gr[e]||(Gr[e]=new de(e)),Gr[e]}static resetCache(){Gr={},Zr={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch(t){return!1}}constructor(e){super(),this.zoneName=e,this.valid=de.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:r}){return Yr(e,t,r,this.name)}formatOffset(e,t){return xt(this.offset(e),t)}offset(e){let t=new Date(e);if(isNaN(t))return NaN;let r=Sl(this.name),[s,i,o,a,u,l,f]=r.formatToParts?xl(r,t):Cl(r,t);a==="BC"&&(s=-Math.abs(s)+1);let y=ir({year:s,month:i,day:o,hour:u===24?0:u,minute:l,second:f,millisecond:0}),h=+t,E=h%1e3;return h-=E>=0?E:1e3+E,(y-h)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}};var di=null,ue=class extends Ce{static get utcInstance(){return di===null&&(di=new ue(0)),di}static instance(e){return e===0?ue.utcInstance:new ue(e)}static parseSpecifier(e){if(e){let t=e.match(/^utc(?:([+-]\\d{1,2})(?::(\\d{2}))?)?$/i);if(t)return new ue(Ht(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${xt(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${xt(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,t){return xt(this.fixed,t)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}};var pn=class extends Ce{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function qe(n,e){let t;if(K(n)||n===null)return e;if(n instanceof Ce)return n;if(_o(n)){let r=n.toLowerCase();return r==="local"||r==="system"?e:r==="utc"||r==="gmt"?ue.utcInstance:ue.parseSpecifier(r)||de.create(n)}else return tt(n)?ue.instance(n):typeof n=="object"&&n.offset&&typeof n.offset=="number"?n:new pn(n)}var Wo=()=>Date.now(),Ho="system",Jo=null,zo=null,Yo=null,Go,X=class{static get now(){return Wo}static set now(e){Wo=e}static set defaultZone(e){Ho=e}static get defaultZone(){return qe(Ho,Ot.instance)}static get defaultLocale(){return Jo}static set defaultLocale(e){Jo=e}static get defaultNumberingSystem(){return zo}static set defaultNumberingSystem(e){zo=e}static get defaultOutputCalendar(){return Yo}static set defaultOutputCalendar(e){Yo=e}static get throwOnInvalid(){return Go}static set throwOnInvalid(e){Go=e}static resetCaches(){Q.resetCache(),de.resetCache()}};var Zo={};function Ol(n,e={}){let t=JSON.stringify([n,e]),r=Zo[t];return r||(r=new Intl.ListFormat(n,e),Zo[t]=r),r}var hi={};function pi(n,e={}){let t=JSON.stringify([n,e]),r=hi[t];return r||(r=new Intl.DateTimeFormat(n,e),hi[t]=r),r}var mi={};function vl(n,e={}){let t=JSON.stringify([n,e]),r=mi[t];return r||(r=new Intl.NumberFormat(n,e),mi[t]=r),r}var Di={};function Il(n,e={}){let o=e,{base:t}=o,r=Gs(o,["base"]),s=JSON.stringify([n,r]),i=Di[s];return i||(i=new Intl.RelativeTimeFormat(n,e),Di[s]=i),i}var ur=null;function Ll(){return ur||(ur=new Intl.DateTimeFormat().resolvedOptions().locale,ur)}function Nl(n){let e=n.indexOf("-u-");if(e===-1)return[n];{let t,r=n.substring(0,e);try{t=pi(n).resolvedOptions()}catch(o){t=pi(r).resolvedOptions()}let{numberingSystem:s,calendar:i}=t;return[r,s,i]}}function Al(n,e,t){return(t||e)&&(n+="-u",t&&(n+=`-ca-${t}`),e&&(n+=`-nu-${e}`)),n}function Ml(n){let e=[];for(let t=1;t<=12;t++){let r=P.utc(2016,t,1);e.push(n(r))}return e}function _l(n){let e=[];for(let t=1;t<=7;t++){let r=P.utc(2016,11,13+t);e.push(n(r))}return e}function Qr(n,e,t,r,s){let i=n.listingMode(t);return i==="error"?null:i==="en"?r(e):s(e)}function Bl(n){return n.numberingSystem&&n.numberingSystem!=="latn"?!1:n.numberingSystem==="latn"||!n.locale||n.locale.startsWith("en")||new Intl.DateTimeFormat(n.intl).resolvedOptions().numberingSystem==="latn"}var yi=class{constructor(e,t,r){this.padTo=r.padTo||0,this.floor=r.floor||!1;let a=r,{padTo:s,floor:i}=a,o=Gs(a,["padTo","floor"]);if(!t||Object.keys(o).length>0){let u=R({useGrouping:!1},r);r.padTo>0&&(u.minimumIntegerDigits=r.padTo),this.inf=vl(e,u)}}format(e){if(this.inf){let t=this.floor?Math.floor(e):e;return this.inf.format(t)}else{let t=this.floor?Math.floor(e):cn(e,3);return ae(t,this.padTo)}}},gi=class{constructor(e,t,r){this.opts=r;let s;if(e.zone.isUniversal){let o=-1*(e.offset/60),a=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&de.create(a).valid?(s=a,this.dt=e):(s="UTC",r.timeZoneName?this.dt=e:this.dt=e.offset===0?e:P.fromMillis(e.ts+e.offset*60*1e3))}else e.zone.type==="system"?this.dt=e:(this.dt=e,s=e.zone.name);let i=R({},this.opts);s&&(i.timeZone=s),this.dtf=pi(t,i)}format(){return this.dtf.format(this.dt.toJSDate())}formatToParts(){return this.dtf.formatToParts(this.dt.toJSDate())}resolvedOptions(){return this.dtf.resolvedOptions()}},bi=class{constructor(e,t,r){this.opts=R({style:"long"},r),!t&&zr()&&(this.rtf=Il(e,r))}format(e,t){return this.rtf?this.rtf.format(e,t):Uo(t,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}},Q=class{static fromOpts(e){return Q.create(e.locale,e.numberingSystem,e.outputCalendar,e.defaultToEN)}static create(e,t,r,s=!1){let i=e||X.defaultLocale,o=i||(s?"en-US":Ll()),a=t||X.defaultNumberingSystem,u=r||X.defaultOutputCalendar;return new Q(o,a,u,i)}static resetCache(){ur=null,hi={},mi={},Di={}}static fromObject({locale:e,numberingSystem:t,outputCalendar:r}={}){return Q.create(e,t,r)}constructor(e,t,r,s){let[i,o,a]=Nl(e);this.locale=i,this.numberingSystem=t||o||null,this.outputCalendar=r||a||null,this.intl=Al(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=s,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=Bl(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),t=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&t?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:Q.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone(be(R({},e),{defaultToEN:!0}))}redefaultToSystem(e={}){return this.clone(be(R({},e),{defaultToEN:!1}))}months(e,t=!1,r=!0){return Qr(this,e,r,si,()=>{let s=t?{month:e,day:"numeric"}:{month:e},i=t?"format":"standalone";return this.monthsCache[i][e]||(this.monthsCache[i][e]=Ml(o=>this.extract(o,s,"month"))),this.monthsCache[i][e]})}weekdays(e,t=!1,r=!0){return Qr(this,e,r,ai,()=>{let s=t?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},i=t?"format":"standalone";return this.weekdaysCache[i][e]||(this.weekdaysCache[i][e]=_l(o=>this.extract(o,s,"weekday"))),this.weekdaysCache[i][e]})}meridiems(e=!0){return Qr(this,void 0,e,()=>ui,()=>{if(!this.meridiemCache){let t={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[P.utc(2016,11,13,9),P.utc(2016,11,13,19)].map(r=>this.extract(r,t,"dayperiod"))}return this.meridiemCache})}eras(e,t=!0){return Qr(this,e,t,li,()=>{let r={era:e};return this.eraCache[e]||(this.eraCache[e]=[P.utc(-40,1,1),P.utc(2017,1,1)].map(s=>this.extract(s,r,"era"))),this.eraCache[e]})}extract(e,t,r){let s=this.dtFormatter(e,t),i=s.formatToParts(),o=i.find(a=>a.type.toLowerCase()===r);return o?o.value:null}numberFormatter(e={}){return new yi(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new gi(e,this.intl,t)}relFormatter(e={}){return new bi(this.intl,this.isEnglish(),e)}listFormatter(e={}){return Ol(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}};function Dn(...n){let e=n.reduce((t,r)=>t+r.source,"");return RegExp(`^${e}$`)}function yn(...n){return e=>n.reduce(([t,r,s],i)=>{let[o,a,u]=i(e,s);return[R(R({},t),o),a||r,u]},[{},null,1]).slice(0,2)}function gn(n,...e){if(n==null)return[null,null];for(let[t,r]of e){let s=t.exec(n);if(s)return r(s)}return[null,null]}function Xo(...n){return(e,t)=>{let r={},s;for(s=0;s<n.length;s++)r[n[s]]=yt(e[t+s]);return[r,null,t+s]}}var ea=/(?:(Z)|([+-]\\d\\d)(?::?(\\d\\d))?)/,Pl=`(?:${ea.source}?(?:\\\\[(${ni.source})\\\\])?)?`,Ei=/(\\d\\d)(?::?(\\d\\d)(?::?(\\d\\d)(?:[.,](\\d{1,30}))?)?)?/,ta=RegExp(`${Ei.source}${Pl}`),Fi=RegExp(`(?:T${ta.source})?`),$l=/([+-]\\d{6}|\\d{4})(?:-?(\\d\\d)(?:-?(\\d\\d))?)?/,Rl=/(\\d{4})-?W(\\d\\d)(?:-?(\\d))?/,jl=/(\\d{4})-?(\\d{3})/,Vl=Xo("weekYear","weekNumber","weekDay"),ql=Xo("year","ordinal"),Ul=/(\\d{4})-(\\d\\d)-(\\d\\d)/,na=RegExp(`${Ei.source} ?(?:${ea.source}|(${ni.source}))?`),Kl=RegExp(`(?: ${na.source})?`);function mn(n,e,t){let r=n[e];return K(r)?t:yt(r)}function Wl(n,e){return[{year:mn(n,e),month:mn(n,e+1,1),day:mn(n,e+2,1)},null,e+3]}function bn(n,e){return[{hours:mn(n,e,0),minutes:mn(n,e+1,0),seconds:mn(n,e+2,0),milliseconds:sr(n[e+3])},null,e+4]}function lr(n,e){let t=!n[e]&&!n[e+1],r=Ht(n[e+1],n[e+2]),s=t?null:ue.instance(r);return[{},s,e+3]}function cr(n,e){let t=n[e]?de.create(n[e]):null;return[{},t,e+1]}var Hl=RegExp(`^T?${Ei.source}$`),Jl=/^-?P(?:(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)Y)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)M)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)W)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)D)?(?:T(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)H)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)M)?(?:(-?\\d{1,20})(?:[.,](-?\\d{1,20}))?S)?)?)$/;function zl(n){let[e,t,r,s,i,o,a,u,l]=n,f=e[0]==="-",d=u&&u[0]==="-",y=(h,E=!1)=>h!==void 0&&(E||h&&f)?-h:h;return[{years:y(Ct(t)),months:y(Ct(r)),weeks:y(Ct(s)),days:y(Ct(i)),hours:y(Ct(o)),minutes:y(Ct(a)),seconds:y(Ct(u),u==="-0"),milliseconds:y(sr(l),d)}]}var Yl={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function wi(n,e,t,r,s,i,o){let a={year:e.length===2?or(yt(e)):yt(e),month:ri.indexOf(t)+1,day:yt(r),hour:yt(s),minute:yt(i)};return o&&(a.second=yt(o)),n&&(a.weekday=n.length>3?ii.indexOf(n)+1:oi.indexOf(n)+1),a}var Gl=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\\s)?(\\d{1,2})\\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s(\\d{2,4})\\s(\\d\\d):(\\d\\d)(?::(\\d\\d))?\\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\\d\\d)(\\d\\d)))$/;function Zl(n){let[,e,t,r,s,i,o,a,u,l,f,d]=n,y=wi(e,s,r,t,i,o,a),h;return u?h=Yl[u]:l?h=0:h=Ht(f,d),[y,new ue(h)]}function Ql(n){return n.replace(/\\([^()]*\\)|[\\n\\t]/g," ").replace(/(\\s\\s+)/g," ").trim()}var Xl=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d\\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\\d{4}) (\\d\\d):(\\d\\d):(\\d\\d) GMT$/,ec=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d\\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d) GMT$/,tc=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \\d|\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d) (\\d{4})$/;function Qo(n){let[,e,t,r,s,i,o,a]=n;return[wi(e,s,r,t,i,o,a),ue.utcInstance]}function nc(n){let[,e,t,r,s,i,o,a]=n;return[wi(e,a,t,r,s,i,o),ue.utcInstance]}var rc=Dn($l,Fi),sc=Dn(Rl,Fi),ic=Dn(jl,Fi),oc=Dn(ta),ra=yn(Wl,bn,lr,cr),ac=yn(Vl,bn,lr,cr),uc=yn(ql,bn,lr,cr),lc=yn(bn,lr,cr);function sa(n){return gn(n,[rc,ra],[sc,ac],[ic,uc],[oc,lc])}function ia(n){return gn(Ql(n),[Gl,Zl])}function oa(n){return gn(n,[Xl,Qo],[ec,Qo],[tc,nc])}function aa(n){return gn(n,[Jl,zl])}var cc=yn(bn);function ua(n){return gn(n,[Hl,cc])}var fc=Dn(Ul,Kl),dc=Dn(na),hc=yn(bn,lr,cr);function la(n){return gn(n,[fc,ra],[dc,hc])}var pc="Invalid Duration",ca={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},mc=R({years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3}},ca),Me=146097/400,En=146097/4800,Dc=R({years:{quarters:4,months:12,weeks:Me/7,days:Me,hours:Me*24,minutes:Me*24*60,seconds:Me*24*60*60,milliseconds:Me*24*60*60*1e3},quarters:{months:3,weeks:Me/28,days:Me/4,hours:Me*24/4,minutes:Me*24*60/4,seconds:Me*24*60*60/4,milliseconds:Me*24*60*60*1e3/4},months:{weeks:En/7,days:En,hours:En*24,minutes:En*24*60,seconds:En*24*60*60,milliseconds:En*24*60*60*1e3}},ca),zt=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],yc=zt.slice(0).reverse();function Jt(n,e,t=!1){let r={values:t?e.values:R(R({},n.values),e.values||{}),loc:n.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||n.conversionAccuracy};return new _(r)}function gc(n){return n<0?Math.floor(n):Math.ceil(n)}function fa(n,e,t,r,s){let i=n[s][t],o=e[t]/i,a=Math.sign(o)===Math.sign(r[s]),u=!a&&r[s]!==0&&Math.abs(o)<=1?gc(o):Math.trunc(o);r[s]+=u,e[t]-=u*i}function bc(n,e){yc.reduce((t,r)=>K(e[r])?t:(t&&fa(n,e,t,e,r),r),null)}var _=class{constructor(e){let t=e.conversionAccuracy==="longterm"||!1;this.values=e.values,this.loc=e.loc||Q.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=t?Dc:mc,this.isLuxonDuration=!0}static fromMillis(e,t){return _.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new me(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new _({values:hn(e,_.normalizeUnit),loc:Q.fromObject(t),conversionAccuracy:t.conversionAccuracy})}static fromDurationLike(e){if(tt(e))return _.fromMillis(e);if(_.isDuration(e))return e;if(typeof e=="object")return _.fromObject(e);throw new me(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){let[r]=aa(e);return r?_.fromObject(r,t):_.invalid("unparsable",`the input "${e}" can\'t be parsed as ISO 8601`)}static fromISOTime(e,t){let[r]=ua(e);return r?_.fromObject(r,t):_.invalid("unparsable",`the input "${e}" can\'t be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new me("need to specify a reason the Duration is invalid");let r=e instanceof De?e:new De(e,t);if(X.throwOnInvalid)throw new Jr(r);return new _({invalid:r})}static normalizeUnit(e){let t={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!t)throw new un(e);return t}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,t={}){let r=be(R({},t),{floor:t.round!==!1&&t.floor!==!1});return this.isValid?ce.create(this.loc,r).formatDurationFromString(this,e):pc}toHuman(e={}){let t=zt.map(r=>{let s=this.values[r];return K(s)?null:this.loc.numberFormatter(be(R({style:"unit",unitDisplay:"long"},e),{unit:r.slice(0,-1)})).format(s)}).filter(r=>r);return this.loc.listFormatter(R({type:"conjunction",style:e.listStyle||"narrow"},e)).format(t)}toObject(){return this.isValid?R({},this.values):{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=cn(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let t=this.toMillis();if(t<0||t>=864e5)return null;e=R({suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended"},e);let r=this.shiftTo("hours","minutes","seconds","milliseconds"),s=e.format==="basic"?"hhmm":"hh:mm";(!e.suppressSeconds||r.seconds!==0||r.milliseconds!==0)&&(s+=e.format==="basic"?"ss":":ss",(!e.suppressMilliseconds||r.milliseconds!==0)&&(s+=".SSS"));let i=r.toFormat(s);return e.includePrefix&&(i="T"+i),i}toJSON(){return this.toISO()}toString(){return this.toISO()}toMillis(){return this.as("milliseconds")}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let t=_.fromDurationLike(e),r={};for(let s of zt)(kt(t.values,s)||kt(this.values,s))&&(r[s]=t.get(s)+this.get(s));return Jt(this,{values:r},!0)}minus(e){if(!this.isValid)return this;let t=_.fromDurationLike(e);return this.plus(t.negate())}mapUnits(e){if(!this.isValid)return this;let t={};for(let r of Object.keys(this.values))t[r]=ti(e(this.values[r],r));return Jt(this,{values:t},!0)}get(e){return this[_.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let t=R(R({},this.values),hn(e,_.normalizeUnit));return Jt(this,{values:t})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:r}={}){let s=this.loc.clone({locale:e,numberingSystem:t}),i={loc:s};return r&&(i.conversionAccuracy=r),Jt(this,i)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return bc(this.matrix,e),Jt(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>_.normalizeUnit(o));let t={},r={},s=this.toObject(),i;for(let o of zt)if(e.indexOf(o)>=0){i=o;let a=0;for(let l in r)a+=this.matrix[l][o]*r[l],r[l]=0;tt(s[o])&&(a+=s[o]);let u=Math.trunc(a);t[o]=u,r[o]=(a*1e3-u*1e3)/1e3;for(let l in s)zt.indexOf(l)>zt.indexOf(o)&&fa(this.matrix,s,l,t,o)}else tt(s[o])&&(r[o]=s[o]);for(let o in r)r[o]!==0&&(t[i]+=o===i?r[o]:r[o]/this.matrix[i][o]);return Jt(this,{values:t},!0).normalize()}negate(){if(!this.isValid)return this;let e={};for(let t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return Jt(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function t(r,s){return r===void 0||r===0?s===void 0||s===0:r===s}for(let r of zt)if(!t(this.values[r],e.values[r]))return!1;return!0}};var fr="Invalid Interval";function Ec(n,e){return!n||!n.isValid?ne.invalid("missing or invalid start"):!e||!e.isValid?ne.invalid("missing or invalid end"):e<n?ne.invalid("end before start",`The end of an interval must be after its start, but you had start=${n.toISO()} and end=${e.toISO()}`):null}var ne=class{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,t=null){if(!e)throw new me("need to specify a reason the Interval is invalid");let r=e instanceof De?e:new De(e,t);if(X.throwOnInvalid)throw new Hr(r);return new ne({invalid:r})}static fromDateTimes(e,t){let r=Fn(e),s=Fn(t),i=Ec(r,s);return i==null?new ne({start:r,end:s}):i}static after(e,t){let r=_.fromDurationLike(t),s=Fn(e);return ne.fromDateTimes(s,s.plus(r))}static before(e,t){let r=_.fromDurationLike(t),s=Fn(e);return ne.fromDateTimes(s.minus(r),s)}static fromISO(e,t){let[r,s]=(e||"").split("/",2);if(r&&s){let i,o;try{i=P.fromISO(r,t),o=i.isValid}catch(l){o=!1}let a,u;try{a=P.fromISO(s,t),u=a.isValid}catch(l){u=!1}if(o&&u)return ne.fromDateTimes(i,a);if(o){let l=_.fromISO(s,t);if(l.isValid)return ne.after(i,l)}else if(u){let l=_.fromISO(r,t);if(l.isValid)return ne.before(a,l)}}return ne.invalid("unparsable",`the input "${e}" can\'t be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds"){if(!this.isValid)return NaN;let t=this.start.startOf(e),r=this.end.startOf(e);return Math.floor(r.diff(t,e).get(e))+1}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:t}={}){return this.isValid?ne.fromDateTimes(e||this.s,t||this.e):this}splitAt(...e){if(!this.isValid)return[];let t=e.map(Fn).filter(o=>this.contains(o)).sort(),r=[],{s}=this,i=0;for(;s<this.e;){let o=t[i]||this.e,a=+o>+this.e?this.e:o;r.push(ne.fromDateTimes(s,a)),s=a,i+=1}return r}splitBy(e){let t=_.fromDurationLike(e);if(!this.isValid||!t.isValid||t.as("milliseconds")===0)return[];let{s:r}=this,s=1,i,o=[];for(;r<this.e;){let a=this.start.plus(t.mapUnits(u=>u*s));i=+a>+this.e?this.e:a,o.push(ne.fromDateTimes(r,i)),r=i,s+=1}return o}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let t=this.s>e.s?this.s:e.s,r=this.e<e.e?this.e:e.e;return t>=r?null:ne.fromDateTimes(t,r)}union(e){if(!this.isValid)return this;let t=this.s<e.s?this.s:e.s,r=this.e>e.e?this.e:e.e;return ne.fromDateTimes(t,r)}static merge(e){let[t,r]=e.sort((s,i)=>s.s-i.s).reduce(([s,i],o)=>i?i.overlaps(o)||i.abutsStart(o)?[s,i.union(o)]:[s.concat([i]),o]:[s,o],[[],null]);return r&&t.push(r),t}static xor(e){let t=null,r=0,s=[],i=e.map(u=>[{time:u.s,type:"s"},{time:u.e,type:"e"}]),o=Array.prototype.concat(...i),a=o.sort((u,l)=>u.time-l.time);for(let u of a)r+=u.type==="s"?1:-1,r===1?t=u.time:(t&&+t!=+u.time&&s.push(ne.fromDateTimes(t,u.time)),t=null);return ne.merge(s)}difference(...e){return ne.xor([this].concat(e)).map(t=>this.intersection(t)).filter(t=>t&&!t.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \\u2013 ${this.e.toISO()})`:fr}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:fr}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:fr}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:fr}toFormat(e,{separator:t=" \\u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:fr}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):_.invalid(this.invalidReason)}mapEndpoints(e){return ne.fromDateTimes(e(this.s),e(this.e))}};var gt=class{static hasDST(e=X.defaultZone){let t=P.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return de.isValidZone(e)}static normalizeZone(e){return qe(e,X.defaultZone)}static months(e="long",{locale:t=null,numberingSystem:r=null,locObj:s=null,outputCalendar:i="gregory"}={}){return(s||Q.create(t,r,i)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:r=null,locObj:s=null,outputCalendar:i="gregory"}={}){return(s||Q.create(t,r,i)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:r=null,locObj:s=null}={}){return(s||Q.create(t,r,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:r=null,locObj:s=null}={}){return(s||Q.create(t,r,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return Q.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return Q.create(t,null,"gregory").eras(e)}static features(){return{relative:zr()}}};function da(n,e){let t=s=>s.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),r=t(e)-t(n);return Math.floor(_.fromMillis(r).as("days"))}function Fc(n,e,t){let r=[["years",(a,u)=>u.year-a.year],["quarters",(a,u)=>u.quarter-a.quarter],["months",(a,u)=>u.month-a.month+(u.year-a.year)*12],["weeks",(a,u)=>{let l=da(a,u);return(l-l%7)/7}],["days",da]],s={},i,o;for(let[a,u]of r)if(t.indexOf(a)>=0){i=a;let l=u(n,e);o=n.plus({[a]:l}),o>e?(n=n.plus({[a]:l-1}),l-=1):n=o,s[a]=l}return[n,s,o,i]}function ha(n,e,t,r){let[s,i,o,a]=Fc(n,e,t),u=e-s,l=t.filter(d=>["hours","minutes","seconds","milliseconds"].indexOf(d)>=0);l.length===0&&(o<e&&(o=s.plus({[a]:1})),o!==s&&(i[a]=(i[a]||0)+u/(o-s)));let f=_.fromObject(i,r);return l.length>0?_.fromMillis(u,r).shiftTo(...l).plus(f):f}var Ti={arab:"[\\u0660-\\u0669]",arabext:"[\\u06F0-\\u06F9]",bali:"[\\u1B50-\\u1B59]",beng:"[\\u09E6-\\u09EF]",deva:"[\\u0966-\\u096F]",fullwide:"[\\uFF10-\\uFF19]",gujr:"[\\u0AE6-\\u0AEF]",hanidec:"[\\u3007|\\u4E00|\\u4E8C|\\u4E09|\\u56DB|\\u4E94|\\u516D|\\u4E03|\\u516B|\\u4E5D]",khmr:"[\\u17E0-\\u17E9]",knda:"[\\u0CE6-\\u0CEF]",laoo:"[\\u0ED0-\\u0ED9]",limb:"[\\u1946-\\u194F]",mlym:"[\\u0D66-\\u0D6F]",mong:"[\\u1810-\\u1819]",mymr:"[\\u1040-\\u1049]",orya:"[\\u0B66-\\u0B6F]",tamldec:"[\\u0BE6-\\u0BEF]",telu:"[\\u0C66-\\u0C6F]",thai:"[\\u0E50-\\u0E59]",tibt:"[\\u0F20-\\u0F29]",latn:"\\\\d"},pa={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},wc=Ti.hanidec.replace(/[\\[|\\]]/g,"").split("");function ma(n){let e=parseInt(n,10);if(isNaN(e)){e="";for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);if(n[t].search(Ti.hanidec)!==-1)e+=wc.indexOf(n[t]);else for(let s in pa){let[i,o]=pa[s];r>=i&&r<=o&&(e+=r-i)}}return parseInt(e,10)}else return e}function _e({numberingSystem:n},e=""){return new RegExp(`${Ti[n||"latn"]}${e}`)}var Tc="missing Intl.DateTimeFormat.formatToParts support";function G(n,e=t=>t){return{regex:n,deser:([t])=>e(ma(t))}}var Sc=String.fromCharCode(160),ga=`[ ${Sc}]`,ba=new RegExp(ga,"g");function kc(n){return n.replace(/\\./g,"\\\\.?").replace(ba,ga)}function Da(n){return n.replace(/\\./g,"").replace(ba," ").toLowerCase()}function Ue(n,e){return n===null?null:{regex:RegExp(n.map(kc).join("|")),deser:([t])=>n.findIndex(r=>Da(t)===Da(r))+e}}function ya(n,e){return{regex:n,deser:([,t,r])=>Ht(t,r),groups:e}}function Si(n){return{regex:n,deser:([e])=>e}}function Cc(n){return n.replace(/[\\-\\[\\]{}()*+?.,\\\\\\^$|#\\s]/g,"\\\\$&")}function xc(n,e){let t=_e(e),r=_e(e,"{2}"),s=_e(e,"{3}"),i=_e(e,"{4}"),o=_e(e,"{6}"),a=_e(e,"{1,2}"),u=_e(e,"{1,3}"),l=_e(e,"{1,6}"),f=_e(e,"{1,9}"),d=_e(e,"{2,4}"),y=_e(e,"{4,6}"),h=T=>({regex:RegExp(Cc(T.val)),deser:([g])=>g,literal:!0}),p=(T=>{if(n.literal)return h(T);switch(T.val){case"G":return Ue(e.eras("short",!1),0);case"GG":return Ue(e.eras("long",!1),0);case"y":return G(l);case"yy":return G(d,or);case"yyyy":return G(i);case"yyyyy":return G(y);case"yyyyyy":return G(o);case"M":return G(a);case"MM":return G(r);case"MMM":return Ue(e.months("short",!0,!1),1);case"MMMM":return Ue(e.months("long",!0,!1),1);case"L":return G(a);case"LL":return G(r);case"LLL":return Ue(e.months("short",!1,!1),1);case"LLLL":return Ue(e.months("long",!1,!1),1);case"d":return G(a);case"dd":return G(r);case"o":return G(u);case"ooo":return G(s);case"HH":return G(r);case"H":return G(a);case"hh":return G(r);case"h":return G(a);case"mm":return G(r);case"m":return G(a);case"q":return G(a);case"qq":return G(r);case"s":return G(a);case"ss":return G(r);case"S":return G(u);case"SSS":return G(s);case"u":return Si(f);case"uu":return Si(a);case"uuu":return G(t);case"a":return Ue(e.meridiems(),0);case"kkkk":return G(i);case"kk":return G(d,or);case"W":return G(a);case"WW":return G(r);case"E":case"c":return G(t);case"EEE":return Ue(e.weekdays("short",!1,!1),1);case"EEEE":return Ue(e.weekdays("long",!1,!1),1);case"ccc":return Ue(e.weekdays("short",!0,!1),1);case"cccc":return Ue(e.weekdays("long",!0,!1),1);case"Z":case"ZZ":return ya(new RegExp(`([+-]${a.source})(?::(${r.source}))?`),2);case"ZZZ":return ya(new RegExp(`([+-]${a.source})(${r.source})?`),2);case"z":return Si(/[a-z_+-/]{1,256}?/i);default:return h(T)}})(n)||{invalidReason:Tc};return p.token=n,p}var Oc={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour:{numeric:"h","2-digit":"hh"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"}};function vc(n,e,t){let{type:r,value:s}=n;if(r==="literal")return{literal:!0,val:s};let i=t[r],o=Oc[r];if(typeof o=="object"&&(o=o[i]),o)return{literal:!1,val:o}}function Ic(n){return[`^${n.map(t=>t.regex).reduce((t,r)=>`${t}(${r.source})`,"")}$`,n]}function Lc(n,e,t){let r=n.match(e);if(r){let s={},i=1;for(let o in t)if(kt(t,o)){let a=t[o],u=a.groups?a.groups+1:1;!a.literal&&a.token&&(s[a.token.val[0]]=a.deser(r.slice(i,i+u))),i+=u}return[r,s]}else return[r,{}]}function Nc(n){let e=i=>{switch(i){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},t=null,r;return K(n.z)||(t=de.create(n.z)),K(n.Z)||(t||(t=new ue(n.Z)),r=n.Z),K(n.q)||(n.M=(n.q-1)*3+1),K(n.h)||(n.h<12&&n.a===1?n.h+=12:n.h===12&&n.a===0&&(n.h=0)),n.G===0&&n.y&&(n.y=-n.y),K(n.u)||(n.S=sr(n.u)),[Object.keys(n).reduce((i,o)=>{let a=e(o);return a&&(i[a]=n[o]),i},{}),t,r]}var ki=null;function Ac(){return ki||(ki=P.fromMillis(1555555555555)),ki}function Mc(n,e){if(n.literal)return n;let t=ce.macroTokenToFormatOpts(n.val);if(!t)return n;let i=ce.create(e,t).formatDateTimeParts(Ac()).map(o=>vc(o,e,t));return i.includes(void 0)?n:i}function _c(n,e){return Array.prototype.concat(...n.map(t=>Mc(t,e)))}function Ci(n,e,t){let r=_c(ce.parseFormat(t),n),s=r.map(o=>xc(o,n)),i=s.find(o=>o.invalidReason);if(i)return{input:e,tokens:r,invalidReason:i.invalidReason};{let[o,a]=Ic(s),u=RegExp(o,"i"),[l,f]=Lc(e,u,a),[d,y,h]=f?Nc(f):[null,null,void 0];if(kt(f,"a")&&kt(f,"H"))throw new Dt("Can\'t include meridiem when specifying 24-hour format");return{input:e,tokens:r,regex:u,rawMatches:l,matches:f,result:d,zone:y,specificOffset:h}}}function Ea(n,e,t){let{result:r,zone:s,specificOffset:i,invalidReason:o}=Ci(n,e,t);return[r,s,i,o]}var Fa=[0,31,59,90,120,151,181,212,243,273,304,334],wa=[0,31,60,91,121,152,182,213,244,274,305,335];function Be(n,e){return new De("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${n}, which is invalid`)}function Ta(n,e,t){let r=new Date(Date.UTC(n,e-1,t));n<100&&n>=0&&r.setUTCFullYear(r.getUTCFullYear()-1900);let s=r.getUTCDay();return s===0?7:s}function Sa(n,e,t){return t+(Kt(n)?wa:Fa)[e-1]}function ka(n,e){let t=Kt(n)?wa:Fa,r=t.findIndex(i=>i<e),s=e-t[r];return{month:r+1,day:s}}function Xr(n){let{year:e,month:t,day:r}=n,s=Sa(e,t,r),i=Ta(e,t,r),o=Math.floor((s-i+10)/7),a;return o<1?(a=e-1,o=dn(a)):o>dn(e)?(a=e+1,o=1):a=e,R({weekYear:a,weekNumber:o,weekday:i},ar(n))}function xi(n){let{weekYear:e,weekNumber:t,weekday:r}=n,s=Ta(e,1,4),i=Wt(e),o=t*7+r-s-3,a;o<1?(a=e-1,o+=Wt(a)):o>i?(a=e+1,o-=Wt(e)):a=e;let{month:u,day:l}=ka(a,o);return R({year:a,month:u,day:l},ar(n))}function es(n){let{year:e,month:t,day:r}=n,s=Sa(e,t,r);return R({year:e,ordinal:s},ar(n))}function Oi(n){let{year:e,ordinal:t}=n,{month:r,day:s}=ka(e,t);return R({year:e,month:r,day:s},ar(n))}function Ca(n){let e=rr(n.weekYear),t=nt(n.weekNumber,1,dn(n.weekYear)),r=nt(n.weekday,1,7);return e?t?r?!1:Be("weekday",n.weekday):Be("week",n.week):Be("weekYear",n.weekYear)}function xa(n){let e=rr(n.year),t=nt(n.ordinal,1,Wt(n.year));return e?t?!1:Be("ordinal",n.ordinal):Be("year",n.year)}function vi(n){let e=rr(n.year),t=nt(n.month,1,12),r=nt(n.day,1,fn(n.year,n.month));return e?t?r?!1:Be("day",n.day):Be("month",n.month):Be("year",n.year)}function Ii(n){let{hour:e,minute:t,second:r,millisecond:s}=n,i=nt(e,0,23)||e===24&&t===0&&r===0&&s===0,o=nt(t,0,59),a=nt(r,0,59),u=nt(s,0,999);return i?o?a?u?!1:Be("millisecond",s):Be("second",r):Be("minute",t):Be("hour",e)}var Li="Invalid DateTime",Oa=864e13;function ts(n){return new De("unsupported zone",`the zone "${n.name}" is not supported`)}function Ni(n){return n.weekData===null&&(n.weekData=Xr(n.c)),n.weekData}function dr(n,e){let t={ts:n.ts,zone:n.zone,c:n.c,o:n.o,loc:n.loc,invalid:n.invalid};return new P(be(R(R({},t),e),{old:t}))}function Ba(n,e,t){let r=n-e*60*1e3,s=t.offset(r);if(e===s)return[r,e];r-=(s-e)*60*1e3;let i=t.offset(r);return s===i?[r,s]:[n-Math.min(s,i)*60*1e3,Math.max(s,i)]}function va(n,e){n+=e*60*1e3;let t=new Date(n);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),millisecond:t.getUTCMilliseconds()}}function rs(n,e,t){return Ba(ir(n),e,t)}function Ia(n,e){let t=n.o,r=n.c.year+Math.trunc(e.years),s=n.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i=be(R({},n.c),{year:r,month:s,day:Math.min(n.c.day,fn(r,s))+Math.trunc(e.days)+Math.trunc(e.weeks)*7}),o=_.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=ir(i),[u,l]=Ba(a,t,n.zone);return o!==0&&(u+=o,l=n.zone.offset(u)),{ts:u,o:l}}function hr(n,e,t,r,s,i){let{setZone:o,zone:a}=t;if(n&&Object.keys(n).length!==0){let u=e||a,l=P.fromObject(n,be(R({},t),{zone:u,specificOffset:i}));return o?l:l.setZone(a)}else return P.invalid(new De("unparsable",`the input "${s}" can\'t be parsed as ${r}`))}function ns(n,e,t=!0){return n.isValid?ce.create(Q.create("en-US"),{allowZ:t,forceSimple:!0}).formatDateTimeFromString(n,e):null}function Ai(n,e){let t=n.c.year>9999||n.c.year<0,r="";return t&&n.c.year>=0&&(r+="+"),r+=ae(n.c.year,t?6:4),e?(r+="-",r+=ae(n.c.month),r+="-",r+=ae(n.c.day)):(r+=ae(n.c.month),r+=ae(n.c.day)),r}function La(n,e,t,r,s,i){let o=ae(n.c.hour);return e?(o+=":",o+=ae(n.c.minute),(n.c.second!==0||!t)&&(o+=":")):o+=ae(n.c.minute),(n.c.second!==0||!t)&&(o+=ae(n.c.second),(n.c.millisecond!==0||!r)&&(o+=".",o+=ae(n.c.millisecond,3))),s&&(n.isOffsetFixed&&n.offset===0&&!i?o+="Z":n.o<0?(o+="-",o+=ae(Math.trunc(-n.o/60)),o+=":",o+=ae(Math.trunc(-n.o%60))):(o+="+",o+=ae(Math.trunc(n.o/60)),o+=":",o+=ae(Math.trunc(n.o%60)))),i&&(o+="["+n.zone.ianaName+"]"),o}var Pa={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Bc={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Pc={ordinal:1,hour:0,minute:0,second:0,millisecond:0},$a=["year","month","day","hour","minute","second","millisecond"],$c=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Rc=["year","ordinal","hour","minute","second","millisecond"];function Na(n){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[n.toLowerCase()];if(!e)throw new un(n);return e}function Aa(n,e){let t=qe(e.zone,X.defaultZone),r=Q.fromObject(e),s=X.now(),i,o;if(K(n.year))i=s;else{for(let l of $a)K(n[l])&&(n[l]=Pa[l]);let a=vi(n)||Ii(n);if(a)return P.invalid(a);let u=t.offset(s);[i,o]=rs(n,u,t)}return new P({ts:i,zone:t,loc:r,o})}function Ma(n,e,t){let r=K(t.round)?!0:t.round,s=(o,a)=>(o=cn(o,r||t.calendary?0:2,!0),e.loc.clone(t).relFormatter(t).format(o,a)),i=o=>t.calendary?e.hasSame(n,o)?0:e.startOf(o).diff(n.startOf(o),o).get(o):e.diff(n,o).get(o);if(t.unit)return s(i(t.unit),t.unit);for(let o of t.units){let a=i(o);if(Math.abs(a)>=1)return s(a,o)}return s(n>e?-0:0,t.units[t.units.length-1])}function _a(n){let e={},t;return n.length>0&&typeof n[n.length-1]=="object"?(e=n[n.length-1],t=Array.from(n).slice(0,n.length-1)):t=Array.from(n),[e,t]}var P=class{constructor(e){let t=e.zone||X.defaultZone,r=e.invalid||(Number.isNaN(e.ts)?new De("invalid input"):null)||(t.isValid?null:ts(t));this.ts=K(e.ts)?X.now():e.ts;let s=null,i=null;if(!r)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[s,i]=[e.old.c,e.old.o];else{let a=t.offset(this.ts);s=va(this.ts,a),r=Number.isNaN(s.year)?new De("invalid input"):null,s=r?null:s,i=r?null:a}this._zone=t,this.loc=e.loc||Q.create(),this.invalid=r,this.weekData=null,this.c=s,this.o=i,this.isLuxonDateTime=!0}static now(){return new P({})}static local(){let[e,t]=_a(arguments),[r,s,i,o,a,u,l]=t;return Aa({year:r,month:s,day:i,hour:o,minute:a,second:u,millisecond:l},e)}static utc(){let[e,t]=_a(arguments),[r,s,i,o,a,u,l]=t;return e.zone=ue.utcInstance,Aa({year:r,month:s,day:i,hour:o,minute:a,second:u,millisecond:l},e)}static fromJSDate(e,t={}){let r=Bo(e)?e.valueOf():NaN;if(Number.isNaN(r))return P.invalid("invalid input");let s=qe(t.zone,X.defaultZone);return s.isValid?new P({ts:r,zone:s,loc:Q.fromObject(t)}):P.invalid(ts(s))}static fromMillis(e,t={}){if(tt(e))return e<-Oa||e>Oa?P.invalid("Timestamp out of range"):new P({ts:e,zone:qe(t.zone,X.defaultZone),loc:Q.fromObject(t)});throw new me(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(tt(e))return new P({ts:e*1e3,zone:qe(t.zone,X.defaultZone),loc:Q.fromObject(t)});throw new me("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};let r=qe(t.zone,X.defaultZone);if(!r.isValid)return P.invalid(ts(r));let s=X.now(),i=K(t.specificOffset)?r.offset(s):t.specificOffset,o=hn(e,Na),a=!K(o.ordinal),u=!K(o.year),l=!K(o.month)||!K(o.day),f=u||l,d=o.weekYear||o.weekNumber,y=Q.fromObject(t);if((f||a)&&d)throw new Dt("Can\'t mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&a)throw new Dt("Can\'t mix ordinal dates with month/day");let h=d||o.weekday&&!f,E,p,T=va(s,i);h?(E=$c,p=Bc,T=Xr(T)):a?(E=Rc,p=Pc,T=es(T)):(E=$a,p=Pa);let g=!1;for(let S of E){let V=o[S];K(V)?g?o[S]=p[S]:o[S]=T[S]:g=!0}let k=h?Ca(o):a?xa(o):vi(o),L=k||Ii(o);if(L)return P.invalid(L);let m=h?xi(o):a?Oi(o):o,[F,O]=rs(m,i,r),x=new P({ts:F,zone:r,o:O,loc:y});return o.weekday&&f&&e.weekday!==x.weekday?P.invalid("mismatched weekday",`you can\'t specify both a weekday of ${o.weekday} and a date of ${x.toISO()}`):x}static fromISO(e,t={}){let[r,s]=sa(e);return hr(r,s,t,"ISO 8601",e)}static fromRFC2822(e,t={}){let[r,s]=ia(e);return hr(r,s,t,"RFC 2822",e)}static fromHTTP(e,t={}){let[r,s]=oa(e);return hr(r,s,t,"HTTP",t)}static fromFormat(e,t,r={}){if(K(e)||K(t))throw new me("fromFormat requires an input string and a format");let{locale:s=null,numberingSystem:i=null}=r,o=Q.fromOpts({locale:s,numberingSystem:i,defaultToEN:!0}),[a,u,l,f]=Ea(o,e,t);return f?P.invalid(f):hr(a,u,r,`format ${t}`,e,l)}static fromString(e,t,r={}){return P.fromFormat(e,t,r)}static fromSQL(e,t={}){let[r,s]=la(e);return hr(r,s,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new me("need to specify a reason the DateTime is invalid");let r=e instanceof De?e:new De(e,t);if(X.throwOnInvalid)throw new Wr(r);return new P({invalid:r})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?Ni(this).weekYear:NaN}get weekNumber(){return this.isValid?Ni(this).weekNumber:NaN}get weekday(){return this.isValid?Ni(this).weekday:NaN}get ordinal(){return this.isValid?es(this.c).ordinal:NaN}get monthShort(){return this.isValid?gt.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?gt.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?gt.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?gt.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}get isInLeapYear(){return Kt(this.year)}get daysInMonth(){return fn(this.year,this.month)}get daysInYear(){return this.isValid?Wt(this.year):NaN}get weeksInWeekYear(){return this.isValid?dn(this.weekYear):NaN}resolvedLocaleOptions(e={}){let{locale:t,numberingSystem:r,calendar:s}=ce.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:r,outputCalendar:s}}toUTC(e=0,t={}){return this.setZone(ue.instance(e),t)}toLocal(){return this.setZone(X.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:r=!1}={}){if(e=qe(e,X.defaultZone),e.equals(this.zone))return this;if(e.isValid){let s=this.ts;if(t||r){let i=e.offset(this.ts),o=this.toObject();[s]=rs(o,i,e)}return dr(this,{ts:s,zone:e})}else return P.invalid(ts(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:r}={}){let s=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:r});return dr(this,{loc:s})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let t=hn(e,Na),r=!K(t.weekYear)||!K(t.weekNumber)||!K(t.weekday),s=!K(t.ordinal),i=!K(t.year),o=!K(t.month)||!K(t.day),a=i||o,u=t.weekYear||t.weekNumber;if((a||s)&&u)throw new Dt("Can\'t mix weekYear/weekNumber units with year/month/day or ordinals");if(o&&s)throw new Dt("Can\'t mix ordinal dates with month/day");let l;r?l=xi(R(R({},Xr(this.c)),t)):K(t.ordinal)?(l=R(R({},this.toObject()),t),K(t.day)&&(l.day=Math.min(fn(l.year,l.month),l.day))):l=Oi(R(R({},es(this.c)),t));let[f,d]=rs(l,this.o,this.zone);return dr(this,{ts:f,o:d})}plus(e){if(!this.isValid)return this;let t=_.fromDurationLike(e);return dr(this,Ia(this,t))}minus(e){if(!this.isValid)return this;let t=_.fromDurationLike(e).negate();return dr(this,Ia(this,t))}startOf(e){if(!this.isValid)return this;let t={},r=_.normalizeUnit(e);switch(r){case"years":t.month=1;case"quarters":case"months":t.day=1;case"weeks":case"days":t.hour=0;case"hours":t.minute=0;case"minutes":t.second=0;case"seconds":t.millisecond=0;break;case"milliseconds":break}if(r==="weeks"&&(t.weekday=1),r==="quarters"){let s=Math.ceil(this.month/3);t.month=(s-1)*3+1}return this.set(t)}endOf(e){return this.isValid?this.plus({[e]:1}).startOf(e).minus(1):this}toFormat(e,t={}){return this.isValid?ce.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):Li}toLocaleString(e=ln,t={}){return this.isValid?ce.create(this.loc.clone(t),e).formatDateTime(this):Li}toLocaleParts(e={}){return this.isValid?ce.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:t=!1,suppressMilliseconds:r=!1,includeOffset:s=!0,extendedZone:i=!1}={}){if(!this.isValid)return null;let o=e==="extended",a=Ai(this,o);return a+="T",a+=La(this,o,t,r,s,i),a}toISODate({format:e="extended"}={}){return this.isValid?Ai(this,e==="extended"):null}toISOWeekDate(){return ns(this,"kkkk-\'W\'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:r=!0,includePrefix:s=!1,extendedZone:i=!1,format:o="extended"}={}){return this.isValid?(s?"T":"")+La(this,o==="extended",t,e,r,i):null}toRFC2822(){return ns(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return ns(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss \'GMT\'")}toSQLDate(){return this.isValid?Ai(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:t=!1,includeOffsetSpace:r=!0}={}){let s="HH:mm:ss.SSS";return(t||e)&&(r&&(s+=" "),t?s+="z":e&&(s+="ZZ")),ns(this,s,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():Li}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let t=R({},this.c);return e.includeConfig&&(t.outputCalendar=this.outputCalendar,t.numberingSystem=this.loc.numberingSystem,t.locale=this.loc.locale),t}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,t="milliseconds",r={}){if(!this.isValid||!e.isValid)return _.invalid("created by diffing an invalid DateTime");let s=R({locale:this.locale,numberingSystem:this.numberingSystem},r),i=Po(t).map(_.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,u=o?e:this,l=ha(a,u,i,s);return o?l.negate():l}diffNow(e="milliseconds",t={}){return this.diff(P.now(),e,t)}until(e){return this.isValid?ne.fromDateTimes(this,e):this}hasSame(e,t){if(!this.isValid)return!1;let r=e.valueOf(),s=this.setZone(e.zone,{keepLocalTime:!0});return s.startOf(t)<=r&&r<=s.endOf(t)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let t=e.base||P.fromObject({},{zone:this.zone}),r=e.padding?this<t?-e.padding:e.padding:0,s=["years","months","days","hours","minutes","seconds"],i=e.unit;return Array.isArray(e.unit)&&(s=e.unit,i=void 0),Ma(t,this.plus(r),be(R({},e),{numeric:"always",units:s,unit:i}))}toRelativeCalendar(e={}){return this.isValid?Ma(e.base||P.fromObject({},{zone:this.zone}),this,be(R({},e),{numeric:"auto",units:["years","months","days"],calendary:!0})):null}static min(...e){if(!e.every(P.isDateTime))throw new me("min requires all arguments be DateTimes");return ei(e,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(P.isDateTime))throw new me("max requires all arguments be DateTimes");return ei(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,r={}){let{locale:s=null,numberingSystem:i=null}=r,o=Q.fromOpts({locale:s,numberingSystem:i,defaultToEN:!0});return Ci(o,e,t)}static fromStringExplain(e,t,r={}){return P.fromFormatExplain(e,t,r)}static get DATE_SHORT(){return ln}static get DATE_MED(){return $n}static get DATE_MED_WITH_WEEKDAY(){return Zs}static get DATE_FULL(){return Rn}static get DATE_HUGE(){return jn}static get TIME_SIMPLE(){return Vn}static get TIME_WITH_SECONDS(){return qn}static get TIME_WITH_SHORT_OFFSET(){return Un}static get TIME_WITH_LONG_OFFSET(){return Kn}static get TIME_24_SIMPLE(){return Wn}static get TIME_24_WITH_SECONDS(){return Hn}static get TIME_24_WITH_SHORT_OFFSET(){return Jn}static get TIME_24_WITH_LONG_OFFSET(){return zn}static get DATETIME_SHORT(){return Yn}static get DATETIME_SHORT_WITH_SECONDS(){return Gn}static get DATETIME_MED(){return Zn}static get DATETIME_MED_WITH_SECONDS(){return Qn}static get DATETIME_MED_WITH_WEEKDAY(){return Qs}static get DATETIME_FULL(){return Xn}static get DATETIME_FULL_WITH_SECONDS(){return er}static get DATETIME_HUGE(){return tr}static get DATETIME_HUGE_WITH_SECONDS(){return nr}};function Fn(n){if(P.isDateTime(n))return n;if(n&&n.valueOf&&tt(n.valueOf()))return P.fromJSDate(n);if(n&&typeof n=="object")return P.fromObject(n);throw new me(`Unknown datetime argument: ${n}, of type ${typeof n}`)}var bt=Kr(ss());var wn=()=>/[#*0-9]\\uFE0F?\\u20E3|[\\xA9\\xAE\\u203C\\u2049\\u2122\\u2139\\u2194-\\u2199\\u21A9\\u21AA\\u231A\\u231B\\u2328\\u23CF\\u23ED-\\u23EF\\u23F1\\u23F2\\u23F8-\\u23FA\\u24C2\\u25AA\\u25AB\\u25B6\\u25C0\\u25FB\\u25FC\\u25FE\\u2600-\\u2604\\u260E\\u2611\\u2614\\u2615\\u2618\\u2620\\u2622\\u2623\\u2626\\u262A\\u262E\\u262F\\u2638-\\u263A\\u2640\\u2642\\u2648-\\u2653\\u265F\\u2660\\u2663\\u2665\\u2666\\u2668\\u267B\\u267E\\u267F\\u2692\\u2694-\\u2697\\u2699\\u269B\\u269C\\u26A0\\u26A7\\u26AA\\u26B0\\u26B1\\u26BD\\u26BE\\u26C4\\u26C8\\u26CF\\u26D1\\u26E9\\u26F0-\\u26F5\\u26F7\\u26F8\\u26FA\\u2702\\u2708\\u2709\\u270F\\u2712\\u2714\\u2716\\u271D\\u2721\\u2733\\u2734\\u2744\\u2747\\u2757\\u2763\\u27A1\\u2934\\u2935\\u2B05-\\u2B07\\u2B1B\\u2B1C\\u2B55\\u3030\\u303D\\u3297\\u3299]\\uFE0F?|[\\u261D\\u270C\\u270D](?:\\uD83C[\\uDFFB-\\uDFFF]|\\uFE0F)?|[\\u270A\\u270B](?:\\uD83C[\\uDFFB-\\uDFFF])?|[\\u23E9-\\u23EC\\u23F0\\u23F3\\u25FD\\u2693\\u26A1\\u26AB\\u26C5\\u26CE\\u26D4\\u26EA\\u26FD\\u2705\\u2728\\u274C\\u274E\\u2753-\\u2755\\u2795-\\u2797\\u27B0\\u27BF\\u2B50]|\\u26D3\\uFE0F?(?:\\u200D\\uD83D\\uDCA5)?|\\u26F9(?:\\uD83C[\\uDFFB-\\uDFFF]|\\uFE0F)?(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|\\u2764\\uFE0F?(?:\\u200D(?:\\uD83D\\uDD25|\\uD83E\\uDE79))?|\\uD83C(?:[\\uDC04\\uDD70\\uDD71\\uDD7E\\uDD7F\\uDE02\\uDE37\\uDF21\\uDF24-\\uDF2C\\uDF36\\uDF7D\\uDF96\\uDF97\\uDF99-\\uDF9B\\uDF9E\\uDF9F\\uDFCD\\uDFCE\\uDFD4-\\uDFDF\\uDFF5\\uDFF7]\\uFE0F?|[\\uDF85\\uDFC2\\uDFC7](?:\\uD83C[\\uDFFB-\\uDFFF])?|[\\uDFC4\\uDFCA](?:\\uD83C[\\uDFFB-\\uDFFF])?(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|[\\uDFCB\\uDFCC](?:\\uD83C[\\uDFFB-\\uDFFF]|\\uFE0F)?(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|[\\uDCCF\\uDD8E\\uDD91-\\uDD9A\\uDE01\\uDE1A\\uDE2F\\uDE32-\\uDE36\\uDE38-\\uDE3A\\uDE50\\uDE51\\uDF00-\\uDF20\\uDF2D-\\uDF35\\uDF37-\\uDF43\\uDF45-\\uDF4A\\uDF4C-\\uDF7C\\uDF7E-\\uDF84\\uDF86-\\uDF93\\uDFA0-\\uDFC1\\uDFC5\\uDFC6\\uDFC8\\uDFC9\\uDFCF-\\uDFD3\\uDFE0-\\uDFF0\\uDFF8-\\uDFFF]|\\uDDE6\\uD83C[\\uDDE8-\\uDDEC\\uDDEE\\uDDF1\\uDDF2\\uDDF4\\uDDF6-\\uDDFA\\uDDFC\\uDDFD\\uDDFF]|\\uDDE7\\uD83C[\\uDDE6\\uDDE7\\uDDE9-\\uDDEF\\uDDF1-\\uDDF4\\uDDF6-\\uDDF9\\uDDFB\\uDDFC\\uDDFE\\uDDFF]|\\uDDE8\\uD83C[\\uDDE6\\uDDE8\\uDDE9\\uDDEB-\\uDDEE\\uDDF0-\\uDDF7\\uDDFA-\\uDDFF]|\\uDDE9\\uD83C[\\uDDEA\\uDDEC\\uDDEF\\uDDF0\\uDDF2\\uDDF4\\uDDFF]|\\uDDEA\\uD83C[\\uDDE6\\uDDE8\\uDDEA\\uDDEC\\uDDED\\uDDF7-\\uDDFA]|\\uDDEB\\uD83C[\\uDDEE-\\uDDF0\\uDDF2\\uDDF4\\uDDF7]|\\uDDEC\\uD83C[\\uDDE6\\uDDE7\\uDDE9-\\uDDEE\\uDDF1-\\uDDF3\\uDDF5-\\uDDFA\\uDDFC\\uDDFE]|\\uDDED\\uD83C[\\uDDF0\\uDDF2\\uDDF3\\uDDF7\\uDDF9\\uDDFA]|\\uDDEE\\uD83C[\\uDDE8-\\uDDEA\\uDDF1-\\uDDF4\\uDDF6-\\uDDF9]|\\uDDEF\\uD83C[\\uDDEA\\uDDF2\\uDDF4\\uDDF5]|\\uDDF0\\uD83C[\\uDDEA\\uDDEC-\\uDDEE\\uDDF2\\uDDF3\\uDDF5\\uDDF7\\uDDFC\\uDDFE\\uDDFF]|\\uDDF1\\uD83C[\\uDDE6-\\uDDE8\\uDDEE\\uDDF0\\uDDF7-\\uDDFB\\uDDFE]|\\uDDF2\\uD83C[\\uDDE6\\uDDE8-\\uDDED\\uDDF0-\\uDDFF]|\\uDDF3\\uD83C[\\uDDE6\\uDDE8\\uDDEA-\\uDDEC\\uDDEE\\uDDF1\\uDDF4\\uDDF5\\uDDF7\\uDDFA\\uDDFF]|\\uDDF4\\uD83C\\uDDF2|\\uDDF5\\uD83C[\\uDDE6\\uDDEA-\\uDDED\\uDDF0-\\uDDF3\\uDDF7-\\uDDF9\\uDDFC\\uDDFE]|\\uDDF6\\uD83C\\uDDE6|\\uDDF7\\uD83C[\\uDDEA\\uDDF4\\uDDF8\\uDDFA\\uDDFC]|\\uDDF8\\uD83C[\\uDDE6-\\uDDEA\\uDDEC-\\uDDF4\\uDDF7-\\uDDF9\\uDDFB\\uDDFD-\\uDDFF]|\\uDDF9\\uD83C[\\uDDE6\\uDDE8\\uDDE9\\uDDEB-\\uDDED\\uDDEF-\\uDDF4\\uDDF7\\uDDF9\\uDDFB\\uDDFC\\uDDFF]|\\uDDFA\\uD83C[\\uDDE6\\uDDEC\\uDDF2\\uDDF3\\uDDF8\\uDDFE\\uDDFF]|\\uDDFB\\uD83C[\\uDDE6\\uDDE8\\uDDEA\\uDDEC\\uDDEE\\uDDF3\\uDDFA]|\\uDDFC\\uD83C[\\uDDEB\\uDDF8]|\\uDDFD\\uD83C\\uDDF0|\\uDDFE\\uD83C[\\uDDEA\\uDDF9]|\\uDDFF\\uD83C[\\uDDE6\\uDDF2\\uDDFC]|\\uDF44(?:\\u200D\\uD83D\\uDFEB)?|\\uDF4B(?:\\u200D\\uD83D\\uDFE9)?|\\uDFC3(?:\\uD83C[\\uDFFB-\\uDFFF])?(?:\\u200D(?:[\\u2640\\u2642]\\uFE0F?(?:\\u200D\\u27A1\\uFE0F?)?|\\u27A1\\uFE0F?))?|\\uDFF3\\uFE0F?(?:\\u200D(?:\\u26A7\\uFE0F?|\\uD83C\\uDF08))?|\\uDFF4(?:\\u200D\\u2620\\uFE0F?|\\uDB40\\uDC67\\uDB40\\uDC62\\uDB40(?:\\uDC65\\uDB40\\uDC6E\\uDB40\\uDC67|\\uDC73\\uDB40\\uDC63\\uDB40\\uDC74|\\uDC77\\uDB40\\uDC6C\\uDB40\\uDC73)\\uDB40\\uDC7F)?)|\\uD83D(?:[\\uDC3F\\uDCFD\\uDD49\\uDD4A\\uDD6F\\uDD70\\uDD73\\uDD76-\\uDD79\\uDD87\\uDD8A-\\uDD8D\\uDDA5\\uDDA8\\uDDB1\\uDDB2\\uDDBC\\uDDC2-\\uDDC4\\uDDD1-\\uDDD3\\uDDDC-\\uDDDE\\uDDE1\\uDDE3\\uDDE8\\uDDEF\\uDDF3\\uDDFA\\uDECB\\uDECD-\\uDECF\\uDEE0-\\uDEE5\\uDEE9\\uDEF0\\uDEF3]\\uFE0F?|[\\uDC42\\uDC43\\uDC46-\\uDC50\\uDC66\\uDC67\\uDC6B-\\uDC6D\\uDC72\\uDC74-\\uDC76\\uDC78\\uDC7C\\uDC83\\uDC85\\uDC8F\\uDC91\\uDCAA\\uDD7A\\uDD95\\uDD96\\uDE4C\\uDE4F\\uDEC0\\uDECC](?:\\uD83C[\\uDFFB-\\uDFFF])?|[\\uDC6E\\uDC70\\uDC71\\uDC73\\uDC77\\uDC81\\uDC82\\uDC86\\uDC87\\uDE45-\\uDE47\\uDE4B\\uDE4D\\uDE4E\\uDEA3\\uDEB4\\uDEB5](?:\\uD83C[\\uDFFB-\\uDFFF])?(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|[\\uDD74\\uDD90](?:\\uD83C[\\uDFFB-\\uDFFF]|\\uFE0F)?|[\\uDC00-\\uDC07\\uDC09-\\uDC14\\uDC16-\\uDC25\\uDC27-\\uDC3A\\uDC3C-\\uDC3E\\uDC40\\uDC44\\uDC45\\uDC51-\\uDC65\\uDC6A\\uDC79-\\uDC7B\\uDC7D-\\uDC80\\uDC84\\uDC88-\\uDC8E\\uDC90\\uDC92-\\uDCA9\\uDCAB-\\uDCFC\\uDCFF-\\uDD3D\\uDD4B-\\uDD4E\\uDD50-\\uDD67\\uDDA4\\uDDFB-\\uDE2D\\uDE2F-\\uDE34\\uDE37-\\uDE41\\uDE43\\uDE44\\uDE48-\\uDE4A\\uDE80-\\uDEA2\\uDEA4-\\uDEB3\\uDEB7-\\uDEBF\\uDEC1-\\uDEC5\\uDED0-\\uDED2\\uDED5-\\uDED7\\uDEDC-\\uDEDF\\uDEEB\\uDEEC\\uDEF4-\\uDEFC\\uDFE0-\\uDFEB\\uDFF0]|\\uDC08(?:\\u200D\\u2B1B)?|\\uDC15(?:\\u200D\\uD83E\\uDDBA)?|\\uDC26(?:\\u200D(?:\\u2B1B|\\uD83D\\uDD25))?|\\uDC3B(?:\\u200D\\u2744\\uFE0F?)?|\\uDC41\\uFE0F?(?:\\u200D\\uD83D\\uDDE8\\uFE0F?)?|\\uDC68(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDC68\\uDC69]\\u200D\\uD83D(?:\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?)|[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?)|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]))|\\uD83C(?:\\uDFFB(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFC-\\uDFFF])))?|\\uDFFC(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])))?|\\uDFFD(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])))?|\\uDFFE(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])))?|\\uDFFF(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?\\uDC68\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C[\\uDFFB-\\uDFFE])))?))?|\\uDC69(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:\\uDC8B\\u200D\\uD83D)?[\\uDC68\\uDC69]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D(?:[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?|\\uDC69\\u200D\\uD83D(?:\\uDC66(?:\\u200D\\uD83D\\uDC66)?|\\uDC67(?:\\u200D\\uD83D[\\uDC66\\uDC67])?))|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]))|\\uD83C(?:\\uDFFB(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFC-\\uDFFF])))?|\\uDFFC(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])))?|\\uDFFD(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])))?|\\uDFFE(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])))?|\\uDFFF(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D\\uD83D(?:[\\uDC68\\uDC69]|\\uDC8B\\u200D\\uD83D[\\uDC68\\uDC69])\\uD83C[\\uDFFB-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83D[\\uDC68\\uDC69]\\uD83C[\\uDFFB-\\uDFFE])))?))?|\\uDC6F(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|\\uDD75(?:\\uD83C[\\uDFFB-\\uDFFF]|\\uFE0F)?(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|\\uDE2E(?:\\u200D\\uD83D\\uDCA8)?|\\uDE35(?:\\u200D\\uD83D\\uDCAB)?|\\uDE36(?:\\u200D\\uD83C\\uDF2B\\uFE0F?)?|\\uDE42(?:\\u200D[\\u2194\\u2195]\\uFE0F?)?|\\uDEB6(?:\\uD83C[\\uDFFB-\\uDFFF])?(?:\\u200D(?:[\\u2640\\u2642]\\uFE0F?(?:\\u200D\\u27A1\\uFE0F?)?|\\u27A1\\uFE0F?))?)|\\uD83E(?:[\\uDD0C\\uDD0F\\uDD18-\\uDD1F\\uDD30-\\uDD34\\uDD36\\uDD77\\uDDB5\\uDDB6\\uDDBB\\uDDD2\\uDDD3\\uDDD5\\uDEC3-\\uDEC5\\uDEF0\\uDEF2-\\uDEF8](?:\\uD83C[\\uDFFB-\\uDFFF])?|[\\uDD26\\uDD35\\uDD37-\\uDD39\\uDD3D\\uDD3E\\uDDB8\\uDDB9\\uDDCD\\uDDCF\\uDDD4\\uDDD6-\\uDDDD](?:\\uD83C[\\uDFFB-\\uDFFF])?(?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|[\\uDDDE\\uDDDF](?:\\u200D[\\u2640\\u2642]\\uFE0F?)?|[\\uDD0D\\uDD0E\\uDD10-\\uDD17\\uDD20-\\uDD25\\uDD27-\\uDD2F\\uDD3A\\uDD3F-\\uDD45\\uDD47-\\uDD76\\uDD78-\\uDDB4\\uDDB7\\uDDBA\\uDDBC-\\uDDCC\\uDDD0\\uDDE0-\\uDDFF\\uDE70-\\uDE7C\\uDE80-\\uDE89\\uDE8F-\\uDEC2\\uDEC6\\uDECE-\\uDEDC\\uDEDF-\\uDEE9]|\\uDD3C(?:\\u200D[\\u2640\\u2642]\\uFE0F?|\\uD83C[\\uDFFB-\\uDFFF])?|\\uDDCE(?:\\uD83C[\\uDFFB-\\uDFFF])?(?:\\u200D(?:[\\u2640\\u2642]\\uFE0F?(?:\\u200D\\u27A1\\uFE0F?)?|\\u27A1\\uFE0F?))?|\\uDDD1(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83E\\uDDD1|\\uDDD1\\u200D\\uD83E\\uDDD2(?:\\u200D\\uD83E\\uDDD2)?|\\uDDD2(?:\\u200D\\uD83E\\uDDD2)?))|\\uD83C(?:\\uDFFB(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1\\uD83C[\\uDFFC-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFF])))?|\\uDFFC(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1\\uD83C[\\uDFFB\\uDFFD-\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFF])))?|\\uDFFD(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFF])))?|\\uDFFE(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFD\\uDFFF]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFF])))?|\\uDFFF(?:\\u200D(?:[\\u2695\\u2696\\u2708]\\uFE0F?|\\u2764\\uFE0F?\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFE]|\\uD83C[\\uDF3E\\uDF73\\uDF7C\\uDF84\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E(?:[\\uDDAF\\uDDBC\\uDDBD](?:\\u200D\\u27A1\\uFE0F?)?|[\\uDDB0-\\uDDB3]|\\uDD1D\\u200D\\uD83E\\uDDD1\\uD83C[\\uDFFB-\\uDFFF])))?))?|\\uDEF1(?:\\uD83C(?:\\uDFFB(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFC-\\uDFFF])?|\\uDFFC(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])?|\\uDFFD(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])?|\\uDFFE(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])?|\\uDFFF(?:\\u200D\\uD83E\\uDEF2\\uD83C[\\uDFFB-\\uDFFE])?))?)/g;function _i(n){return n==null?n:n.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds").normalize()}function Ra(n,e,t,r){return n.second==0&&n.minute==0&&n.hour==0?n.toLocal().toFormat(e,{locale:r}):n.toLocal().toFormat(t,{locale:r})}function ja(n){n=_i(n);let e="";return n.years&&(e+=`${n.years} years, `),n.months&&(e+=`${n.months} months, `),n.weeks&&(e+=`${n.weeks} weeks, `),n.days&&(e+=`${n.days} days, `),n.hours&&(e+=`${n.hours} hours, `),n.minutes&&(e+=`${n.minutes} minutes, `),n.seconds&&(e+=`${Math.round(n.seconds)} seconds, `),n.milliseconds&&(e+=`${Math.round(n.milliseconds)} ms, `),e.endsWith(", ")&&(e=e.substring(0,e.length-2)),e}function Tn(n){return n.includes("/")&&(n=n.substring(n.lastIndexOf("/")+1)),n.endsWith(".md")&&(n=n.substring(0,n.length-3)),n}function Va(n){return n.includes(".")?n.substring(n.lastIndexOf(".")+1):""}var jc=bt.alt(bt.regex(new RegExp(wn(),"")),bt.regex(/[0-9\\p{Letter}_-]+/u),bt.whitespace.map(n=>" "),bt.any.map(n=>" ")).many().map(n=>n.join("").split(/\\s+/).join(" ").trim());function qa(n){return jc.tryParse(n)}var ee=class{static file(e,t=!1,r){return new ee({path:e,embed:t,display:r,subpath:void 0,type:"file"})}static infer(e,t=!1,r){if(e.includes("#^")){let s=e.split("#^");return ee.block(s[0],s[1],t,r)}else if(e.includes("#")){let s=e.split("#");return ee.header(s[0],s[1],t,r)}else return ee.file(e,t,r)}static header(e,t,r,s){return new ee({path:e,embed:r,display:s,subpath:qa(t),type:"header"})}static block(e,t,r,s){return new ee({path:e,embed:r,display:s,subpath:t,type:"block"})}static fromObject(e){return new ee(e)}static parseInner(e){let[t,r]=Vc(e);return ee.infer(t,!1,r)}constructor(e){Object.assign(this,e)}withPath(e){return new ee(Object.assign({},this,{path:e}))}withDisplay(e){return new ee(Object.assign({},this,{display:e}))}withEmbed(e){return this.embed==e?this:new ee(Object.assign({},this,{embed:e}))}withHeader(e){return ee.header(this.path,e,this.embed,this.display)}withBlock(e){return ee.block(this.path,e,this.embed,this.display)}equals(e){return e==null||e==null?!1:this.path==e.path&&this.type==e.type&&this.subpath==e.subpath}toString(){return this.markdown()}toObject(){return{path:this.path,type:this.type,subpath:this.subpath,display:this.display,embed:this.embed}}toFile(){return ee.file(this.path,this.embed,this.display)}toEmbed(){return this.withEmbed(!0)}fromEmbed(){return this.withEmbed(!1)}markdown(){let e=(this.embed?"!":"")+"[["+this.obsidianLink();return e+="|",e+=this.displayOrDefault(),e+="]]",e}displayOrDefault(){if(this.display)return this.display;{let e=Tn(this.path);return(this.type=="header"||this.type=="block")&&(e+=" > "+this.subpath),e}}obsidianLink(){var t,r;let e=this.path.replace("|","\\\\|");return this.type=="header"?e+"#"+((t=this.subpath)==null?void 0:t.replace("|","\\\\|")):this.type=="block"?e+"#^"+((r=this.subpath)==null?void 0:r.replace("|","\\\\|")):e}fileName(){return Tn(this.path)}};function Vc(n){let e=-1;for(;(e=n.indexOf("|",e+1))>=0;)if(!(e>0&&n[e-1]=="\\\\"))return[n.substring(0,e).replace(/\\\\\\|/g,"|"),n.substring(e+1)];return[n.replace(/\\\\\\|/g,"|"),void 0]}var is=Symbol.for("yaml.alias"),os=Symbol.for("yaml.document"),Ke=Symbol.for("yaml.map"),Bi=Symbol.for("yaml.pair"),Ie=Symbol.for("yaml.scalar"),Et=Symbol.for("yaml.seq"),Se=Symbol.for("yaml.node.type"),Pe=n=>!!n&&typeof n=="object"&&n[Se]===is,rt=n=>!!n&&typeof n=="object"&&n[Se]===os,We=n=>!!n&&typeof n=="object"&&n[Se]===Ke,W=n=>!!n&&typeof n=="object"&&n[Se]===Bi,U=n=>!!n&&typeof n=="object"&&n[Se]===Ie,He=n=>!!n&&typeof n=="object"&&n[Se]===Et;function Z(n){if(n&&typeof n=="object")switch(n[Se]){case Ke:case Et:return!0}return!1}function H(n){if(n&&typeof n=="object")switch(n[Se]){case is:case Ke:case Ie:case Et:return!0}return!1}var as=n=>(U(n)||Z(n))&&!!n.anchor;var xe=Symbol("break visit"),Ua=Symbol("skip children"),st=Symbol("remove node");function it(n,e){let t=Ka(e);rt(n)?Sn(null,n.contents,t,Object.freeze([n]))===st&&(n.contents=null):Sn(null,n,t,Object.freeze([]))}it.BREAK=xe;it.SKIP=Ua;it.REMOVE=st;function Sn(n,e,t,r){let s=Wa(n,e,t,r);if(H(s)||W(s))return Ha(n,r,s),Sn(n,s,t,r);if(typeof s!="symbol"){if(Z(e)){r=Object.freeze(r.concat(e));for(let i=0;i<e.items.length;++i){let o=Sn(i,e.items[i],t,r);if(typeof o=="number")i=o-1;else{if(o===xe)return xe;o===st&&(e.items.splice(i,1),i-=1)}}}else if(W(e)){r=Object.freeze(r.concat(e));let i=Sn("key",e.key,t,r);if(i===xe)return xe;i===st&&(e.key=null);let o=Sn("value",e.value,t,r);if(o===xe)return xe;o===st&&(e.value=null)}}return s}async function us(n,e){let t=Ka(e);rt(n)?await kn(null,n.contents,t,Object.freeze([n]))===st&&(n.contents=null):await kn(null,n,t,Object.freeze([]))}us.BREAK=xe;us.SKIP=Ua;us.REMOVE=st;async function kn(n,e,t,r){let s=await Wa(n,e,t,r);if(H(s)||W(s))return Ha(n,r,s),kn(n,s,t,r);if(typeof s!="symbol"){if(Z(e)){r=Object.freeze(r.concat(e));for(let i=0;i<e.items.length;++i){let o=await kn(i,e.items[i],t,r);if(typeof o=="number")i=o-1;else{if(o===xe)return xe;o===st&&(e.items.splice(i,1),i-=1)}}}else if(W(e)){r=Object.freeze(r.concat(e));let i=await kn("key",e.key,t,r);if(i===xe)return xe;i===st&&(e.key=null);let o=await kn("value",e.value,t,r);if(o===xe)return xe;o===st&&(e.value=null)}}return s}function Ka(n){return typeof n=="object"&&(n.Collection||n.Node||n.Value)?Object.assign({Alias:n.Node,Map:n.Node,Scalar:n.Node,Seq:n.Node},n.Value&&{Map:n.Value,Scalar:n.Value,Seq:n.Value},n.Collection&&{Map:n.Collection,Seq:n.Collection},n):n}function Wa(n,e,t,r){var s,i,o,a,u;if(typeof t=="function")return t(n,e,r);if(We(e))return(s=t.Map)==null?void 0:s.call(t,n,e,r);if(He(e))return(i=t.Seq)==null?void 0:i.call(t,n,e,r);if(W(e))return(o=t.Pair)==null?void 0:o.call(t,n,e,r);if(U(e))return(a=t.Scalar)==null?void 0:a.call(t,n,e,r);if(Pe(e))return(u=t.Alias)==null?void 0:u.call(t,n,e,r)}function Ha(n,e,t){let r=e[e.length-1];if(Z(r))r.items[n]=t;else if(W(r))n==="key"?r.key=t:r.value=t;else if(rt(r))r.contents=t;else{let s=Pe(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}var qc={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Uc=n=>n.replace(/[!,[\\]{}]/g,e=>qc[e]),he=class{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},he.defaultYaml,e),this.tags=Object.assign({},he.defaultTags,t)}clone(){let e=new he(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new he(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:he.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},he.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:he.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},he.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \\t]+/),s=r.shift();switch(s){case"%TAG":{if(r.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[i,o]=r;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[i]=r;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let o=/^\\d+\\.\\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${s}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren\'t resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}let[,r,s]=e.match(new RegExp("^(.*!)([^!]*)$","s"));s||t(`The ${e} tag has no suffix`);let i=this.tags[r];if(i)try{return i+decodeURIComponent(s)}catch(o){return t(String(o)),null}return r==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,r]of Object.entries(this.tags))if(e.startsWith(r))return t+Uc(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),s;if(e&&r.length>0&&H(e.contents)){let i={};it(e.contents,(o,a)=>{H(a)&&a.tag&&(i[a.tag]=!0)}),s=Object.keys(i)}else s=[];for(let[i,o]of r)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||s.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`\n`)}};he.defaultYaml={explicit:!1,version:"1.2"};he.defaultTags={"!!":"tag:yaml.org,2002:"};function ls(n){if(/[\\x00-\\x19\\s,[\\]{}]/.test(n)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(n)}`;throw new Error(t)}return!0}function Pi(n){let e=new Set;return it(n,{Value(t,r){r.anchor&&e.add(r.anchor)}}),e}function $i(n,e){for(let t=1;;++t){let r=`${n}${t}`;if(!e.has(r))return r}}function Ja(n,e){let t=[],r=new Map,s=null;return{onAnchor:i=>{t.push(i),s!=null||(s=Pi(n));let o=$i(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=r.get(i);if(typeof o=="object"&&o.anchor&&(U(o.node)||Z(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:r}}function vt(n,e,t,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let s=0,i=r.length;s<i;++s){let o=r[s],a=vt(n,r,String(s),o);a===void 0?delete r[s]:a!==o&&(r[s]=a)}else if(r instanceof Map)for(let s of Array.from(r.keys())){let i=r.get(s),o=vt(n,r,s,i);o===void 0?r.delete(s):o!==i&&r.set(s,o)}else if(r instanceof Set)for(let s of Array.from(r)){let i=vt(n,r,s,s);i===void 0?r.delete(s):i!==s&&(r.delete(s),r.add(i))}else for(let[s,i]of Object.entries(r)){let o=vt(n,r,s,i);o===void 0?delete r[s]:o!==i&&(r[s]=o)}return n.call(e,t,r)}function pe(n,e,t){if(Array.isArray(n))return n.map((r,s)=>pe(r,String(s),t));if(n&&typeof n.toJSON=="function"){if(!t||!as(n))return n.toJSON(e,t);let r={aliasCount:0,count:1,res:void 0};t.anchors.set(n,r),t.onCreate=i=>{r.res=i,delete t.onCreate};let s=n.toJSON(e,t);return t.onCreate&&t.onCreate(s),s}return typeof n=="bigint"&&!(t!=null&&t.keep)?Number(n):n}var It=class{constructor(e){Object.defineProperty(this,Se,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:r,onAnchor:s,reviver:i}={}){if(!rt(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=pe(this,"",o);if(typeof s=="function")for(let{count:u,res:l}of o.anchors.values())s(l,u);return typeof i=="function"?vt(i,{"":a},"",a):a}};var Ft=class extends It{constructor(e){super(is),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let r;t!=null&&t.aliasResolveCache?r=t.aliasResolveCache:(r=[],it(e,{Node:(i,o)=>{(Pe(o)||as(o))&&r.push(o)}}),t&&(t.aliasResolveCache=r));let s;for(let i of r){if(i===this)break;i.anchor===this.source&&(s=i)}return s}toJSON(e,t){if(!t)return{source:this.source};let{anchors:r,doc:s,maxAliasCount:i}=t,o=this.resolve(s,t);if(!o){let u=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(u)}let a=r.get(o);if(a||(pe(o,null,t),a=r.get(o)),!a||a.res===void 0){let u="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(u)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=cs(s,o,r)),a.count*a.aliasCount>i)){let u="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(u)}return a.res}toString(e,t,r){let s=`*${this.source}`;if(e){if(ls(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${s} `}return s}};function cs(n,e,t){if(Pe(e)){let r=e.resolve(n),s=t&&r&&t.get(r);return s?s.count*s.aliasCount:0}else if(Z(e)){let r=0;for(let s of e.items){let i=cs(n,s,t);i>r&&(r=i)}return r}else if(W(e)){let r=cs(n,e.key,t),s=cs(n,e.value,t);return Math.max(r,s)}return 1}var fs=n=>!n||typeof n!="function"&&typeof n!="object",$=class extends It{constructor(e){super(Ie),this.value=e}toJSON(e,t){return t!=null&&t.keep?this.value:pe(this.value,e,t)}toString(){return String(this.value)}};$.BLOCK_FOLDED="BLOCK_FOLDED";$.BLOCK_LITERAL="BLOCK_LITERAL";$.PLAIN="PLAIN";$.QUOTE_DOUBLE="QUOTE_DOUBLE";$.QUOTE_SINGLE="QUOTE_SINGLE";var Kc="tag:yaml.org,2002:";function Wc(n,e,t){var r;if(e){let s=t.filter(o=>o.tag===e),i=(r=s.find(o=>!o.format))!=null?r:s[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(s=>{var i;return((i=s.identify)==null?void 0:i.call(s,n))&&!s.format})}function wt(n,e,t){var d,y,h,E;if(rt(n)&&(n=n.contents),H(n))return n;if(W(n)){let p=(y=(d=t.schema[Ke]).createNode)==null?void 0:y.call(d,t.schema,null,t);return p.items.push(n),p}(n instanceof String||n instanceof Number||n instanceof Boolean||typeof BigInt!="undefined"&&n instanceof BigInt)&&(n=n.valueOf());let{aliasDuplicateObjects:r,onAnchor:s,onTagObj:i,schema:o,sourceObjects:a}=t,u;if(r&&n&&typeof n=="object"){if(u=a.get(n),u)return(h=u.anchor)!=null||(u.anchor=s(n)),new Ft(u.anchor);u={anchor:null,node:null},a.set(n,u)}e!=null&&e.startsWith("!!")&&(e=Kc+e.slice(2));let l=Wc(n,e,o.tags);if(!l){if(n&&typeof n.toJSON=="function"&&(n=n.toJSON()),!n||typeof n!="object"){let p=new $(n);return u&&(u.node=p),p}l=n instanceof Map?o[Ke]:Symbol.iterator in Object(n)?o[Et]:o[Ke]}i&&(i(l),delete t.onTagObj);let f=l!=null&&l.createNode?l.createNode(t.schema,n,t):typeof((E=l==null?void 0:l.nodeClass)==null?void 0:E.from)=="function"?l.nodeClass.from(t.schema,n,t):new $(n);return e?f.tag=e:l.default||(f.tag=l.tag),u&&(u.node=f),f}function mr(n,e,t){let r=t;for(let s=e.length-1;s>=0;--s){let i=e[s];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let o=[];o[i]=r,r=o}else r=new Map([[i,r]])}return wt(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:n,sourceObjects:new Map})}var xn=n=>n==null||typeof n=="object"&&!!n[Symbol.iterator]().next().done,Cn=class extends It{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(r=>H(r)||W(r)?r.clone(e):r),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(xn(e))this.add(t);else{let[r,...s]=e,i=this.get(r,!0);if(Z(i))i.addIn(s,t);else if(i===void 0&&this.schema)this.set(r,mr(this.schema,s,t));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${s}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let s=this.get(t,!0);if(Z(s))return s.deleteIn(r);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...s]=e,i=this.get(r,!0);return s.length===0?!t&&U(i)?i.value:i:Z(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!W(t))return!1;let r=t.value;return r==null||e&&U(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let s=this.get(t,!0);return Z(s)?s.hasIn(r):!1}setIn(e,t){let[r,...s]=e;if(s.length===0)this.set(r,t);else{let i=this.get(r,!0);if(Z(i))i.setIn(s,t);else if(i===void 0&&this.schema)this.set(r,mr(this.schema,s,t));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${s}`)}}};var za=n=>n.replace(/^(?!$)(?: $)?/gm,"#");function $e(n,e){return/^\\n+$/.test(n)?n.substring(1):e?n.replace(/^(?! *$)/gm,e):n}var ot=(n,e,t)=>n.endsWith(`\n`)?$e(t,e):t.includes(`\n`)?`\n`+$e(t,e):(n.endsWith(" ")?"":" ")+t;var Ri="flow",ds="block",Dr="quoted";function yr(n,e,t="flow",{indentAtStart:r,lineWidth:s=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!s||s<0)return n;s<i&&(i=0);let u=Math.max(1+i,1+s-e.length);if(n.length<=u)return n;let l=[],f={},d=s-e.length;typeof r=="number"&&(r>s-Math.max(2,i)?l.push(0):d=s-r);let y,h,E=!1,p=-1,T=-1,g=-1;t===ds&&(p=Ya(n,p,e.length),p!==-1&&(d=p+u));for(let L;L=n[p+=1];){if(t===Dr&&L==="\\\\"){switch(T=p,n[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}g=p}if(L===`\n`)t===ds&&(p=Ya(n,p,e.length)),d=p+e.length+u,y=void 0;else{if(L===" "&&h&&h!==" "&&h!==`\n`&&h!=="	"){let m=n[p+1];m&&m!==" "&&m!==`\n`&&m!=="	"&&(y=p)}if(p>=d)if(y)l.push(y),d=y+u,y=void 0;else if(t===Dr){for(;h===" "||h==="	";)h=L,L=n[p+=1],E=!0;let m=p>g+1?p-2:T-1;if(f[m])return n;l.push(m),f[m]=!0,d=m+u,y=void 0}else E=!0}h=L}if(E&&a&&a(),l.length===0)return n;o&&o();let k=n.slice(0,l[0]);for(let L=0;L<l.length;++L){let m=l[L],F=l[L+1]||n.length;m===0?k=`\n${e}${n.slice(0,F)}`:(t===Dr&&f[m]&&(k+=`${n[m]}\\\\`),k+=`\n${e}${n.slice(m+1,F)}`)}return k}function Ya(n,e,t){let r=e,s=e+1,i=n[s];for(;i===" "||i==="	";)if(e<s+t)i=n[++e];else{do i=n[++e];while(i&&i!==`\n`);r=e,s=e+1,i=n[s]}return r}var ps=(n,e)=>({indentAtStart:e?n.indent.length:n.indentAtStart,lineWidth:n.options.lineWidth,minContentWidth:n.options.minContentWidth}),ms=n=>/^(%|---|\\.\\.\\.)/m.test(n);function Hc(n,e,t){if(!e||e<0)return!1;let r=e-t,s=n.length;if(s<=r)return!1;for(let i=0,o=0;i<s;++i)if(n[i]===`\n`){if(i-o>r)return!0;if(o=i+1,s-o<=r)return!1}return!0}function gr(n,e){let t=JSON.stringify(n);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:r}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(ms(n)?"  ":""),o="",a=0;for(let u=0,l=t[u];l;l=t[++u])if(l===" "&&t[u+1]==="\\\\"&&t[u+2]==="n"&&(o+=t.slice(a,u)+"\\\\ ",u+=1,a=u,l="\\\\"),l==="\\\\")switch(t[u+1]){case"u":{o+=t.slice(a,u);let f=t.substr(u+2,4);switch(f){case"0000":o+="\\\\0";break;case"0007":o+="\\\\a";break;case"000b":o+="\\\\v";break;case"001b":o+="\\\\e";break;case"0085":o+="\\\\N";break;case"00a0":o+="\\\\_";break;case"2028":o+="\\\\L";break;case"2029":o+="\\\\P";break;default:f.substr(0,2)==="00"?o+="\\\\x"+f.substr(2):o+=t.substr(u,6)}u+=5,a=u+1}break;case"n":if(r||t[u+2]===\'"\'||t.length<s)u+=1;else{for(o+=t.slice(a,u)+`\n\n`;t[u+2]==="\\\\"&&t[u+3]==="n"&&t[u+4]!==\'"\';)o+=`\n`,u+=2;o+=i,t[u+2]===" "&&(o+="\\\\"),u+=1,a=u+1}break;default:u+=1}return o=a?o+t.slice(a):t,r?o:yr(o,i,Dr,ps(e,!1))}function ji(n,e){if(e.options.singleQuote===!1||e.implicitKey&&n.includes(`\n`)||/[ \\t]\\n|\\n[ \\t]/.test(n))return gr(n,e);let t=e.indent||(ms(n)?"  ":""),r="\'"+n.replace(/\'/g,"\'\'").replace(/\\n+/g,`$&\n${t}`)+"\'";return e.implicitKey?r:yr(r,t,Ri,ps(e,!1))}function On(n,e){let{singleQuote:t}=e.options,r;if(t===!1)r=gr;else{let s=n.includes(\'"\'),i=n.includes("\'");s&&!i?r=ji:i&&!s?r=gr:r=t?ji:gr}return r(n,e)}var Vi;try{Vi=new RegExp(`(^|(?<!\n))\n+(?!\n|$)`,"g")}catch(n){Vi=/\\n+(?!\\n|$)/g}function hs({comment:n,type:e,value:t},r,s,i){let{blockQuote:o,commentString:a,lineWidth:u}=r.options;if(!o||/\\n[\\t ]+$/.test(t)||/^\\s*$/.test(t))return On(t,r);let l=r.indent||(r.forceBlockIndent||ms(t)?"  ":""),f=o==="literal"?!0:o==="folded"||e===$.BLOCK_FOLDED?!1:e===$.BLOCK_LITERAL?!0:!Hc(t,u,l.length);if(!t)return f?`|\n`:`>\n`;let d,y;for(y=t.length;y>0;--y){let F=t[y-1];if(F!==`\n`&&F!=="	"&&F!==" ")break}let h=t.substring(y),E=h.indexOf(`\n`);E===-1?d="-":t===h||E!==h.length-1?(d="+",i&&i()):d="",h&&(t=t.slice(0,-h.length),h[h.length-1]===`\n`&&(h=h.slice(0,-1)),h=h.replace(Vi,`$&${l}`));let p=!1,T,g=-1;for(T=0;T<t.length;++T){let F=t[T];if(F===" ")p=!0;else if(F===`\n`)g=T;else break}let k=t.substring(0,g<T?g+1:T);k&&(t=t.substring(k.length),k=k.replace(/\\n+/g,`$&${l}`));let m=(p?l?"2":"1":"")+d;if(n&&(m+=" "+a(n.replace(/ ?[\\r\\n]+/g," ")),s&&s()),!f){let F=t.replace(/\\n+/g,`\n$&`).replace(/(?:^|\\n)([\\t ].*)(?:([\\n\\t ]*)\\n(?![\\n\\t ]))?/g,"$1$2").replace(/\\n+/g,`$&${l}`),O=!1,x=ps(r,!0);o!=="folded"&&e!==$.BLOCK_FOLDED&&(x.onOverflow=()=>{O=!0});let S=yr(`${k}${F}${h}`,l,ds,x);if(!O)return`>${m}\n${l}${S}`}return t=t.replace(/\\n+/g,`$&${l}`),`|${m}\n${l}${k}${t}${h}`}function Jc(n,e,t,r){let{type:s,value:i}=n,{actualString:o,implicitKey:a,indent:u,indentStep:l,inFlow:f}=e;if(a&&i.includes(`\n`)||f&&/[[\\]{},]/.test(i))return On(i,e);if(/^[\\n\\t ,[\\]{}#&*!|>\'"%@`]|^[?-]$|^[?-][ \\t]|[\\n:][ \\t]|[ \\t]\\n|[\\n\\t ]#|[\\n\\t :]$/.test(i))return a||f||!i.includes(`\n`)?On(i,e):hs(n,e,t,r);if(!a&&!f&&s!==$.PLAIN&&i.includes(`\n`))return hs(n,e,t,r);if(ms(i)){if(u==="")return e.forceBlockIndent=!0,hs(n,e,t,r);if(a&&u===l)return On(i,e)}let d=i.replace(/\\n+/g,`$&\n${u}`);if(o){let y=p=>{var T;return p.default&&p.tag!=="tag:yaml.org,2002:str"&&((T=p.test)==null?void 0:T.test(d))},{compat:h,tags:E}=e.doc.schema;if(E.some(y)||h!=null&&h.some(y))return On(i,e)}return a?d:yr(d,u,Ri,ps(e,!1))}function Yt(n,e,t,r){let{implicitKey:s,inFlow:i}=e,o=typeof n.value=="string"?n:Object.assign({},n,{value:String(n.value)}),{type:a}=n;a!==$.QUOTE_DOUBLE&&/[\\x00-\\x08\\x0b-\\x1f\\x7f-\\x9f\\u{D800}-\\u{DFFF}]/u.test(o.value)&&(a=$.QUOTE_DOUBLE);let u=f=>{switch(f){case $.BLOCK_FOLDED:case $.BLOCK_LITERAL:return s||i?On(o.value,e):hs(o,e,t,r);case $.QUOTE_DOUBLE:return gr(o.value,e);case $.QUOTE_SINGLE:return ji(o.value,e);case $.PLAIN:return Jc(o,e,t,r);default:return null}},l=u(a);if(l===null){let{defaultKeyType:f,defaultStringType:d}=e.options,y=s&&f||d;if(l=u(y),l===null)throw new Error(`Unsupported default string type ${y}`)}return l}function Ds(n,e){let t=Object.assign({blockQuote:!0,commentString:za,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},n.schema.toStringOptions,e),r;switch(t.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:n,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):"  ",inFlow:r,options:t}}function zc(n,e){var s,i,o,a;if(e.tag){let u=n.filter(l=>l.tag===e.tag);if(u.length>0)return(s=u.find(l=>l.format===e.format))!=null?s:u[0]}let t,r;if(U(e)){r=e.value;let u=n.filter(l=>{var f;return(f=l.identify)==null?void 0:f.call(l,r)});if(u.length>1){let l=u.filter(f=>f.test);l.length>0&&(u=l)}t=(i=u.find(l=>l.format===e.format))!=null?i:u.find(l=>!l.format)}else r=e,t=n.find(u=>u.nodeClass&&r instanceof u.nodeClass);if(!t){let u=(a=(o=r==null?void 0:r.constructor)==null?void 0:o.name)!=null?a:r===null?"null":typeof r;throw new Error(`Tag not resolved for ${u} value`)}return t}function Yc(n,e,{anchors:t,doc:r}){var a;if(!r.directives)return"";let s=[],i=(U(n)||Z(n))&&n.anchor;i&&ls(i)&&(t.add(i),s.push(`&${i}`));let o=(a=n.tag)!=null?a:e.default?null:e.tag;return o&&s.push(r.directives.tagString(o)),s.join(" ")}function Tt(n,e,t,r){var u,l;if(W(n))return n.toString(e,t,r);if(Pe(n)){if(e.doc.directives)return n.toString(e);if((u=e.resolvedAliases)!=null&&u.has(n))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(n):e.resolvedAliases=new Set([n]),n=n.resolve(e.doc)}let s,i=H(n)?n:e.doc.createNode(n,{onTagObj:f=>s=f});s!=null||(s=zc(e.doc.schema.tags,i));let o=Yc(i,s,e);o.length>0&&(e.indentAtStart=((l=e.indentAtStart)!=null?l:0)+o.length+1);let a=typeof s.stringify=="function"?s.stringify(i,e,t,r):U(i)?Yt(i,e,t,r):i.toString(e,t,r);return o?U(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}\n${e.indent}${a}`:a}function Ga({key:n,value:e},t,r,s){var x,S;let{allNullValues:i,doc:o,indent:a,indentStep:u,options:{commentString:l,indentSeq:f,simpleKeys:d}}=t,y=H(n)&&n.comment||null;if(d){if(y)throw new Error("With simple keys, key nodes cannot have comments");if(Z(n)||!H(n)&&typeof n=="object"){let V="With simple keys, collection cannot be used as a key value";throw new Error(V)}}let h=!d&&(!n||y&&e==null&&!t.inFlow||Z(n)||(U(n)?n.type===$.BLOCK_FOLDED||n.type===$.BLOCK_LITERAL:typeof n=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!h&&(d||!i),indent:a+u});let E=!1,p=!1,T=Tt(n,t,()=>E=!0,()=>p=!0);if(!h&&!t.inFlow&&T.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(t.inFlow){if(i||e==null)return E&&r&&r(),T===""?"?":h?`? ${T}`:T}else if(i&&!d||e==null&&h)return T=`? ${T}`,y&&!E?T+=ot(T,t.indent,l(y)):p&&s&&s(),T;E&&(y=null),h?(y&&(T+=ot(T,t.indent,l(y))),T=`? ${T}\n${a}:`):(T=`${T}:`,y&&(T+=ot(T,t.indent,l(y))));let g,k,L;H(e)?(g=!!e.spaceBefore,k=e.commentBefore,L=e.comment):(g=!1,k=null,L=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!h&&!y&&U(e)&&(t.indentAtStart=T.length+1),p=!1,!f&&u.length>=2&&!t.inFlow&&!h&&He(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let m=!1,F=Tt(e,t,()=>m=!0,()=>p=!0),O=" ";if(y||g||k){if(O=g?`\n`:"",k){let V=l(k);O+=`\n${$e(V,t.indent)}`}F===""&&!t.inFlow?O===`\n`&&(O=`\n\n`):O+=`\n${t.indent}`}else if(!h&&Z(e)){let V=F[0],j=F.indexOf(`\n`),Y=j!==-1,te=(S=(x=t.inFlow)!=null?x:e.flow)!=null?S:e.items.length===0;if(Y||!te){let v=!1;if(Y&&(V==="&"||V==="!")){let A=F.indexOf(" ");V==="&"&&A!==-1&&A<j&&F[A+1]==="!"&&(A=F.indexOf(" ",A+1)),(A===-1||j<A)&&(v=!0)}v||(O=`\n${t.indent}`)}}else(F===""||F[0]===`\n`)&&(O="");return T+=O+F,t.inFlow?m&&r&&r():L&&!m?T+=ot(T,t.indent,l(L)):p&&s&&s(),T}function ys(n,e){(n==="debug"||n==="warn")&&console.warn(e)}var gs="<<",Je={identify:n=>n===gs||typeof n=="symbol"&&n.description===gs,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new $(Symbol(gs)),{addToJSMap:Ui}),stringify:()=>gs},Za=(n,e)=>(Je.identify(e)||U(e)&&(!e.type||e.type===$.PLAIN)&&Je.identify(e.value))&&(n==null?void 0:n.doc.schema.tags.some(t=>t.tag===Je.tag&&t.default));function Ui(n,e,t){if(t=n&&Pe(t)?t.resolve(n.doc):t,He(t))for(let r of t.items)qi(n,e,r);else if(Array.isArray(t))for(let r of t)qi(n,e,r);else qi(n,e,t)}function qi(n,e,t){let r=n&&Pe(t)?t.resolve(n.doc):t;if(!We(r))throw new Error("Merge sources must be maps or map aliases");let s=r.toJSON(null,n,Map);for(let[i,o]of s)e instanceof Map?e.has(i)||e.set(i,o):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function bs(n,e,{key:t,value:r}){if(H(t)&&t.addToJSMap)t.addToJSMap(n,e,r);else if(Za(n,t))Ui(n,e,r);else{let s=pe(t,"",n);if(e instanceof Map)e.set(s,pe(r,s,n));else if(e instanceof Set)e.add(s);else{let i=Gc(t,s,n),o=pe(r,i,n);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}function Gc(n,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(H(n)&&(t!=null&&t.doc)){let r=Ds(t.doc,{});r.anchors=new Set;for(let i of t.anchors.keys())r.anchors.add(i.anchor);r.inFlow=!0,r.inStringifyKey=!0;let s=n.toString(r);if(!t.mapKeyWarned){let i=JSON.stringify(s);i.length>40&&(i=i.substring(0,36)+\'..."\'),ys(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return s}return JSON.stringify(e)}function vn(n,e,t){let r=wt(n,void 0,t),s=wt(e,void 0,t);return new ie(r,s)}var ie=class{constructor(e,t=null){Object.defineProperty(this,Se,{value:Bi}),this.key=e,this.value=t}clone(e){let{key:t,value:r}=this;return H(t)&&(t=t.clone(e)),H(r)&&(r=r.clone(e)),new ie(t,r)}toJSON(e,t){let r=t!=null&&t.mapAsMap?new Map:{};return bs(t,r,this)}toString(e,t,r){return e!=null&&e.doc?Ga(this,e,t,r):JSON.stringify(this)}};function Fs(n,e,t){var i;return(((i=e.inFlow)!=null?i:n.flow)?Qc:Zc)(n,e,t)}function Zc({comment:n,items:e},t,{blockItemPrefix:r,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:u,options:{commentString:l}}=t,f=Object.assign({},t,{indent:i,type:null}),d=!1,y=[];for(let E=0;E<e.length;++E){let p=e[E],T=null;if(H(p))!d&&p.spaceBefore&&y.push(""),Es(t,y,p.commentBefore,d),p.comment&&(T=p.comment);else if(W(p)){let k=H(p.key)?p.key:null;k&&(!d&&k.spaceBefore&&y.push(""),Es(t,y,k.commentBefore,d))}d=!1;let g=Tt(p,f,()=>T=null,()=>d=!0);T&&(g+=ot(g,i,l(T))),d&&T&&(d=!1),y.push(r+g)}let h;if(y.length===0)h=s.start+s.end;else{h=y[0];for(let E=1;E<y.length;++E){let p=y[E];h+=p?`\n${u}${p}`:`\n`}}return n?(h+=`\n`+$e(l(n),u),a&&a()):d&&o&&o(),h}function Qc({items:n},e,{flowChars:t,itemIndent:r}){let{indent:s,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;r+=i;let u=Object.assign({},e,{indent:r,inFlow:!0,type:null}),l=!1,f=0,d=[];for(let E=0;E<n.length;++E){let p=n[E],T=null;if(H(p))p.spaceBefore&&d.push(""),Es(e,d,p.commentBefore,!1),p.comment&&(T=p.comment);else if(W(p)){let k=H(p.key)?p.key:null;k&&(k.spaceBefore&&d.push(""),Es(e,d,k.commentBefore,!1),k.comment&&(l=!0));let L=H(p.value)?p.value:null;L?(L.comment&&(T=L.comment),L.commentBefore&&(l=!0)):p.value==null&&(k!=null&&k.comment)&&(T=k.comment)}T&&(l=!0);let g=Tt(p,u,()=>T=null);E<n.length-1&&(g+=","),T&&(g+=ot(g,r,a(T))),!l&&(d.length>f||g.includes(`\n`))&&(l=!0),d.push(g),f=d.length}let{start:y,end:h}=t;if(d.length===0)return y+h;if(!l){let E=d.reduce((p,T)=>p+T.length+2,2);l=e.options.lineWidth>0&&E>e.options.lineWidth}if(l){let E=y;for(let p of d)E+=p?`\n${i}${s}${p}`:`\n`;return`${E}\n${s}${h}`}else return`${y}${o}${d.join(" ")}${o}${h}`}function Es({indent:n,options:{commentString:e}},t,r,s){if(r&&s&&(r=r.replace(/^\\n+/,"")),r){let i=$e(e(r),n);t.push(i.trimStart())}}function Lt(n,e){let t=U(e)?e.value:e;for(let r of n)if(W(r)&&(r.key===e||r.key===t||U(r.key)&&r.key.value===t))return r}var le=class extends Cn{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ke,e),this.items=[]}static from(e,t,r){let{keepUndefined:s,replacer:i}=r,o=new this(e),a=(u,l)=>{if(typeof i=="function")l=i.call(t,u,l);else if(Array.isArray(i)&&!i.includes(u))return;(l!==void 0||s)&&o.items.push(vn(u,l,r))};if(t instanceof Map)for(let[u,l]of t)a(u,l);else if(t&&typeof t=="object")for(let u of Object.keys(t))a(u,t[u]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){var o;let r;W(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new ie(e,e==null?void 0:e.value):r=new ie(e.key,e.value);let s=Lt(this.items,r.key),i=(o=this.schema)==null?void 0:o.sortMapEntries;if(s){if(!t)throw new Error(`Key ${r.key} already set`);U(s.value)&&fs(r.value)?s.value.value=r.value:s.value=r.value}else if(i){let a=this.items.findIndex(u=>i(r,u)<0);a===-1?this.items.push(r):this.items.splice(a,0,r)}else this.items.push(r)}delete(e){let t=Lt(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){var i;let r=Lt(this.items,e),s=r==null?void 0:r.value;return(i=!t&&U(s)?s.value:s)!=null?i:void 0}has(e){return!!Lt(this.items,e)}set(e,t){this.add(new ie(e,t),!0)}toJSON(e,t,r){let s=r?new r:t!=null&&t.mapAsMap?new Map:{};t!=null&&t.onCreate&&t.onCreate(s);for(let i of this.items)bs(t,s,i);return s}toString(e,t,r){if(!e)return JSON.stringify(this);for(let s of this.items)if(!W(s))throw new Error(`Map items must all be pairs; found ${JSON.stringify(s)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Fs(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:t})}};var ze={collection:"map",default:!0,nodeClass:le,tag:"tag:yaml.org,2002:map",resolve(n,e){return We(n)||e("Expected a mapping for this tag"),n},createNode:(n,e,t)=>le.from(n,e,t)};var Ee=class extends Cn{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Et,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=ws(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let r=ws(e);if(typeof r!="number")return;let s=this.items[r];return!t&&U(s)?s.value:s}has(e){let t=ws(e);return typeof t=="number"&&t<this.items.length}set(e,t){let r=ws(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let s=this.items[r];U(s)&&fs(t)?s.value=t:this.items[r]=t}toJSON(e,t){let r=[];t!=null&&t.onCreate&&t.onCreate(r);let s=0;for(let i of this.items)r.push(pe(i,String(s++),t));return r}toString(e,t,r){return e?Fs(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+"  ",onChompKeep:r,onComment:t}):JSON.stringify(this)}static from(e,t,r){let{replacer:s}=r,i=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof s=="function"){let u=t instanceof Set?a:String(o++);a=s.call(t,u,a)}i.items.push(wt(a,void 0,r))}}return i}};function ws(n){let e=U(n)?n.value:n;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}var Ye={collection:"seq",default:!0,nodeClass:Ee,tag:"tag:yaml.org,2002:seq",resolve(n,e){return He(n)||e("Expected a sequence for this tag"),n},createNode:(n,e,t)=>Ee.from(n,e,t)};var Nt={identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify(n,e,t,r){return e=Object.assign({actualString:!0},e),Yt(n,e,t,r)}};var Gt={identify:n=>n==null,createNode:()=>new $(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new $(null),stringify:({source:n},e)=>typeof n=="string"&&Gt.test.test(n)?n:e.options.nullStr};var br={identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:n=>new $(n[0]==="t"||n[0]==="T"),stringify({source:n,value:e},t){if(n&&br.test.test(n)){let r=n[0]==="t"||n[0]==="T";if(e===r)return n}return e?t.options.trueStr:t.options.falseStr}};function Fe({format:n,minFractionDigits:e,tag:t,value:r}){if(typeof r=="bigint")return String(r);let s=typeof r=="number"?r:Number(r);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let i=JSON.stringify(r);if(!n&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\\d/.test(i)){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=e-(i.length-o-1);for(;a-- >0;)i+="0"}return i}var Ts={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Fe},Ss={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\\.[0-9]+|[0-9]+(?:\\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():Fe(n)}},ks={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\\.[0-9]+|[0-9]+\\.[0-9]*)$/,resolve(n){let e=new $(parseFloat(n)),t=n.indexOf(".");return t!==-1&&n[n.length-1]==="0"&&(e.minFractionDigits=n.length-t-1),e},stringify:Fe};var Cs=n=>typeof n=="bigint"||Number.isInteger(n),Ki=(n,e,t,{intAsBigInt:r})=>r?BigInt(n):parseInt(n.substring(e),t);function Qa(n,e,t){let{value:r}=n;return Cs(r)&&r>=0?t+r.toString(e):Fe(n)}var xs={identify:n=>Cs(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(n,e,t)=>Ki(n,2,8,t),stringify:n=>Qa(n,8,"0o")},Os={identify:Cs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(n,e,t)=>Ki(n,0,10,t),stringify:Fe},vs={identify:n=>Cs(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(n,e,t)=>Ki(n,2,16,t),stringify:n=>Qa(n,16,"0x")};var Xa=[ze,Ye,Nt,Gt,br,xs,Os,vs,Ts,Ss,ks];function eu(n){return typeof n=="bigint"||Number.isInteger(n)}var Is=({value:n})=>JSON.stringify(n),Xc=[{identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify:Is},{identify:n=>n==null,createNode:()=>new $(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Is},{identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:n=>n==="true",stringify:Is},{identify:eu,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(n,e,{intAsBigInt:t})=>t?BigInt(n):parseInt(n,10),stringify:({value:n})=>eu(n)?n.toString():JSON.stringify(n)},{identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:n=>parseFloat(n),stringify:Is}],ef={default:!0,tag:"",test:/^/,resolve(n,e){return e(`Unresolved plain scalar ${JSON.stringify(n)}`),n}},tu=[ze,Ye].concat(Xc,ef);var Er={identify:n=>n instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(n,e){if(typeof atob=="function"){let t=atob(n.replace(/[\\n\\r]/g,"")),r=new Uint8Array(t.length);for(let s=0;s<t.length;++s)r[s]=t.charCodeAt(s);return r}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),n},stringify({comment:n,type:e,value:t},r,s,i){if(!t)return"";let o=t,a;if(typeof btoa=="function"){let u="";for(let l=0;l<o.length;++l)u+=String.fromCharCode(o[l]);a=btoa(u)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e!=null||(e=$.BLOCK_LITERAL),e!==$.QUOTE_DOUBLE){let u=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(a.length/u),f=new Array(l);for(let d=0,y=0;d<l;++d,y+=u)f[d]=a.substr(y,u);a=f.join(e===$.BLOCK_LITERAL?`\n`:" ")}return Yt({comment:n,type:e,value:a},r,s,i)}};function Wi(n,e){var t;if(He(n))for(let r=0;r<n.items.length;++r){let s=n.items[r];if(!W(s)){if(We(s)){s.items.length>1&&e("Each pair must have its own sequence indicator");let i=s.items[0]||new ie(new $(null));if(s.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${s.commentBefore}\n${i.key.commentBefore}`:s.commentBefore),s.comment){let o=(t=i.value)!=null?t:i.key;o.comment=o.comment?`${s.comment}\n${o.comment}`:s.comment}s=i}n.items[r]=W(s)?s:new ie(s)}}else e("Expected a sequence for this tag");return n}function Hi(n,e,t){let{replacer:r}=t,s=new Ee(n);s.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof r=="function"&&(o=r.call(e,String(i++),o));let a,u;if(Array.isArray(o))if(o.length===2)a=o[0],u=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],u=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;s.items.push(vn(a,u,t))}return s}var Fr={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Wi,createNode:Hi};var At=class extends Ee{constructor(){super(),this.add=le.prototype.add.bind(this),this.delete=le.prototype.delete.bind(this),this.get=le.prototype.get.bind(this),this.has=le.prototype.has.bind(this),this.set=le.prototype.set.bind(this),this.tag=At.tag}toJSON(e,t){if(!t)return super.toJSON(e);let r=new Map;t!=null&&t.onCreate&&t.onCreate(r);for(let s of this.items){let i,o;if(W(s)?(i=pe(s.key,"",t),o=pe(s.value,i,t)):i=pe(s,"",t),r.has(i))throw new Error("Ordered maps must not include duplicate keys");r.set(i,o)}return r}static from(e,t,r){let s=Hi(e,t,r),i=new this;return i.items=s.items,i}};At.tag="tag:yaml.org,2002:omap";var wr={collection:"seq",identify:n=>n instanceof Map,nodeClass:At,default:!1,tag:"tag:yaml.org,2002:omap",resolve(n,e){let t=Wi(n,e),r=[];for(let{key:s}of t.items)U(s)&&(r.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):r.push(s.value));return Object.assign(new At,t)},createNode:(n,e,t)=>At.from(n,e,t)};function nu({value:n,source:e},t){return e&&(n?Ji:zi).test.test(e)?e:n?t.options.trueStr:t.options.falseStr}var Ji={identify:n=>n===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new $(!0),stringify:nu},zi={identify:n=>n===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new $(!1),stringify:nu};var ru={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Fe},su={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n.replace(/_/g,"")),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():Fe(n)}},iu={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\\.[0-9_]*$/,resolve(n){let e=new $(parseFloat(n.replace(/_/g,""))),t=n.indexOf(".");if(t!==-1){let r=n.substring(t+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:Fe};var Tr=n=>typeof n=="bigint"||Number.isInteger(n);function Ls(n,e,t,{intAsBigInt:r}){let s=n[0];if((s==="-"||s==="+")&&(e+=1),n=n.substring(e).replace(/_/g,""),r){switch(t){case 2:n=`0b${n}`;break;case 8:n=`0o${n}`;break;case 16:n=`0x${n}`;break}let o=BigInt(n);return s==="-"?BigInt(-1)*o:o}let i=parseInt(n,t);return s==="-"?-1*i:i}function Yi(n,e,t){let{value:r}=n;if(Tr(r)){let s=r.toString(e);return r<0?"-"+t+s.substr(1):t+s}return Fe(n)}var ou={identify:Tr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(n,e,t)=>Ls(n,2,2,t),stringify:n=>Yi(n,2,"0b")},au={identify:Tr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(n,e,t)=>Ls(n,1,8,t),stringify:n=>Yi(n,8,"0")},uu={identify:Tr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(n,e,t)=>Ls(n,0,10,t),stringify:Fe},lu={identify:Tr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(n,e,t)=>Ls(n,2,16,t),stringify:n=>Yi(n,16,"0x")};var Mt=class extends le{constructor(e){super(e),this.tag=Mt.tag}add(e){let t;W(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new ie(e.key,null):t=new ie(e,null),Lt(this.items,t.key)||this.items.push(t)}get(e,t){let r=Lt(this.items,e);return!t&&W(r)?U(r.key)?r.key.value:r.key:r}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let r=Lt(this.items,e);r&&!t?this.items.splice(this.items.indexOf(r),1):!r&&t&&this.items.push(new ie(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,r);throw new Error("Set items must all have null values")}static from(e,t,r){let{replacer:s}=r,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof s=="function"&&(o=s.call(t,o,o)),i.items.push(vn(o,null,r));return i}};Mt.tag="tag:yaml.org,2002:set";var Sr={collection:"map",identify:n=>n instanceof Set,nodeClass:Mt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(n,e,t)=>Mt.from(n,e,t),resolve(n,e){if(We(n)){if(n.hasAllNullValues(!0))return Object.assign(new Mt,n);e("Set items must all have null values")}else e("Expected a mapping for this tag");return n}};function Gi(n,e){let t=n[0],r=t==="-"||t==="+"?n.substring(1):n,s=o=>e?BigInt(o):Number(o),i=r.replace(/_/g,"").split(":").reduce((o,a)=>o*s(60)+s(a),s(0));return t==="-"?s(-1)*i:i}function cu(n){let{value:e}=n,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Fe(n);let r="";e<0&&(r="-",e*=t(-1));let s=t(60),i=[e%s];return e<60?i.unshift(0):(e=(e-i[0])/s,i.unshift(e%s),e>=60&&(e=(e-i[0])/s,i.unshift(e))),r+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\\d*$/,"")}var Ns={identify:n=>typeof n=="bigint"||Number.isInteger(n),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(n,e,{intAsBigInt:t})=>Gi(n,t),stringify:cu},As={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*$/,resolve:n=>Gi(n,!1),stringify:cu},In={identify:n=>n instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\\\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\\\.[0-9]+)?)(?:[ \\\\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(n){let e=n.match(In.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,r,s,i,o,a]=e.map(Number),u=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,r-1,s,i||0,o||0,a||0,u),f=e[8];if(f&&f!=="Z"){let d=Gi(f,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:n})=>{var e;return(e=n==null?void 0:n.toISOString().replace(/(T00:00:00)?\\.000Z$/,""))!=null?e:""}};var Zi=[ze,Ye,Nt,Gt,Ji,zi,ou,au,uu,lu,ru,su,iu,Er,Je,wr,Fr,Sr,Ns,As,In];var fu=new Map([["core",Xa],["failsafe",[ze,Ye,Nt]],["json",tu],["yaml11",Zi],["yaml-1.1",Zi]]),du={binary:Er,bool:br,float:ks,floatExp:Ss,floatNaN:Ts,floatTime:As,int:Os,intHex:vs,intOct:xs,intTime:Ns,map:ze,merge:Je,null:Gt,omap:wr,pairs:Fr,seq:Ye,set:Sr,timestamp:In},hu={"tag:yaml.org,2002:binary":Er,"tag:yaml.org,2002:merge":Je,"tag:yaml.org,2002:omap":wr,"tag:yaml.org,2002:pairs":Fr,"tag:yaml.org,2002:set":Sr,"tag:yaml.org,2002:timestamp":In};function Ms(n,e,t){let r=fu.get(e);if(r&&!n)return t&&!r.includes(Je)?r.concat(Je):r.slice();let s=r;if(!s)if(Array.isArray(n))s=[];else{let i=Array.from(fu.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(n))for(let i of n)s=s.concat(i);else typeof n=="function"&&(s=n(s.slice()));return t&&(s=s.concat(Je)),s.reduce((i,o)=>{let a=typeof o=="string"?du[o]:o;if(!a){let u=JSON.stringify(o),l=Object.keys(du).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${u}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}var tf=(n,e)=>n.key<e.key?-1:n.key>e.key?1:0,Zt=class{constructor({compat:e,customTags:t,merge:r,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Ms(e,"compat"):e?Ms(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?hu:{},this.tags=Ms(t,this.name,r),this.toStringOptions=a!=null?a:null,Object.defineProperty(this,Ke,{value:ze}),Object.defineProperty(this,Ie,{value:Nt}),Object.defineProperty(this,Et,{value:Ye}),this.sortMapEntries=typeof o=="function"?o:o===!0?tf:null}clone(){let e=Object.create(Zt.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function pu(n,e){var u;let t=[],r=e.directives===!0;if(e.directives!==!1&&n.directives){let l=n.directives.toString(n);l?(t.push(l),r=!0):n.directives.docStart&&(r=!0)}r&&t.push("---");let s=Ds(n,e),{commentString:i}=s.options;if(n.commentBefore){t.length!==1&&t.unshift("");let l=i(n.commentBefore);t.unshift($e(l,""))}let o=!1,a=null;if(n.contents){if(H(n.contents)){if(n.contents.spaceBefore&&r&&t.push(""),n.contents.commentBefore){let d=i(n.contents.commentBefore);t.push($e(d,""))}s.forceBlockIndent=!!n.comment,a=n.contents.comment}let l=a?void 0:()=>o=!0,f=Tt(n.contents,s,()=>a=null,l);a&&(f+=ot(f,"",i(a))),(f[0]==="|"||f[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${f}`:t.push(f)}else t.push(Tt(n.contents,s));if((u=n.directives)!=null&&u.docEnd)if(n.comment){let l=i(n.comment);l.includes(`\n`)?(t.push("..."),t.push($e(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=n.comment;l&&o&&(l=l.replace(/^\\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push($e(i(l),"")))}return t.join(`\n`)+`\n`}var at=class{constructor(e,t,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Se,{value:os});let s=null;typeof t=="function"||Array.isArray(t)?s=t:r===void 0&&t&&(r=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=i;let{version:o}=i;r!=null&&r._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new he({version:o}),this.setSchema(o,r),this.contents=e===void 0?null:this.createNode(e,s,r)}clone(){let e=Object.create(at.prototype,{[Se]:{value:os}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=H(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ln(this.contents)&&this.contents.add(e)}addIn(e,t){Ln(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let r=Pi(this);e.anchor=!t||r.has(t)?$i(t||"a",r):t}return new Ft(e.anchor)}createNode(e,t,r){let s;if(typeof t=="function")e=t.call({"":e},"",e),s=t;else if(Array.isArray(t)){let T=k=>typeof k=="number"||k instanceof String||k instanceof Number,g=t.filter(T).map(String);g.length>0&&(t=t.concat(g)),s=t}else r===void 0&&t&&(r=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:u,onTagObj:l,tag:f}=r!=null?r:{},{onAnchor:d,setAnchors:y,sourceObjects:h}=Ja(this,o||"a"),E={aliasDuplicateObjects:i!=null?i:!0,keepUndefined:u!=null?u:!1,onAnchor:d,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:h},p=wt(e,f,E);return a&&Z(p)&&(p.flow=!0),y(),p}createPair(e,t,r={}){let s=this.createNode(e,null,r),i=this.createNode(t,null,r);return new ie(s,i)}delete(e){return Ln(this.contents)?this.contents.delete(e):!1}deleteIn(e){return xn(e)?this.contents==null?!1:(this.contents=null,!0):Ln(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return Z(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return xn(e)?!t&&U(this.contents)?this.contents.value:this.contents:Z(this.contents)?this.contents.getIn(e,t):void 0}has(e){return Z(this.contents)?this.contents.has(e):!1}hasIn(e){return xn(e)?this.contents!==void 0:Z(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=mr(this.schema,[e],t):Ln(this.contents)&&this.contents.set(e,t)}setIn(e,t){xn(e)?this.contents=t:this.contents==null?this.contents=mr(this.schema,Array.from(e),t):Ln(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new he({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new he({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let s=JSON.stringify(e);throw new Error(`Expected \'1.1\', \'1.2\' or null as first argument, but found: ${s}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(r)this.schema=new Zt(Object.assign(r,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:r,maxAliasCount:s,onAnchor:i,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},u=pe(this.contents,t!=null?t:"",a);if(typeof i=="function")for(let{count:l,res:f}of a.anchors.values())i(f,l);return typeof o=="function"?vt(o,{"":u},"",u):u}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return pu(this,e)}};function Ln(n){if(Z(n))return!0;throw new Error("Expected a YAML collection as document contents")}var kr=class extends Error{constructor(e,t,r,s){super(),this.name=e,this.code=r,this.message=s,this.pos=t}},Ge=class extends kr{constructor(e,t,r){super("YAMLParseError",e,t,r)}},Cr=class extends kr{constructor(e,t,r){super("YAMLWarning",e,t,r)}},Qi=(n,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:r,col:s}=t.linePos[0];t.message+=` at line ${r}, column ${s}`;let i=s-1,o=n.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\\n\\r]+$/,"");if(i>=60&&o.length>80){let a=Math.min(i-39,o.length-79);o="\\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\\u2026"),r>1&&/^ *$/.test(o.substring(0,i))){let a=n.substring(e.lineStarts[r-2],e.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\\u2026\n`),o=a+o}if(/[^ ]/.test(o)){let a=1,u=t.linePos[1];u&&u.line===r&&u.col>s&&(a=Math.max(1,Math.min(u.col-s,80-i)));let l=" ".repeat(i)+"^".repeat(a);t.message+=`:\n\n${o}\n${l}\n`}};function ut(n,{flow:e,indicator:t,next:r,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let u=!1,l=a,f=a,d="",y="",h=!1,E=!1,p=null,T=null,g=null,k=null,L=null,m=null,F=null;for(let S of n)switch(E&&(S.type!=="space"&&S.type!=="newline"&&S.type!=="comma"&&i(S.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),E=!1),p&&(l&&S.type!=="comment"&&S.type!=="newline"&&i(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),S.type){case"space":!e&&(t!=="doc-start"||(r==null?void 0:r.type)!=="flow-collection")&&S.source.includes("	")&&(p=S),f=!0;break;case"comment":{f||i(S,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let V=S.source.substring(1)||" ";d?d+=y+V:d=V,y="",l=!1;break}case"newline":l?d?d+=S.source:(!m||t!=="seq-item-ind")&&(u=!0):y+=S.source,l=!0,h=!0,(T||g)&&(k=S),f=!0;break;case"anchor":T&&i(S,"MULTIPLE_ANCHORS","A node can have at most one anchor"),S.source.endsWith(":")&&i(S.offset+S.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),T=S,F!=null||(F=S.offset),l=!1,f=!1,E=!0;break;case"tag":{g&&i(S,"MULTIPLE_TAGS","A node can have at most one tag"),g=S,F!=null||(F=S.offset),l=!1,f=!1,E=!0;break}case t:(T||g)&&i(S,"BAD_PROP_ORDER",`Anchors and tags must be after the ${S.source} indicator`),m&&i(S,"UNEXPECTED_TOKEN",`Unexpected ${S.source} in ${e!=null?e:"collection"}`),m=S,l=t==="seq-item-ind"||t==="explicit-key-ind",f=!1;break;case"comma":if(e){L&&i(S,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),L=S,l=!1,f=!1;break}default:i(S,"UNEXPECTED_TOKEN",`Unexpected ${S.type} token`),l=!1,f=!1}let O=n[n.length-1],x=O?O.offset+O.source.length:s;return E&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&i(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||(r==null?void 0:r.type)==="block-map"||(r==null?void 0:r.type)==="block-seq")&&i(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:L,found:m,spaceBefore:u,comment:d,hasNewline:h,anchor:T,tag:g,newlineAfterProp:k,end:x,start:F!=null?F:x}}function _t(n){if(!n)return null;switch(n.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(n.source.includes(`\n`))return!0;if(n.end){for(let e of n.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of n.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(_t(e.key)||_t(e.value))return!0}return!1;default:return!0}}function xr(n,e,t){if((e==null?void 0:e.type)==="flow-collection"){let r=e.end[0];r.indent===n&&(r.source==="]"||r.source==="}")&&_t(e)&&t(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function _s(n,e,t){let{uniqueKeys:r}=n.options;if(r===!1)return!1;let s=typeof r=="function"?r:(i,o)=>i===o||U(i)&&U(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}var mu="All mapping items must start at the same column";function Du({composeNode:n,composeEmptyNode:e},t,r,s,i){var f,d;let o=(f=i==null?void 0:i.nodeClass)!=null?f:le,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let u=r.offset,l=null;for(let y of r.items){let{start:h,key:E,sep:p,value:T}=y,g=ut(h,{indicator:"explicit-key-ind",next:E!=null?E:p==null?void 0:p[0],offset:u,onError:s,parentIndent:r.indent,startOnNewline:!0}),k=!g.found;if(k){if(E&&(E.type==="block-seq"?s(u,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in E&&E.indent!==r.indent&&s(u,"BAD_INDENT",mu)),!g.anchor&&!g.tag&&!p){l=g.end,g.comment&&(a.comment?a.comment+=`\n`+g.comment:a.comment=g.comment);continue}(g.newlineAfterProp||_t(E))&&s(E!=null?E:h[h.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else((d=g.found)==null?void 0:d.indent)!==r.indent&&s(u,"BAD_INDENT",mu);t.atKey=!0;let L=g.end,m=E?n(t,E,g,s):e(t,L,h,null,g,s);t.schema.compat&&xr(r.indent,E,s),t.atKey=!1,_s(t,a.items,m)&&s(L,"DUPLICATE_KEY","Map keys must be unique");let F=ut(p!=null?p:[],{indicator:"map-value-ind",next:T,offset:m.range[2],onError:s,parentIndent:r.indent,startOnNewline:!E||E.type==="block-scalar"});if(u=F.end,F.found){k&&((T==null?void 0:T.type)==="block-map"&&!F.hasNewline&&s(u,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&g.start<F.found.offset-1024&&s(m.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let O=T?n(t,T,F,s):e(t,u,p,null,F,s);t.schema.compat&&xr(r.indent,T,s),u=O.range[2];let x=new ie(m,O);t.options.keepSourceTokens&&(x.srcToken=y),a.items.push(x)}else{k&&s(m.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),F.comment&&(m.comment?m.comment+=`\n`+F.comment:m.comment=F.comment);let O=new ie(m);t.options.keepSourceTokens&&(O.srcToken=y),a.items.push(O)}}return l&&l<u&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,u,l!=null?l:u],a}function yu({composeNode:n,composeEmptyNode:e},t,r,s,i){var f;let o=(f=i==null?void 0:i.nodeClass)!=null?f:Ee,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=r.offset,l=null;for(let{start:d,value:y}of r.items){let h=ut(d,{indicator:"seq-item-ind",next:y,offset:u,onError:s,parentIndent:r.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||y)y&&y.type==="block-seq"?s(h.end,"BAD_INDENT","All sequence items must start at the same column"):s(u,"MISSING_CHAR","Sequence item without - indicator");else{l=h.end,h.comment&&(a.comment=h.comment);continue}let E=y?n(t,y,h,s):e(t,h.end,d,null,h,s);t.schema.compat&&xr(r.indent,y,s),u=E.range[2],a.items.push(E)}return a.range=[r.offset,u,l!=null?l:u],a}function lt(n,e,t,r){let s="";if(n){let i=!1,o="";for(let a of n){let{source:u,type:l}=a;switch(l){case"space":i=!0;break;case"comment":{t&&!i&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=u.substring(1)||" ";s?s+=o+f:s=f,o="";break}case"newline":s&&(o+=u),i=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=u.length}}return{comment:s,offset:e}}var Xi="Block collections are not allowed within flow collections",eo=n=>n&&(n.type==="block-map"||n.type==="block-seq");function gu({composeNode:n,composeEmptyNode:e},t,r,s,i){var T,g;let o=r.start.source==="{",a=o?"flow map":"flow sequence",u=(T=i==null?void 0:i.nodeClass)!=null?T:o?le:Ee,l=new u(t.schema);l.flow=!0;let f=t.atRoot;f&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let d=r.offset+r.start.source.length;for(let k=0;k<r.items.length;++k){let L=r.items[k],{start:m,key:F,sep:O,value:x}=L,S=ut(m,{flow:a,indicator:"explicit-key-ind",next:F!=null?F:O==null?void 0:O[0],offset:d,onError:s,parentIndent:r.indent,startOnNewline:!1});if(!S.found){if(!S.anchor&&!S.tag&&!O&&!x){k===0&&S.comma?s(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):k<r.items.length-1&&s(S.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),S.comment&&(l.comment?l.comment+=`\n`+S.comment:l.comment=S.comment),d=S.end;continue}!o&&t.options.strict&&_t(F)&&s(F,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(k===0)S.comma&&s(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(S.comma||s(S.start,"MISSING_CHAR",`Missing , between ${a} items`),S.comment){let V="";e:for(let j of m)switch(j.type){case"comma":case"space":break;case"comment":V=j.source.substring(1);break e;default:break e}if(V){let j=l.items[l.items.length-1];W(j)&&(j=(g=j.value)!=null?g:j.key),j.comment?j.comment+=`\n`+V:j.comment=V,S.comment=S.comment.substring(V.length+1)}}if(!o&&!O&&!S.found){let V=x?n(t,x,S,s):e(t,S.end,O,null,S,s);l.items.push(V),d=V.range[2],eo(x)&&s(V.range,"BLOCK_IN_FLOW",Xi)}else{t.atKey=!0;let V=S.end,j=F?n(t,F,S,s):e(t,V,m,null,S,s);eo(F)&&s(j.range,"BLOCK_IN_FLOW",Xi),t.atKey=!1;let Y=ut(O!=null?O:[],{flow:a,indicator:"map-value-ind",next:x,offset:j.range[2],onError:s,parentIndent:r.indent,startOnNewline:!1});if(Y.found){if(!o&&!S.found&&t.options.strict){if(O)for(let A of O){if(A===Y.found)break;if(A.type==="newline"){s(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}S.start<Y.found.offset-1024&&s(Y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else x&&("source"in x&&x.source&&x.source[0]===":"?s(x,"MISSING_CHAR",`Missing space after : in ${a}`):s(Y.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let te=x?n(t,x,Y,s):Y.found?e(t,Y.end,O,null,Y,s):null;te?eo(x)&&s(te.range,"BLOCK_IN_FLOW",Xi):Y.comment&&(j.comment?j.comment+=`\n`+Y.comment:j.comment=Y.comment);let v=new ie(j,te);if(t.options.keepSourceTokens&&(v.srcToken=L),o){let A=l;_s(t,A.items,j)&&s(V,"DUPLICATE_KEY","Map keys must be unique"),A.items.push(v)}else{let A=new le(t.schema);A.flow=!0,A.items.push(v);let z=(te!=null?te:j).range;A.range=[j.range[0],z[1],z[2]],l.items.push(A)}d=te?te.range[2]:Y.end}}let y=o?"}":"]",[h,...E]=r.end,p=d;if(h&&h.source===y)p=h.offset+h.source.length;else{let k=a[0].toUpperCase()+a.substring(1),L=f?`${k} must end with a ${y}`:`${k} in block collection must be sufficiently indented and end with a ${y}`;s(d,f?"MISSING_CHAR":"BAD_INDENT",L),h&&h.source.length!==1&&E.unshift(h)}if(E.length>0){let k=lt(E,p,t.options.strict,s);k.comment&&(l.comment?l.comment+=`\n`+k.comment:l.comment=k.comment),l.range=[r.offset,p,k.offset]}else l.range=[r.offset,p,p];return l}function to(n,e,t,r,s,i){let o=t.type==="block-map"?Du(n,e,t,r,i):t.type==="block-seq"?yu(n,e,t,r,i):gu(n,e,t,r,i),a=o.constructor;return s==="!"||s===a.tagName?(o.tag=a.tagName,o):(s&&(o.tag=s),o)}function bu(n,e,t,r,s){var y,h,E;let i=r.tag,o=i?e.directives.tagName(i.source,p=>s(i,"TAG_RESOLVE_FAILED",p)):null;if(t.type==="block-seq"){let{anchor:p,newlineAfterProp:T}=r,g=p&&i?p.offset>i.offset?p:i:p!=null?p:i;g&&(!T||T.offset<g.offset)&&s(g,"MISSING_CHAR","Missing newline after block sequence props")}let a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===le.tagName&&a==="map"||o===Ee.tagName&&a==="seq")return to(n,e,t,s,o);let u=e.schema.tags.find(p=>p.tag===o&&p.collection===a);if(!u){let p=e.schema.knownTags[o];if(p&&p.collection===a)e.schema.tags.push(Object.assign({},p,{default:!1})),u=p;else return p?s(i,"BAD_COLLECTION_TYPE",`${p.tag} used for ${a} collection, but expects ${(y=p.collection)!=null?y:"scalar"}`,!0):s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),to(n,e,t,s,o)}let l=to(n,e,t,s,o,u),f=(E=(h=u.resolve)==null?void 0:h.call(u,l,p=>s(i,"TAG_RESOLVE_FAILED",p),e.options))!=null?E:l,d=H(f)?f:new $(f);return d.range=l.range,d.tag=o,u!=null&&u.format&&(d.format=u.format),d}function no(n,e,t){let r=e.offset,s=nf(e,n.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[r,r,r]};let i=s.mode===">"?$.BLOCK_FOLDED:$.BLOCK_LITERAL,o=e.source?rf(e.source):[],a=o.length;for(let p=o.length-1;p>=0;--p){let T=o[p][1];if(T===""||T==="\\r")a=p;else break}if(a===0){let p=s.chomp==="+"&&o.length>0?`\n`.repeat(Math.max(1,o.length-1)):"",T=r+s.length;return e.source&&(T+=e.source.length),{value:p,type:i,comment:s.comment,range:[r,T,T]}}let u=e.indent+s.indent,l=e.offset+s.length,f=0;for(let p=0;p<a;++p){let[T,g]=o[p];if(g===""||g==="\\r")s.indent===0&&T.length>u&&(u=T.length);else{if(T.length<u){let k="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";t(l+T.length,"MISSING_CHAR",k)}s.indent===0&&(u=T.length),f=p,u===0&&!n.atRoot&&t(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=T.length+g.length+1}for(let p=o.length-1;p>=a;--p)o[p][0].length>u&&(a=p+1);let d="",y="",h=!1;for(let p=0;p<f;++p)d+=o[p][0].slice(u)+`\n`;for(let p=f;p<a;++p){let[T,g]=o[p];l+=T.length+g.length+1;let k=g[g.length-1]==="\\r";if(k&&(g=g.slice(0,-1)),g&&T.length<u){let m=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;t(l-g.length-(k?2:1),"BAD_INDENT",m),T=""}i===$.BLOCK_LITERAL?(d+=y+T.slice(u)+g,y=`\n`):T.length>u||g[0]==="	"?(y===" "?y=`\n`:!h&&y===`\n`&&(y=`\n\n`),d+=y+T.slice(u)+g,y=`\n`,h=!0):g===""?y===`\n`?d+=`\n`:y=`\n`:(d+=y+g,y=" ",h=!1)}switch(s.chomp){case"-":break;case"+":for(let p=a;p<o.length;++p)d+=`\n`+o[p][0].slice(u);d[d.length-1]!==`\n`&&(d+=`\n`);break;default:d+=`\n`}let E=r+s.length+e.source.length;return{value:d,type:i,comment:s.comment,range:[r,E,E]}}function nf({offset:n,props:e},t,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:s}=e[0],i=s[0],o=0,a="",u=-1;for(let y=1;y<s.length;++y){let h=s[y];if(!a&&(h==="-"||h==="+"))a=h;else{let E=Number(h);!o&&E?o=E:u===-1&&(u=n+y)}}u!==-1&&r(u,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,f="",d=s.length;for(let y=1;y<e.length;++y){let h=e[y];switch(h.type){case"space":l=!0;case"newline":d+=h.source.length;break;case"comment":t&&!l&&r(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=h.source.length,f=h.source.substring(1);break;case"error":r(h,"UNEXPECTED_TOKEN",h.message),d+=h.source.length;break;default:{let E=`Unexpected token in block scalar header: ${h.type}`;r(h,"UNEXPECTED_TOKEN",E);let p=h.source;p&&typeof p=="string"&&(d+=p.length)}}}return{mode:i,indent:o,chomp:a,comment:f,length:d}}function rf(n){let e=n.split(/\\n( *)/),t=e[0],r=t.match(/^( *)/),i=[r!=null&&r[1]?[r[1],t.slice(r[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)i.push([e[o],e[o+1]]);return i}function ro(n,e,t){let{offset:r,type:s,source:i,end:o}=n,a,u,l=(y,h,E)=>t(r+y,h,E);switch(s){case"scalar":a=$.PLAIN,u=sf(i,l);break;case"single-quoted-scalar":a=$.QUOTE_SINGLE,u=of(i,l);break;case"double-quoted-scalar":a=$.QUOTE_DOUBLE,u=af(i,l);break;default:return t(n,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[r,r+i.length,r+i.length]}}let f=r+i.length,d=lt(o,f,e,t);return{value:u,type:a,comment:d.comment,range:[r,f,d.offset]}}function sf(n,e){let t="";switch(n[0]){case"	":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${n[0]}`;break}case"@":case"`":{t=`reserved character ${n[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Eu(n)}function of(n,e){return(n[n.length-1]!=="\'"||n.length===1)&&e(n.length,"MISSING_CHAR","Missing closing \'quote"),Eu(n.slice(1,-1)).replace(/\'\'/g,"\'")}function Eu(n){var u;let e,t;try{e=new RegExp(`(.*?)(?<![ 	])[ 	]*\\r?\n`,"sy"),t=new RegExp(`[ 	]*(.*?)(?:(?<![ 	])[ 	]*)?\\r?\n`,"sy")}catch(l){e=new RegExp("(.*?)[ \\\\t]*\\\\r?\\\\n","sy"),t=new RegExp("[ \\\\t]*(.*?)[ \\\\t]*\\\\r?\\\\n","sy")}let r=e.exec(n);if(!r)return n;let s=r[1],i=" ",o=e.lastIndex;for(t.lastIndex=o;r=t.exec(n);)r[1]===""?i===`\n`?s+=i:i=`\n`:(s+=i+r[1],i=" "),o=t.lastIndex;let a=new RegExp("[ \\\\t]*(.*)","sy");return a.lastIndex=o,r=a.exec(n),s+i+((u=r==null?void 0:r[1])!=null?u:"")}function af(n,e){let t="";for(let r=1;r<n.length-1;++r){let s=n[r];if(!(s==="\\r"&&n[r+1]===`\n`))if(s===`\n`){let{fold:i,offset:o}=uf(n,r);t+=i,r=o}else if(s==="\\\\"){let i=n[++r],o=lf[i];if(o)t+=o;else if(i===`\n`)for(i=n[r+1];i===" "||i==="	";)i=n[++r+1];else if(i==="\\r"&&n[r+1]===`\n`)for(i=n[++r+1];i===" "||i==="	";)i=n[++r+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];t+=cf(n,r+1,a,e),r+=a}else{let a=n.substr(r-1,2);e(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(s===" "||s==="	"){let i=r,o=n[r+1];for(;o===" "||o==="	";)o=n[++r+1];o!==`\n`&&!(o==="\\r"&&n[r+2]===`\n`)&&(t+=r>i?n.slice(i,r+1):s)}else t+=s}return(n[n.length-1]!==\'"\'||n.length===1)&&e(n.length,"MISSING_CHAR",\'Missing closing "quote\'),t}function uf(n,e){let t="",r=n[e+1];for(;(r===" "||r==="	"||r===`\n`||r==="\\r")&&!(r==="\\r"&&n[e+2]!==`\n`);)r===`\n`&&(t+=`\n`),e+=1,r=n[e+1];return t||(t=" "),{fold:t,offset:e}}var lf={0:"\\0",a:"\\x07",b:"\\b",e:"\\x1B",f:"\\f",n:`\n`,r:"\\r",t:"	",v:"\\v",N:"\\x85",_:"\\xA0",L:"\\u2028",P:"\\u2029"," ":" ",\'"\':\'"\',"/":"/","\\\\":"\\\\","	":"	"};function cf(n,e,t,r){let s=n.substr(e,t),o=s.length===t&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;if(isNaN(o)){let a=n.substr(e-2,t+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}function so(n,e,t,r){let{value:s,type:i,comment:o,range:a}=e.type==="block-scalar"?no(n,e,r):ro(e,n.options.strict,r),u=t?n.directives.tagName(t.source,d=>r(t,"TAG_RESOLVE_FAILED",d)):null,l;n.options.stringKeys&&n.atKey?l=n.schema[Ie]:u?l=ff(n.schema,s,u,t,r):e.type==="scalar"?l=df(n,s,e,r):l=n.schema[Ie];let f;try{let d=l.resolve(s,y=>r(t!=null?t:e,"TAG_RESOLVE_FAILED",y),n.options);f=U(d)?d:new $(d)}catch(d){let y=d instanceof Error?d.message:String(d);r(t!=null?t:e,"TAG_RESOLVE_FAILED",y),f=new $(s)}return f.range=a,f.source=s,i&&(f.type=i),u&&(f.tag=u),l.format&&(f.format=l.format),o&&(f.comment=o),f}function ff(n,e,t,r,s){var a;if(t==="!")return n[Ie];let i=[];for(let u of n.tags)if(!u.collection&&u.tag===t)if(u.default&&u.test)i.push(u);else return u;for(let u of i)if((a=u.test)!=null&&a.test(e))return u;let o=n.knownTags[t];return o&&!o.collection?(n.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(s(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),n[Ie])}function df({atKey:n,directives:e,schema:t},r,s,i){var a;let o=t.tags.find(u=>{var l;return(u.default===!0||n&&u.default==="key")&&((l=u.test)==null?void 0:l.test(r))})||t[Ie];if(t.compat){let u=(a=t.compat.find(l=>{var f;return l.default&&((f=l.test)==null?void 0:f.test(r))}))!=null?a:t[Ie];if(o.tag!==u.tag){let l=e.tagString(o.tag),f=e.tagString(u.tag),d=`Value may be parsed as either ${l} or ${f}`;i(s,"TAG_RESOLVE_FAILED",d,!0)}}return o}function Fu(n,e,t){if(e){t!=null||(t=e.length);for(let r=t-1;r>=0;--r){let s=e[r];switch(s.type){case"space":case"comment":case"newline":n-=s.source.length;continue}for(s=e[++r];(s==null?void 0:s.type)==="space";)n+=s.source.length,s=e[++r];break}}return n}var hf={composeNode:io,composeEmptyNode:Bs};function io(n,e,t,r){let s=n.atKey,{spaceBefore:i,comment:o,anchor:a,tag:u}=t,l,f=!0;switch(e.type){case"alias":l=pf(n,e,r),(a||u)&&r(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=so(n,e,u,r),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=bu(hf,n,e,t,r),a&&(l.anchor=a.source.substring(1));break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",d),l=Bs(n,e.offset,void 0,null,t,r),f=!1}}if(a&&l.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&n.options.stringKeys&&(!U(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")){let d="With stringKeys, all keys must be strings";r(u!=null?u:e,"NON_STRING_KEY",d)}return i&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),n.options.keepSourceTokens&&f&&(l.srcToken=e),l}function Bs(n,e,t,r,{spaceBefore:s,comment:i,anchor:o,tag:a,end:u},l){let f={type:"scalar",offset:Fu(e,t,r),indent:-1,source:""},d=so(n,f,a,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(d.spaceBefore=!0),i&&(d.comment=i,d.range[2]=u),d}function pf({options:n},{offset:e,source:t,end:r},s){let i=new Ft(t.substring(1));i.source===""&&s(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&s(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=lt(r,o,n.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}function wu(n,e,{offset:t,start:r,value:s,end:i},o){let a=Object.assign({_directives:e},n),u=new at(void 0,a),l={atKey:!1,atRoot:!0,directives:u.directives,options:u.options,schema:u.schema},f=ut(r,{indicator:"doc-start",next:s!=null?s:i==null?void 0:i[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(u.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),u.contents=s?io(l,s,f,o):Bs(l,f.end,r,null,f,o);let d=u.contents.range[2],y=lt(i,d,!1,o);return y.comment&&(u.comment=y.comment),u.range=[t,d,y.offset],u}function Or(n){if(typeof n=="number")return[n,n+1];if(Array.isArray(n))return n.length===2?n:[n[0],n[1]];let{offset:e,source:t}=n;return[e,e+(typeof t=="string"?t.length:1)]}function Tu(n){var s;let e="",t=!1,r=!1;for(let i=0;i<n.length;++i){let o=n[i];switch(o[0]){case"#":e+=(e===""?"":r?`\n\n`:`\n`)+(o.substring(1)||" "),t=!0,r=!1;break;case"%":((s=n[i+1])==null?void 0:s[0])!=="#"&&(i+=1),t=!1;break;default:t||(r=!0),t=!1}}return{comment:e,afterEmptyLine:r}}var vr=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,r,s,i)=>{let o=Or(t);i?this.warnings.push(new Cr(o,r,s)):this.errors.push(new Ge(o,r,s))},this.directives=new he({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:r,afterEmptyLine:s}=Tu(this.prelude);if(r){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${r}`:r;else if(s||e.directives.docStart||!i)e.commentBefore=r;else if(Z(i)&&!i.flow&&i.items.length>0){let o=i.items[0];W(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${r}\n${a}`:r}else{let o=i.commentBefore;i.commentBefore=o?`${r}\n${o}`:r}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Tu(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,r=-1){for(let s of e)yield*this.next(s);yield*this.end(t,r)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(t,r,s)=>{let i=Or(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",r,s)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=wu(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new Ge(Or(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new Ge(Or(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let t=lt(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let r=this.doc.comment;this.doc.comment=r?`${r}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Ge(Or(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),s=new at(void 0,r);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),s.range=[0,t,t],this.decorate(s,!1),yield s}}};var oo=Symbol("break visit"),mf=Symbol("skip children"),Su=Symbol("remove item");function Qt(n,e){"type"in n&&n.type==="document"&&(n={start:n.start,value:n.value}),ku(Object.freeze([]),n,e)}Qt.BREAK=oo;Qt.SKIP=mf;Qt.REMOVE=Su;Qt.itemAtPath=(n,e)=>{let t=n;for(let[r,s]of e){let i=t==null?void 0:t[r];if(i&&"items"in i)t=i.items[s];else return}return t};Qt.parentCollection=(n,e)=>{let t=Qt.itemAtPath(n,e.slice(0,-1)),r=e[e.length-1][0],s=t==null?void 0:t[r];if(s&&"items"in s)return s;throw new Error("Parent collection not found")};function ku(n,e,t){let r=t(e,n);if(typeof r=="symbol")return r;for(let s of["key","value"]){let i=e[s];if(i&&"items"in i){for(let o=0;o<i.items.length;++o){let a=ku(Object.freeze(n.concat([[s,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===oo)return oo;a===Su&&(i.items.splice(o,1),o-=1)}}typeof r=="function"&&s==="key"&&(r=r(e,n))}}return typeof r=="function"?r(e,n):r}var ao="\\uFEFF",uo="",lo="",Ps="";function Cu(n){switch(n){case ao:return"byte-order-mark";case uo:return"doc-mode";case lo:return"flow-error-end";case Ps:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`\n`:case`\\r\n`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(n[0]){case" ":case"	":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"\'":return"single-quoted-scalar";case\'"\':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}function Ze(n){switch(n){case void 0:case" ":case`\n`:case"\\r":case"	":return!0;default:return!1}}var xu=new Set("0123456789ABCDEFabcdef"),yf=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*\'()"),$s=new Set(",[]{}"),gf=new Set(` ,[]{}\n\\r	`),co=n=>!n||gf.has(n),Ir=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){var s;if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let r=(s=this.next)!=null?s:"stream";for(;r&&(t||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t==="	";)t=this.buffer[++e];return!t||t==="#"||t===`\n`?!0:t==="\\r"?this.buffer[e+1]===`\n`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let r=0;for(;t===" ";)t=this.buffer[++r+e];if(t==="\\r"){let s=this.buffer[r+e+1];if(s===`\n`||!s&&!this.atEnd)return e+r+1}return t===`\n`||r>=this.indentNext||!t&&!this.atEnd?e+r:-1}if(t==="-"||t==="."){let r=this.buffer.substr(e,3);if((r==="---"||r==="...")&&Ze(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`\n`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===ao&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,r=e.indexOf("#");for(;r!==-1;){let i=e[r-1];if(i===" "||i==="	"){t=r-1;break}else r=e.indexOf("#",r+1)}for(;;){let i=e[t-1];if(i===" "||i==="	")t-=1;else break}let s=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-s),this.pushNewline(),"stream"}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield uo,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let t=this.peek(3);if((t==="---"||t==="...")&&Ze(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ze(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Ze(t)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(co),"doc";case\'"\':case"\'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,r=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=r=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let s=this.getLine();if(s===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&s[0]!=="#"||r===0&&(s.startsWith("---")||s.startsWith("..."))&&Ze(s[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield lo,yield*this.parseLineStart();let i=0;for(;s[i]===",";)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),s[i]){case void 0:return"flow";case"#":return yield*this.pushCount(s.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(co),"flow";case\'"\':case"\'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ze(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e==="\'")for(;t!==-1&&this.buffer[t+1]==="\'";)t=this.buffer.indexOf("\'",t+2);else for(;t!==-1;){let i=0;for(;this.buffer[t-1-i]==="\\\\";)i+=1;if(i%2===0)break;t=this.buffer.indexOf(\'"\',t+1)}let r=this.buffer.substring(0,t),s=r.indexOf(`\n`,this.pos);if(s!==-1){for(;s!==-1;){let i=this.continueScalar(s+1);if(i===-1)break;s=r.indexOf(`\n`,i)}s!==-1&&(t=s-(r[s-1]==="\\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>Ze(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,r;e:for(let i=this.pos;r=this.buffer[i];++i)switch(r){case" ":t+=1;break;case`\n`:e=i,t=0;break;case"\\r":{let o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`\n`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let i=this.continueScalar(e+1);if(i===-1)break;e=this.buffer.indexOf(`\n`,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let s=e+1;for(r=this.buffer[s];r===" ";)r=this.buffer[++s];if(r==="	"){for(;r==="	"||r===" "||r==="\\r"||r===`\n`;)r=this.buffer[++s];e=s-1}else if(!this.blockScalarKeep)do{let i=e-1,o=this.buffer[i];o==="\\r"&&(o=this.buffer[--i]);let a=i;for(;o===" ";)o=this.buffer[--i];if(o===`\n`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield Ps,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,r=this.pos-1,s;for(;s=this.buffer[++r];)if(s===":"){let i=this.buffer[r+1];if(Ze(i)||e&&$s.has(i))break;t=r}else if(Ze(s)){let i=this.buffer[r+1];if(s==="\\r"&&(i===`\n`?(r+=1,s=`\n`,i=this.buffer[r+1]):t=r),i==="#"||e&&$s.has(i))break;if(s===`\n`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(e&&$s.has(s))break;t=r}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield Ps,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(co))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(Ze(t)||e&&$s.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!Ze(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(yf.has(t))t=this.buffer[++e];else if(t==="%"&&xu.has(this.buffer[e+1])&&xu.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`\n`?yield*this.pushCount(1):e==="\\r"&&this.charAt(1)===`\n`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,r;do r=this.buffer[++t];while(r===" "||e&&r==="	");let s=t-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=t),s}*pushUntil(e){let t=this.pos,r=this.buffer[t];for(;!e(r);)r=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};var Lr=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,r=this.lineStarts.length;for(;t<r;){let i=t+r>>1;this.lineStarts[i]<e?t=i+1:r=i}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let s=this.lineStarts[t-1];return{line:t,col:e-s+1}}}};function Bt(n,e){for(let t=0;t<n.length;++t)if(n[t].type===e)return!0;return!1}function Ou(n){for(let e=0;e<n.length;++e)switch(n[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function Iu(n){switch(n==null?void 0:n.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Rs(n){var e;switch(n.type){case"document":return n.start;case"block-map":{let t=n.items[n.items.length-1];return(e=t.sep)!=null?e:t.start}case"block-seq":return n.items[n.items.length-1].start;default:return[]}}function Nn(n){var t;if(n.length===0)return[];let e=n.length;e:for(;--e>=0;)switch(n[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;((t=n[++e])==null?void 0:t.type)==="space";);return n.splice(e,n.length)}function vu(n){if(n.start.type==="flow-seq-start")for(let e of n.items)e.sep&&!e.value&&!Bt(e.start,"explicit-key-ind")&&!Bt(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Iu(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}var Nr=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Ir,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(e,t))yield*this.next(r);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Cu(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let r=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&(!e||e.type!=="doc-end")){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e!=null?e:this.stack.pop();if(t)if(this.stack.length===0)yield t;else{let r=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in r?r.indent:0:t.type==="flow-collection"&&r.type==="document"&&(t.indent=0),t.type==="flow-collection"&&vu(t),r.type){case"document":r.value=t;break;case"block-scalar":r.props.push(t);break;case"block-map":{let s=r.items[r.items.length-1];if(s.value){r.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(s.sep)s.value=t;else{Object.assign(s,{key:t,sep:[]}),this.onKeyLine=!s.explicitKey;return}break}case"block-seq":{let s=r.items[r.items.length-1];s.value?r.items.push({start:[],value:t}):s.value=t;break}case"flow-collection":{let s=r.items[r.items.length-1];!s||s.value?r.items.push({start:[],key:t,sep:[]}):s.sep?s.value=t:Object.assign(s,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let s=t.items[t.items.length-1];s&&!s.sep&&!s.value&&s.start.length>0&&Ou(s.start)===-1&&(t.indent===0||s.start.every(i=>i.type!=="comment"||i.indent<t.indent))&&(r.type==="document"?r.end=s.start:r.items.push({start:s.start}),t.items.splice(-1,1))}}else{let r="Tried to pop an empty stack";yield{type:"error",offset:this.offset,source:"",message:r}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Ou(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let t=Rs(this.peek(2)),r=Nn(t),s;e.end?(s=e.end,s.push(this.sourceToken),delete e.end):s=[this.sourceToken];let i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`\n`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`\n`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){var r;let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let s="end"in t.value?t.value.end:void 0,i=Array.isArray(s)?s[s.length-1]:void 0;(i==null?void 0:i.type)==="comment"?s==null||s.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2],i=(r=s==null?void 0:s.value)==null?void 0:r.end;if(Array.isArray(i)){Array.prototype.push.apply(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let s=!this.onKeyLine&&this.indent===e.indent,i=s&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",o=[];if(i&&t.sep&&!t.value){let a=[];for(let u=0;u<t.sep.length;++u){let l=t.sep[u];switch(l.type){case"newline":a.push(u);break;case"space":break;case"comment":l.indent>e.indent&&(a.length=0);break;default:a.length=0}}a.length>=2&&(o=t.sep.splice(a[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(o.push(this.sourceToken),e.items.push({start:o}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(o.push(this.sourceToken),e.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Bt(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(Iu(t.key)&&!Bt(t.sep,"newline")){let a=Nn(t.start),u=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:u,sep:l}]})}else o.length>0?t.sep=t.sep.concat(o,this.sourceToken):t.sep.push(this.sourceToken);else if(Bt(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let a=Nn(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:o,key:null,sep:[this.sourceToken]}):Bt(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let a=this.flowScalar(this.type);i||t.value?(e.items.push({start:o,key:a,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(a):(Object.assign(t,{key:a,sep:[]}),this.onKeyLine=!0);return}default:{let a=this.startBlockValue(e);if(a){if(a.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Bt(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else s&&e.items.push({start:o});this.stack.push(a);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){var r;let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let s="end"in t.value?t.value.end:void 0,i=Array.isArray(s)?s[s.length-1]:void 0;(i==null?void 0:i.type)==="comment"?s==null||s.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2],i=(r=s==null?void 0:s.value)==null?void 0:r.end;if(Array.isArray(i)){Array.prototype.push.apply(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||Bt(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let s=this.startBlockValue(e);if(s){this.stack.push(s);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r&&r.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:s,sep:[]}):t.sep?this.stack.push(s):Object.assign(t,{key:s,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let s=Rs(r),i=Nn(s);vu(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`\n`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`\n`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=Rs(e),r=Nn(t);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=Rs(e),r=Nn(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};function bf(n){let e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new Lr||null,prettyErrors:e}}function Lu(n,e={}){let{lineCounter:t,prettyErrors:r}=bf(e),s=new Nr(t==null?void 0:t.addNewLine),i=new vr(e),o=null;for(let a of i.compose(s.parse(n),!0,n.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Ge(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&t&&(o.errors.forEach(Qi(n,t)),o.warnings.forEach(Qi(n,t))),o}function fo(n,e,t){let r;typeof e=="function"?r=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=Lu(n,t);if(!s)return null;if(s.warnings.forEach(i=>ys(s.options.logLevel,i)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:r},t))}var qs=Kr(Pu());var b=Kr(ss());var Qe;(L=>{L.DEFAULT_TO_STRING={nullRepresentation:"-",dateFormat:"MMMM dd, yyyy",dateTimeFormat:"h:mm a - MMMM dd, yyyy"};function e(m,F=L.DEFAULT_TO_STRING,O=!1){let x=t(m);if(!x)return F.nullRepresentation;switch(x.type){case"null":return F.nullRepresentation;case"string":return x.value;case"number":case"boolean":return""+x.value;case"link":return x.value.markdown();case"function":return"<function>";case"array":let S="";return O&&(S+="["),S+=x.value.map(V=>e(V,F,!0)).join(", "),O&&(S+="]"),S;case"object":return"{ "+Object.entries(x.value).map(V=>V[0]+": "+e(V[1],F,!0)).join(", ")+" }";case"date":return Ra(x.value,F.dateFormat,F.dateTimeFormat);case"duration":return ja(x.value)}}L.toString=e;function t(m){return h(m)?{type:"null",value:null}:f(m)?{type:"number",value:m}:l(m)?{type:"string",value:m}:p(m)?{type:"boolean",value:m}:y(m)?{type:"duration",value:m}:d(m)?{type:"date",value:m}:E(m)?{type:"array",value:m}:T(m)?{type:"link",value:m}:k(m)?{type:"function",value:m}:g(m)?{type:"object",value:m}:void 0}L.wrapValue=t;function r(m,F){if(g(m)){let O={};for(let[x,S]of Object.entries(m))O[x]=r(S,F);return O}else if(E(m)){let O=[];for(let x of m)O.push(r(x,F));return O}else return F(m)}L.mapLeaves=r;function s(m,F){return i(m,F)==0}L.equals=s;function i(m,F,O){var V,j;if(m===F||(m===void 0&&(m=null),F===void 0&&(F=null),m===null&&F===null))return 0;if(m===null)return-1;if(F===null)return 1;let x=t(m),S=t(F);if(x===void 0&&S===void 0)return 0;if(x===void 0)return-1;if(S===void 0)return 1;if(x.type!=S.type)return x.type.localeCompare(S.type);if(x.value===S.value)return 0;switch(x.type){case"string":return x.value.localeCompare(S.value);case"number":return x.value<S.value?-1:x.value==S.value?0:1;case"null":return 0;case"boolean":return x.value==S.value?0:x.value?1:-1;case"link":let Y=x.value,te=S.value,v=O!=null?O:Ae=>Ae,A=v(Y.path).localeCompare(v(te.path));if(A!=0)return A;let z=Y.type.localeCompare(te.type);return z!=0?z:Y.subpath&&!te.subpath?1:!Y.subpath&&te.subpath?-1:!Y.subpath&&!te.subpath?0:((V=Y.subpath)!=null?V:"").localeCompare((j=te.subpath)!=null?j:"");case"date":return x.value<S.value?-1:x.value.equals(S.value)?0:1;case"duration":return x.value<S.value?-1:x.value.equals(S.value)?0:1;case"array":let we=x.value,se=S.value;for(let Ae=0;Ae<Math.min(we.length,se.length);Ae++){let jt=i(we[Ae],se[Ae]);if(jt!=0)return jt}return we.length-se.length;case"object":let Xe=x.value,tn=S.value,et=Array.from(Object.keys(Xe)),$t=Array.from(Object.keys(tn));et.sort(),$t.sort();let Rt=i(et,$t);if(Rt!=0)return Rt;for(let Ae of et){let jt=i(Xe[Ae],tn[Ae]);if(jt!=0)return jt}return 0;case"function":return 0}}L.compare=i;function o(m){var F;return(F=t(m))==null?void 0:F.type}L.typeOf=o;function a(m){let F=t(m);if(!F)return!1;switch(F.type){case"number":return F.value!=0;case"string":return F.value.length>0;case"boolean":return F.value;case"link":return!!F.value.path;case"date":return F.value.toMillis()!=0;case"duration":return F.value.as("seconds")!=0;case"object":return Object.keys(F.value).length>0;case"array":return F.value.length>0;case"null":return!1;case"function":return!0}}L.isTruthy=a;function u(m){if(m==null)return m;if(L.isArray(m))return[].concat(m.map(F=>u(F)));if(L.isObject(m)){let F={};for(let[O,x]of Object.entries(m))F[O]=u(x);return F}else return m}L.deepCopy=u;function l(m){return typeof m=="string"}L.isString=l;function f(m){return typeof m=="number"}L.isNumber=f;function d(m){return m instanceof P}L.isDate=d;function y(m){return m instanceof _}L.isDuration=y;function h(m){return m==null}L.isNull=h;function E(m){return Array.isArray(m)}L.isArray=E;function p(m){return typeof m=="boolean"}L.isBoolean=p;function T(m){return m instanceof ee}L.isLink=T;function g(m){return m!==void 0&&typeof m=="object"&&!E(m)&&!y(m)&&!d(m)&&!T(m)&&!h(m)}L.isObject=g;function k(m){return typeof m=="function"}L.isFunction=k})(Qe||(Qe={}));var $u;(i=>{function n(o){return Qe.isObject(o)&&Object.keys(o).length==2&&"key"in o&&"rows"in o}i.isElementGroup=n;function e(o){for(let a of o)if(!n(a))return!1;return!0}i.isGrouping=e;function t(o){for(let a of o)if(n(a))return!1;return!0}i.isLeaf=t;function r(o){if(n(o))return r(o.rows);if(e(o)){let a=0;for(let u of o)a+=r(u.rows);return a}else return o.length}i.count=r;function s(o,a,u){if(u<=a)return[];if(t(o))return o.slice(a,u);let l=0,f=0;for(;l<o.length&&f+r(o[l])<=a;)f+=r(o[l]),l++;if(l>=o.length)return[];let d=[];for(;l<o.length&&f<u;){let y=o[l],h=r(y),E=Math.max(f,a),p=Math.min(h+f,u);d.push({key:y.key,rows:s(y.rows,E-f,p-f)}),f+=h,l++}return d}i.slice=s})($u||($u={}));var Mr=class{constructor(e){this.value=e;this.successful=!0}map(e){return new Mr(e(this.value))}flatMap(e){return e(this.value)}mapErr(e){return this.castErr()}bimap(e,t){return this.map(e).castErr()}orElse(e){return this.value}cast(){return this}castErr(){return this}orElseThrow(e){return this.value}},_r=class{constructor(e){this.error=e;this.successful=!1}map(e){return this.cast()}flatMap(e){return this.cast()}mapErr(e){return new _r(e(this.error))}bimap(e,t){return this.mapErr(t).cast()}orElse(e){return e}cast(){return this}castErr(){return this}orElseThrow(e){throw e?new Error(e(this.error)):new Error(""+this.error)}},ke;(a=>{function n(u){return new Mr(u)}a.success=n;function e(u){return new _r(u)}a.failure=e;function t(u,l,f){return u.successful?l.successful?f(u.value,l.value):e(l.error):e(u.error)}a.flatMap2=t;function r(u,l,f){return t(u,l,(d,y)=>n(f(d,y)))}a.map2=r;function s(u,l){let f=[];for(let d of u){let y=l(d);if(!y.successful)return y.cast();f.push(y.value)}return a.success(f)}a.mapAll=s;function i(u){try{return a.success(u())}catch(l){return a.failure(l)}}a.trying=i;async function o(u){try{return a.success(await u)}catch(l){return a.failure(l)}}a.async=o})(ke||(ke={}));var Pt;(L=>{L.EVERYTHING={type:"everything"},L.NOTHING={type:"nothing"},L.EMPTY_SET=new Set;function r(m){return m.size==0?L.NOTHING:{type:"atom",value:m}}L.atom=r;function s(m){return m?L.EVERYTHING:L.NOTHING}L.constant=s;function i(m){return m!==void 0?r(m):L.NOTHING}L.nullableAtom=i;function o(m){return m.size==0?L.EVERYTHING:{type:"negated",value:m}}L.negated=o;function a(m){switch(m.type){case"everything":return L.NOTHING;case"nothing":return L.EVERYTHING;case"atom":return o(m.value);case"negated":return r(m.value)}}L.negate=a;function u(m){switch(m.type){case"everything":return!1;case"negated":return!1;case"atom":return m.value.size==0;case"nothing":return!0}}L.empty=u;function l(m,F){switch(m.type){case"everything":return F;case"nothing":return L.EMPTY_SET;case"atom":return m.value;case"negated":return k(F,m.value)}}L.resolve=l;function f(m){return d(m,F=>F)}L.intersect=f;function d(m,F){return y(m,O=>ke.success(F(O))).orElseThrow()}L.lazyIntersect=d;function y(m,F){let O=[],x=[];for(let S of m){let V=F(S);if(!V.successful)return V.cast();let j=V.value;if(j!==void 0){if(u(j))return ke.success(L.NOTHING);j.type!=="everything"&&(j.type=="atom"?O.push(j.value):j.type=="negated"&&x.push(j.value))}}return O.length==0&&x.length==0?ke.success(L.EVERYTHING):O.length>0&&x.length==0?ke.success(r(T(O))):O.length==0&&x.length>0?ke.success(o(g(x))):ke.success(L.atom(k(T(O),g(x))))}L.lazyFailableIntersection=y;function h(m){return E(m,F=>F)}L.union=h;function E(m,F){return p(m,O=>ke.success(F(O))).orElseThrow()}L.lazyUnion=E;function p(m,F){let O=[],x=[];for(let S of m){let V=F(S);if(!V.successful)return V.cast();let j=V.value;if(j!==void 0){if(j.type==="everything")return ke.success(L.EVERYTHING);u(j)||(j.type=="atom"?O.push(j.value):j.type=="negated"&&x.push(j.value))}}return O.length==0&&x.length==0?ke.success(L.NOTHING):O.length>0&&x.length==0?ke.success(L.atom(g(O))):O.length==0&&x.length>0?ke.success(L.negated(T(x))):ke.success(o(k(T(x),g(O))))}L.lazyFailableUnion=p;function T(m){if(m.length==0)return new Set;if(m.length==1)return m[0];let F=[].concat(m).sort((O,x)=>O.size-x.size);for(;F.length>1;){let O=new Set,x=F.pop();for(let S of F[0])x.has(S)&&O.add(S);F[0]=O}return F[0]}L.setIntersect=T;function g(m){if(m.length==0)return new Set;if(m.length==1)return m[0];let F=new Set;for(let O of m)for(let x of O)F.add(x);return F}L.setUnion=g;function k(m,F){if(m.size>F.size){let O=new Set(m);for(let x of F)O.delete(x);return O}else{let O=new Set;for(let x of m)F.has(x)||O.add(x);return O}}L.setIntersectNegation=k})(Pt||(Pt={}));var oe;(T=>{T.ROW="$row";function e(g){return{type:"variable",name:g}}T.variable=e;function t(g){return{type:"literal",value:g}}T.literal=t;function r(g,k,L){return{type:"binaryop",left:g,op:k,right:L}}T.binaryOp=r;function s(g,k){return{type:"binaryop",left:g,right:k,op:"index"}}T.index=s;function i(g){let k=g.split("."),L=T.variable(k[0]);for(let m=1;m<k.length;m++)L=T.index(L,T.literal(k[m]));return L}T.indexVariable=i;function o(g,k){return{type:"lambda",arguments:g,value:k}}T.lambda=o;function a(g,k,L){return{type:"method",target:g,func:k,arguments:L}}T.method=a;function u(g,k){return{type:"function",func:g,arguments:k}}T.func=u;function l(g){return{type:"list",values:g}}T.list=l;function f(g){return{type:"object",values:g}}T.object=f;function d(g){return{type:"negated",child:g}}T.negate=d;function y(g){return g=="<="||g=="<"||g==">"||g==">="||g=="!="||g=="="}T.isCompareOp=y;function h(g,k=new Set([T.ROW])){switch(g.type){case"binaryop":return g.op==="index"&&g.left.type=="variable"&&g.left.name==T.ROW&&g.right.type=="literal"&&Qe.isString(g.right.value)?k.has(g.right.value)?new Set:new Set([g.right.value]):Pt.setUnion([h(g.left,k),h(g.right,k)]);case"function":let L=g.arguments.map(S=>h(S,k)),m=h(g.func,k);return Pt.setUnion(L.concat(m));case"method":let F=g.arguments.map(S=>h(S,k)),O=h(g.target,k);return Pt.setUnion(F.concat(O));case"lambda":let x=k!=null?k:new Set;for(let S of g.arguments)x.add(S);return h(g.value,x);case"list":return Pt.setUnion(g.values.map(S=>h(S,k)));case"negated":return h(g.child,k);case"object":return Pt.setUnion(Object.values(g.values).map(S=>h(S,k)));case"variable":return k&&k.has(g.name)?new Set:new Set([g.name]);case"literal":return new Set}}T.unboundVariables=h;function E(g){switch(g.type){case"binaryop":return g.op==="index"?`${E(g.left)}[${E(g.right)}]`:`${E(g.left)} ${g.op} ${E(g.right)}`;case"function":return`${E(g.func)}(${g.arguments.map(E).join(", ")})`;case"method":return`${E(g.target)}.${g.func}(${g.arguments.map(E).join(", ")})`;case"lambda":return`(${g.arguments.join(", ")}) => ${E(g.value)}`;case"list":return`[${g.values.map(E).join(", ")}]`;case"negated":return`!${E(g.child)}`;case"object":return`{${Object.entries(g.values).map(([L,m])=>`${L}: ${E(m)}`).join(", ")}}`;case"variable":return g.name;case"literal":let k=Qe.wrapValue(g.value);if(!k)return"null";switch(k.type){case"string":return`"${k.value}"`;default:return Qe.toString(k.value)}}}T.toString=E,T.NULL=T.literal(null)})(oe||(oe={}));var J=b.createLanguage({number:n=>b.regexp(/-?[0-9]+(\\.[0-9]+)?/).map(e=>Number.parseFloat(e)).desc("number"),string:n=>b.string(\'"\').then(b.alt(n.escapeCharacter,b.noneOf(\'"\\\\\')).atLeast(0).map(e=>e.join(""))).skip(b.string(\'"\')).desc("string"),escapeCharacter:n=>b.string("\\\\").then(b.any).map(e=>e===\'"\'?\'"\':e==="\\\\"?"\\\\":"\\\\"+e),bool:n=>b.regexp(/true|false|True|False/).map(e=>e.toLowerCase()=="true").desc("boolean"),tag:n=>b.seqMap(b.string("#"),b.alt(b.regexp(/[^\\u2000-\\u206F\\u2E00-\\u2E7F\'!"#$%&()*+,.:;<=>?@^`{|}~\\[\\]\\\\\\s]/).desc("text")).many(),(e,t)=>e+t.join("")).desc("tag"),identifier:n=>b.seqMap(b.alt(b.regexp(/[\\p{Letter}$]/u),b.regexp(Ru).desc("text")),b.alt(b.regexp(/[0-9\\p{Letter}$_-]/u),b.regexp(Ru).desc("text")).many(),(e,t)=>e+t.join("")).desc("variable"),link:n=>b.regexp(/\\[\\[([^\\[\\]]*?)\\]\\]/u,1).map(e=>ee.parseInner(e)).desc("file link"),embedLink:n=>b.seqMap(b.string("!").atMost(1),n.link,(e,t)=>(e.length>0&&(t.embed=!0),t)).desc("file link"),binaryPlusMinus:n=>b.regexp(/\\+|-/).map(e=>e).desc("\'+\' or \'-\'"),binaryMulDiv:n=>b.regexp(/\\*|\\/|%/).map(e=>e).desc("\'*\' or \'/\' or \'%\'"),binaryCompareOp:n=>b.regexp(/>=|<=|!=|>|<|=/).map(e=>e).desc("\'>=\' or \'<=\' or \'!=\' or \'=\' or \'>\' or \'<\'"),binaryAndOp:n=>b.regexp(/and|&/i).map(e=>"&").desc("\'and\'"),binaryOrOp:n=>b.regexp(/or|\\|/i).map(e=>"|").desc("\'or\'"),rootDate:n=>b.seqMap(b.regexp(/\\d{4}/),b.string("-"),b.regexp(/\\d{2}/),(e,t,r)=>P.fromObject({year:Number.parseInt(e),month:Number.parseInt(r)})).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"),dateShorthand:n=>b.alt(...Object.keys(Vu).sort((e,t)=>t.length-e.length).map(b.string)),date:n=>Cf(n.rootDate,e=>b.seqMap(b.string("-"),b.regexp(/\\d{2}/),(t,r)=>e.set({day:Number.parseInt(r)})),e=>b.seqMap(b.string("T"),b.regexp(/\\d{2}/),(t,r)=>e.set({hour:Number.parseInt(r)})),e=>b.seqMap(b.string(":"),b.regexp(/\\d{2}/),(t,r)=>e.set({minute:Number.parseInt(r)})),e=>b.seqMap(b.string(":"),b.regexp(/\\d{2}/),(t,r)=>e.set({second:Number.parseInt(r)})),e=>b.alt(b.seqMap(b.string("."),b.regexp(/\\d{3}/),(t,r)=>e.set({millisecond:Number.parseInt(r)})),b.succeed(e)),e=>b.alt(b.seqMap(b.string("+").or(b.string("-")),b.regexp(/\\d{1,2}(:\\d{2})?/),(t,r)=>e.setZone("UTC"+t+r,{keepLocalTime:!0})),b.seqMap(b.string("Z"),()=>e.setZone("utc",{keepLocalTime:!0})),b.seqMap(b.string("["),b.regexp(/[0-9A-Za-z+-\\/]+/u),b.string("]"),(t,r,s)=>e.setZone(r,{keepLocalTime:!0})))).assert(e=>e.isValid,"valid date").desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"),datePlus:n=>b.alt(n.dateShorthand.map(e=>Vu[e]()),n.date).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS] or in shorthand"),durationType:n=>b.alt(...Object.keys(ju).sort((e,t)=>t.length-e.length).map(b.string)),duration:n=>b.seqMap(n.number,b.optWhitespace,n.durationType,(e,t,r)=>ju[r].mapUnits(s=>s*e)).sepBy1(b.string(",").trim(b.optWhitespace).or(b.optWhitespace)).map(e=>e.reduce((t,r)=>t.plus(r))).desc("duration like 4hr2min"),rawNull:n=>b.string("null"),atomInlineField:n=>b.alt(n.date,n.duration.map(e=>_i(e)),n.string,n.tag,n.embedLink,n.bool,n.number,n.rawNull),inlineFieldList:n=>n.atomInlineField.sepBy(b.string(",").trim(b.optWhitespace).lookahead(n.atomInlineField)),inlineField:n=>b.alt(b.seqMap(n.atomInlineField,b.string(",").trim(b.optWhitespace),n.inlineFieldList,(e,t,r)=>[e].concat(r)),n.atomInlineField)}),Ru=new RegExp(wn(),""),ju={year:_.fromObject({years:1}),years:_.fromObject({years:1}),yr:_.fromObject({years:1}),yrs:_.fromObject({years:1}),month:_.fromObject({months:1}),months:_.fromObject({months:1}),mo:_.fromObject({months:1}),mos:_.fromObject({months:1}),week:_.fromObject({weeks:1}),weeks:_.fromObject({weeks:1}),wk:_.fromObject({weeks:1}),wks:_.fromObject({weeks:1}),w:_.fromObject({weeks:1}),day:_.fromObject({days:1}),days:_.fromObject({days:1}),d:_.fromObject({days:1}),hour:_.fromObject({hours:1}),hours:_.fromObject({hours:1}),hr:_.fromObject({hours:1}),hrs:_.fromObject({hours:1}),h:_.fromObject({hours:1}),minute:_.fromObject({minutes:1}),minutes:_.fromObject({minutes:1}),min:_.fromObject({minutes:1}),mins:_.fromObject({minutes:1}),m:_.fromObject({minutes:1}),second:_.fromObject({seconds:1}),seconds:_.fromObject({seconds:1}),sec:_.fromObject({seconds:1}),secs:_.fromObject({seconds:1}),s:_.fromObject({seconds:1})},Vu={now:()=>P.local(),today:()=>P.local().startOf("day"),yesterday:()=>P.local().startOf("day").minus(_.fromObject({days:1})),tomorrow:()=>P.local().startOf("day").plus(_.fromObject({days:1})),sow:()=>P.local().startOf("week"),"start-of-week":()=>P.local().startOf("week"),eow:()=>P.local().endOf("week"),"end-of-week":()=>P.local().endOf("week"),soy:()=>P.local().startOf("year"),"start-of-year":()=>P.local().startOf("year"),eoy:()=>P.local().endOf("year"),"end-of-year":()=>P.local().endOf("year"),som:()=>P.local().startOf("month"),"start-of-month":()=>P.local().startOf("month"),eom:()=>P.local().endOf("month"),"end-of-month":()=>P.local().endOf("month")},qu=b.createLanguage({variable:n=>J.identifier.map(oe.variable).desc("variable"),number:n=>J.number.map(oe.literal).desc("number"),string:n=>J.string.map(oe.literal).desc("string"),bool:n=>J.bool.map(oe.literal).desc("boolean"),date:n=>St("date",J.datePlus).map(([e,t])=>oe.literal(t)).desc("date"),duration:n=>St("dur",J.duration).map(([e,t])=>oe.literal(t)).desc("duration"),null:n=>J.rawNull.map(e=>oe.NULL),link:n=>J.link.map(oe.literal),list:n=>n.expression.sepBy(b.string(",").trim(b.optWhitespace)).wrap(b.string("[").skip(b.optWhitespace),b.optWhitespace.then(b.string("]"))).map(e=>oe.list(e)).desc("list"),object:n=>b.seqMap(J.identifier.or(J.string),b.string(":").trim(b.optWhitespace),n.expression,(e,t,r)=>({name:e,value:r})).sepBy(b.string(",").trim(b.optWhitespace)).wrap(b.string("{").skip(b.optWhitespace),b.optWhitespace.then(b.string("}"))).map(e=>{let t={};for(let r of e)t[r.name]=r.value;return oe.object(t)}).desc("object (\'{ a: 1, b: 2 }\')"),atom:n=>b.alt(J.embedLink.map(e=>oe.literal(e)),n.negated,n.link,n.list,n.object,n.lambda,n.parens,n.bool,n.number,n.string,n.date,n.duration,n.null,n.variable),index:n=>b.seqMap(n.atom,b.alt(n.methodPostfix,n.functionPostfix,n.indexPostfix,n.dotPostfix).many(),(e,t)=>{let r=e;for(let s of t)switch(s.type){case"dot":r=oe.index(r,oe.literal(s.expr));break;case"index":r=oe.index(r,s.expr);break;case"function":r=oe.func(r,s.exprs);break;case"method":r=oe.method(r,s.func,s.exprs);break}return r}),negated:n=>b.seqMap(b.string("!"),n.index,(e,t)=>oe.negate(t)).desc("negated field"),parens:n=>n.expression.trim(b.optWhitespace).wrap(b.string("("),b.string(")")),lambda:n=>b.seqMap(J.identifier.sepBy(b.string(",").trim(b.optWhitespace)).wrap(b.string("(").trim(b.optWhitespace),b.string(")").trim(b.optWhitespace)),b.string("=>").trim(b.optWhitespace),n.expression,(e,t,r)=>({type:"lambda",arguments:e,value:r})),dotPostfix:n=>b.string(".").then(J.identifier).map(e=>({type:"dot",expr:e})),indexPostfix:n=>n.expression.trim(b.optWhitespace).wrap(b.string("["),b.string("]")).map(e=>({type:"index",expr:e})),functionPostfix:n=>n.expression.sepBy(b.string(",").trim(b.optWhitespace)).trim(b.optWhitespace).wrap(b.string("("),b.string(")")).map(e=>({type:"function",exprs:e})),methodPostfix:n=>b.seqMap(b.string("."),J.identifier.trim(b.optWhitespace),n.expression.sepBy(b.string(",").trim(b.optWhitespace)).trim(b.optWhitespace).wrap(b.string("("),b.string(")")),(e,t,r)=>({type:"method",func:t,exprs:r})),binaryMulDiv:n=>Mn(n.index,J.binaryMulDiv,oe.binaryOp),binaryPlusMinus:n=>Mn(n.binaryMulDiv,J.binaryPlusMinus,oe.binaryOp),binaryCompare:n=>Mn(n.binaryPlusMinus,J.binaryCompareOp,oe.binaryOp),binaryBoolean:n=>Mn(n.binaryCompare,J.binaryAndOp.or(J.binaryOrOp),oe.binaryOp),binaryOp:n=>n.binaryBoolean,expression:n=>n.binaryOp}),nb=b.createLanguage({queryTag:n=>J.tag.map(e=>({type:"tagged",value:e})),queryId:n=>St("id",J.string).map(([e,t])=>({type:"id",value:t})),queryType:n=>b.string("@").then(J.identifier).map(e=>({type:"typed",value:e})),queryPath:n=>St(b.regexp(/e?path/i).desc("[e]path"),J.string).map(([e,t])=>({type:"path",value:t,exact:e.toLowerCase()==="epath"})),queryParentOf:n=>St(b.regexp(/parentof|supertree/i).desc("parentof"),n.query).map(([e,t])=>({type:"parent-of",children:t,inclusive:e.toLowerCase()==="supertree"})),queryChildOf:n=>St(b.regexp(/childof|subtree/i).desc("childof"),n.query).map(([e,t])=>({type:"child-of",parents:t,inclusive:e.toLowerCase()==="subtree"})),querySimpleLinked:n=>J.link.map(e=>({type:"linked",source:{type:"link",value:e},direction:"incoming"})),queryLinked:n=>St(b.regexp(/linksto|linkedfrom|connected/i).desc("connected"),n.query).map(([e,t])=>({type:"linked",source:t.type=="linked"&&t.source.type=="link"?t.source:t,direction:e.toLowerCase()=="linksto"?"incoming":e.toLowerCase()=="linkedfrom"?"outgoing":"both"})),queryExists:n=>St(b.regexp(/exists/i).desc("exists"),J.identifier.or(J.string)).map(([e,t])=>({type:"field",value:t})),queryQuotedExpression:n=>St(b.regexp(/expr/i).desc("expr"),qu.expression).map(([e,t])=>({type:"expression",expression:t})),queryRawExpression:n=>qu.binaryCompare.map(e=>({type:"expression",expression:e})),queryParens:n=>n.query.trim(b.optWhitespace).wrap(b.string("("),b.string(")")),queryNegate:n=>b.string("!").skip(b.optWhitespace).then(n.queryAtom).map(e=>({type:"not",element:e})),queryAtom:n=>b.alt(n.queryParens,n.queryNegate,n.querySimpleLinked,n.queryTag,n.queryType,n.queryId,n.queryExists,n.queryChildOf,n.queryParentOf,n.queryLinked,n.queryPath,n.queryQuotedExpression,n.queryRawExpression),queryAnds:n=>Mn(n.queryAtom,J.binaryAndOp,(e,t,r)=>({type:"and",elements:[e,r]})),queryOrs:n=>Mn(n.queryAnds,J.binaryOrOp,(e,t,r)=>({type:"or",elements:[e,r]})),query:n=>n.queryOrs.trim(b.optWhitespace)});function Mn(n,e,t){return b.seqMap(n,b.seq(b.optWhitespace,e,b.optWhitespace,n).many(),(r,s)=>{if(s.length==0)return r;let i=t(r,s[0][1],s[0][3]);for(let o=1;o<s.length;o++)i=t(i,s[o][1],s[o][3]);return i})}function St(n,e){let t=typeof n=="string"?b.string(n):n;return b.seqMap(t.skip(b.optWhitespace),e.trim(b.optWhitespace).wrap(b.string("("),b.string(")")),(r,s)=>[r,s])}function Cf(n,...e){return b.custom((t,r)=>(s,i)=>{let o=n._(s,i);if(!o.status)return o;for(let a of e){let u=o.value,l=a(u)._(s,o.index);if(!l.status)return o;o=l}return o})}var en=Kr(ss());function Xt(n,e){let t={};for(let[r,s]of Object.entries(n))t[r]=e(s);return t}var _n;(r=>{r.NOOP_NORMALIZER=s=>s;function e(s){let i=Qe.wrapValue(s);if(!i)return null;switch(i==null?void 0:i.type){case"array":return i.value.map(r.json);case"object":return Xt(i.value,r.json);case"date":return{$_type:"date",value:i.value.toISO({extendedZone:!0,includeOffset:!0})};case"link":return{$_type:"link",value:i.value.toObject()};case"duration":return{$_type:"duration",value:i.value.toISO()};case"boolean":case"number":case"string":return i.value;case"function":case"null":return null}}r.json=e;function t(s,i=r.NOOP_NORMALIZER){if(s==null)return null;if(Array.isArray(s))return i(s.map(o=>r.value(o,i)));if(typeof s=="object"){if(!("$_type"in s))return Xt(s,o=>r.value(o,i));switch(s.$_type){case"date":return i(P.fromISO(s.value,{setZone:!0}));case"duration":return i(_.fromISO(s.value));case"link":return i(ee.fromObject(s.value));default:throw new Error(`Unrecognized serialized type \'${s.$_type}\'!`)}}return i(s)}r.value=t})(_n||(_n={}));function Uu(n){return Object.assign({},n,{value:_n.json(n.value)})}function Br(n,e){return Array.isArray(n)?n.map(t=>Br(t,e)):{key:n.key,raw:n.value,value:vf(n.value),position:{line:e,start:n.start,startValue:n.startValue,end:n.end},wrapping:n.wrapping}}var js=Object.freeze({"[":"]","(":")"});function xf(n,e,t,r){let s=0,i=!1;for(let o=e;o<n.length;o++){let a=n.charAt(o);if(a=="\\\\"){i=!i;continue}if(i){i=!1;continue}if(a==t?s++:a==r&&s--,s<0)return{value:n.substring(e,o).trim(),endIndex:o+1};i=!1}}function Ku(n,e){let t=n.indexOf("::",e);if(!(t<0))return{key:n.substring(e,t).trim(),valueIndex:t+2}}function Of(n,e){let t=n.charAt(e),r=Ku(n,e+1);if(r===void 0)return;for(let i of Object.keys(js).concat(Object.values(js)))if(r.key.includes(i))return;let s=xf(n,r.valueIndex,t,js[t]);if(s!==void 0)return{key:r.key,value:s.value,start:e,startValue:r.valueIndex,end:s.endIndex,wrapping:t}}function vf(n){if(n.trim()=="")return null;let e=J.inlineField.parse(n);return e.status?e.value:n}function Wu(n){let e=[];for(let r of Object.keys(js)){let s=n.indexOf(r);for(;s>=0;){let i=Of(n,s);if(!i){s=n.indexOf(r,s+1);continue}e.push(i),s=n.indexOf(r,i.end)}}e.sort((r,s)=>r.start-s.start);let t=[];for(let r=0;r<e.length;r++)(r==0||t[t.length-1].end<e[r].start)&&t.push(e[r]);return t}var If=en.alt(en.regexp(new RegExp(wn(),"u")),en.regexp(/[0-9\\p{Letter}\\w\\s_/-]+/u)).many().map(n=>n.join("")),Lf=en.regexp(/[^0-9\\w\\p{Letter}]*/u).then(If).skip(en.regexp(/[_\\*~`]*/u));function Hu(n){let e=Ku(n,0);if(!e)return;let t=Lf.parse(e.key);if(t.status)return{key:t.value,value:n.substring(e.valueIndex).trim(),start:0,startValue:e.valueIndex,end:n.length}}var Nf=/\\u{2795}\\s*(\\d{4}-\\d{2}-\\d{2})/u,Af=/(?:\\u{1F4C5}|\\u{1F4C6}|\\u{1F5D3}\\u{FE0F}?)\\s*(\\d{4}-\\d{2}-\\d{2})/u,Mf=/\\u{2705}\\s*(\\d{4}-\\d{2}-\\d{2})/u,_f=/[\\u{23F3}\\u{231B}]\\s*(\\d{4}-\\d{2}-\\d{2})/u,Bf=/\\u{1F6EB}\\s*(\\d{4}-\\d{2}-\\d{2})/u,Pf=[{regex:Nf,key:"created"},{regex:Bf,key:"start"},{regex:_f,key:"scheduled"},{regex:Af,key:"due"},{regex:Mf,key:"completion"}];function Ju(n){let e=[];for(let{regex:t,key:r}of Pf){let s=t.exec(n);s&&e.push({key:r,value:s[1],start:s.index,startValue:s.index+1,end:s.index+s[0].length,wrapping:"emoji-shorthand"})}return e}var Vs;(t=>{function n(r){let s=Qe.wrapValue(e);if(!s)return null;switch(s.type){case"string":case"boolean":case"null":case"number":return s.value;case"array":return s.value.map(n);case"date":return s.value.toISO();case"duration":return s.value.toHuman();case"function":return null;case"link":return s.value.markdown();case"object":return Xt(s.value,n)}}t.yaml=n;function e(r){if(r==null)return null;if(typeof r=="object")if(Array.isArray(r)){let s=[];for(let i of r)s.push(e(i));return s}else{if(r instanceof Date)return P.fromJSDate(r);{let s=r,i={};for(let o in s)i[o]=e(s[o]);return i}}else{if(typeof r=="number")return r;if(typeof r=="boolean")return r;if(typeof r=="string"){let s=J.date.parse(r);if(s.status)return s.value;let i=J.duration.parse(r);if(i.status)return i.value;let o=J.link.parse(r);return o.status?o.value:r}}return null}t.literal=e})(Vs||(Vs={}));var $f=/```yaml:data/i,Rf=/^(?:```|~~~)(.*)$/im,jf=/^[\\s>]*(\\d+\\.|\\d+\\)|\\*|-|\\+)\\s*(\\[.{0,1}\\])?\\s*(.*)$/mu;function Gu(n,e,t,r){let{lines:s,metadata:i,frontmatter:o,sections:a}=bo(n,e,t);return new po(n,r,s.length,i,a,o).build()}function bo(n,e,t){var y,h,E,p,T,g,k,L,m,F,O,x,S,V,j,Y,te;let r=t.frontmatter?Yu(t.frontmatter):void 0,s=e.split(/\\r\\n|\\r|\\n/),i=new Re,o=[],a=(y=t.headings)!=null?y:[];a.sort((v,A)=>v.position.start.line-A.position.start.line);let u=new qs.default(void 0,(v,A)=>v-A);for(let v=0;v<a.length;v++){let A=a[v],z=A.position.start.line,we=v==a.length-1?s.length:a[v+1].position.start.line,se=new Pr(z,we,A.heading,A.level,v+1);u.set(z,se)}if(u.size==0){if(!zu(s,0,s.length)){let v=new Pr(0,s.length,Tn(n),1,0);u.set(0,v)}}else{let v=(h=u.getPairOrNextHigher(0))==null?void 0:h[1];if(v.start>0&&!zu(s,0,v.start)){let A=new Pr(0,v.start,Tn(n),1,0);u.set(0,A)}}let l=new qs.default(void 0,(v,A)=>v-A),f=1;for(let v of t.sections||[]){if(v.type==="heading")continue;let A=v.position.start.line,z=v.position.end.line+1,we=s[A];if(v.type==="list")l.set(A,new mo(A,z,f++,v.id));else if(v.type=="code"&&$f.test(we)){let se=s.slice(A+1,z-1).join(`\n`).replace(/\\t/gm,"  "),Xe=Yu(fo(se));l.set(A,new Do(A,z,f++,Xe,v.id))}else if(v.type==="code"){let se=we.match(Rf);if(!se)l.set(A,new Us(A,z,f++,[],"indent",A,z,v.id));else{let tn=(se.length>1&&se[1]?se[1].split(","):[]).map(et=>et.trim()).filter(et=>et.length>0);l.set(A,new Us(A,z,f++,tn,"fenced",A+1,z-1,v.id))}}else l.set(A,new yo(A,z,f++,v.type,v.id))}for(let v of l.values())(E=ft(v.start,u))==null||E.block(v);let d=new qs.default(void 0,(v,A)=>v-A);for(let v of t.listItems||[]){let z=s[v.position.start.line].match(jf),we,se;z&&(we=z[1],se=z[3]);let Xe=new go(v.position.start.line,v.position.end.line+1,v.parent,we,v.id,v.task,se);d.set(Xe.start,Xe)}for(let v of d.values())if(v.parentLine<0){let A=(p=l.getPairOrNextHigher(-v.parentLine-1))==null?void 0:p[1];if(!A||A.type!=="list")continue;A.items.push(v)}else(T=d.get(v.parentLine))==null||T.elements.push(v);for(let v of(g=t.tags)!=null?g:[]){let A=v.tag.startsWith("#")?v.tag:"#"+v.tag,z=v.position.start.line;i.tag(A),(k=ft(z,u))==null||k.metadata.tag(A),(L=ft(z,l))==null||L.metadata.tag(A),(m=ft(z,d))==null||m.metadata.tag(A)}if(t.frontmatter)for(let v of Vf(t.frontmatter)){let A=v.startsWith("#")?v:"#"+v;i.tag(A)}for(let v of(F=t.links)!=null?F:[]){let A=ee.infer(v.link,!1,v.displayText),z=v.position.start.line;i.link(A),(O=ft(z,u))==null||O.metadata.link(A),(x=ft(z,l))==null||x.metadata.link(A),(S=ft(z,d))==null||S.metadata.link(A)}for(let v of(V=t.frontmatterLinks)!=null?V:[])i.link(ee.infer(v.link,!1,v.displayText));for(let v of Eo(s)){let A=v.position.line;i.inlineField(v),(j=ft(A,u))==null||j.metadata.inlineField(v),(Y=ft(A,l))==null||Y.metadata.inlineField(v),(te=ft(A,d))==null||te.metadata.inlineField(v)}for(let v of d.values())for(let A=v.start;A<v.end;A++){let z=Ju(s[A]);for(let we of z)v.metadata.inlineField(Br(we,A))}return o.push(...u.values()),{lines:s,frontmatter:r,metadata:i,sections:o}}function zu(n,e,t){for(let r=e;r<t;r++)if(n[r].trim()!=="")return!1;return!0}function*Eo(n){for(let e=0;e<n.length;e++){let t=n[e];if(t.length>32768||!t.includes("::"))continue;let r=Wu(t);if(r.length>0)for(let s of r)yield Br(s,e);else{let s=Hu(t);s&&(yield Br(s,e))}}}function Yu(n){let e={};for(let t of Object.keys(n)){let r=n[t];e[t.toLowerCase()]={key:t,value:_n.json(Vs.literal(r)),raw:r}}return e}function ft(n,e){var r;let t=(r=e.getPairOrNextLower(n))==null?void 0:r[1];if(t&&t.end>=n)return t}function Vf(n){return Object.keys(n).filter(t=>t.toLowerCase()=="tags"||t.toLowerCase()=="tag").map(t=>Zu(n[t],/[,\\s]+/)).reduce((t,r)=>t.concat(r),[]).map(t=>t.startsWith("#")?t:"#"+t)}function Zu(n,e){return n==null||n==null?[]:Array.isArray(n)?n.filter(t=>!!t).map(t=>Zu(t,e)).reduce((t,r)=>t.concat(r),[]):(""+n).split(e).filter(t=>!!t).map(t=>t.trim()).filter(t=>t.length>0)}var Re=class{constructor(){this.tags=new Set;this.links=[];this.inlineFields={}}tag(e){this.tags.add(e)}link(e){this.links.find(t=>t.equals(e))||this.links.push(e)}inlineField(e){let t=e.key.toLowerCase();Object.keys(this.inlineFields).some(r=>r.toLowerCase()==t)||(this.inlineFields[t]=e)}finishTags(){return Array.from(this.tags)}finishLinks(){return this.links.map(e=>e.toObject())}finishInlineFields(){return Xt(this.inlineFields,Uu)}},po=class{constructor(e,t,r,s,i,o){this.path=e;this.stats=t;this.length=r;this.metadata=s;this.sections=i;this.frontmatter=o}build(){return{$path:this.path,$ctime:this.stats.ctime,$mtime:this.stats.mtime,$size:this.stats.size,$extension:Va(this.path),$position:{start:0,end:this.length},$tags:this.metadata.finishTags(),$links:this.metadata.finishLinks(),$infields:this.metadata.finishInlineFields(),$sections:this.sections.map(e=>e.build()),$frontmatter:this.frontmatter}}},Pr=class{constructor(e,t,r,s,i){this.start=e;this.end=t;this.title=r;this.level=s;this.ordinal=i;this.blocks=[];this.metadata=new Re}block(e){this.blocks.push(e)}build(){return{$title:this.title,$ordinal:this.ordinal,$level:this.level,$tags:this.metadata.finishTags(),$infields:this.metadata.finishInlineFields(),$links:this.metadata.finishLinks(),$position:{start:this.start,end:this.end},$blocks:this.blocks.map(e=>e.build())}}},mo=class{constructor(e,t,r,s){this.start=e;this.end=t;this.ordinal=r;this.blockId=s;this.type="list";this.metadata=new Re;this.items=[]}build(){return{$ordinal:this.ordinal,$position:{start:this.start,end:this.end},$infields:this.metadata.finishInlineFields(),$tags:this.metadata.finishTags(),$links:this.metadata.finishLinks(),$type:"list",$blockId:this.blockId,$elements:this.items.map(e=>e.build())}}},Us=class{constructor(e,t,r,s,i,o,a,u){this.start=e;this.end=t;this.ordinal=r;this.languages=s;this.style=i;this.contentStart=o;this.contentEnd=a;this.blockId=u;this.type="codeblock";this.metadata=new Re}build(){return{$type:"codeblock",$ordinal:this.ordinal,$position:{start:this.start,end:this.end},$infields:this.metadata.finishInlineFields(),$tags:this.metadata.finishTags(),$links:this.metadata.finishLinks(),$blockId:this.blockId,$languages:this.languages,$style:this.style,$contentPosition:{start:this.contentStart,end:this.contentEnd}}}},Do=class{constructor(e,t,r,s,i){this.start=e;this.end=t;this.ordinal=r;this.data=s;this.blockId=i;this.type="datablock";this.metadata=new Re}build(){return{$type:"datablock",$ordinal:this.ordinal,$position:{start:this.start,end:this.end},$infields:this.metadata.finishInlineFields(),$tags:this.metadata.finishTags(),$links:this.metadata.finishLinks(),$blockId:this.blockId,$data:this.data}}},yo=class{constructor(e,t,r,s,i){this.start=e;this.end=t;this.ordinal=r;this.type=s;this.blockId=i;this.metadata=new Re}build(){return{$type:this.type,$ordinal:this.ordinal,$position:{start:this.start,end:this.end},$infields:this.metadata.finishInlineFields(),$tags:this.metadata.finishTags(),$links:this.metadata.finishLinks(),$blockId:this.blockId}}},go=class{constructor(e,t,r,s,i,o,a){this.start=e;this.end=t;this.parentLine=r;this.symbol=s;this.blockId=i;this.status=o;this.text=a;this.metadata=new Re;this.elements=[]}build(){return{$parentLine:this.parentLine,$position:{start:this.start,end:this.end},$blockId:this.blockId,$elements:this.elements.map(e=>e.build()),$type:this.status?"task":"list",$infields:this.metadata.finishInlineFields(),$tags:this.metadata.finishTags(),$links:this.metadata.finishLinks(),$status:this.status,$symbol:this.symbol,$text:this.text}}};function Qu(n,e,t,r){var o,a;let s=new wo(n,r),i=JSON.parse(e);for(let u of i.nodes)if(u.type!="group")if(u.type=="text"){let{frontmatter:l,metadata:f,lines:d,sections:y}=bo(n,u.text,(o=t.caches[u.id])!=null?o:{}),h=new Ks(n,u.id,u,l);y.forEach(E=>h.section(E)),s.card(h);for(let E in f.tags)s.metadata.tag(E);for(let E of(a=f.links)!=null?a:[])s.metadata.link(E);for(let E of Eo(d))s.metadata.inlineField(E)}else{let l=new Ks(n,u.id,u);s.card(l)}return s.build()}var Fo=class{constructor(e,t,r){this.path=e;this.id=t;this.nodeJson=r;this.metadata=new Re}build(){return{$file:this.path,$id:this.id,$position:{x:this.nodeJson.x,y:this.nodeJson.y},$dimensions:{width:this.nodeJson.width,height:this.nodeJson.height},$color:this.nodeJson.color,$link:ee.file(this.path).withBlock(this.id).toObject()}}},Ks=class extends Fo{constructor(t,r,s,i){super(t,r,s);this.path=t;this.id=r;this.nodeJson=s;this.frontmatter=i;this.sections=[]}section(t){return this.sections.push(t),t}build(){switch(this.nodeJson.type){case"text":return be(R({},super.build()),{$infields:this.metadata.finishInlineFields(),$frontmatter:this.frontmatter,$sections:this.sections.map(t=>t.build()),$tags:this.metadata.finishTags(),$links:this.metadata.finishLinks(),$type:"text-card",$color:this.nodeJson.color});case"file":return be(R({},super.build()),{$linkedFile:this.nodeJson.file});case"link":return be(R({},super.build()),{$url:this.nodeJson.url})}}},wo=class{constructor(e,t){this.path=e;this.stats=t;this.cards=[];this.metadata=new Re}card(e){return this.cards.push(e),e}build(){return{$cards:this.cards.map(e=>e.build()),$ctime:this.stats.ctime,$mtime:this.stats.mtime,$infields:this.metadata.finishInlineFields(),$links:this.metadata.finishLinks(),$tags:this.metadata.finishTags(),$path:this.path,$size:this.stats.size}}};onmessage=async n=>{try{let e=n.data;if(e.type==="markdown"){let t=Gu(e.path,e.contents,e.metadata,e.stat);postMessage({type:"markdown",result:t})}else if(e.type==="canvas"){let t=Qu(e.path,e.contents,e.index,e.stat);postMessage({type:"canvas",result:t})}else postMessage({$error:"Unsupported import method."})}catch(e){console.error(`Datacore failed to index ${n.data.path}: ${e}`),postMessage({$error:e.message})}};\n');
}

// src/index/web-worker/importer.ts
var import_obsidian6 = require("obsidian");
var import_queue = __toESM(require_queue2());
var DEFAULT_THROTTLE = {
  workers: 2,
  utilization: 0.75
};
var FileImporter = class extends import_obsidian6.Component {
  constructor(vault, fileManager, metadataCache, throttle) {
    super();
    this.vault = vault;
    this.fileManager = fileManager;
    this.metadataCache = metadataCache;
    this.workers = /* @__PURE__ */ new Map();
    this.shutdown = false;
    this.nextWorkerId = 0;
    this.throttle = throttle != null ? throttle : () => DEFAULT_THROTTLE;
    this.queue = new import_queue.Queue();
    this.outstanding = /* @__PURE__ */ new Map();
  }
  /**
   * Queue the given file for importing. Multiple import requests for the same file in a short time period will be de-bounced
   * and all be resolved by a single actual file reload.
   */
  import(file) {
    let existing = this.outstanding.get(file.path);
    if (existing)
      return existing;
    let promise = deferred();
    this.outstanding.set(file.path, promise);
    this.queue.enqueue([file, promise]);
    this.schedule();
    return promise;
  }
  /** Reset any active throttles on the importer (such as if the utilization changes). */
  unthrottle() {
    for (let worker of this.workers.values()) {
      worker.availableAt = Date.now();
    }
  }
  /** Poll from the queue and execute if there is an available worker. */
  async schedule() {
    var _a, _b, _c, _d, _e, _f;
    if (this.queue.size() == 0 || this.shutdown)
      return;
    const worker = this.availableWorker();
    if (!worker)
      return;
    const [file, promise] = this.queue.dequeue();
    worker.active = [file, promise, Date.now()];
    try {
      switch (file.extension) {
        case "markdown":
        case "md": {
          const contents = await this.vault.cachedRead(file);
          worker.worker.postMessage({
            type: "markdown",
            path: file.path,
            contents,
            stat: file.stat,
            metadata: this.metadataCache.getFileCache(file)
          });
          break;
        }
        case "canvas": {
          const contents = await this.vault.cachedRead(file);
          worker.worker.postMessage({
            type: "canvas",
            path: file.path,
            contents,
            stat: file.stat,
            index: (_f = (_e = (_d = (_c = (_b = (_a = this.fileManager.linkUpdaters) == null ? void 0 : _a.canvas) == null ? void 0 : _b.canvas) == null ? void 0 : _c.index) == null ? void 0 : _d.index) == null ? void 0 : _e[file.path]) != null ? _f : {
              caches: {},
              embeds: []
            }
          });
          break;
        }
      }
    } catch (ex) {
      console.error("Datacore: Background file reloading failed. " + ex);
      worker.active = void 0;
    }
  }
  /** Finish the parsing of a file, potentially queueing a new file. */
  finish(worker, data) {
    if (!worker.active) {
      return;
    }
    const [file, promise, start] = worker.active;
    if ("$error" in data)
      promise.reject(data["$error"]);
    else
      promise.resolve(data);
    this.outstanding.delete(file.path);
    if (this.workers.size > this.throttle().workers) {
      this.workers.delete(worker.id);
      terminate(worker);
    } else {
      const now2 = Date.now();
      const throttle = Math.max(0.1, this.throttle().utilization) - 1;
      const delay = (now2 - start) * throttle;
      worker.active = void 0;
      if (delay <= 1e-10) {
        worker.availableAt = now2;
        this.schedule();
      } else {
        worker.availableAt = now2 + delay;
        window.setTimeout(this.schedule.bind(this), delay);
      }
    }
  }
  /** Obtain an available worker, returning undefined if one does not exist. */
  availableWorker() {
    const now2 = Date.now();
    for (let worker of this.workers.values()) {
      if (!worker.active && worker.availableAt <= now2) {
        return worker;
      }
    }
    if (this.workers.size < this.throttle().workers) {
      let worker = this.newWorker();
      this.workers.set(worker.id, worker);
      return worker;
    }
    return void 0;
  }
  /** Create a new worker bound to this importer. */
  newWorker() {
    let worker = {
      id: this.nextWorkerId++,
      availableAt: Date.now(),
      worker: new Worker2()
    };
    worker.worker.onmessage = (evt) => this.finish(worker, evt.data);
    return worker;
  }
  /** Reject all outstanding promises and close all workers on close. */
  onunload() {
    for (let worker of this.workers.values()) {
      terminate(worker);
    }
    while (!this.queue.isEmpty()) {
      const [_file, promise] = this.queue.pop();
      promise.reject("Terminated");
    }
    this.shutdown = true;
  }
};
function terminate(worker) {
  worker.worker.terminate();
  if (worker.active)
    worker.active[1].reject("Terminated");
  worker.active = void 0;
}

// src/index/datacore.ts
var import_obsidian8 = require("obsidian");

// src/index/types/files.ts
var _GenericFile = class {
  constructor(path, ctime, mtime, size) {
    this.$types = _GenericFile.TYPES;
    this.$typename = "File";
    this.$path = path;
    this.$ctime = ctime;
    this.$mtime = mtime;
    this.$size = size;
    const lastDot = path.lastIndexOf(".");
    this.$extension = lastDot < 0 ? "" : path.substring(lastDot + 1);
  }
  get fields() {
    return _GenericFile.FIELD_DEF(this);
  }
  field(key) {
    var _a;
    return (_a = _GenericFile.FIELD_DEF(this, key)) == null ? void 0 : _a[0];
  }
  /** Get the value for the given field. */
  value(key) {
    var _a;
    return (_a = this.field(key)) == null ? void 0 : _a.value;
  }
  /** Unique ID for this object. */
  get $id() {
    return this.$path;
  }
  /** The file for the file is the file. */
  get $file() {
    return this.$path;
  }
  /** A link to the file. */
  get $link() {
    return Link.file(this.$path);
  }
};
var GenericFile = _GenericFile;
GenericFile.TYPES = [FILE_TYPE, FIELDBEARING_TYPE, LINKABLE_TYPE];
GenericFile.FIELD_DEF = Extractors.intrinsics();

// src/index/embed-queue.ts
var import_queue2 = __toESM(require_queue2());
var import_obsidian7 = require("obsidian");
var EmbedQueue = class extends import_obsidian7.Component {
  constructor(vault, concurrency) {
    super();
    this.vault = vault;
    this.concurrency = concurrency;
    /** Set of pending loads. */
    this.queue = new import_queue2.Queue();
    /** Set of promises waiting on each path. */
    this.promises = /* @__PURE__ */ new Map();
    /** Active set of loads. */
    this.active = /* @__PURE__ */ new Map();
    /** If true, prevent any further loads. */
    this.shutdown = false;
  }
  /** Read a file asynchronously, controlling concurrency to prevent too many files being loaded simultaneously. */
  async read(file) {
    if (this.shutdown)
      return Promise.reject("Embed queue is shutdown.");
    const promise = deferred();
    if (!this.promises.has(file.path)) {
      this.queue.push(file);
      this.promises.set(file.path, [promise]);
    } else {
      this.promises.get(file.path).push(promise);
    }
    this.schedule();
    return promise;
  }
  /** Schedule more loads from the queue into the active set if there is available space. */
  schedule() {
    while (this.active.size < this.concurrency() && this.queue.size() > 0) {
      const file = this.queue.pop();
      const read = this.vault.cachedRead(file);
      this.active.set(file.path, read);
      this.run(file, read);
    }
  }
  /** Wait on the read promise and then finish the load, catching errors. */
  async run(file, data) {
    try {
      const content = await data;
      this.finish(file, Result.success(content));
    } catch (error) {
      this.finish(file, Result.failure(error));
    }
  }
  /** Communicate the result of a loaded file and then schedule more files to be loaded. */
  finish(file, result) {
    var _a;
    this.active.delete(file.path);
    const promises = (_a = this.promises.get(file.path)) != null ? _a : [];
    this.promises.delete(file.path);
    if (result.successful) {
      promises.forEach((promise) => promise.resolve(result.value));
    } else {
      promises.forEach((promise) => promise.reject(result.error));
    }
    this.schedule();
  }
  /** Cancell all outstanding loads on unload. */
  onunload() {
    for (const promises of this.promises.values()) {
      promises.forEach((promise) => promise.reject("Embed queue is shutting down."));
    }
    this.shutdown = true;
  }
};

// src/index/types/canvas.ts
var _Canvas = class {
  constructor(init) {
    this.$types = _Canvas.TYPES;
    this.$typename = "Canvas";
    /** File extension - for canvas files, generally always 'canvas'. */
    this.$extension = "canvas";
    this.$cards = [];
    this.$size = 0;
    Object.assign(this, init);
  }
  /** The full path of the canvas file. */
  get $file() {
    return this.$path;
  }
  get $id() {
    return this.$path;
  }
  /** A link object pointing to the canvas file. */
  get $link() {
    return Link.file(this.$path);
  }
  get fields() {
    return _Canvas.FIELD_DEF(this);
  }
  field(key) {
    var _a;
    return (_a = _Canvas.FIELD_DEF(this, key)) == null ? void 0 : _a[0];
  }
  json() {
    return {
      $cards: this.$cards.map((x4) => x4.json()),
      $ctime: this.$ctime.toMillis(),
      $mtime: this.$mtime.toMillis(),
      $size: this.$size,
      $links: this.$links,
      $path: this.$path,
      $infields: mapObjectValues(this.$infields, jsonInlineField),
      $tags: this.$tags
    };
  }
  static from(raw, normalizer = NOOP_NORMALIZER) {
    const cards = raw.$cards.map((s4) => {
      switch (s4.$type) {
        case "text-card":
          return CanvasTextCard.from(s4, raw.$path, normalizer);
        case "file-card":
          return CanvasFileCard.from(s4);
        case "web-card":
          return CanvasWebCard.from(s4, raw.$path);
      }
      return null;
    }).filter((x4) => !!x4);
    return new _Canvas({
      $cards: cards,
      $ctime: DateTime.fromMillis(raw.$ctime),
      $mtime: DateTime.fromMillis(raw.$mtime),
      $size: raw.$size,
      $extension: "canvas",
      $path: raw.$path,
      $links: raw.$links.map((l4) => normalizer(Link.fromObject(l4))),
      $infields: raw.$infields ? mapObjectValues(raw.$infields, (field) => normalizeLinks(valueInlineField(field), normalizer)) : {},
      $tags: raw.$tags
    });
  }
};
var Canvas = _Canvas;
Canvas.TYPES = [FILE_TYPE, "canvas", TAGGABLE_TYPE, LINKABLE_TYPE, FIELDBEARING_TYPE];
Canvas.FIELD_DEF = Extractors.merge(
  Extractors.inlineFields((f4) => f4.$infields),
  Extractors.intrinsics()
);
var BaseCanvasCard = class {
  constructor(init) {
    Object.assign(this, init);
  }
  get $link() {
    return Link.file(this.$file).withBlock(this.$id);
  }
  /** @internal */
  json() {
    const { $id, $position, $color, $dimensions, $file, $link } = this;
    return {
      $id,
      $position,
      $color,
      $dimensions,
      $file,
      $link: $link.toObject()
    };
  }
};
var _CanvasTextCard = class extends BaseCanvasCard {
  constructor(init) {
    super(init);
    this.$types = _CanvasTextCard.TYPES;
    this.$typename = "Text card";
    this.$type = "canvas-card";
  }
  get fields() {
    return _CanvasTextCard.FIELD_DEF(this);
  }
  field(key) {
    var _a;
    return (_a = _CanvasTextCard.FIELD_DEF(this, key)) == null ? void 0 : _a[0];
  }
  /** @internal */
  json() {
    return Object.assign(super.json(), {
      $infields: this.$infields,
      $links: this.$links,
      $tags: this.$tags,
      $type: "text-card",
      $sections: this.$sections.map((a3) => a3.json())
    });
  }
  /** @internal */
  static from(raw, file, normalizer = NOOP_NORMALIZER) {
    let $sections = raw.$sections.map((s4) => MarkdownSection.from(s4, file, normalizer));
    return new _CanvasTextCard({
      $file: file,
      $id: raw.$id,
      $sections,
      $links: raw.$links.map((l4) => normalizer(Link.fromObject(l4))),
      $dimensions: raw.$dimensions,
      $position: raw.$position,
      $frontmatter: raw.$frontmatter ? mapObjectValues(raw.$frontmatter, (fm) => normalizeLinks(valueFrontmatterEntry(fm), normalizer)) : void 0,
      $infields: raw.$infields ? mapObjectValues(raw.$infields, (field) => normalizeLinks(valueInlineField(field), normalizer)) : {},
      $tags: raw.$tags
    });
  }
};
var CanvasTextCard = _CanvasTextCard;
CanvasTextCard.TYPES = ["canvas-card", "markdown", "canvas-text-card", TAGGABLE_TYPE, LINKABLE_TYPE, FIELDBEARING_TYPE];
CanvasTextCard.FIELD_DEF = Extractors.merge(
  Extractors.intrinsics(),
  Extractors.inlineFields((f4) => f4.$infields),
  Extractors.frontmatter((f4) => f4.$frontmatter)
);
var _CanvasFileCard = class extends BaseCanvasCard {
  constructor(init) {
    super(init);
    this.$types = CanvasTextCard.TYPES;
    this.$typename = "File card";
    this.$type = "file-card";
  }
  /** @internal */
  json() {
    return Object.assign(super.json(), {
      $linkedFile: this.$linkedFile,
      $type: "file-card"
    });
  }
  /** @internal */
  static from(raw) {
    return new _CanvasFileCard({
      $file: raw.$file,
      $id: raw.$id,
      $position: raw.$position,
      $dimensions: raw.$dimensions,
      $linkedFile: raw.$linkedFile
    });
  }
};
var CanvasFileCard = _CanvasFileCard;
CanvasFileCard.TYPES = ["canvas-card", "markdown", "canvas-file-card", TAGGABLE_TYPE, LINKABLE_TYPE, FIELDBEARING_TYPE];
var _CanvasWebCard = class extends BaseCanvasCard {
  constructor(init) {
    super(init);
    this.$types = CanvasTextCard.TYPES;
    this.$type = "web-card";
    this.$typename = "Web card";
  }
  /** @internal */
  json() {
    return Object.assign(super.json(), {
      $url: this.$url,
      $type: "web-card"
    });
  }
  /** @internal */
  static from(raw, file) {
    return new _CanvasWebCard({
      $dimensions: raw.$dimensions,
      $position: raw.$position,
      $file: file,
      $id: raw.$id,
      $url: raw.$url
    });
  }
};
var CanvasWebCard = _CanvasWebCard;
CanvasWebCard.TYPES = ["canvas-card", "markdown", "canvas-web-card", TAGGABLE_TYPE, LINKABLE_TYPE, FIELDBEARING_TYPE];

// src/index/datacore.ts
var Datacore = class extends import_obsidian8.Component {
  constructor(app, version, settings) {
    super();
    this.app = app;
    this.version = version;
    this.settings = settings;
    this.vault = app.vault;
    this.metadataCache = app.metadataCache;
    this.persister = new LocalStorageCache("primary", version);
    this.events = new import_obsidian8.Events();
    this.datastore = new Datastore(app.vault, app.metadataCache, settings);
    this.initialized = false;
    this.addChild(
      this.importer = new FileImporter(app.vault, app.fileManager, app.metadataCache, () => {
        return {
          workers: settings.importerNumThreads,
          utilization: Math.max(0.1, Math.min(1, settings.importerUtilization))
        };
      })
    );
    this.addChild(this.reads = new EmbedQueue(app.vault, () => 8));
  }
  /** Obtain the current index revision, for determining if anything has changed. */
  get revision() {
    return this.datastore.revision;
  }
  /** Initialize datacore by scanning persisted caches and all available files, and queueing parses as needed. */
  initialize() {
    this.registerEvent(this.metadataCache.on("resolve", (file) => this.reload(file)));
    this.registerEvent(this.vault.on("rename", this.rename, this));
    this.registerEvent(
      this.vault.on("create", (file) => {
        if (!(file instanceof import_obsidian8.TFile))
          return;
        if (INDEXABLE_EXTENSIONS.has(file.extension.toLowerCase()))
          return;
        this.reload(file);
      })
    );
    this.registerEvent(
      this.vault.on("modify", (file) => {
        if (!(file instanceof import_obsidian8.TFile))
          return;
        if (INDEXABLE_EXTENSIONS.has(file.extension.toLowerCase()))
          return;
        this.reload(file);
      })
    );
    this.registerEvent(
      this.vault.on("delete", (file) => {
        if (!(file instanceof import_obsidian8.TFile))
          return;
        if (this.datastore.delete(file.path)) {
          this.trigger("update", this.revision);
        }
      })
    );
    this.index();
  }
  /** Clears all current state and caches and reindexes the entire vault from scratch. */
  async reindex() {
    this.initialized = false;
    this.datastore.clear();
    await this.persister.recreate();
    await this.index();
  }
  /** Indexes all documents in the vault. Wait on this if you want to wait for the whole index to be ready. */
  async index() {
    const init = this.initializer = new DatacoreInitializer(this);
    this.addChild(init);
    await init.finished();
    this.initialized = true;
    this.initializer = void 0;
    this.removeChild(init);
    this.datastore.touch();
    this.trigger("update", this.revision);
    this.trigger("initialized");
    const currentFiles = this.vault.getFiles().map((file) => file.path);
    this.persister.synchronize(currentFiles);
  }
  async rename(file, oldPath) {
    if (!(file instanceof import_obsidian8.TFile)) {
      return;
    }
    this.datastore.delete(oldPath);
    await this.reload(file);
    this.trigger("rename", file.path, oldPath);
  }
  /**
   * Read a file from the Obsidian cache efficiently, limiting the number of concurrent request and debouncing
   * multiple requests for the same file.
   */
  async read(file) {
    return this.reads.read(file);
  }
  /** Queue a file for reloading; this is done asynchronously in the background and may take a few seconds. */
  async reload(file) {
    if (!INDEXABLE_EXTENSIONS.has(file.extension)) {
      const result2 = new GenericFile(
        file.path,
        DateTime.fromMillis(file.stat.ctime),
        DateTime.fromMillis(file.stat.mtime),
        file.stat.size
      );
      this.datastore.store(result2);
      return result2;
    }
    const result = await this.importer.import(file);
    if (result.type === "error") {
      throw new Error(`Failed to import file '${file.name}': ${result.$error}`);
    } else if (result.type === "markdown") {
      const parsed = MarkdownPage.from(result.result, (link) => {
        const rpath = this.metadataCache.getFirstLinkpathDest(link.path, result.result.$path);
        if (rpath)
          return link.withPath(rpath.path);
        else
          return link;
      });
      this.storeMarkdown(parsed);
      this.persister.storeFile(parsed.$path, parsed.json());
      this.trigger("update", this.revision);
      return parsed;
    } else if (result.type === "canvas") {
      const parsed = Canvas.from(result.result, (link) => {
        const rpath = this.metadataCache.getFirstLinkpathDest(link.path, result.result.$path);
        if (rpath)
          return link.withPath(rpath.path);
        else
          return link;
      });
      this.storeCanvas(parsed);
      this.persister.storeFile(parsed.$path, parsed.json());
      this.trigger("update", this.revision);
      return parsed;
    }
    throw new Error("Encountered unrecognized import result type: " + result.type);
  }
  /** Store a canvas document. */
  storeCanvas(data) {
    this.datastore.store(data, (object, store) => {
      store(object.$cards, (card, store2) => {
        if (card instanceof CanvasTextCard) {
          store2(card.$sections, (section, store3) => {
            store3(section.$blocks, (block, store4) => {
              if (block instanceof MarkdownListBlock) {
                const storeRec = (item, store5) => store5(item.$elements, storeRec);
                store4(block.$elements, storeRec);
              }
            });
          });
        }
      });
    });
  }
  /** Store a markdown document. */
  storeMarkdown(data) {
    this.datastore.store(data, (object, store) => {
      store(object.$sections, (section, store2) => {
        store2(section.$blocks, (block, store3) => {
          if (block instanceof MarkdownListBlock) {
            const storeRec = (item, store4) => store4(item.$elements, storeRec);
            store3(block.$elements, storeRec);
          }
        });
      });
    });
  }
  on(evt, callback, context) {
    return this.events.on(evt, callback, context);
  }
  /** Unsubscribe from an event using the event and original callback. */
  off(evt, callback) {
    this.events.off(evt, callback);
  }
  /** Unsubscribe from an event using the event reference.  */
  offref(ref) {
    this.events.offref(ref);
  }
  /** Trigger an event. */
  trigger(evt, ...args) {
    this.events.trigger(evt, ...args);
  }
};
var _DatacoreInitializer = class extends import_obsidian8.Component {
  constructor(core) {
    super();
    this.core = core;
    this.active = false;
    this.queue = this.core.vault.getFiles();
    this.targetTotal = this.queue.length;
    this.files = this.queue.length;
    this.start = Date.now();
    this.current = [];
    this.done = deferred();
    this.initialized = this.imported = this.skipped = this.cached = 0;
  }
  async onload() {
    this.active = true;
    this.runNext();
  }
  /** Promise which resolves when the initialization completes. */
  finished() {
    return this.done;
  }
  /** Cancel initialization. */
  onunload() {
    if (this.active) {
      this.active = false;
      this.done.reject("Initialization was cancelled before completing.");
    }
  }
  /** Poll for another task to execute from the queue. */
  runNext() {
    if (!this.active || this.current.length >= _DatacoreInitializer.BATCH_SIZE) {
      return;
    }
    const next2 = this.queue.pop();
    if (next2) {
      this.current.push(next2);
      (async () => {
        try {
          const result = await this.init(next2);
          this.handleResult(next2, result);
        } catch (error) {
          this.handleResult(next2, { status: "skipped" });
        }
      })();
      this.runNext();
    } else if (!next2 && this.current.length == 0) {
      this.active = false;
      this.done.resolve({
        durationMs: Date.now() - this.start,
        files: this.files,
        imported: this.imported,
        skipped: this.skipped,
        cached: this.cached
      });
    }
  }
  /** Process the result of an initialization and queue more runs. */
  handleResult(file, result) {
    this.current.remove(file);
    this.initialized++;
    if (result.status === "skipped")
      this.skipped++;
    else if (result.status === "imported")
      this.imported++;
    else if (result.status === "cached")
      this.cached++;
    this.runNext();
  }
  /** Initialize a specific file. */
  async init(file) {
    try {
      const cached = await this.core.persister.loadFile(file.path);
      if (cached && cached.time >= file.stat.mtime && cached.version == this.core.version) {
        if (file.extension === "md") {
          const data = MarkdownPage.from(cached.data, (link) => link);
          this.core.storeMarkdown(data);
          return { status: "cached" };
        }
      }
      await this.core.reload(file);
      return { status: "imported" };
    } catch (ex) {
      console.log("Datacore: Failed to import file: ", ex);
      return { status: "skipped" };
    }
  }
};
var DatacoreInitializer = _DatacoreInitializer;
/** Number of concurrent operations the initializer will perform. */
DatacoreInitializer.BATCH_SIZE = 8;

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

// src/settings.ts
var DEFAULT_SETTINGS = Object.freeze({
  importerNumThreads: 2,
  importerUtilization: 0.75,
  enableJs: false,
  defaultPagingEnabled: true,
  defaultPageSize: 50,
  scrollOnPageChange: false,
  maxRecursiveRenderDepth: 5,
  defaultDateFormat: "MMMM dd, yyyy",
  defaultDateTimeFormat: "h:mm a - MMMM dd, yyyy",
  renderNullAs: "-",
  indexInlineFields: true,
  indexListItems: true
});

// src/main.ts
var DatacorePlugin = class extends import_obsidian9.Plugin {
  async onload() {
    var _a;
    this.settings = Object.assign({}, DEFAULT_SETTINGS, (_a = await this.loadData()) != null ? _a : {});
    this.addSettingTab(new GeneralSettingsTab(this.app, this));
    this.addChild(this.core = new Datacore(this.app, this.manifest.version, this.settings));
    this.api = new DatacoreApi(this.core);
    this.registerMarkdownCodeBlockProcessor(
      "datacorejs",
      async (source, el, ctx) => this.api.executeJs(source, el, ctx, ctx.sourcePath),
      -100
    );
    this.registerMarkdownCodeBlockProcessor(
      "datacorejsx",
      async (source, el, ctx) => this.api.executeJsx(source, el, ctx, ctx.sourcePath),
      -100
    );
    this.registerMarkdownCodeBlockProcessor(
      "datacorets",
      async (source, el, ctx) => this.api.executeTs(source, el, ctx, ctx.sourcePath),
      -100
    );
    this.registerMarkdownCodeBlockProcessor(
      "datacoretsx",
      async (source, el, ctx) => this.api.executeTsx(source, el, ctx, ctx.sourcePath),
      -100
    );
    this.addCommand({
      id: "datacore-reindex-vault",
      name: "Reindex entire vault",
      callback: async () => {
        console.log("Datacore: dropping the datastore and reindexing all items.");
        await this.core.reindex();
      }
    });
    this.register(this.registerCodeblockHighlighting());
    this.app.workspace.onLayoutReady(async () => this.core.initialize());
    window.datacore = this.api;
  }
  /** Register codeblock highlighting and return a closure which unregisters. */
  registerCodeblockHighlighting() {
    window.CodeMirror.defineMode("datacorejs", (config) => window.CodeMirror.getMode(config, "javascript"));
    window.CodeMirror.defineMode("datacorejsx", (config) => window.CodeMirror.getMode(config, "jsx"));
    window.CodeMirror.defineMode("datacorets", (config) => window.CodeMirror.getMode(config, "text/typescript"));
    window.CodeMirror.defineMode(
      "datacoretsx",
      (config) => window.CodeMirror.getMode(config, "text/typescript-jsx")
    );
    return () => {
      window.CodeMirror.defineMode("datacorejs", (config) => window.CodeMirror.getMode(config, "null"));
      window.CodeMirror.defineMode("datacorejsx", (config) => window.CodeMirror.getMode(config, "null"));
      window.CodeMirror.defineMode("datacorets", (config) => window.CodeMirror.getMode(config, "null"));
      window.CodeMirror.defineMode("datacoretsx", (config) => window.CodeMirror.getMode(config, "null"));
    };
  }
  /** Update the given settings to new values. */
  async updateSettings(settings) {
    Object.assign(this.settings, settings);
    await this.saveData(this.settings);
  }
};
var GeneralSettingsTab = class extends import_obsidian9.PluginSettingTab {
  constructor(app, plugin) {
    super(app, plugin);
    this.plugin = plugin;
  }
  display() {
    this.containerEl.empty();
    new import_obsidian9.Setting(this.containerEl).setName("Views").setHeading();
    new import_obsidian9.Setting(this.containerEl).setName("Pagination").setDesc(
      "If enabled, splits up views into pages of results which can be traversed via buttons at the top and bottom of the view. This substantially improves the performance of large views, and can help with visual clutter. Note that this setting can also be set on a per-view basis."
    ).addToggle((toggle) => {
      toggle.setValue(this.plugin.settings.defaultPagingEnabled).onChange(async (value) => {
        await this.plugin.updateSettings({ defaultPagingEnabled: value });
      });
    });
    new import_obsidian9.Setting(this.containerEl).setName("Default page size").setDesc("The number of entries to show per page, by default. This can be overriden on a per-view basis.").addDropdown((dropdown) => {
      const OPTIONS = {
        "25": "25",
        "50": "50",
        "100": "100",
        "200": "200",
        "500": "500"
      };
      const current = "" + this.plugin.settings.defaultPageSize;
      if (!(current in OPTIONS))
        OPTIONS[current] = current;
      dropdown.addOptions(OPTIONS).setValue(current).onChange(async (value) => {
        const parsed = parseFloat(value);
        if (isNaN(parsed))
          return;
        await this.plugin.updateSettings({ defaultPageSize: parsed | 0 });
      });
    });
    new import_obsidian9.Setting(this.containerEl).setName("Scroll on page change").setDesc(
      "If enabled, table that are paged will scroll to the top of the table when the page changes. This can be overriden on a per-view basis."
    ).addToggle((toggle) => {
      toggle.setValue(this.plugin.settings.scrollOnPageChange).onChange(async (value) => {
        await this.plugin.updateSettings({ scrollOnPageChange: value });
      });
    });
    new import_obsidian9.Setting(this.containerEl).setName("Formatting").setHeading();
    new import_obsidian9.Setting(this.containerEl).setName("Empty values").setDesc("What to show for unset/empty properties.").addText((text) => {
      text.setValue(this.plugin.settings.renderNullAs).onChange(async (value) => {
        await this.plugin.updateSettings({ renderNullAs: value });
      });
    });
    new import_obsidian9.Setting(this.containerEl).setName("Default date format").setDesc(
      "The default format that dates are rendered in. Uses luxon date formatting (https://github.com/moment/luxon/blob/master/docs/formatting.md#formatting-with-tokens-strings-for-cthulhu)."
    ).addText((text) => {
      text.setValue(this.plugin.settings.defaultDateFormat).onChange(async (value) => {
        try {
          DateTime.fromMillis(Date.now()).toFormat(value);
        } catch (e3) {
          return;
        }
        await this.plugin.updateSettings({ defaultDateFormat: value });
      });
    });
    new import_obsidian9.Setting(this.containerEl).setName("Default date/time format").setDesc(
      "The default format that date-times are rendered in. Uses luxon date formatting (https://github.com/moment/luxon/blob/master/docs/formatting.md#formatting-with-tokens-strings-for-cthulhu)."
    ).addText((text) => {
      text.setValue(this.plugin.settings.defaultDateTimeFormat).onChange(async (value) => {
        try {
          DateTime.fromMillis(Date.now()).toFormat(value);
        } catch (e3) {
          return;
        }
        await this.plugin.updateSettings({ defaultDateTimeFormat: value });
      });
    });
    new import_obsidian9.Setting(this.containerEl).setName("Performance").setHeading();
    new import_obsidian9.Setting(this.containerEl).setName("Inline fields").setDesc(
      "If enabled, inline fields will be parsed in all documents. Finding inline fields requires a full text scan through each document, which noticably slows down indexing for large vaults. Disabling this functionality will mean metadata will only come from tags, links, and Properties / frontmatter"
    ).addToggle((toggle) => {
      toggle.setValue(this.plugin.settings.indexInlineFields).onChange(async (value) => {
        await this.plugin.updateSettings({ indexInlineFields: value });
      });
    });
    new import_obsidian9.Setting(this.containerEl).setName("Importer threads").setDesc("The number of importer threads to use for parsing metadata.").addText((text) => {
      text.setValue("" + this.plugin.settings.importerNumThreads).onChange(async (value) => {
        const parsed = parseInt(value);
        if (isNaN(parsed))
          return;
        await this.plugin.updateSettings({ importerNumThreads: parsed });
      });
    });
    new import_obsidian9.Setting(this.containerEl).setName("Importer utilization").setDesc("How much CPU time each importer thread should use, as a fraction (0.1 - 1.0).").addText((text) => {
      text.setValue(this.plugin.settings.importerUtilization.toFixed(2)).onChange(async (value) => {
        const parsed = parseFloat(value);
        if (isNaN(parsed))
          return;
        const limited = Math.max(0.1, Math.min(1, parsed));
        await this.plugin.updateSettings({ importerUtilization: limited });
      });
    });
    new import_obsidian9.Setting(this.containerEl).setName("Maximum recursive render depth").setDesc(
      "Maximum depth that objects will be rendered to (i.e., how many levels of subproperties will be rendered by default). This avoids infinite recursion due to self-referential objects and ensures that rendering objects is acceptably performant."
    ).addText((text) => {
      text.setValue(this.plugin.settings.maxRecursiveRenderDepth.toString()).onChange(async (value) => {
        const parsed = parseInt(value);
        if (isNaN(parsed))
          return;
        await this.plugin.updateSettings({ maxRecursiveRenderDepth: parsed });
      });
    });
  }
};
//! Utilities for running javascript.
//! Utilities for forcing types to be of a specific type or returning 'undefined' if not, allowing for much more concise typing.
//! Provides utilities for executing queries against the storage layer.
/*! Bundled license information:

localforage/dist/localforage.js:
  (*!
      localForage -- Offline Storage, Improved
      Version 1.10.0
      https://localforage.github.io/localForage
      (c) 2013-2017 Mozilla, Apache License 2.0
  *)

@datastructures-js/queue/src/queue.js:
  (**
   * @license MIT
   * @copyright 2020 Eyas Ranjous <eyas.ranjous@gmail.com>
   *
   * @class
   *)
*/


/* nosourcemap */
/* nosourcemap */