var Ar = Object.defineProperty;
var br = (n, e, t) => e in n ? Ar(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
var V = (n, e, t) => br(n, typeof e != "symbol" ? e + "" : e, t);
/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const Je = globalThis, Dt = Je.ShadowRoot && (Je.ShadyCSS === void 0 || Je.ShadyCSS.nativeShadow) && "adoptedStyleSheets" in Document.prototype && "replace" in CSSStyleSheet.prototype, Nt = Symbol(), qt = /* @__PURE__ */ new WeakMap();
let Ln = class {
  constructor(e, t, r) {
    if (this._$cssResult$ = !0, r !== Nt) throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");
    this.cssText = e, this.t = t;
  }
  get styleSheet() {
    let e = this.o;
    const t = this.t;
    if (Dt && e === void 0) {
      const r = t !== void 0 && t.length === 1;
      r && (e = qt.get(t)), e === void 0 && ((this.o = e = new CSSStyleSheet()).replaceSync(this.cssText), r && qt.set(t, e));
    }
    return e;
  }
  toString() {
    return this.cssText;
  }
};
const Er = (n) => new Ln(typeof n == "string" ? n : n + "", void 0, Nt), _r = (n, ...e) => {
  const t = n.length === 1 ? n[0] : e.reduce((r, s, i) => r + ((o) => {
    if (o._$cssResult$ === !0) return o.cssText;
    if (typeof o == "number") return o;
    throw Error("Value passed to 'css' function must be a 'css' function result: " + o + ". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.");
  })(s) + n[i + 1], n[0]);
  return new Ln(t, n, Nt);
}, Ir = (n, e) => {
  if (Dt) n.adoptedStyleSheets = e.map((t) => t instanceof CSSStyleSheet ? t : t.styleSheet);
  else for (const t of e) {
    const r = document.createElement("style"), s = Je.litNonce;
    s !== void 0 && r.setAttribute("nonce", s), r.textContent = t.cssText, n.appendChild(r);
  }
}, Jt = Dt ? (n) => n : (n) => n instanceof CSSStyleSheet ? ((e) => {
  let t = "";
  for (const r of e.cssRules) t += r.cssText;
  return Er(t);
})(n) : n;
/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const { is: Tr, defineProperty: Or, getOwnPropertyDescriptor: Dr, getOwnPropertyNames: Nr, getOwnPropertySymbols: $r, getPrototypeOf: Ur } = Object, pe = globalThis, Xt = pe.trustedTypes, Pr = Xt ? Xt.emptyScript : "", mt = pe.reactiveElementPolyfillSupport, Pe = (n, e) => n, Ze = { toAttribute(n, e) {
  switch (e) {
    case Boolean:
      n = n ? Pr : null;
      break;
    case Object:
    case Array:
      n = n == null ? n : JSON.stringify(n);
  }
  return n;
}, fromAttribute(n, e) {
  let t = n;
  switch (e) {
    case Boolean:
      t = n !== null;
      break;
    case Number:
      t = n === null ? null : Number(n);
      break;
    case Object:
    case Array:
      try {
        t = JSON.parse(n);
      } catch {
        t = null;
      }
  }
  return t;
} }, $t = (n, e) => !Tr(n, e), Zt = { attribute: !0, type: String, converter: Ze, reflect: !1, useDefault: !1, hasChanged: $t };
Symbol.metadata ?? (Symbol.metadata = Symbol("metadata")), pe.litPropertyMetadata ?? (pe.litPropertyMetadata = /* @__PURE__ */ new WeakMap());
let ve = class extends HTMLElement {
  static addInitializer(e) {
    this._$Ei(), (this.l ?? (this.l = [])).push(e);
  }
  static get observedAttributes() {
    return this.finalize(), this._$Eh && [...this._$Eh.keys()];
  }
  static createProperty(e, t = Zt) {
    if (t.state && (t.attribute = !1), this._$Ei(), this.prototype.hasOwnProperty(e) && ((t = Object.create(t)).wrapped = !0), this.elementProperties.set(e, t), !t.noAccessor) {
      const r = Symbol(), s = this.getPropertyDescriptor(e, r, t);
      s !== void 0 && Or(this.prototype, e, s);
    }
  }
  static getPropertyDescriptor(e, t, r) {
    const { get: s, set: i } = Dr(this.prototype, e) ?? { get() {
      return this[t];
    }, set(o) {
      this[t] = o;
    } };
    return { get: s, set(o) {
      const c = s == null ? void 0 : s.call(this);
      i == null || i.call(this, o), this.requestUpdate(e, c, r);
    }, configurable: !0, enumerable: !0 };
  }
  static getPropertyOptions(e) {
    return this.elementProperties.get(e) ?? Zt;
  }
  static _$Ei() {
    if (this.hasOwnProperty(Pe("elementProperties"))) return;
    const e = Ur(this);
    e.finalize(), e.l !== void 0 && (this.l = [...e.l]), this.elementProperties = new Map(e.elementProperties);
  }
  static finalize() {
    if (this.hasOwnProperty(Pe("finalized"))) return;
    if (this.finalized = !0, this._$Ei(), this.hasOwnProperty(Pe("properties"))) {
      const t = this.properties, r = [...Nr(t), ...$r(t)];
      for (const s of r) this.createProperty(s, t[s]);
    }
    const e = this[Symbol.metadata];
    if (e !== null) {
      const t = litPropertyMetadata.get(e);
      if (t !== void 0) for (const [r, s] of t) this.elementProperties.set(r, s);
    }
    this._$Eh = /* @__PURE__ */ new Map();
    for (const [t, r] of this.elementProperties) {
      const s = this._$Eu(t, r);
      s !== void 0 && this._$Eh.set(s, t);
    }
    this.elementStyles = this.finalizeStyles(this.styles);
  }
  static finalizeStyles(e) {
    const t = [];
    if (Array.isArray(e)) {
      const r = new Set(e.flat(1 / 0).reverse());
      for (const s of r) t.unshift(Jt(s));
    } else e !== void 0 && t.push(Jt(e));
    return t;
  }
  static _$Eu(e, t) {
    const r = t.attribute;
    return r === !1 ? void 0 : typeof r == "string" ? r : typeof e == "string" ? e.toLowerCase() : void 0;
  }
  constructor() {
    super(), this._$Ep = void 0, this.isUpdatePending = !1, this.hasUpdated = !1, this._$Em = null, this._$Ev();
  }
  _$Ev() {
    var e;
    this._$ES = new Promise((t) => this.enableUpdating = t), this._$AL = /* @__PURE__ */ new Map(), this._$E_(), this.requestUpdate(), (e = this.constructor.l) == null || e.forEach((t) => t(this));
  }
  addController(e) {
    var t;
    (this._$EO ?? (this._$EO = /* @__PURE__ */ new Set())).add(e), this.renderRoot !== void 0 && this.isConnected && ((t = e.hostConnected) == null || t.call(e));
  }
  removeController(e) {
    var t;
    (t = this._$EO) == null || t.delete(e);
  }
  _$E_() {
    const e = /* @__PURE__ */ new Map(), t = this.constructor.elementProperties;
    for (const r of t.keys()) this.hasOwnProperty(r) && (e.set(r, this[r]), delete this[r]);
    e.size > 0 && (this._$Ep = e);
  }
  createRenderRoot() {
    const e = this.shadowRoot ?? this.attachShadow(this.constructor.shadowRootOptions);
    return Ir(e, this.constructor.elementStyles), e;
  }
  connectedCallback() {
    var e;
    this.renderRoot ?? (this.renderRoot = this.createRenderRoot()), this.enableUpdating(!0), (e = this._$EO) == null || e.forEach((t) => {
      var r;
      return (r = t.hostConnected) == null ? void 0 : r.call(t);
    });
  }
  enableUpdating(e) {
  }
  disconnectedCallback() {
    var e;
    (e = this._$EO) == null || e.forEach((t) => {
      var r;
      return (r = t.hostDisconnected) == null ? void 0 : r.call(t);
    });
  }
  attributeChangedCallback(e, t, r) {
    this._$AK(e, r);
  }
  _$ET(e, t) {
    var i;
    const r = this.constructor.elementProperties.get(e), s = this.constructor._$Eu(e, r);
    if (s !== void 0 && r.reflect === !0) {
      const o = (((i = r.converter) == null ? void 0 : i.toAttribute) !== void 0 ? r.converter : Ze).toAttribute(t, r.type);
      this._$Em = e, o == null ? this.removeAttribute(s) : this.setAttribute(s, o), this._$Em = null;
    }
  }
  _$AK(e, t) {
    var i, o;
    const r = this.constructor, s = r._$Eh.get(e);
    if (s !== void 0 && this._$Em !== s) {
      const c = r.getPropertyOptions(s), a = typeof c.converter == "function" ? { fromAttribute: c.converter } : ((i = c.converter) == null ? void 0 : i.fromAttribute) !== void 0 ? c.converter : Ze;
      this._$Em = s;
      const l = a.fromAttribute(t, c.type);
      this[s] = l ?? ((o = this._$Ej) == null ? void 0 : o.get(s)) ?? l, this._$Em = null;
    }
  }
  requestUpdate(e, t, r) {
    var s;
    if (e !== void 0) {
      const i = this.constructor, o = this[e];
      if (r ?? (r = i.getPropertyOptions(e)), !((r.hasChanged ?? $t)(o, t) || r.useDefault && r.reflect && o === ((s = this._$Ej) == null ? void 0 : s.get(e)) && !this.hasAttribute(i._$Eu(e, r)))) return;
      this.C(e, t, r);
    }
    this.isUpdatePending === !1 && (this._$ES = this._$EP());
  }
  C(e, t, { useDefault: r, reflect: s, wrapped: i }, o) {
    r && !(this._$Ej ?? (this._$Ej = /* @__PURE__ */ new Map())).has(e) && (this._$Ej.set(e, o ?? t ?? this[e]), i !== !0 || o !== void 0) || (this._$AL.has(e) || (this.hasUpdated || r || (t = void 0), this._$AL.set(e, t)), s === !0 && this._$Em !== e && (this._$Eq ?? (this._$Eq = /* @__PURE__ */ new Set())).add(e));
  }
  async _$EP() {
    this.isUpdatePending = !0;
    try {
      await this._$ES;
    } catch (t) {
      Promise.reject(t);
    }
    const e = this.scheduleUpdate();
    return e != null && await e, !this.isUpdatePending;
  }
  scheduleUpdate() {
    return this.performUpdate();
  }
  performUpdate() {
    var r;
    if (!this.isUpdatePending) return;
    if (!this.hasUpdated) {
      if (this.renderRoot ?? (this.renderRoot = this.createRenderRoot()), this._$Ep) {
        for (const [i, o] of this._$Ep) this[i] = o;
        this._$Ep = void 0;
      }
      const s = this.constructor.elementProperties;
      if (s.size > 0) for (const [i, o] of s) {
        const { wrapped: c } = o, a = this[i];
        c !== !0 || this._$AL.has(i) || a === void 0 || this.C(i, void 0, o, a);
      }
    }
    let e = !1;
    const t = this._$AL;
    try {
      e = this.shouldUpdate(t), e ? (this.willUpdate(t), (r = this._$EO) == null || r.forEach((s) => {
        var i;
        return (i = s.hostUpdate) == null ? void 0 : i.call(s);
      }), this.update(t)) : this._$EM();
    } catch (s) {
      throw e = !1, this._$EM(), s;
    }
    e && this._$AE(t);
  }
  willUpdate(e) {
  }
  _$AE(e) {
    var t;
    (t = this._$EO) == null || t.forEach((r) => {
      var s;
      return (s = r.hostUpdated) == null ? void 0 : s.call(r);
    }), this.hasUpdated || (this.hasUpdated = !0, this.firstUpdated(e)), this.updated(e);
  }
  _$EM() {
    this._$AL = /* @__PURE__ */ new Map(), this.isUpdatePending = !1;
  }
  get updateComplete() {
    return this.getUpdateComplete();
  }
  getUpdateComplete() {
    return this._$ES;
  }
  shouldUpdate(e) {
    return !0;
  }
  update(e) {
    this._$Eq && (this._$Eq = this._$Eq.forEach((t) => this._$ET(t, this[t]))), this._$EM();
  }
  updated(e) {
  }
  firstUpdated(e) {
  }
};
ve.elementStyles = [], ve.shadowRootOptions = { mode: "open" }, ve[Pe("elementProperties")] = /* @__PURE__ */ new Map(), ve[Pe("finalized")] = /* @__PURE__ */ new Map(), mt == null || mt({ ReactiveElement: ve }), (pe.reactiveElementVersions ?? (pe.reactiveElementVersions = [])).push("2.1.1");
/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const Re = globalThis, Qe = Re.trustedTypes, Qt = Qe ? Qe.createPolicy("lit-html", { createHTML: (n) => n }) : void 0, Bn = "$lit$", de = `lit$${Math.random().toFixed(9).slice(2)}$`, Fn = "?" + de, Rr = `<${Fn}>`, we = document, Me = () => we.createComment(""), Ce = (n) => n === null || typeof n != "object" && typeof n != "function", Ut = Array.isArray, kr = (n) => Ut(n) || typeof (n == null ? void 0 : n[Symbol.iterator]) == "function", St = `[ 	
\f\r]`, Ne = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g, en = /-->/g, tn = />/g, ye = RegExp(`>|${St}(?:([^\\s"'>=/]+)(${St}*=${St}*(?:[^ 	
\f\r"'\`<>=]|("|')|))|$)`, "g"), nn = /'/g, rn = /"/g, Vn = /^(?:script|style|textarea|title)$/i, zr = (n) => (e, ...t) => ({ _$litType$: n, strings: e, values: t }), ae = zr(1), be = Symbol.for("lit-noChange"), K = Symbol.for("lit-nothing"), sn = /* @__PURE__ */ new WeakMap(), me = we.createTreeWalker(we, 129);
function jn(n, e) {
  if (!Ut(n) || !n.hasOwnProperty("raw")) throw Error("invalid template strings array");
  return Qt !== void 0 ? Qt.createHTML(e) : e;
}
const Mr = (n, e) => {
  const t = n.length - 1, r = [];
  let s, i = e === 2 ? "<svg>" : e === 3 ? "<math>" : "", o = Ne;
  for (let c = 0; c < t; c++) {
    const a = n[c];
    let l, d, u = -1, h = 0;
    for (; h < a.length && (o.lastIndex = h, d = o.exec(a), d !== null); ) h = o.lastIndex, o === Ne ? d[1] === "!--" ? o = en : d[1] !== void 0 ? o = tn : d[2] !== void 0 ? (Vn.test(d[2]) && (s = RegExp("</" + d[2], "g")), o = ye) : d[3] !== void 0 && (o = ye) : o === ye ? d[0] === ">" ? (o = s ?? Ne, u = -1) : d[1] === void 0 ? u = -2 : (u = o.lastIndex - d[2].length, l = d[1], o = d[3] === void 0 ? ye : d[3] === '"' ? rn : nn) : o === rn || o === nn ? o = ye : o === en || o === tn ? o = Ne : (o = ye, s = void 0);
    const m = o === ye && n[c + 1].startsWith("/>") ? " " : "";
    i += o === Ne ? a + Rr : u >= 0 ? (r.push(l), a.slice(0, u) + Bn + a.slice(u) + de + m) : a + de + (u === -2 ? c : m);
  }
  return [jn(n, i + (n[t] || "<?>") + (e === 2 ? "</svg>" : e === 3 ? "</math>" : "")), r];
};
class Le {
  constructor({ strings: e, _$litType$: t }, r) {
    let s;
    this.parts = [];
    let i = 0, o = 0;
    const c = e.length - 1, a = this.parts, [l, d] = Mr(e, t);
    if (this.el = Le.createElement(l, r), me.currentNode = this.el.content, t === 2 || t === 3) {
      const u = this.el.content.firstChild;
      u.replaceWith(...u.childNodes);
    }
    for (; (s = me.nextNode()) !== null && a.length < c; ) {
      if (s.nodeType === 1) {
        if (s.hasAttributes()) for (const u of s.getAttributeNames()) if (u.endsWith(Bn)) {
          const h = d[o++], m = s.getAttribute(u).split(de), g = /([.?@])?(.*)/.exec(h);
          a.push({ type: 1, index: i, name: g[2], strings: m, ctor: g[1] === "." ? Lr : g[1] === "?" ? Br : g[1] === "@" ? Fr : nt }), s.removeAttribute(u);
        } else u.startsWith(de) && (a.push({ type: 6, index: i }), s.removeAttribute(u));
        if (Vn.test(s.tagName)) {
          const u = s.textContent.split(de), h = u.length - 1;
          if (h > 0) {
            s.textContent = Qe ? Qe.emptyScript : "";
            for (let m = 0; m < h; m++) s.append(u[m], Me()), me.nextNode(), a.push({ type: 2, index: ++i });
            s.append(u[h], Me());
          }
        }
      } else if (s.nodeType === 8) if (s.data === Fn) a.push({ type: 2, index: i });
      else {
        let u = -1;
        for (; (u = s.data.indexOf(de, u + 1)) !== -1; ) a.push({ type: 7, index: i }), u += de.length - 1;
      }
      i++;
    }
  }
  static createElement(e, t) {
    const r = we.createElement("template");
    return r.innerHTML = e, r;
  }
}
function Ee(n, e, t = n, r) {
  var o, c;
  if (e === be) return e;
  let s = r !== void 0 ? (o = t._$Co) == null ? void 0 : o[r] : t._$Cl;
  const i = Ce(e) ? void 0 : e._$litDirective$;
  return (s == null ? void 0 : s.constructor) !== i && ((c = s == null ? void 0 : s._$AO) == null || c.call(s, !1), i === void 0 ? s = void 0 : (s = new i(n), s._$AT(n, t, r)), r !== void 0 ? (t._$Co ?? (t._$Co = []))[r] = s : t._$Cl = s), s !== void 0 && (e = Ee(n, s._$AS(n, e.values), s, r)), e;
}
class Cr {
  constructor(e, t) {
    this._$AV = [], this._$AN = void 0, this._$AD = e, this._$AM = t;
  }
  get parentNode() {
    return this._$AM.parentNode;
  }
  get _$AU() {
    return this._$AM._$AU;
  }
  u(e) {
    const { el: { content: t }, parts: r } = this._$AD, s = ((e == null ? void 0 : e.creationScope) ?? we).importNode(t, !0);
    me.currentNode = s;
    let i = me.nextNode(), o = 0, c = 0, a = r[0];
    for (; a !== void 0; ) {
      if (o === a.index) {
        let l;
        a.type === 2 ? l = new Ve(i, i.nextSibling, this, e) : a.type === 1 ? l = new a.ctor(i, a.name, a.strings, this, e) : a.type === 6 && (l = new Vr(i, this, e)), this._$AV.push(l), a = r[++c];
      }
      o !== (a == null ? void 0 : a.index) && (i = me.nextNode(), o++);
    }
    return me.currentNode = we, s;
  }
  p(e) {
    let t = 0;
    for (const r of this._$AV) r !== void 0 && (r.strings !== void 0 ? (r._$AI(e, r, t), t += r.strings.length - 2) : r._$AI(e[t])), t++;
  }
}
class Ve {
  get _$AU() {
    var e;
    return ((e = this._$AM) == null ? void 0 : e._$AU) ?? this._$Cv;
  }
  constructor(e, t, r, s) {
    this.type = 2, this._$AH = K, this._$AN = void 0, this._$AA = e, this._$AB = t, this._$AM = r, this.options = s, this._$Cv = (s == null ? void 0 : s.isConnected) ?? !0;
  }
  get parentNode() {
    let e = this._$AA.parentNode;
    const t = this._$AM;
    return t !== void 0 && (e == null ? void 0 : e.nodeType) === 11 && (e = t.parentNode), e;
  }
  get startNode() {
    return this._$AA;
  }
  get endNode() {
    return this._$AB;
  }
  _$AI(e, t = this) {
    e = Ee(this, e, t), Ce(e) ? e === K || e == null || e === "" ? (this._$AH !== K && this._$AR(), this._$AH = K) : e !== this._$AH && e !== be && this._(e) : e._$litType$ !== void 0 ? this.$(e) : e.nodeType !== void 0 ? this.T(e) : kr(e) ? this.k(e) : this._(e);
  }
  O(e) {
    return this._$AA.parentNode.insertBefore(e, this._$AB);
  }
  T(e) {
    this._$AH !== e && (this._$AR(), this._$AH = this.O(e));
  }
  _(e) {
    this._$AH !== K && Ce(this._$AH) ? this._$AA.nextSibling.data = e : this.T(we.createTextNode(e)), this._$AH = e;
  }
  $(e) {
    var i;
    const { values: t, _$litType$: r } = e, s = typeof r == "number" ? this._$AC(e) : (r.el === void 0 && (r.el = Le.createElement(jn(r.h, r.h[0]), this.options)), r);
    if (((i = this._$AH) == null ? void 0 : i._$AD) === s) this._$AH.p(t);
    else {
      const o = new Cr(s, this), c = o.u(this.options);
      o.p(t), this.T(c), this._$AH = o;
    }
  }
  _$AC(e) {
    let t = sn.get(e.strings);
    return t === void 0 && sn.set(e.strings, t = new Le(e)), t;
  }
  k(e) {
    Ut(this._$AH) || (this._$AH = [], this._$AR());
    const t = this._$AH;
    let r, s = 0;
    for (const i of e) s === t.length ? t.push(r = new Ve(this.O(Me()), this.O(Me()), this, this.options)) : r = t[s], r._$AI(i), s++;
    s < t.length && (this._$AR(r && r._$AB.nextSibling, s), t.length = s);
  }
  _$AR(e = this._$AA.nextSibling, t) {
    var r;
    for ((r = this._$AP) == null ? void 0 : r.call(this, !1, !0, t); e !== this._$AB; ) {
      const s = e.nextSibling;
      e.remove(), e = s;
    }
  }
  setConnected(e) {
    var t;
    this._$AM === void 0 && (this._$Cv = e, (t = this._$AP) == null || t.call(this, e));
  }
}
class nt {
  get tagName() {
    return this.element.tagName;
  }
  get _$AU() {
    return this._$AM._$AU;
  }
  constructor(e, t, r, s, i) {
    this.type = 1, this._$AH = K, this._$AN = void 0, this.element = e, this.name = t, this._$AM = s, this.options = i, r.length > 2 || r[0] !== "" || r[1] !== "" ? (this._$AH = Array(r.length - 1).fill(new String()), this.strings = r) : this._$AH = K;
  }
  _$AI(e, t = this, r, s) {
    const i = this.strings;
    let o = !1;
    if (i === void 0) e = Ee(this, e, t, 0), o = !Ce(e) || e !== this._$AH && e !== be, o && (this._$AH = e);
    else {
      const c = e;
      let a, l;
      for (e = i[0], a = 0; a < i.length - 1; a++) l = Ee(this, c[r + a], t, a), l === be && (l = this._$AH[a]), o || (o = !Ce(l) || l !== this._$AH[a]), l === K ? e = K : e !== K && (e += (l ?? "") + i[a + 1]), this._$AH[a] = l;
    }
    o && !s && this.j(e);
  }
  j(e) {
    e === K ? this.element.removeAttribute(this.name) : this.element.setAttribute(this.name, e ?? "");
  }
}
class Lr extends nt {
  constructor() {
    super(...arguments), this.type = 3;
  }
  j(e) {
    this.element[this.name] = e === K ? void 0 : e;
  }
}
class Br extends nt {
  constructor() {
    super(...arguments), this.type = 4;
  }
  j(e) {
    this.element.toggleAttribute(this.name, !!e && e !== K);
  }
}
class Fr extends nt {
  constructor(e, t, r, s, i) {
    super(e, t, r, s, i), this.type = 5;
  }
  _$AI(e, t = this) {
    if ((e = Ee(this, e, t, 0) ?? K) === be) return;
    const r = this._$AH, s = e === K && r !== K || e.capture !== r.capture || e.once !== r.once || e.passive !== r.passive, i = e !== K && (r === K || s);
    s && this.element.removeEventListener(this.name, this, r), i && this.element.addEventListener(this.name, this, e), this._$AH = e;
  }
  handleEvent(e) {
    var t;
    typeof this._$AH == "function" ? this._$AH.call(((t = this.options) == null ? void 0 : t.host) ?? this.element, e) : this._$AH.handleEvent(e);
  }
}
class Vr {
  constructor(e, t, r) {
    this.element = e, this.type = 6, this._$AN = void 0, this._$AM = t, this.options = r;
  }
  get _$AU() {
    return this._$AM._$AU;
  }
  _$AI(e) {
    Ee(this, e);
  }
}
const wt = Re.litHtmlPolyfillSupport;
wt == null || wt(Le, Ve), (Re.litHtmlVersions ?? (Re.litHtmlVersions = [])).push("3.3.1");
const jr = (n, e, t) => {
  const r = (t == null ? void 0 : t.renderBefore) ?? e;
  let s = r._$litPart$;
  if (s === void 0) {
    const i = (t == null ? void 0 : t.renderBefore) ?? null;
    r._$litPart$ = s = new Ve(e.insertBefore(Me(), i), i, void 0, t ?? {});
  }
  return s._$AI(n), s;
};
/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const Se = globalThis;
class ke extends ve {
  constructor() {
    super(...arguments), this.renderOptions = { host: this }, this._$Do = void 0;
  }
  createRenderRoot() {
    var t;
    const e = super.createRenderRoot();
    return (t = this.renderOptions).renderBefore ?? (t.renderBefore = e.firstChild), e;
  }
  update(e) {
    const t = this.render();
    this.hasUpdated || (this.renderOptions.isConnected = this.isConnected), super.update(e), this._$Do = jr(t, this.renderRoot, this.renderOptions);
  }
  connectedCallback() {
    var e;
    super.connectedCallback(), (e = this._$Do) == null || e.setConnected(!0);
  }
  disconnectedCallback() {
    var e;
    super.disconnectedCallback(), (e = this._$Do) == null || e.setConnected(!1);
  }
  render() {
    return be;
  }
}
var Cn;
ke._$litElement$ = !0, ke.finalized = !0, (Cn = Se.litElementHydrateSupport) == null || Cn.call(Se, { LitElement: ke });
const xt = Se.litElementPolyfillSupport;
xt == null || xt({ LitElement: ke });
(Se.litElementVersions ?? (Se.litElementVersions = [])).push("4.2.1");
/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const Hr = (n) => (e, t) => {
  t !== void 0 ? t.addInitializer(() => {
    customElements.define(n, e);
  }) : customElements.define(n, e);
};
/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const Wr = { attribute: !0, type: String, converter: Ze, reflect: !1, hasChanged: $t }, Yr = (n = Wr, e, t) => {
  const { kind: r, metadata: s } = t;
  let i = globalThis.litPropertyMetadata.get(s);
  if (i === void 0 && globalThis.litPropertyMetadata.set(s, i = /* @__PURE__ */ new Map()), r === "setter" && ((n = Object.create(n)).wrapped = !0), i.set(t.name, n), r === "accessor") {
    const { name: o } = t;
    return { set(c) {
      const a = e.get.call(this);
      e.set.call(this, c), this.requestUpdate(o, a, n);
    }, init(c) {
      return c !== void 0 && this.C(o, void 0, n, c), c;
    } };
  }
  if (r === "setter") {
    const { name: o } = t;
    return function(c) {
      const a = this[o];
      e.call(this, c), this.requestUpdate(o, a, n);
    };
  }
  throw Error("Unsupported decorator location: " + r);
};
function xe(n) {
  return (e, t) => typeof t == "object" ? Yr(n, e, t) : ((r, s, i) => {
    const o = s.hasOwnProperty(i);
    return s.constructor.createProperty(i, r), o ? Object.getOwnPropertyDescriptor(s, i) : void 0;
  })(n, e, t);
}
/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
function je(n) {
  return xe({ ...n, state: !0, attribute: !1 });
}
/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const Kr = (n, e, t) => (t.configurable = !0, t.enumerable = !0, Reflect.decorate && typeof e != "object" && Object.defineProperty(n, e, t), t);
/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
function Hn(n, e) {
  return (t, r, s) => {
    const i = (o) => {
      var c;
      return ((c = o.renderRoot) == null ? void 0 : c.querySelector(n)) ?? null;
    };
    return Kr(t, r, { get() {
      return i(this);
    } });
  };
}
new TextEncoder();
const Gr = 4096;
function Wn(n, e, t) {
  let r = e;
  const s = r + t, i = [];
  let o = "";
  for (; r < s; ) {
    const c = n[r++];
    if (!(c & 128))
      i.push(c);
    else if ((c & 224) === 192) {
      const a = n[r++] & 63;
      i.push((c & 31) << 6 | a);
    } else if ((c & 240) === 224) {
      const a = n[r++] & 63, l = n[r++] & 63;
      i.push((c & 31) << 12 | a << 6 | l);
    } else if ((c & 248) === 240) {
      const a = n[r++] & 63, l = n[r++] & 63, d = n[r++] & 63;
      let u = (c & 7) << 18 | a << 12 | l << 6 | d;
      u > 65535 && (u -= 65536, i.push(u >>> 10 & 1023 | 55296), u = 56320 | u & 1023), i.push(u);
    } else
      i.push(c);
    i.length >= Gr && (o += String.fromCharCode(...i), i.length = 0);
  }
  return i.length > 0 && (o += String.fromCharCode(...i)), o;
}
const qr = new TextDecoder(), Jr = 200;
function Xr(n, e, t) {
  const r = n.subarray(e, e + t);
  return qr.decode(r);
}
function Zr(n, e, t) {
  return t > Jr ? Xr(n, e, t) : Wn(n, e, t);
}
class Ke {
  constructor(e, t) {
    this.type = e, this.data = t;
  }
}
class ee extends Error {
  constructor(e) {
    super(e);
    const t = Object.create(ee.prototype);
    Object.setPrototypeOf(this, t), Object.defineProperty(this, "name", {
      configurable: !0,
      enumerable: !1,
      value: ee.name
    });
  }
}
const $e = 4294967295;
function Qr(n, e, t) {
  const r = Math.floor(t / 4294967296), s = t;
  n.setUint32(e, r), n.setUint32(e + 4, s);
}
function Yn(n, e) {
  const t = n.getInt32(e), r = n.getUint32(e + 4);
  return t * 4294967296 + r;
}
function es(n, e) {
  const t = n.getUint32(e), r = n.getUint32(e + 4);
  return t * 4294967296 + r;
}
const ts = -1, ns = 4294967296 - 1, rs = 17179869184 - 1;
function ss({ sec: n, nsec: e }) {
  if (n >= 0 && e >= 0 && n <= rs)
    if (e === 0 && n <= ns) {
      const t = new Uint8Array(4);
      return new DataView(t.buffer).setUint32(0, n), t;
    } else {
      const t = n / 4294967296, r = n & 4294967295, s = new Uint8Array(8), i = new DataView(s.buffer);
      return i.setUint32(0, e << 2 | t & 3), i.setUint32(4, r), s;
    }
  else {
    const t = new Uint8Array(12), r = new DataView(t.buffer);
    return r.setUint32(0, e), Qr(r, 4, n), t;
  }
}
function is(n) {
  const e = n.getTime(), t = Math.floor(e / 1e3), r = (e - t * 1e3) * 1e6, s = Math.floor(r / 1e9);
  return {
    sec: t + s,
    nsec: r - s * 1e9
  };
}
function os(n) {
  if (n instanceof Date) {
    const e = is(n);
    return ss(e);
  } else
    return null;
}
function cs(n) {
  const e = new DataView(n.buffer, n.byteOffset, n.byteLength);
  switch (n.byteLength) {
    case 4:
      return { sec: e.getUint32(0), nsec: 0 };
    case 8: {
      const t = e.getUint32(0), r = e.getUint32(4), s = (t & 3) * 4294967296 + r, i = t >>> 2;
      return { sec: s, nsec: i };
    }
    case 12: {
      const t = Yn(e, 4), r = e.getUint32(0);
      return { sec: t, nsec: r };
    }
    default:
      throw new ee(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${n.length}`);
  }
}
function as(n) {
  const e = cs(n);
  return new Date(e.sec * 1e3 + e.nsec / 1e6);
}
const ls = {
  type: ts,
  encode: os,
  decode: as
};
class It {
  constructor() {
    this.builtInEncoders = [], this.builtInDecoders = [], this.encoders = [], this.decoders = [], this.register(ls);
  }
  register({ type: e, encode: t, decode: r }) {
    if (e >= 0)
      this.encoders[e] = t, this.decoders[e] = r;
    else {
      const s = -1 - e;
      this.builtInEncoders[s] = t, this.builtInDecoders[s] = r;
    }
  }
  tryToEncode(e, t) {
    for (let r = 0; r < this.builtInEncoders.length; r++) {
      const s = this.builtInEncoders[r];
      if (s != null) {
        const i = s(e, t);
        if (i != null) {
          const o = -1 - r;
          return new Ke(o, i);
        }
      }
    }
    for (let r = 0; r < this.encoders.length; r++) {
      const s = this.encoders[r];
      if (s != null) {
        const i = s(e, t);
        if (i != null) {
          const o = r;
          return new Ke(o, i);
        }
      }
    }
    return e instanceof Ke ? e : null;
  }
  decode(e, t, r) {
    const s = t < 0 ? this.builtInDecoders[-1 - t] : this.decoders[t];
    return s ? s(e, t, r) : new Ke(t, e);
  }
}
It.defaultCodec = new It();
function fs(n) {
  return n instanceof ArrayBuffer || typeof SharedArrayBuffer < "u" && n instanceof SharedArrayBuffer;
}
function on(n) {
  return n instanceof Uint8Array ? n : ArrayBuffer.isView(n) ? new Uint8Array(n.buffer, n.byteOffset, n.byteLength) : fs(n) ? new Uint8Array(n) : Uint8Array.from(n);
}
function vt(n) {
  return `${n < 0 ? "-" : ""}0x${Math.abs(n).toString(16).padStart(2, "0")}`;
}
const us = 16, ds = 16;
class hs {
  constructor(e = us, t = ds) {
    this.hit = 0, this.miss = 0, this.maxKeyLength = e, this.maxLengthPerKey = t, this.caches = [];
    for (let r = 0; r < this.maxKeyLength; r++)
      this.caches.push([]);
  }
  canBeCached(e) {
    return e > 0 && e <= this.maxKeyLength;
  }
  find(e, t, r) {
    const s = this.caches[r - 1];
    e: for (const i of s) {
      const o = i.bytes;
      for (let c = 0; c < r; c++)
        if (o[c] !== e[t + c])
          continue e;
      return i.str;
    }
    return null;
  }
  store(e, t) {
    const r = this.caches[e.length - 1], s = { bytes: e, str: t };
    r.length >= this.maxLengthPerKey ? r[Math.random() * r.length | 0] = s : r.push(s);
  }
  decode(e, t, r) {
    const s = this.find(e, t, r);
    if (s != null)
      return this.hit++, s;
    this.miss++;
    const i = Wn(e, t, r), o = Uint8Array.prototype.slice.call(e, t, t + r);
    return this.store(o, i), i;
  }
}
const Tt = "array", ze = "map_key", Kn = "map_value", ps = (n) => {
  if (typeof n == "string" || typeof n == "number")
    return n;
  throw new ee("The type of key must be string or number but " + typeof n);
};
class gs {
  constructor() {
    this.stack = [], this.stackHeadPosition = -1;
  }
  get length() {
    return this.stackHeadPosition + 1;
  }
  top() {
    return this.stack[this.stackHeadPosition];
  }
  pushArrayState(e) {
    const t = this.getUninitializedStateFromPool();
    t.type = Tt, t.position = 0, t.size = e, t.array = new Array(e);
  }
  pushMapState(e) {
    const t = this.getUninitializedStateFromPool();
    t.type = ze, t.readCount = 0, t.size = e, t.map = {};
  }
  getUninitializedStateFromPool() {
    if (this.stackHeadPosition++, this.stackHeadPosition === this.stack.length) {
      const e = {
        type: void 0,
        size: 0,
        array: void 0,
        position: 0,
        readCount: 0,
        map: void 0,
        key: null
      };
      this.stack.push(e);
    }
    return this.stack[this.stackHeadPosition];
  }
  release(e) {
    if (this.stack[this.stackHeadPosition] !== e)
      throw new Error("Invalid stack state. Released state is not on top of the stack.");
    if (e.type === Tt) {
      const r = e;
      r.size = 0, r.array = void 0, r.position = 0, r.type = void 0;
    }
    if (e.type === ze || e.type === Kn) {
      const r = e;
      r.size = 0, r.map = void 0, r.readCount = 0, r.type = void 0;
    }
    this.stackHeadPosition--;
  }
  reset() {
    this.stack.length = 0, this.stackHeadPosition = -1;
  }
}
const Ue = -1, Pt = new DataView(new ArrayBuffer(0)), ys = new Uint8Array(Pt.buffer);
try {
  Pt.getInt8(0);
} catch (n) {
  if (!(n instanceof RangeError))
    throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access");
}
const cn = new RangeError("Insufficient data"), ms = new hs();
class Rt {
  constructor(e) {
    this.totalPos = 0, this.pos = 0, this.view = Pt, this.bytes = ys, this.headByte = Ue, this.stack = new gs(), this.entered = !1, this.extensionCodec = (e == null ? void 0 : e.extensionCodec) ?? It.defaultCodec, this.context = e == null ? void 0 : e.context, this.useBigInt64 = (e == null ? void 0 : e.useBigInt64) ?? !1, this.rawStrings = (e == null ? void 0 : e.rawStrings) ?? !1, this.maxStrLength = (e == null ? void 0 : e.maxStrLength) ?? $e, this.maxBinLength = (e == null ? void 0 : e.maxBinLength) ?? $e, this.maxArrayLength = (e == null ? void 0 : e.maxArrayLength) ?? $e, this.maxMapLength = (e == null ? void 0 : e.maxMapLength) ?? $e, this.maxExtLength = (e == null ? void 0 : e.maxExtLength) ?? $e, this.keyDecoder = (e == null ? void 0 : e.keyDecoder) !== void 0 ? e.keyDecoder : ms, this.mapKeyConverter = (e == null ? void 0 : e.mapKeyConverter) ?? ps;
  }
  clone() {
    return new Rt({
      extensionCodec: this.extensionCodec,
      context: this.context,
      useBigInt64: this.useBigInt64,
      rawStrings: this.rawStrings,
      maxStrLength: this.maxStrLength,
      maxBinLength: this.maxBinLength,
      maxArrayLength: this.maxArrayLength,
      maxMapLength: this.maxMapLength,
      maxExtLength: this.maxExtLength,
      keyDecoder: this.keyDecoder
    });
  }
  reinitializeState() {
    this.totalPos = 0, this.headByte = Ue, this.stack.reset();
  }
  setBuffer(e) {
    const t = on(e);
    this.bytes = t, this.view = new DataView(t.buffer, t.byteOffset, t.byteLength), this.pos = 0;
  }
  appendBuffer(e) {
    if (this.headByte === Ue && !this.hasRemaining(1))
      this.setBuffer(e);
    else {
      const t = this.bytes.subarray(this.pos), r = on(e), s = new Uint8Array(t.length + r.length);
      s.set(t), s.set(r, t.length), this.setBuffer(s);
    }
  }
  hasRemaining(e) {
    return this.view.byteLength - this.pos >= e;
  }
  createExtraByteError(e) {
    const { view: t, pos: r } = this;
    return new RangeError(`Extra ${t.byteLength - r} of ${t.byteLength} byte(s) found at buffer[${e}]`);
  }
  /**
   * @throws {@link DecodeError}
   * @throws {@link RangeError}
   */
  decode(e) {
    if (this.entered)
      return this.clone().decode(e);
    try {
      this.entered = !0, this.reinitializeState(), this.setBuffer(e);
      const t = this.doDecodeSync();
      if (this.hasRemaining(1))
        throw this.createExtraByteError(this.pos);
      return t;
    } finally {
      this.entered = !1;
    }
  }
  *decodeMulti(e) {
    if (this.entered) {
      yield* this.clone().decodeMulti(e);
      return;
    }
    try {
      for (this.entered = !0, this.reinitializeState(), this.setBuffer(e); this.hasRemaining(1); )
        yield this.doDecodeSync();
    } finally {
      this.entered = !1;
    }
  }
  async decodeAsync(e) {
    if (this.entered)
      return this.clone().decodeAsync(e);
    try {
      this.entered = !0;
      let t = !1, r;
      for await (const c of e) {
        if (t)
          throw this.entered = !1, this.createExtraByteError(this.totalPos);
        this.appendBuffer(c);
        try {
          r = this.doDecodeSync(), t = !0;
        } catch (a) {
          if (!(a instanceof RangeError))
            throw a;
        }
        this.totalPos += this.pos;
      }
      if (t) {
        if (this.hasRemaining(1))
          throw this.createExtraByteError(this.totalPos);
        return r;
      }
      const { headByte: s, pos: i, totalPos: o } = this;
      throw new RangeError(`Insufficient data in parsing ${vt(s)} at ${o} (${i} in the current buffer)`);
    } finally {
      this.entered = !1;
    }
  }
  decodeArrayStream(e) {
    return this.decodeMultiAsync(e, !0);
  }
  decodeStream(e) {
    return this.decodeMultiAsync(e, !1);
  }
  async *decodeMultiAsync(e, t) {
    if (this.entered) {
      yield* this.clone().decodeMultiAsync(e, t);
      return;
    }
    try {
      this.entered = !0;
      let r = t, s = -1;
      for await (const i of e) {
        if (t && s === 0)
          throw this.createExtraByteError(this.totalPos);
        this.appendBuffer(i), r && (s = this.readArraySize(), r = !1, this.complete());
        try {
          for (; yield this.doDecodeSync(), --s !== 0; )
            ;
        } catch (o) {
          if (!(o instanceof RangeError))
            throw o;
        }
        this.totalPos += this.pos;
      }
    } finally {
      this.entered = !1;
    }
  }
  doDecodeSync() {
    e: for (; ; ) {
      const e = this.readHeadByte();
      let t;
      if (e >= 224)
        t = e - 256;
      else if (e < 192)
        if (e < 128)
          t = e;
        else if (e < 144) {
          const s = e - 128;
          if (s !== 0) {
            this.pushMapState(s), this.complete();
            continue e;
          } else
            t = {};
        } else if (e < 160) {
          const s = e - 144;
          if (s !== 0) {
            this.pushArrayState(s), this.complete();
            continue e;
          } else
            t = [];
        } else {
          const s = e - 160;
          t = this.decodeString(s, 0);
        }
      else if (e === 192)
        t = null;
      else if (e === 194)
        t = !1;
      else if (e === 195)
        t = !0;
      else if (e === 202)
        t = this.readF32();
      else if (e === 203)
        t = this.readF64();
      else if (e === 204)
        t = this.readU8();
      else if (e === 205)
        t = this.readU16();
      else if (e === 206)
        t = this.readU32();
      else if (e === 207)
        this.useBigInt64 ? t = this.readU64AsBigInt() : t = this.readU64();
      else if (e === 208)
        t = this.readI8();
      else if (e === 209)
        t = this.readI16();
      else if (e === 210)
        t = this.readI32();
      else if (e === 211)
        this.useBigInt64 ? t = this.readI64AsBigInt() : t = this.readI64();
      else if (e === 217) {
        const s = this.lookU8();
        t = this.decodeString(s, 1);
      } else if (e === 218) {
        const s = this.lookU16();
        t = this.decodeString(s, 2);
      } else if (e === 219) {
        const s = this.lookU32();
        t = this.decodeString(s, 4);
      } else if (e === 220) {
        const s = this.readU16();
        if (s !== 0) {
          this.pushArrayState(s), this.complete();
          continue e;
        } else
          t = [];
      } else if (e === 221) {
        const s = this.readU32();
        if (s !== 0) {
          this.pushArrayState(s), this.complete();
          continue e;
        } else
          t = [];
      } else if (e === 222) {
        const s = this.readU16();
        if (s !== 0) {
          this.pushMapState(s), this.complete();
          continue e;
        } else
          t = {};
      } else if (e === 223) {
        const s = this.readU32();
        if (s !== 0) {
          this.pushMapState(s), this.complete();
          continue e;
        } else
          t = {};
      } else if (e === 196) {
        const s = this.lookU8();
        t = this.decodeBinary(s, 1);
      } else if (e === 197) {
        const s = this.lookU16();
        t = this.decodeBinary(s, 2);
      } else if (e === 198) {
        const s = this.lookU32();
        t = this.decodeBinary(s, 4);
      } else if (e === 212)
        t = this.decodeExtension(1, 0);
      else if (e === 213)
        t = this.decodeExtension(2, 0);
      else if (e === 214)
        t = this.decodeExtension(4, 0);
      else if (e === 215)
        t = this.decodeExtension(8, 0);
      else if (e === 216)
        t = this.decodeExtension(16, 0);
      else if (e === 199) {
        const s = this.lookU8();
        t = this.decodeExtension(s, 1);
      } else if (e === 200) {
        const s = this.lookU16();
        t = this.decodeExtension(s, 2);
      } else if (e === 201) {
        const s = this.lookU32();
        t = this.decodeExtension(s, 4);
      } else
        throw new ee(`Unrecognized type byte: ${vt(e)}`);
      this.complete();
      const r = this.stack;
      for (; r.length > 0; ) {
        const s = r.top();
        if (s.type === Tt)
          if (s.array[s.position] = t, s.position++, s.position === s.size)
            t = s.array, r.release(s);
          else
            continue e;
        else if (s.type === ze) {
          if (t === "__proto__")
            throw new ee("The key __proto__ is not allowed");
          s.key = this.mapKeyConverter(t), s.type = Kn;
          continue e;
        } else if (s.map[s.key] = t, s.readCount++, s.readCount === s.size)
          t = s.map, r.release(s);
        else {
          s.key = null, s.type = ze;
          continue e;
        }
      }
      return t;
    }
  }
  readHeadByte() {
    return this.headByte === Ue && (this.headByte = this.readU8()), this.headByte;
  }
  complete() {
    this.headByte = Ue;
  }
  readArraySize() {
    const e = this.readHeadByte();
    switch (e) {
      case 220:
        return this.readU16();
      case 221:
        return this.readU32();
      default: {
        if (e < 160)
          return e - 144;
        throw new ee(`Unrecognized array type byte: ${vt(e)}`);
      }
    }
  }
  pushMapState(e) {
    if (e > this.maxMapLength)
      throw new ee(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);
    this.stack.pushMapState(e);
  }
  pushArrayState(e) {
    if (e > this.maxArrayLength)
      throw new ee(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);
    this.stack.pushArrayState(e);
  }
  decodeString(e, t) {
    return !this.rawStrings || this.stateIsMapKey() ? this.decodeUtf8String(e, t) : this.decodeBinary(e, t);
  }
  /**
   * @throws {@link RangeError}
   */
  decodeUtf8String(e, t) {
    var i;
    if (e > this.maxStrLength)
      throw new ee(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);
    if (this.bytes.byteLength < this.pos + t + e)
      throw cn;
    const r = this.pos + t;
    let s;
    return this.stateIsMapKey() && ((i = this.keyDecoder) != null && i.canBeCached(e)) ? s = this.keyDecoder.decode(this.bytes, r, e) : s = Zr(this.bytes, r, e), this.pos += t + e, s;
  }
  stateIsMapKey() {
    return this.stack.length > 0 ? this.stack.top().type === ze : !1;
  }
  /**
   * @throws {@link RangeError}
   */
  decodeBinary(e, t) {
    if (e > this.maxBinLength)
      throw new ee(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);
    if (!this.hasRemaining(e + t))
      throw cn;
    const r = this.pos + t, s = this.bytes.subarray(r, r + e);
    return this.pos += t + e, s;
  }
  decodeExtension(e, t) {
    if (e > this.maxExtLength)
      throw new ee(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);
    const r = this.view.getInt8(this.pos + t), s = this.decodeBinary(
      e,
      t + 1
      /* extType */
    );
    return this.extensionCodec.decode(s, r, this.context);
  }
  lookU8() {
    return this.view.getUint8(this.pos);
  }
  lookU16() {
    return this.view.getUint16(this.pos);
  }
  lookU32() {
    return this.view.getUint32(this.pos);
  }
  readU8() {
    const e = this.view.getUint8(this.pos);
    return this.pos++, e;
  }
  readI8() {
    const e = this.view.getInt8(this.pos);
    return this.pos++, e;
  }
  readU16() {
    const e = this.view.getUint16(this.pos);
    return this.pos += 2, e;
  }
  readI16() {
    const e = this.view.getInt16(this.pos);
    return this.pos += 2, e;
  }
  readU32() {
    const e = this.view.getUint32(this.pos);
    return this.pos += 4, e;
  }
  readI32() {
    const e = this.view.getInt32(this.pos);
    return this.pos += 4, e;
  }
  readU64() {
    const e = es(this.view, this.pos);
    return this.pos += 8, e;
  }
  readI64() {
    const e = Yn(this.view, this.pos);
    return this.pos += 8, e;
  }
  readU64AsBigInt() {
    const e = this.view.getBigUint64(this.pos);
    return this.pos += 8, e;
  }
  readI64AsBigInt() {
    const e = this.view.getBigInt64(this.pos);
    return this.pos += 8, e;
  }
  readF32() {
    const e = this.view.getFloat32(this.pos);
    return this.pos += 4, e;
  }
  readF64() {
    const e = this.view.getFloat64(this.pos);
    return this.pos += 8, e;
  }
}
function Ss(n, e) {
  return new Rt(e).decode(n);
}
const Gn = {
  arabic: "ar",
  armenian: "am",
  bulgarian: "bg",
  czech: "cz",
  danish: "dk",
  dutch: "nl",
  english: "en",
  finnish: "fi",
  french: "fr",
  german: "de",
  greek: "gr",
  hungarian: "hu",
  indian: "in",
  indonesian: "id",
  irish: "ie",
  italian: "it",
  lithuanian: "lt",
  nepali: "np",
  norwegian: "no",
  portuguese: "pt",
  romanian: "ro",
  russian: "ru",
  serbian: "rs",
  slovenian: "ru",
  spanish: "es",
  swedish: "se",
  tamil: "ta",
  turkish: "tr",
  ukrainian: "uk",
  sanskrit: "sk"
}, ws = {
  dutch: /[^A-Za-zàèéìòóù0-9_'-]+/gim,
  english: /[^A-Za-zàèéìòóù0-9_'-]+/gim,
  french: /[^a-z0-9äâàéèëêïîöôùüûœç-]+/gim,
  italian: /[^A-Za-zàèéìòóù0-9_'-]+/gim,
  norwegian: /[^a-z0-9_æøåÆØÅäÄöÖüÜ]+/gim,
  portuguese: /[^a-z0-9à-úÀ-Ú]/gim,
  russian: /[^a-z0-9а-яА-ЯёЁ]+/gim,
  spanish: /[^a-z0-9A-Zá-úÁ-ÚñÑüÜ]+/gim,
  swedish: /[^a-z0-9_åÅäÄöÖüÜ-]+/gim,
  german: /[^a-z0-9A-ZäöüÄÖÜß]+/gim,
  finnish: /[^a-z0-9äöÄÖ]+/gim,
  danish: /[^a-z0-9æøåÆØÅ]+/gim,
  hungarian: /[^a-z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ]+/gim,
  romanian: /[^a-z0-9ăâîșțĂÂÎȘȚ]+/gim,
  serbian: /[^a-z0-9čćžšđČĆŽŠĐ]+/gim,
  turkish: /[^a-z0-9çÇğĞıİöÖşŞüÜ]+/gim,
  lithuanian: /[^a-z0-9ąčęėįšųūžĄČĘĖĮŠŲŪŽ]+/gim,
  arabic: /[^a-z0-9أ-ي]+/gim,
  nepali: /[^a-z0-9अ-ह]+/gim,
  irish: /[^a-z0-9áéíóúÁÉÍÓÚ]+/gim,
  indian: /[^a-z0-9अ-ह]+/gim,
  armenian: /[^a-z0-9ա-ֆ]+/gim,
  greek: /[^a-z0-9α-ωά-ώ]+/gim,
  indonesian: /[^a-z0-9]+/gim,
  ukrainian: /[^a-z0-9а-яА-ЯіїєІЇЄ]+/gim,
  slovenian: /[^a-z0-9čžšČŽŠ]+/gim,
  bulgarian: /[^a-z0-9а-яА-Я]+/gim,
  tamil: /[^a-z0-9அ-ஹ]+/gim,
  sanskrit: /[^a-z0-9A-Zāīūṛḷṃṁḥśṣṭḍṇṅñḻḹṝ]+/gim,
  czech: /[^A-Z0-9a-zěščřžýáíéúůóťďĚŠČŘŽÝÁÍÉÓÚŮŤĎ-]+/gim
}, kt = Object.keys(Gn);
function xs(n) {
  return n !== void 0 && kt.includes(n) ? Gn[n] : void 0;
}
const vs = Date.now().toString().slice(5);
let As = 0;
const an = BigInt(1e3), ln = BigInt(1e6), fn = BigInt(1e9), At = 65535;
function qn(n, e) {
  if (e.length < At)
    Array.prototype.push.apply(n, e);
  else {
    const t = e.length;
    for (let r = 0; r < t; r += At)
      Array.prototype.push.apply(n, e.slice(r, r + At));
  }
}
function bs(n, ...e) {
  return n.replace(/%(?:(?<position>\d+)\$)?(?<width>-?\d*\.?\d*)(?<type>[dfs])/g, function(...t) {
    const r = t[t.length - 1], { width: s, type: i, position: o } = r, c = o ? e[Number.parseInt(o) - 1] : e.shift(), a = s === "" ? 0 : Number.parseInt(s);
    switch (i) {
      case "d":
        return c.toString().padStart(a, "0");
      case "f": {
        let l = c;
        const [d, u] = s.split(".").map((h) => Number.parseFloat(h));
        return typeof u == "number" && u >= 0 && (l = l.toFixed(u)), typeof d == "number" && d >= 0 ? l.toString().padStart(a, "0") : l.toString();
      }
      case "s":
        return a < 0 ? c.toString().padEnd(-a, " ") : c.toString().padStart(a, " ");
      default:
        return c;
    }
  });
}
function Es() {
  return typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope;
}
function _s() {
  return typeof process < "u" && process.release && process.release.name === "node";
}
function un() {
  return BigInt(Math.floor(performance.now() * 1e6));
}
function zt(n) {
  return typeof n == "number" && (n = BigInt(n)), n < an ? `${n}ns` : n < ln ? `${n / an}μs` : n < fn ? `${n / ln}ms` : `${n / fn}s`;
}
function _e() {
  var n;
  return Es() ? un() : _s() || typeof process < "u" && typeof ((n = process == null ? void 0 : process.hrtime) == null ? void 0 : n.bigint) == "function" ? process.hrtime.bigint() : typeof performance < "u" ? un() : BigInt(0);
}
function Jn() {
  return `${vs}-${As++}`;
}
function bt(n, e) {
  return Object.hasOwn === void 0 ? Object.prototype.hasOwnProperty.call(n, e) ? n[e] : void 0 : Object.hasOwn(n, e) ? n[e] : void 0;
}
function Xn(n, e) {
  return e[1] === n[1] ? n[0] - e[0] : e[1] - n[1];
}
function Is(n) {
  if (n.length === 0)
    return [];
  if (n.length === 1)
    return n[0];
  for (let t = 1; t < n.length; t++)
    if (n[t].length < n[0].length) {
      const r = n[0];
      n[0] = n[t], n[t] = r;
    }
  const e = /* @__PURE__ */ new Map();
  for (const t of n[0])
    e.set(t, 1);
  for (let t = 1; t < n.length; t++) {
    let r = 0;
    for (const s of n[t]) {
      const i = e.get(s);
      i === t && (e.set(s, i + 1), r++);
    }
    if (r === 0)
      return [];
  }
  return n[0].filter((t) => {
    const r = e.get(t);
    return r !== void 0 && e.set(t, 0), r === n.length;
  });
}
function Zn(n, e) {
  const t = {}, r = e.length;
  for (let s = 0; s < r; s++) {
    const i = e[s], o = i.split(".");
    let c = n;
    const a = o.length;
    for (let l = 0; l < a; l++)
      if (c = c[o[l]], typeof c == "object") {
        if (c !== null && "lat" in c && "lon" in c && typeof c.lat == "number" && typeof c.lon == "number") {
          c = t[i] = c;
          break;
        } else if (!Array.isArray(c) && c !== null && l === a - 1) {
          c = void 0;
          break;
        }
      } else if ((c === null || typeof c != "object") && l < a - 1) {
        c = void 0;
        break;
      }
    typeof c < "u" && (t[i] = c);
  }
  return t;
}
function Mt(n, e) {
  return Zn(n, [e])[e];
}
const Ts = {
  cm: 0.01,
  m: 1,
  km: 1e3,
  ft: 0.3048,
  yd: 0.9144,
  mi: 1609.344
};
function Qn(n, e) {
  const t = Ts[e];
  if (t === void 0)
    throw new Error(C("INVALID_DISTANCE_SUFFIX", n).message);
  return n * t;
}
function er(n, e) {
  n.hits = n.hits.map((t) => ({
    ...t,
    document: {
      ...t.document,
      // Remove embeddings from the result
      ...e.reduce((r, s) => {
        const i = s.split("."), o = i.pop();
        let c = r;
        for (const a of i)
          c[a] = c[a] ?? {}, c = c[a];
        return c[o] = null, r;
      }, t.document)
    }
  }));
}
function rt(n) {
  var e;
  return Array.isArray(n) ? n.some((t) => rt(t)) : ((e = n == null ? void 0 : n.constructor) == null ? void 0 : e.name) === "AsyncFunction";
}
const dn = "intersection" in /* @__PURE__ */ new Set();
function hn(...n) {
  if (n.length === 0)
    return /* @__PURE__ */ new Set();
  if (n.length === 1)
    return n[0];
  if (n.length === 2) {
    const r = n[0], s = n[1];
    if (dn)
      return r.intersection(s);
    const i = /* @__PURE__ */ new Set(), o = r.size < s.size ? r : s, c = o === r ? s : r;
    for (const a of o)
      c.has(a) && i.add(a);
    return i;
  }
  const e = {
    index: 0,
    size: n[0].size
  };
  for (let r = 1; r < n.length; r++)
    n[r].size < e.size && (e.index = r, e.size = n[r].size);
  if (dn) {
    let r = n[e.index];
    for (let s = 0; s < n.length; s++)
      s !== e.index && (r = r.intersection(n[s]));
    return r;
  }
  const t = n[e.index];
  for (let r = 0; r < n.length; r++) {
    if (r === e.index)
      continue;
    const s = n[r];
    for (const i of t)
      s.has(i) || t.delete(i);
  }
  return t;
}
const Os = "union" in /* @__PURE__ */ new Set();
function Ge(n, e) {
  return Os ? n ? n.union(e) : e : n ? /* @__PURE__ */ new Set([...n, ...e]) : new Set(e);
}
function Ds(n, e) {
  const t = /* @__PURE__ */ new Set();
  for (const r of n)
    e.has(r) || t.add(r);
  return t;
}
const Ns = kt.join(`
 - `), $s = {
  NO_LANGUAGE_WITH_CUSTOM_TOKENIZER: "Do not pass the language option to create when using a custom tokenizer.",
  LANGUAGE_NOT_SUPPORTED: `Language "%s" is not supported.
Supported languages are:
 - ${Ns}`,
  INVALID_STEMMER_FUNCTION_TYPE: "config.stemmer property must be a function.",
  MISSING_STEMMER: 'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.orama.com/docs/orama-js/text-analysis/stemming for more information.',
  CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY: "Custom stop words array must only contain strings.",
  UNSUPPORTED_COMPONENT: 'Unsupported component "%s".',
  COMPONENT_MUST_BE_FUNCTION: 'The component "%s" must be a function.',
  COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS: 'The component "%s" must be a function or an array of functions.',
  INVALID_SCHEMA_TYPE: 'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',
  DOCUMENT_ID_MUST_BE_STRING: 'Document id must be of type "string". Got "%s" instead.',
  DOCUMENT_ALREADY_EXISTS: 'A document with id "%s" already exists.',
  DOCUMENT_DOES_NOT_EXIST: 'A document with id "%s" does not exists.',
  MISSING_DOCUMENT_PROPERTY: 'Missing searchable property "%s".',
  INVALID_DOCUMENT_PROPERTY: 'Invalid document property "%s": expected "%s", got "%s"',
  UNKNOWN_INDEX: 'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',
  INVALID_BOOST_VALUE: "Boost value must be a number greater than, or less than 0.",
  INVALID_FILTER_OPERATION: "You can only use one operation per filter, you requested %d.",
  SCHEMA_VALIDATION_FAILURE: 'Cannot insert document due schema validation failure on "%s" property.',
  INVALID_SORT_SCHEMA_TYPE: 'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',
  CANNOT_SORT_BY_ARRAY: 'Cannot configure sort for "%s" because it is an array (%s).',
  UNABLE_TO_SORT_ON_UNKNOWN_FIELD: 'Unable to sort on unknown field "%s". Allowed fields: %s',
  SORT_DISABLED: "Sort is disabled. Please read the documentation at https://docs.orama.com/docs/orama-js for more information.",
  UNKNOWN_GROUP_BY_PROPERTY: 'Unknown groupBy property "%s".',
  INVALID_GROUP_BY_PROPERTY: 'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',
  UNKNOWN_FILTER_PROPERTY: 'Unknown filter property "%s".',
  UNKNOWN_VECTOR_PROPERTY: 'Unknown vector property "%s". Make sure the property exists in the schema and is configured as a vector.',
  INVALID_VECTOR_SIZE: 'Vector size must be a number greater than 0. Got "%s" instead.',
  INVALID_VECTOR_VALUE: 'Vector value must be a number greater than 0. Got "%s" instead.',
  INVALID_INPUT_VECTOR: `Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,
  WRONG_SEARCH_PROPERTY_TYPE: 'Property "%s" is not searchable. Only "string" properties are searchable.',
  FACET_NOT_SUPPORTED: `Facet doens't support the type "%s".`,
  INVALID_DISTANCE_SUFFIX: 'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',
  INVALID_SEARCH_MODE: 'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',
  MISSING_VECTOR_AND_SECURE_PROXY: "No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",
  MISSING_TERM: '"term" is a required parameter when performing hybrid search. Please provide a search term.',
  INVALID_VECTOR_INPUT: 'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',
  PLUGIN_CRASHED: "A plugin crashed during initialization. Please check the error message for more information:",
  PLUGIN_SECURE_PROXY_NOT_FOUND: `Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.
Please install it before proceeding with creating an answer session.
Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#plugin-secure-proxy
`,
  PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL: `Could not find a chat model defined in the secure proxy plugin configuration.
Please provide a chat model before proceeding with creating an answer session.
Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#plugin-secure-proxy
`,
  ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT: "The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.",
  PLUGIN_COMPONENT_CONFLICT: 'The component "%s" is already defined. The plugin "%s" is trying to redefine it.'
};
function C(n, ...e) {
  const t = new Error(bs($s[n] ?? `Unsupported Orama Error code: ${n}`, ...e));
  return t.code = n, "captureStackTrace" in Error.prototype && Error.captureStackTrace(t), t;
}
function Us(n) {
  return {
    raw: Number(n),
    formatted: zt(n)
  };
}
function Ps(n) {
  if (n.id) {
    if (typeof n.id != "string")
      throw C("DOCUMENT_ID_MUST_BE_STRING", typeof n.id);
    return n.id;
  }
  return Jn();
}
function tr(n, e) {
  for (const [t, r] of Object.entries(e)) {
    const s = n[t];
    if (!(typeof s > "u") && !(r === "geopoint" && typeof s == "object" && typeof s.lon == "number" && typeof s.lat == "number") && !(r === "enum" && (typeof s == "string" || typeof s == "number"))) {
      if (r === "enum[]" && Array.isArray(s)) {
        const i = s.length;
        for (let o = 0; o < i; o++)
          if (typeof s[o] != "string" && typeof s[o] != "number")
            return t + "." + o;
        continue;
      }
      if (He(r)) {
        const i = rr(r);
        if (!Array.isArray(s) || s.length !== i)
          throw C("INVALID_INPUT_VECTOR", t, i, s.length);
        continue;
      }
      if (Ct(r)) {
        if (!Array.isArray(s))
          return t;
        const i = nr(r), o = s.length;
        for (let c = 0; c < o; c++)
          if (typeof s[c] !== i)
            return t + "." + c;
        continue;
      }
      if (typeof r == "object") {
        if (!s || typeof s != "object")
          return t;
        const i = tr(s, r);
        if (i)
          return t + "." + i;
        continue;
      }
      if (typeof s !== r)
        return t;
    }
  }
}
const Rs = {
  string: !1,
  number: !1,
  boolean: !1,
  enum: !1,
  geopoint: !1,
  "string[]": !0,
  "number[]": !0,
  "boolean[]": !0,
  "enum[]": !0
}, ks = {
  "string[]": "string",
  "number[]": "number",
  "boolean[]": "boolean",
  "enum[]": "enum"
};
function He(n) {
  return typeof n == "string" && /^vector\[\d+\]$/.test(n);
}
function Ct(n) {
  return typeof n == "string" && Rs[n];
}
function nr(n) {
  return ks[n];
}
function rr(n) {
  const e = Number(n.slice(7, -1));
  switch (!0) {
    case isNaN(e):
      throw C("INVALID_VECTOR_VALUE", n);
    case e <= 0:
      throw C("INVALID_VECTOR_SIZE", n);
    default:
      return e;
  }
}
function zs() {
  return {
    idToInternalId: /* @__PURE__ */ new Map(),
    internalIdToId: [],
    save: Ms,
    load: Cs
  };
}
function Ms(n) {
  return {
    internalIdToId: n.internalIdToId
  };
}
function Cs(n, e) {
  const { internalIdToId: t } = e;
  n.internalDocumentIDStore.idToInternalId.clear(), n.internalDocumentIDStore.internalIdToId = [];
  const r = t.length;
  for (let s = 0; s < r; s++) {
    const i = t[s];
    n.internalDocumentIDStore.idToInternalId.set(i, s + 1), n.internalDocumentIDStore.internalIdToId.push(i);
  }
}
function re(n, e) {
  if (typeof e == "string") {
    const t = n.idToInternalId.get(e);
    if (t)
      return t;
    const r = n.idToInternalId.size + 1;
    return n.idToInternalId.set(e, r), n.internalIdToId.push(e), r;
  }
  return e > n.internalIdToId.length ? re(n, e.toString()) : e;
}
function st(n, e) {
  if (n.internalIdToId.length < e)
    throw new Error(`Invalid internalId ${e}`);
  return n.internalIdToId[e - 1];
}
function Ls(n, e) {
  return {
    sharedInternalDocumentStore: e,
    docs: {},
    count: 0
  };
}
function Bs(n, e) {
  const t = re(n.sharedInternalDocumentStore, e);
  return n.docs[t];
}
function Fs(n, e) {
  const t = e.length, r = Array.from({ length: t });
  for (let s = 0; s < t; s++) {
    const i = re(n.sharedInternalDocumentStore, e[s]);
    r[s] = n.docs[i];
  }
  return r;
}
function Vs(n) {
  return n.docs;
}
function js(n, e, t, r) {
  return typeof n.docs[t] < "u" ? !1 : (n.docs[t] = r, n.count++, !0);
}
function Hs(n, e) {
  const t = re(n.sharedInternalDocumentStore, e);
  return typeof n.docs[t] > "u" ? !1 : (delete n.docs[t], n.count--, !0);
}
function Ws(n) {
  return n.count;
}
function Ys(n, e) {
  const t = e;
  return {
    docs: t.docs,
    count: t.count,
    sharedInternalDocumentStore: n
  };
}
function Ks(n) {
  return {
    docs: n.docs,
    count: n.count
  };
}
function Gs() {
  return {
    create: Ls,
    get: Bs,
    getMultiple: Fs,
    getAll: Vs,
    store: js,
    remove: Hs,
    count: Ws,
    load: Ys,
    save: Ks
  };
}
const qs = [
  "beforeInsert",
  "afterInsert",
  "beforeRemove",
  "afterRemove",
  "beforeUpdate",
  "afterUpdate",
  "beforeUpsert",
  "afterUpsert",
  "beforeSearch",
  "afterSearch",
  "beforeInsertMultiple",
  "afterInsertMultiple",
  "beforeRemoveMultiple",
  "afterRemoveMultiple",
  "beforeUpdateMultiple",
  "afterUpdateMultiple",
  "beforeUpsertMultiple",
  "afterUpsertMultiple",
  "beforeLoad",
  "afterLoad",
  "afterCreate"
];
function Js(n, e) {
  var s;
  const t = [], r = (s = n.plugins) == null ? void 0 : s.length;
  if (!r)
    return t;
  for (let i = 0; i < r; i++)
    try {
      const o = n.plugins[i];
      typeof o[e] == "function" && t.push(o[e]);
    } catch (o) {
      throw console.error("Caught error in getAllPluginsByHook:", o), C("PLUGIN_CRASHED");
    }
  return t;
}
const Xs = ["tokenizer", "index", "documentsStore", "sorter", "pinning"], pn = [
  "validateSchema",
  "getDocumentIndexId",
  "getDocumentProperties",
  "formatElapsedTime"
];
function Lt(n, e, t, r, s) {
  if (n.some(rt))
    return (async () => {
      for (const o of n)
        await o(e, t, r, s);
    })();
  for (const o of n)
    o(e, t, r, s);
}
function Bt(n, e, t, r) {
  if (n.some(rt))
    return (async () => {
      for (const i of n)
        await i(e, t, r);
    })();
  for (const i of n)
    i(e, t, r);
}
function Zs(n, e) {
  if (n.some(rt))
    return (async () => {
      for (const r of n)
        await r(e);
    })();
  for (const r of n)
    r(e);
}
class te {
  constructor(e, t) {
    V(this, "k");
    V(this, "v");
    V(this, "l", null);
    V(this, "r", null);
    V(this, "h", 1);
    this.k = e, this.v = new Set(t);
  }
  updateHeight() {
    this.h = Math.max(te.getHeight(this.l), te.getHeight(this.r)) + 1;
  }
  static getHeight(e) {
    return e ? e.h : 0;
  }
  getBalanceFactor() {
    return te.getHeight(this.l) - te.getHeight(this.r);
  }
  rotateLeft() {
    const e = this.r;
    return this.r = e.l, e.l = this, this.updateHeight(), e.updateHeight(), e;
  }
  rotateRight() {
    const e = this.l;
    return this.l = e.r, e.r = this, this.updateHeight(), e.updateHeight(), e;
  }
  toJSON() {
    return {
      k: this.k,
      v: Array.from(this.v),
      l: this.l ? this.l.toJSON() : null,
      r: this.r ? this.r.toJSON() : null,
      h: this.h
    };
  }
  static fromJSON(e) {
    const t = new te(e.k, e.v);
    return t.l = e.l ? te.fromJSON(e.l) : null, t.r = e.r ? te.fromJSON(e.r) : null, t.h = e.h, t;
  }
}
class it {
  constructor(e, t) {
    V(this, "root", null);
    V(this, "insertCount", 0);
    e !== void 0 && t !== void 0 && (this.root = new te(e, t));
  }
  insert(e, t, r = 1e3) {
    this.root = this.insertNode(this.root, e, t, r);
  }
  insertMultiple(e, t, r = 1e3) {
    for (const s of t)
      this.insert(e, s, r);
  }
  // Rebalance the tree if the insert count reaches the threshold.
  // This will improve insertion performance since we won't be rebalancing the tree on every insert.
  // When inserting docs using `insertMultiple`, the threshold will be set to the number of docs being inserted.
  // We can force rebalancing the tree by setting the threshold to 1 (default).
  rebalance() {
    this.root && (this.root = this.rebalanceNode(this.root));
  }
  toJSON() {
    return {
      root: this.root ? this.root.toJSON() : null,
      insertCount: this.insertCount
    };
  }
  static fromJSON(e) {
    const t = new it();
    return t.root = e.root ? te.fromJSON(e.root) : null, t.insertCount = e.insertCount || 0, t;
  }
  insertNode(e, t, r, s) {
    if (e === null)
      return new te(t, [r]);
    const i = [];
    let o = e, c = null;
    for (; o !== null; )
      if (i.push({ parent: c, node: o }), t < o.k)
        if (o.l === null) {
          o.l = new te(t, [r]), i.push({ parent: o, node: o.l });
          break;
        } else
          c = o, o = o.l;
      else if (t > o.k)
        if (o.r === null) {
          o.r = new te(t, [r]), i.push({ parent: o, node: o.r });
          break;
        } else
          c = o, o = o.r;
      else
        return o.v.add(r), e;
    let a = !1;
    this.insertCount++ % s === 0 && (a = !0);
    for (let l = i.length - 1; l >= 0; l--) {
      const { parent: d, node: u } = i[l];
      if (u.updateHeight(), a) {
        const h = this.rebalanceNode(u);
        d ? d.l === u ? d.l = h : d.r === u && (d.r = h) : e = h;
      }
    }
    return e;
  }
  rebalanceNode(e) {
    const t = e.getBalanceFactor();
    if (t > 1) {
      if (e.l && e.l.getBalanceFactor() >= 0)
        return e.rotateRight();
      if (e.l)
        return e.l = e.l.rotateLeft(), e.rotateRight();
    }
    if (t < -1) {
      if (e.r && e.r.getBalanceFactor() <= 0)
        return e.rotateLeft();
      if (e.r)
        return e.r = e.r.rotateRight(), e.rotateLeft();
    }
    return e;
  }
  find(e) {
    const t = this.findNodeByKey(e);
    return t ? t.v : null;
  }
  contains(e) {
    return this.find(e) !== null;
  }
  getSize() {
    let e = 0;
    const t = [];
    let r = this.root;
    for (; r || t.length > 0; ) {
      for (; r; )
        t.push(r), r = r.l;
      r = t.pop(), e++, r = r.r;
    }
    return e;
  }
  isBalanced() {
    if (!this.root)
      return !0;
    const e = [this.root];
    for (; e.length > 0; ) {
      const t = e.pop(), r = t.getBalanceFactor();
      if (Math.abs(r) > 1)
        return !1;
      t.l && e.push(t.l), t.r && e.push(t.r);
    }
    return !0;
  }
  remove(e) {
    this.root = this.removeNode(this.root, e);
  }
  removeDocument(e, t) {
    const r = this.findNodeByKey(e);
    r && (r.v.size === 1 ? this.root = this.removeNode(this.root, e) : r.v = new Set([...r.v.values()].filter((s) => s !== t)));
  }
  findNodeByKey(e) {
    let t = this.root;
    for (; t; )
      if (e < t.k)
        t = t.l;
      else if (e > t.k)
        t = t.r;
      else
        return t;
    return null;
  }
  removeNode(e, t) {
    if (e === null)
      return null;
    const r = [];
    let s = e;
    for (; s !== null && s.k !== t; )
      r.push(s), t < s.k ? s = s.l : s = s.r;
    if (s === null)
      return e;
    if (s.l === null || s.r === null) {
      const i = s.l ? s.l : s.r;
      if (r.length === 0)
        e = i;
      else {
        const o = r[r.length - 1];
        o.l === s ? o.l = i : o.r = i;
      }
    } else {
      let i = s, o = s.r;
      for (; o.l !== null; )
        i = o, o = o.l;
      s.k = o.k, s.v = o.v, i.l === o ? i.l = o.r : i.r = o.r, s = i;
    }
    r.push(s);
    for (let i = r.length - 1; i >= 0; i--) {
      const o = r[i];
      o.updateHeight();
      const c = this.rebalanceNode(o);
      if (i > 0) {
        const a = r[i - 1];
        a.l === o ? a.l = c : a.r === o && (a.r = c);
      } else
        e = c;
    }
    return e;
  }
  rangeSearch(e, t) {
    const r = /* @__PURE__ */ new Set(), s = [];
    let i = this.root;
    for (; i || s.length > 0; ) {
      for (; i; )
        s.push(i), i = i.l;
      if (i = s.pop(), i.k >= e && i.k <= t)
        for (const o of i.v)
          r.add(o);
      if (i.k > t)
        break;
      i = i.r;
    }
    return r;
  }
  greaterThan(e, t = !1) {
    const r = /* @__PURE__ */ new Set(), s = [];
    let i = this.root;
    for (; i || s.length > 0; ) {
      for (; i; )
        s.push(i), i = i.r;
      if (i = s.pop(), t && i.k >= e || !t && i.k > e)
        for (const o of i.v)
          r.add(o);
      else if (i.k <= e)
        break;
      i = i.l;
    }
    return r;
  }
  lessThan(e, t = !1) {
    const r = /* @__PURE__ */ new Set(), s = [];
    let i = this.root;
    for (; i || s.length > 0; ) {
      for (; i; )
        s.push(i), i = i.l;
      if (i = s.pop(), t && i.k <= e || !t && i.k < e)
        for (const o of i.v)
          r.add(o);
      else if (i.k > e)
        break;
      i = i.r;
    }
    return r;
  }
}
class ot {
  constructor() {
    V(this, "numberToDocumentId");
    this.numberToDocumentId = /* @__PURE__ */ new Map();
  }
  insert(e, t) {
    this.numberToDocumentId.has(e) ? this.numberToDocumentId.get(e).add(t) : this.numberToDocumentId.set(e, /* @__PURE__ */ new Set([t]));
  }
  find(e) {
    const t = this.numberToDocumentId.get(e);
    return t ? Array.from(t) : null;
  }
  remove(e) {
    this.numberToDocumentId.delete(e);
  }
  removeDocument(e, t) {
    const r = this.numberToDocumentId.get(t);
    r && (r.delete(e), r.size === 0 && this.numberToDocumentId.delete(t));
  }
  contains(e) {
    return this.numberToDocumentId.has(e);
  }
  getSize() {
    let e = 0;
    for (const t of this.numberToDocumentId.values())
      e += t.size;
    return e;
  }
  filter(e) {
    const t = Object.keys(e);
    if (t.length !== 1)
      throw new Error("Invalid operation");
    const r = t[0];
    switch (r) {
      case "eq": {
        const s = e[r], i = this.numberToDocumentId.get(s);
        return i ? Array.from(i) : [];
      }
      case "in": {
        const s = e[r], i = /* @__PURE__ */ new Set();
        for (const o of s) {
          const c = this.numberToDocumentId.get(o);
          if (c)
            for (const a of c)
              i.add(a);
        }
        return Array.from(i);
      }
      case "nin": {
        const s = new Set(e[r]), i = /* @__PURE__ */ new Set();
        for (const [o, c] of this.numberToDocumentId.entries())
          if (!s.has(o))
            for (const a of c)
              i.add(a);
        return Array.from(i);
      }
      default:
        throw new Error("Invalid operation");
    }
  }
  filterArr(e) {
    const t = Object.keys(e);
    if (t.length !== 1)
      throw new Error("Invalid operation");
    const r = t[0];
    switch (r) {
      case "containsAll": {
        const i = e[r].map((c) => this.numberToDocumentId.get(c) ?? /* @__PURE__ */ new Set());
        if (i.length === 0)
          return [];
        const o = i.reduce((c, a) => new Set([...c].filter((l) => a.has(l))));
        return Array.from(o);
      }
      case "containsAny": {
        const i = e[r].map((c) => this.numberToDocumentId.get(c) ?? /* @__PURE__ */ new Set());
        if (i.length === 0)
          return [];
        const o = i.reduce((c, a) => /* @__PURE__ */ new Set([...c, ...a]));
        return Array.from(o);
      }
      default:
        throw new Error("Invalid operation");
    }
  }
  static fromJSON(e) {
    if (!e.numberToDocumentId)
      throw new Error("Invalid Flat Tree JSON");
    const t = new ot();
    for (const [r, s] of e.numberToDocumentId)
      t.numberToDocumentId.set(r, new Set(s));
    return t;
  }
  toJSON() {
    return {
      numberToDocumentId: Array.from(this.numberToDocumentId.entries()).map(([e, t]) => [e, Array.from(t)])
    };
  }
}
function Qs(n, e, t) {
  if (t < 0)
    return -1;
  if (n === e)
    return 0;
  const r = n.length, s = e.length;
  if (r === 0)
    return s <= t ? s : -1;
  if (s === 0)
    return r <= t ? r : -1;
  const i = Math.abs(r - s);
  if (n.startsWith(e))
    return i <= t ? i : -1;
  if (e.startsWith(n))
    return 0;
  if (i > t)
    return -1;
  const o = [];
  for (let c = 0; c <= r; c++) {
    o[c] = [c];
    for (let a = 1; a <= s; a++)
      o[c][a] = c === 0 ? a : 0;
  }
  for (let c = 1; c <= r; c++) {
    let a = 1 / 0;
    for (let l = 1; l <= s; l++)
      n[c - 1] === e[l - 1] ? o[c][l] = o[c - 1][l - 1] : o[c][l] = Math.min(
        o[c - 1][l] + 1,
        // deletion
        o[c][l - 1] + 1,
        // insertion
        o[c - 1][l - 1] + 1
        // substitution
      ), a = Math.min(a, o[c][l]);
    if (a > t)
      return -1;
  }
  return o[r][s] <= t ? o[r][s] : -1;
}
function gn(n, e, t) {
  const r = Qs(n, e, t);
  return {
    distance: r,
    isBounded: r >= 0
  };
}
class he {
  constructor(e, t, r) {
    // Node key
    V(this, "k");
    // Node subword
    V(this, "s");
    // Node children
    V(this, "c", /* @__PURE__ */ new Map());
    // Node documents
    V(this, "d", /* @__PURE__ */ new Set());
    // Node end
    V(this, "e");
    // Node word
    V(this, "w", "");
    this.k = e, this.s = t, this.e = r;
  }
  updateParent(e) {
    this.w = e.w + this.s;
  }
  addDocument(e) {
    this.d.add(e);
  }
  removeDocument(e) {
    return this.d.delete(e);
  }
  findAllWords(e, t, r, s) {
    const i = [this];
    for (; i.length > 0; ) {
      const o = i.pop();
      if (o.e) {
        const { w: c, d: a } = o;
        if (r && c !== t)
          continue;
        if (bt(e, c) !== null)
          if (s)
            if (Math.abs(t.length - c.length) <= s && gn(t, c, s).isBounded)
              e[c] = [];
            else
              continue;
          else
            e[c] = [];
        if (bt(e, c) != null && a.size > 0) {
          const l = e[c];
          for (const d of a)
            l.includes(d) || l.push(d);
        }
      }
      o.c.size > 0 && i.push(...o.c.values());
    }
    return e;
  }
  insert(e, t) {
    let r = this, s = 0;
    const i = e.length;
    for (; s < i; ) {
      const o = e[s], c = r.c.get(o);
      if (c) {
        const a = c.s, l = a.length;
        let d = 0;
        for (; d < l && s + d < i && a[d] === e[s + d]; )
          d++;
        if (d === l) {
          if (r = c, s += d, s === i) {
            c.e || (c.e = !0), c.addDocument(t);
            return;
          }
          continue;
        }
        const u = a.slice(0, d), h = a.slice(d), m = e.slice(s + d), g = new he(u[0], u, !1);
        if (r.c.set(u[0], g), g.updateParent(r), c.s = h, c.k = h[0], g.c.set(h[0], c), c.updateParent(g), m) {
          const y = new he(m[0], m, !0);
          y.addDocument(t), g.c.set(m[0], y), y.updateParent(g);
        } else
          g.e = !0, g.addDocument(t);
        return;
      } else {
        const a = new he(o, e.slice(s), !0);
        a.addDocument(t), r.c.set(o, a), a.updateParent(r);
        return;
      }
    }
    r.e || (r.e = !0), r.addDocument(t);
  }
  _findLevenshtein(e, t, r, s, i) {
    const o = [{ node: this, index: t, tolerance: r }];
    for (; o.length > 0; ) {
      const { node: c, index: a, tolerance: l } = o.pop();
      if (c.w.startsWith(e)) {
        c.findAllWords(i, e, !1, 0);
        continue;
      }
      if (l < 0)
        continue;
      if (c.e) {
        const { w: u, d: h } = c;
        if (u && (gn(e, u, s).isBounded && (i[u] = []), bt(i, u) !== void 0 && h.size > 0)) {
          const m = new Set(i[u]);
          for (const g of h)
            m.add(g);
          i[u] = Array.from(m);
        }
      }
      if (a >= e.length)
        continue;
      const d = e[a];
      if (c.c.has(d)) {
        const u = c.c.get(d);
        o.push({ node: u, index: a + 1, tolerance: l });
      }
      o.push({ node: c, index: a + 1, tolerance: l - 1 });
      for (const [u, h] of c.c)
        o.push({ node: h, index: a, tolerance: l - 1 }), u !== d && o.push({ node: h, index: a + 1, tolerance: l - 1 });
    }
  }
  find(e) {
    const { term: t, exact: r, tolerance: s } = e;
    if (s && !r) {
      const i = {};
      return this._findLevenshtein(t, 0, s, s, i), i;
    } else {
      let i = this, o = 0;
      const c = t.length;
      for (; o < c; ) {
        const l = t[o], d = i.c.get(l);
        if (d) {
          const u = d.s, h = u.length;
          let m = 0;
          for (; m < h && o + m < c && u[m] === t[o + m]; )
            m++;
          if (m === h)
            i = d, o += m;
          else if (o + m === c)
            if (m === c - o) {
              if (r)
                return {};
              {
                const g = {};
                return d.findAllWords(g, t, r, s), g;
              }
            } else
              return {};
          else
            return {};
        } else
          return {};
      }
      const a = {};
      return i.findAllWords(a, t, r, s), a;
    }
  }
  contains(e) {
    let t = this, r = 0;
    const s = e.length;
    for (; r < s; ) {
      const i = e[r], o = t.c.get(i);
      if (o) {
        const c = o.s, a = c.length;
        let l = 0;
        for (; l < a && r + l < s && c[l] === e[r + l]; )
          l++;
        if (l < a)
          return !1;
        r += a, t = o;
      } else
        return !1;
    }
    return !0;
  }
  removeWord(e) {
    if (!e)
      return !1;
    let t = this;
    const r = e.length, s = [];
    for (let i = 0; i < r; i++) {
      const o = e[i];
      if (t.c.has(o)) {
        const c = t.c.get(o);
        s.push({ parent: t, character: o }), i += c.s.length - 1, t = c;
      } else
        return !1;
    }
    for (t.d.clear(), t.e = !1; s.length > 0 && t.c.size === 0 && !t.e && t.d.size === 0; ) {
      const { parent: i, character: o } = s.pop();
      i.c.delete(o), t = i;
    }
    return !0;
  }
  removeDocumentByWord(e, t, r = !0) {
    if (!e)
      return !0;
    let s = this;
    const i = e.length;
    for (let o = 0; o < i; o++) {
      const c = e[o];
      if (s.c.has(c)) {
        const a = s.c.get(c);
        o += a.s.length - 1, s = a, r && s.w !== e || s.removeDocument(t);
      } else
        return !1;
    }
    return !0;
  }
  static getCommonPrefix(e, t) {
    const r = Math.min(e.length, t.length);
    let s = 0;
    for (; s < r && e.charCodeAt(s) === t.charCodeAt(s); )
      s++;
    return e.slice(0, s);
  }
  toJSON() {
    var e, t;
    return {
      w: this.w,
      s: this.s,
      e: this.e,
      k: this.k,
      d: Array.from(this.d),
      c: (t = Array.from((e = this.c) == null ? void 0 : e.entries())) == null ? void 0 : t.map(([r, s]) => [r, s.toJSON()])
    };
  }
  static fromJSON(e) {
    var r;
    const t = new he(e.k, e.s, e.e);
    return t.w = e.w, t.d = new Set(e.d), t.c = new Map(((r = e == null ? void 0 : e.c) == null ? void 0 : r.map(([s, i]) => [s, he.fromJSON(i)])) || []), t;
  }
}
class ct extends he {
  constructor() {
    super("", "", !1);
  }
  static fromJSON(e) {
    var r;
    const t = new ct();
    return t.w = e.w, t.s = e.s, t.e = e.e, t.k = e.k, t.d = new Set(e.d), t.c = new Map(((r = e == null ? void 0 : e.c) == null ? void 0 : r.map(([s, i]) => [s, he.fromJSON(i)])) || []), t;
  }
  toJSON() {
    return super.toJSON();
  }
}
const ei = 2, ti = 6371e3;
class Ae {
  constructor(e, t) {
    V(this, "point");
    V(this, "docIDs");
    V(this, "left");
    V(this, "right");
    V(this, "parent");
    this.point = e, this.docIDs = new Set(t), this.left = null, this.right = null, this.parent = null;
  }
  toJSON() {
    return {
      point: this.point,
      docIDs: Array.from(this.docIDs),
      left: this.left ? this.left.toJSON() : null,
      right: this.right ? this.right.toJSON() : null
    };
  }
  static fromJSON(e, t = null) {
    const r = new Ae(e.point, e.docIDs);
    return r.parent = t, e.left && (r.left = Ae.fromJSON(e.left, r)), e.right && (r.right = Ae.fromJSON(e.right, r)), r;
  }
}
class ne {
  constructor() {
    V(this, "root");
    V(this, "nodeMap");
    this.root = null, this.nodeMap = /* @__PURE__ */ new Map();
  }
  getPointKey(e) {
    return `${e.lon},${e.lat}`;
  }
  insert(e, t) {
    const r = this.getPointKey(e), s = this.nodeMap.get(r);
    if (s) {
      t.forEach((a) => s.docIDs.add(a));
      return;
    }
    const i = new Ae(e, t);
    if (this.nodeMap.set(r, i), this.root == null) {
      this.root = i;
      return;
    }
    let o = this.root, c = 0;
    for (; ; ) {
      if (c % ei === 0)
        if (e.lon < o.point.lon) {
          if (o.left == null) {
            o.left = i, i.parent = o;
            return;
          }
          o = o.left;
        } else {
          if (o.right == null) {
            o.right = i, i.parent = o;
            return;
          }
          o = o.right;
        }
      else if (e.lat < o.point.lat) {
        if (o.left == null) {
          o.left = i, i.parent = o;
          return;
        }
        o = o.left;
      } else {
        if (o.right == null) {
          o.right = i, i.parent = o;
          return;
        }
        o = o.right;
      }
      c++;
    }
  }
  contains(e) {
    const t = this.getPointKey(e);
    return this.nodeMap.has(t);
  }
  getDocIDsByCoordinates(e) {
    const t = this.getPointKey(e), r = this.nodeMap.get(t);
    return r ? Array.from(r.docIDs) : null;
  }
  removeDocByID(e, t) {
    const r = this.getPointKey(e), s = this.nodeMap.get(r);
    s && (s.docIDs.delete(t), s.docIDs.size === 0 && (this.nodeMap.delete(r), this.deleteNode(s)));
  }
  deleteNode(e) {
    const t = e.parent, r = e.left ? e.left : e.right;
    r && (r.parent = t), t ? t.left === e ? t.left = r : t.right === e && (t.right = r) : (this.root = r, this.root && (this.root.parent = null));
  }
  searchByRadius(e, t, r = !0, s = "asc", i = !1) {
    const o = i ? ne.vincentyDistance : ne.haversineDistance, c = [{ node: this.root, depth: 0 }], a = [];
    for (; c.length > 0; ) {
      const { node: l, depth: d } = c.pop();
      if (l == null)
        continue;
      const u = o(e, l.point);
      (r ? u <= t : u > t) && a.push({ point: l.point, docIDs: Array.from(l.docIDs) }), l.left != null && c.push({ node: l.left, depth: d + 1 }), l.right != null && c.push({ node: l.right, depth: d + 1 });
    }
    return s && a.sort((l, d) => {
      const u = o(e, l.point), h = o(e, d.point);
      return s.toLowerCase() === "asc" ? u - h : h - u;
    }), a;
  }
  searchByPolygon(e, t = !0, r = null, s = !1) {
    const i = [{ node: this.root, depth: 0 }], o = [];
    for (; i.length > 0; ) {
      const { node: a, depth: l } = i.pop();
      if (a == null)
        continue;
      a.left != null && i.push({ node: a.left, depth: l + 1 }), a.right != null && i.push({ node: a.right, depth: l + 1 });
      const d = ne.isPointInPolygon(e, a.point);
      (d && t || !d && !t) && o.push({ point: a.point, docIDs: Array.from(a.docIDs) });
    }
    const c = ne.calculatePolygonCentroid(e);
    if (r) {
      const a = s ? ne.vincentyDistance : ne.haversineDistance;
      o.sort((l, d) => {
        const u = a(c, l.point), h = a(c, d.point);
        return r.toLowerCase() === "asc" ? u - h : h - u;
      });
    }
    return o;
  }
  toJSON() {
    return {
      root: this.root ? this.root.toJSON() : null
    };
  }
  static fromJSON(e) {
    const t = new ne();
    return e.root && (t.root = Ae.fromJSON(e.root), t.buildNodeMap(t.root)), t;
  }
  buildNodeMap(e) {
    if (e == null)
      return;
    const t = this.getPointKey(e.point);
    this.nodeMap.set(t, e), e.left && this.buildNodeMap(e.left), e.right && this.buildNodeMap(e.right);
  }
  static calculatePolygonCentroid(e) {
    let t = 0, r = 0, s = 0;
    const i = e.length;
    for (let c = 0, a = i - 1; c < i; a = c++) {
      const l = e[c].lon, d = e[c].lat, u = e[a].lon, h = e[a].lat, m = l * h - u * d;
      t += m, r += (l + u) * m, s += (d + h) * m;
    }
    t /= 2;
    const o = 6 * t;
    return r /= o, s /= o, { lon: r, lat: s };
  }
  static isPointInPolygon(e, t) {
    let r = !1;
    const s = t.lon, i = t.lat, o = e.length;
    for (let c = 0, a = o - 1; c < o; a = c++) {
      const l = e[c].lon, d = e[c].lat, u = e[a].lon, h = e[a].lat;
      d > i != h > i && s < (u - l) * (i - d) / (h - d) + l && (r = !r);
    }
    return r;
  }
  static haversineDistance(e, t) {
    const r = Math.PI / 180, s = e.lat * r, i = t.lat * r, o = (t.lat - e.lat) * r, c = (t.lon - e.lon) * r, a = Math.sin(o / 2) * Math.sin(o / 2) + Math.cos(s) * Math.cos(i) * Math.sin(c / 2) * Math.sin(c / 2), l = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return ti * l;
  }
  static vincentyDistance(e, t) {
    const s = 0.0033528106647474805, i = (1 - s) * 6378137, o = Math.PI / 180, c = e.lat * o, a = t.lat * o, l = (t.lon - e.lon) * o, d = Math.atan((1 - s) * Math.tan(c)), u = Math.atan((1 - s) * Math.tan(a)), h = Math.sin(d), m = Math.cos(d), g = Math.sin(u), y = Math.cos(u);
    let f = l, p, v = 1e3, w, x, N, T, A, U;
    do {
      const M = Math.sin(f), z = Math.cos(f);
      if (w = Math.sqrt(y * M * (y * M) + (m * g - h * y * z) * (m * g - h * y * z)), w === 0)
        return 0;
      x = h * g + m * y * z, N = Math.atan2(w, x), T = m * y * M / w, A = 1 - T * T, U = x - 2 * h * g / A, isNaN(U) && (U = 0);
      const F = s / 16 * A * (4 + s * (4 - 3 * A));
      p = f, f = l + (1 - F) * s * T * (N + F * w * (U + F * x * (-1 + 2 * U * U)));
    } while (Math.abs(f - p) > 1e-12 && --v > 0);
    if (v === 0)
      return NaN;
    const E = A * (6378137 * 6378137 - i * i) / (i * i), G = 1 + E / 16384 * (4096 + E * (-768 + E * (320 - 175 * E))), R = E / 1024 * (256 + E * (-128 + E * (74 - 47 * E))), W = R * w * (U + R / 4 * (x * (-1 + 2 * U * U) - R / 6 * U * (-3 + 4 * w * w) * (-3 + 4 * U * U)));
    return i * G * (N - W);
  }
}
class at {
  constructor() {
    V(this, "true");
    V(this, "false");
    this.true = /* @__PURE__ */ new Set(), this.false = /* @__PURE__ */ new Set();
  }
  insert(e, t) {
    t ? this.true.add(e) : this.false.add(e);
  }
  delete(e, t) {
    t ? this.true.delete(e) : this.false.delete(e);
  }
  getSize() {
    return this.true.size + this.false.size;
  }
  toJSON() {
    return {
      true: Array.from(this.true),
      false: Array.from(this.false)
    };
  }
  static fromJSON(e) {
    const t = new at();
    return t.true = new Set(e.true), t.false = new Set(e.false), t;
  }
}
function ni(n, e, t, r, s, { k: i, b: o, d: c }) {
  return Math.log(1 + (t - e + 0.5) / (e + 0.5)) * (c + n * (i + 1)) / (n + i * (1 - o + o * r / s));
}
const ri = 0.8;
class lt {
  constructor(e) {
    V(this, "size");
    V(this, "vectors", /* @__PURE__ */ new Map());
    this.size = e;
  }
  add(e, t) {
    t instanceof Float32Array || (t = new Float32Array(t));
    const r = sr(t, this.size);
    this.vectors.set(e, [r, t]);
  }
  remove(e) {
    this.vectors.delete(e);
  }
  find(e, t, r) {
    return e instanceof Float32Array || (e = new Float32Array(e)), si(e, r, this.vectors, this.size, t);
  }
  toJSON() {
    const e = [];
    for (const [t, [r, s]] of this.vectors)
      e.push([t, [r, Array.from(s)]]);
    return {
      size: this.size,
      vectors: e
    };
  }
  static fromJSON(e) {
    const t = e, r = new lt(t.size);
    for (const [s, [i, o]] of t.vectors)
      r.vectors.set(s, [i, new Float32Array(o)]);
    return r;
  }
}
function sr(n, e) {
  let t = 0;
  for (let r = 0; r < e; r++)
    t += n[r] * n[r];
  return Math.sqrt(t);
}
function si(n, e, t, r, s) {
  const i = sr(n, r), o = [], c = e || t.keys();
  for (const a of c) {
    const l = t.get(a);
    if (!l)
      continue;
    const d = l[0], u = l[1];
    let h = 0;
    for (let g = 0; g < r; g++)
      h += n[g] * u[g];
    const m = h / (i * d);
    m >= s && o.push([a, m]);
  }
  return o;
}
function ii(n, e, t, r, s) {
  const i = re(n.sharedInternalDocumentStore, t);
  n.avgFieldLength[e] = ((n.avgFieldLength[e] ?? 0) * (s - 1) + r.length) / s, n.fieldLengths[e][i] = r.length, n.frequencies[e][i] = {};
}
function oi(n, e, t, r, s) {
  let i = 0;
  for (const a of r)
    a === s && i++;
  const o = re(n.sharedInternalDocumentStore, t), c = i / r.length;
  n.frequencies[e][o][s] = c, s in n.tokenOccurrences[e] || (n.tokenOccurrences[e][s] = 0), n.tokenOccurrences[e][s] = (n.tokenOccurrences[e][s] ?? 0) + 1;
}
function ci(n, e, t, r) {
  const s = re(n.sharedInternalDocumentStore, t);
  r > 1 ? n.avgFieldLength[e] = (n.avgFieldLength[e] * r - n.fieldLengths[e][s]) / (r - 1) : n.avgFieldLength[e] = void 0, n.fieldLengths[e][s] = void 0, n.frequencies[e][s] = void 0;
}
function ai(n, e, t) {
  n.tokenOccurrences[e][t]--;
}
function ir(n, e, t, r, s = "") {
  r || (r = {
    sharedInternalDocumentStore: e,
    indexes: {},
    vectorIndexes: {},
    searchableProperties: [],
    searchablePropertiesWithTypes: {},
    frequencies: {},
    tokenOccurrences: {},
    avgFieldLength: {},
    fieldLengths: {}
  });
  for (const [i, o] of Object.entries(t)) {
    const c = `${s}${s ? "." : ""}${i}`;
    if (typeof o == "object" && !Array.isArray(o)) {
      ir(n, e, o, r, c);
      continue;
    }
    if (He(o))
      r.searchableProperties.push(c), r.searchablePropertiesWithTypes[c] = o, r.vectorIndexes[c] = {
        type: "Vector",
        node: new lt(rr(o)),
        isArray: !1
      };
    else {
      const a = /\[/.test(o);
      switch (o) {
        case "boolean":
        case "boolean[]":
          r.indexes[c] = { type: "Bool", node: new at(), isArray: a };
          break;
        case "number":
        case "number[]":
          r.indexes[c] = { type: "AVL", node: new it(0, []), isArray: a };
          break;
        case "string":
        case "string[]":
          r.indexes[c] = { type: "Radix", node: new ct(), isArray: a }, r.avgFieldLength[c] = 0, r.frequencies[c] = {}, r.tokenOccurrences[c] = {}, r.fieldLengths[c] = {};
          break;
        case "enum":
        case "enum[]":
          r.indexes[c] = { type: "Flat", node: new ot(), isArray: a };
          break;
        case "geopoint":
          r.indexes[c] = { type: "BKD", node: new ne(), isArray: a };
          break;
        default:
          throw C("INVALID_SCHEMA_TYPE", Array.isArray(o) ? "array" : o, c);
      }
      r.searchableProperties.push(c), r.searchablePropertiesWithTypes[c] = o;
    }
  }
  return r;
}
function li(n, e, t, r, s, i, o, c) {
  return (a) => {
    const { type: l, node: d } = e.indexes[t];
    switch (l) {
      case "Bool": {
        d[a ? "true" : "false"].add(r);
        break;
      }
      case "AVL": {
        const u = (c == null ? void 0 : c.avlRebalanceThreshold) ?? 1;
        d.insert(a, r, u);
        break;
      }
      case "Radix": {
        const u = i.tokenize(a, s, t, !1);
        n.insertDocumentScoreParameters(e, t, r, u, o);
        for (const h of u)
          n.insertTokenScoreParameters(e, t, r, u, h), d.insert(h, r);
        break;
      }
      case "Flat": {
        d.insert(a, r);
        break;
      }
      case "BKD": {
        d.insert(a, [r]);
        break;
      }
    }
  };
}
function fi(n, e, t, r, s, i, o, c, a, l, d) {
  if (He(o))
    return ui(e, t, i, r, s);
  const u = li(n, e, t, s, c, a, l, d);
  if (!Ct(o))
    return u(i);
  const h = i, m = h.length;
  for (let g = 0; g < m; g++)
    u(h[g]);
}
function ui(n, e, t, r, s) {
  n.vectorIndexes[e].node.add(s, t);
}
function yn(n, e, t, r, s, i, o, c, a, l) {
  if (He(o))
    return e.vectorIndexes[t].node.remove(s), !0;
  const { type: d, node: u } = e.indexes[t];
  switch (d) {
    case "AVL":
      return u.removeDocument(i, s), !0;
    case "Bool":
      return u[i ? "true" : "false"].delete(s), !0;
    case "Radix": {
      const h = a.tokenize(i, c, t);
      n.removeDocumentScoreParameters(e, t, r, l);
      for (const m of h)
        n.removeTokenScoreParameters(e, t, m), u.removeDocumentByWord(m, s);
      return !0;
    }
    case "Flat":
      return u.removeDocument(s, i), !0;
    case "BKD":
      return u.removeDocByID(i, s), !1;
  }
}
function di(n, e, t, r, s, i, o, c, a, l) {
  if (!Ct(o))
    return yn(n, e, t, r, s, i, o, c, a, l);
  const d = nr(o), u = i, h = u.length;
  for (let m = 0; m < h; m++)
    yn(n, e, t, r, s, u[m], d, c, a, l);
  return !0;
}
function or(n, e, t, r, s, i, o, c, a, l) {
  var p;
  const d = Array.from(r), u = n.avgFieldLength[e], h = n.fieldLengths[e], m = n.tokenOccurrences[e], g = n.frequencies[e], y = typeof m[t] == "number" ? m[t] ?? 0 : 0, f = d.length;
  for (let v = 0; v < f; v++) {
    const w = d[v];
    if (a && !a.has(w))
      continue;
    l.has(w) || l.set(w, /* @__PURE__ */ new Map());
    const x = l.get(w);
    x.set(e, (x.get(e) || 0) + 1);
    const N = ((p = g == null ? void 0 : g[w]) == null ? void 0 : p[t]) ?? 0, T = ni(N, y, s, h[w], u, i);
    o.has(w) ? o.set(w, o.get(w) + T * c) : o.set(w, T * c);
  }
}
function hi(n, e, t, r, s, i, o, c, a, l, d, u = 0) {
  const h = t.tokenize(e, r), m = h.length || 1, g = /* @__PURE__ */ new Map(), y = /* @__PURE__ */ new Map(), f = /* @__PURE__ */ new Map();
  for (const w of s) {
    if (!(w in n.indexes))
      continue;
    const x = n.indexes[w], { type: N } = x;
    if (N !== "Radix")
      throw C("WRONG_SEARCH_PROPERTY_TYPE", w);
    const T = c[w] ?? 1;
    if (T <= 0)
      throw C("INVALID_BOOST_VALUE", T);
    h.length === 0 && !e && h.push("");
    const A = h.length;
    for (let U = 0; U < A; U++) {
      const E = h[U], G = x.node.find({ term: E, exact: i, tolerance: o }), R = Object.keys(G);
      R.length > 0 && y.set(E, !0);
      const W = R.length;
      for (let P = 0; P < W; P++) {
        const M = R[P], z = G[M];
        or(n, w, M, z, l, a, f, T, d, g);
      }
    }
  }
  const p = Array.from(f.entries()).map(([w, x]) => [w, x]).sort((w, x) => x[1] - w[1]);
  if (p.length === 0)
    return [];
  if (u === 1)
    return p;
  if (u === 0) {
    if (m === 1)
      return p;
    for (const x of h)
      if (!y.get(x))
        return [];
    return p.filter(([x]) => {
      const N = g.get(x);
      return N ? Array.from(N.values()).some((T) => T === m) : !1;
    });
  }
  const v = p.filter(([w]) => {
    const x = g.get(w);
    return x ? Array.from(x.values()).some((N) => N === m) : !1;
  });
  if (v.length > 0) {
    const w = p.filter(([N]) => !v.some(([T]) => T === N)), x = Math.ceil(w.length * u);
    return [...v, ...w.slice(0, x)];
  }
  return p;
}
function Xe(n, e, t, r) {
  if ("and" in t && t.and && Array.isArray(t.and)) {
    const o = t.and;
    if (o.length === 0)
      return /* @__PURE__ */ new Set();
    const c = o.map((a) => Xe(n, e, a, r));
    return hn(...c);
  }
  if ("or" in t && t.or && Array.isArray(t.or)) {
    const o = t.or;
    return o.length === 0 ? /* @__PURE__ */ new Set() : o.map((a) => Xe(n, e, a, r)).reduce((a, l) => Ge(a, l), /* @__PURE__ */ new Set());
  }
  if ("not" in t && t.not) {
    const o = t.not, c = /* @__PURE__ */ new Set(), a = n.sharedInternalDocumentStore;
    for (let d = 1; d <= a.internalIdToId.length; d++)
      c.add(d);
    const l = Xe(n, e, o, r);
    return Ds(c, l);
  }
  const s = Object.keys(t), i = s.reduce((o, c) => ({
    [c]: /* @__PURE__ */ new Set(),
    ...o
  }), {});
  for (const o of s) {
    const c = t[o];
    if (typeof n.indexes[o] > "u")
      throw C("UNKNOWN_FILTER_PROPERTY", o);
    const { node: a, type: l, isArray: d } = n.indexes[o];
    if (l === "Bool") {
      const h = a, m = c ? h.true : h.false;
      i[o] = Ge(i[o], m);
      continue;
    }
    if (l === "BKD") {
      let h;
      if ("radius" in c)
        h = "radius";
      else if ("polygon" in c)
        h = "polygon";
      else
        throw new Error(`Invalid operation ${c}`);
      if (h === "radius") {
        const { value: m, coordinates: g, unit: y = "m", inside: f = !0, highPrecision: p = !1 } = c[h], v = Qn(m, y), w = a.searchByRadius(g, v, f, void 0, p);
        i[o] = mn(i[o], w);
      } else {
        const { coordinates: m, inside: g = !0, highPrecision: y = !1 } = c[h], f = a.searchByPolygon(m, g, void 0, y);
        i[o] = mn(i[o], f);
      }
      continue;
    }
    if (l === "Radix" && (typeof c == "string" || Array.isArray(c))) {
      for (const h of [c].flat()) {
        const m = e.tokenize(h, r, o);
        for (const g of m) {
          const y = a.find({ term: g, exact: !0 });
          i[o] = vi(i[o], y);
        }
      }
      continue;
    }
    const u = Object.keys(c);
    if (u.length > 1)
      throw C("INVALID_FILTER_OPERATION", u.length);
    if (l === "Flat") {
      const h = new Set(d ? a.filterArr(c) : a.filter(c));
      i[o] = Ge(i[o], h);
      continue;
    }
    if (l === "AVL") {
      const h = u[0], m = c[h];
      let g;
      switch (h) {
        case "gt": {
          g = a.greaterThan(m, !1);
          break;
        }
        case "gte": {
          g = a.greaterThan(m, !0);
          break;
        }
        case "lt": {
          g = a.lessThan(m, !1);
          break;
        }
        case "lte": {
          g = a.lessThan(m, !0);
          break;
        }
        case "eq": {
          g = a.find(m) ?? /* @__PURE__ */ new Set();
          break;
        }
        case "between": {
          const [y, f] = m;
          g = a.rangeSearch(y, f);
          break;
        }
        default:
          throw C("INVALID_FILTER_OPERATION", h);
      }
      i[o] = Ge(i[o], g);
    }
  }
  return hn(...Object.values(i));
}
function pi(n) {
  return n.searchableProperties;
}
function gi(n) {
  return n.searchablePropertiesWithTypes;
}
function yi(n, e) {
  const { indexes: t, vectorIndexes: r, searchableProperties: s, searchablePropertiesWithTypes: i, frequencies: o, tokenOccurrences: c, avgFieldLength: a, fieldLengths: l } = e, d = {}, u = {};
  for (const h of Object.keys(t)) {
    const { node: m, type: g, isArray: y } = t[h];
    switch (g) {
      case "Radix":
        d[h] = {
          type: "Radix",
          node: ct.fromJSON(m),
          isArray: y
        };
        break;
      case "Flat":
        d[h] = {
          type: "Flat",
          node: ot.fromJSON(m),
          isArray: y
        };
        break;
      case "AVL":
        d[h] = {
          type: "AVL",
          node: it.fromJSON(m),
          isArray: y
        };
        break;
      case "BKD":
        d[h] = {
          type: "BKD",
          node: ne.fromJSON(m),
          isArray: y
        };
        break;
      case "Bool":
        d[h] = {
          type: "Bool",
          node: at.fromJSON(m),
          isArray: y
        };
        break;
      default:
        d[h] = t[h];
    }
  }
  for (const h of Object.keys(r))
    u[h] = {
      type: "Vector",
      isArray: !1,
      node: lt.fromJSON(r[h])
    };
  return {
    sharedInternalDocumentStore: n,
    indexes: d,
    vectorIndexes: u,
    searchableProperties: s,
    searchablePropertiesWithTypes: i,
    frequencies: o,
    tokenOccurrences: c,
    avgFieldLength: a,
    fieldLengths: l
  };
}
function mi(n) {
  const { indexes: e, vectorIndexes: t, searchableProperties: r, searchablePropertiesWithTypes: s, frequencies: i, tokenOccurrences: o, avgFieldLength: c, fieldLengths: a } = n, l = {};
  for (const u of Object.keys(t))
    l[u] = t[u].node.toJSON();
  const d = {};
  for (const u of Object.keys(e)) {
    const { type: h, node: m, isArray: g } = e[u];
    h === "Flat" || h === "Radix" || h === "AVL" || h === "BKD" || h === "Bool" ? d[u] = {
      type: h,
      node: m.toJSON(),
      isArray: g
    } : (d[u] = e[u], d[u].node = d[u].node.toJSON());
  }
  return {
    indexes: d,
    vectorIndexes: l,
    searchableProperties: r,
    searchablePropertiesWithTypes: s,
    frequencies: i,
    tokenOccurrences: o,
    avgFieldLength: c,
    fieldLengths: a
  };
}
function Si() {
  return {
    create: ir,
    insert: fi,
    remove: di,
    insertDocumentScoreParameters: ii,
    insertTokenScoreParameters: oi,
    removeDocumentScoreParameters: ci,
    removeTokenScoreParameters: ai,
    calculateResultScores: or,
    search: hi,
    searchByWhereClause: Xe,
    getSearchableProperties: pi,
    getSearchablePropertiesWithTypes: gi,
    load: yi,
    save: mi
  };
}
function mn(n, e) {
  n || (n = /* @__PURE__ */ new Set());
  const t = e.length;
  for (let r = 0; r < t; r++) {
    const s = e[r].docIDs, i = s.length;
    for (let o = 0; o < i; o++)
      n.add(s[o]);
  }
  return n;
}
function Sn(n, e, t = !1) {
  const r = t ? ne.vincentyDistance : ne.haversineDistance, s = [], i = [];
  for (const { point: a } of n)
    i.push(r(e, a));
  const o = Math.max(...i);
  let c = 0;
  for (const { docIDs: a } of n) {
    const l = i[c], d = o - l + 1;
    for (const u of a)
      s.push([u, d]);
    c++;
  }
  return s.sort((a, l) => l[1] - a[1]), s;
}
function wi(n, e) {
  const t = Object.keys(n);
  if (t.length !== 1)
    return { isGeoOnly: !1 };
  const r = t[0], s = n[r];
  if (typeof e.indexes[r] > "u")
    return { isGeoOnly: !1 };
  const { type: i } = e.indexes[r];
  return i === "BKD" && s && ("radius" in s || "polygon" in s) ? { isGeoOnly: !0, geoProperty: r, geoOperation: s } : { isGeoOnly: !1 };
}
function xi(n, e) {
  const t = n, r = wi(e, t);
  if (!r.isGeoOnly || !r.geoProperty || !r.geoOperation)
    return null;
  const { node: s } = t.indexes[r.geoProperty], i = r.geoOperation, o = s;
  let c;
  if ("radius" in i) {
    const { value: a, coordinates: l, unit: d = "m", inside: u = !0, highPrecision: h = !1 } = i.radius, m = l, g = Qn(a, d);
    return c = o.searchByRadius(m, g, u, "asc", h), Sn(c, m, h);
  } else if ("polygon" in i) {
    const { coordinates: a, inside: l = !0, highPrecision: d = !1 } = i.polygon;
    c = o.searchByPolygon(a, l, "asc", d);
    const u = ne.calculatePolygonCentroid(a);
    return Sn(c, u, d);
  }
  return null;
}
function vi(n, e) {
  n || (n = /* @__PURE__ */ new Set());
  const t = Object.keys(e), r = t.length;
  for (let s = 0; s < r; s++) {
    const i = e[t[s]], o = i.length;
    for (let c = 0; c < o; c++)
      n.add(i[c]);
  }
  return n;
}
function cr(n, e, t, r, s) {
  const i = {
    language: n.tokenizer.language,
    sharedInternalDocumentStore: e,
    enabled: !0,
    isSorted: !0,
    sortableProperties: [],
    sortablePropertiesWithTypes: {},
    sorts: {}
  };
  for (const [o, c] of Object.entries(t)) {
    const a = `${s}${s ? "." : ""}${o}`;
    if (!r.includes(a)) {
      if (typeof c == "object" && !Array.isArray(c)) {
        const l = cr(n, e, c, r, a);
        qn(i.sortableProperties, l.sortableProperties), i.sorts = {
          ...i.sorts,
          ...l.sorts
        }, i.sortablePropertiesWithTypes = {
          ...i.sortablePropertiesWithTypes,
          ...l.sortablePropertiesWithTypes
        };
        continue;
      }
      if (!He(c))
        switch (c) {
          case "boolean":
          case "number":
          case "string":
            i.sortableProperties.push(a), i.sortablePropertiesWithTypes[a] = c, i.sorts[a] = {
              docs: /* @__PURE__ */ new Map(),
              orderedDocsToRemove: /* @__PURE__ */ new Map(),
              orderedDocs: [],
              type: c
            };
            break;
          case "geopoint":
          case "enum":
            continue;
          case "enum[]":
          case "boolean[]":
          case "number[]":
          case "string[]":
            continue;
          default:
            throw C("INVALID_SORT_SCHEMA_TYPE", Array.isArray(c) ? "array" : c, a);
        }
    }
  }
  return i;
}
function Ai(n, e, t, r) {
  return (r == null ? void 0 : r.enabled) !== !1 ? cr(n, e, t, (r || {}).unsortableProperties || [], "") : {
    disabled: !0
  };
}
function bi(n, e, t, r) {
  if (!n.enabled)
    return;
  n.isSorted = !1;
  const s = re(n.sharedInternalDocumentStore, t), i = n.sorts[e];
  i.orderedDocsToRemove.has(s) && Ft(n, e), i.docs.set(s, i.orderedDocs.length), i.orderedDocs.push([s, r]);
}
function ar(n) {
  if (n.isSorted || !n.enabled)
    return;
  const e = Object.keys(n.sorts);
  for (const t of e)
    Ti(n, t);
  n.isSorted = !0;
}
function Ei(n, e, t) {
  return e[1].localeCompare(t[1], xs(n));
}
function _i(n, e) {
  return n[1] - e[1];
}
function Ii(n, e) {
  return e[1] ? -1 : 1;
}
function Ti(n, e) {
  const t = n.sorts[e];
  let r;
  switch (t.type) {
    case "string":
      r = Ei.bind(null, n.language);
      break;
    case "number":
      r = _i.bind(null);
      break;
    case "boolean":
      r = Ii.bind(null);
      break;
  }
  t.orderedDocs.sort(r);
  const s = t.orderedDocs.length;
  for (let i = 0; i < s; i++) {
    const o = t.orderedDocs[i][0];
    t.docs.set(o, i);
  }
}
function Oi(n) {
  const e = Object.keys(n.sorts);
  for (const t of e)
    Ft(n, t);
}
function Ft(n, e) {
  const t = n.sorts[e];
  t.orderedDocsToRemove.size && (t.orderedDocs = t.orderedDocs.filter((r) => !t.orderedDocsToRemove.has(r[0])), t.orderedDocsToRemove.clear());
}
function Di(n, e, t) {
  if (!n.enabled)
    return;
  const r = n.sorts[e], s = re(n.sharedInternalDocumentStore, t);
  r.docs.get(s) && (r.docs.delete(s), r.orderedDocsToRemove.set(s, !0));
}
function Ni(n, e, t) {
  if (!n.enabled)
    throw C("SORT_DISABLED");
  const r = t.property, s = t.order === "DESC", i = n.sorts[r];
  if (!i)
    throw C("UNABLE_TO_SORT_ON_UNKNOWN_FIELD", r, n.sortableProperties.join(", "));
  return Ft(n, r), ar(n), e.sort((o, c) => {
    const a = i.docs.get(re(n.sharedInternalDocumentStore, o[0])), l = i.docs.get(re(n.sharedInternalDocumentStore, c[0])), d = typeof a < "u", u = typeof l < "u";
    return !d && !u ? 0 : d ? u ? s ? l - a : a - l : -1 : 1;
  }), e;
}
function $i(n) {
  return n.enabled ? n.sortableProperties : [];
}
function Ui(n) {
  return n.enabled ? n.sortablePropertiesWithTypes : {};
}
function Pi(n, e) {
  const t = e;
  if (!t.enabled)
    return {
      enabled: !1
    };
  const r = Object.keys(t.sorts).reduce((s, i) => {
    const { docs: o, orderedDocs: c, type: a } = t.sorts[i];
    return s[i] = {
      docs: new Map(Object.entries(o).map(([l, d]) => [+l, d])),
      orderedDocsToRemove: /* @__PURE__ */ new Map(),
      orderedDocs: c,
      type: a
    }, s;
  }, {});
  return {
    sharedInternalDocumentStore: n,
    language: t.language,
    sortableProperties: t.sortableProperties,
    sortablePropertiesWithTypes: t.sortablePropertiesWithTypes,
    sorts: r,
    enabled: !0,
    isSorted: t.isSorted
  };
}
function Ri(n) {
  if (!n.enabled)
    return {
      enabled: !1
    };
  Oi(n), ar(n);
  const e = Object.keys(n.sorts).reduce((t, r) => {
    const { docs: s, orderedDocs: i, type: o } = n.sorts[r];
    return t[r] = {
      docs: Object.fromEntries(s.entries()),
      orderedDocs: i,
      type: o
    }, t;
  }, {});
  return {
    language: n.language,
    sortableProperties: n.sortableProperties,
    sortablePropertiesWithTypes: n.sortablePropertiesWithTypes,
    sorts: e,
    enabled: n.enabled,
    isSorted: n.isSorted
  };
}
function ki() {
  return {
    create: Ai,
    insert: bi,
    remove: Di,
    save: Ri,
    load: Pi,
    sortBy: Ni,
    getSortableProperties: $i,
    getSortablePropertiesWithTypes: Ui
  };
}
const wn = 192, zi = 383, Mi = [
  65,
  65,
  65,
  65,
  65,
  65,
  65,
  67,
  69,
  69,
  69,
  69,
  73,
  73,
  73,
  73,
  69,
  78,
  79,
  79,
  79,
  79,
  79,
  null,
  79,
  85,
  85,
  85,
  85,
  89,
  80,
  115,
  97,
  97,
  97,
  97,
  97,
  97,
  97,
  99,
  101,
  101,
  101,
  101,
  105,
  105,
  105,
  105,
  101,
  110,
  111,
  111,
  111,
  111,
  111,
  null,
  111,
  117,
  117,
  117,
  117,
  121,
  112,
  121,
  65,
  97,
  65,
  97,
  65,
  97,
  67,
  99,
  67,
  99,
  67,
  99,
  67,
  99,
  68,
  100,
  68,
  100,
  69,
  101,
  69,
  101,
  69,
  101,
  69,
  101,
  69,
  101,
  71,
  103,
  71,
  103,
  71,
  103,
  71,
  103,
  72,
  104,
  72,
  104,
  73,
  105,
  73,
  105,
  73,
  105,
  73,
  105,
  73,
  105,
  73,
  105,
  74,
  106,
  75,
  107,
  107,
  76,
  108,
  76,
  108,
  76,
  108,
  76,
  108,
  76,
  108,
  78,
  110,
  78,
  110,
  78,
  110,
  110,
  78,
  110,
  79,
  111,
  79,
  111,
  79,
  111,
  79,
  111,
  82,
  114,
  82,
  114,
  82,
  114,
  83,
  115,
  83,
  115,
  83,
  115,
  83,
  115,
  84,
  116,
  84,
  116,
  84,
  116,
  85,
  117,
  85,
  117,
  85,
  117,
  85,
  117,
  85,
  117,
  85,
  117,
  87,
  119,
  89,
  121,
  89,
  90,
  122,
  90,
  122,
  90,
  122,
  115
];
function Ci(n) {
  return n < wn || n > zi ? n : Mi[n - wn] || n;
}
function Li(n) {
  const e = [];
  for (let t = 0; t < n.length; t++)
    e[t] = Ci(n.charCodeAt(t));
  return String.fromCharCode(...e);
}
const Bi = {
  ational: "ate",
  tional: "tion",
  enci: "ence",
  anci: "ance",
  izer: "ize",
  bli: "ble",
  alli: "al",
  entli: "ent",
  eli: "e",
  ousli: "ous",
  ization: "ize",
  ation: "ate",
  ator: "ate",
  alism: "al",
  iveness: "ive",
  fulness: "ful",
  ousness: "ous",
  aliti: "al",
  iviti: "ive",
  biliti: "ble",
  logi: "log"
}, Fi = {
  icate: "ic",
  ative: "",
  alize: "al",
  iciti: "ic",
  ical: "ic",
  ful: "",
  ness: ""
}, Vi = "[^aeiou]", et = "[aeiouy]", le = Vi + "[^aeiouy]*", Be = et + "[aeiou]*", Et = "^(" + le + ")?" + Be + le, ji = "^(" + le + ")?" + Be + le + "(" + Be + ")?$", qe = "^(" + le + ")?" + Be + le + Be + le, xn = "^(" + le + ")?" + et;
function Hi(n) {
  let e, t, r, s, i, o;
  if (n.length < 3)
    return n;
  const c = n.substring(0, 1);
  if (c == "y" && (n = c.toUpperCase() + n.substring(1)), r = /^(.+?)(ss|i)es$/, s = /^(.+?)([^s])s$/, r.test(n) ? n = n.replace(r, "$1$2") : s.test(n) && (n = n.replace(s, "$1$2")), r = /^(.+?)eed$/, s = /^(.+?)(ed|ing)$/, r.test(n)) {
    const a = r.exec(n);
    r = new RegExp(Et), r.test(a[1]) && (r = /.$/, n = n.replace(r, ""));
  } else s.test(n) && (e = s.exec(n)[1], s = new RegExp(xn), s.test(e) && (n = e, s = /(at|bl|iz)$/, i = new RegExp("([^aeiouylsz])\\1$"), o = new RegExp("^" + le + et + "[^aeiouwxy]$"), s.test(n) ? n = n + "e" : i.test(n) ? (r = /.$/, n = n.replace(r, "")) : o.test(n) && (n = n + "e")));
  if (r = /^(.+?)y$/, r.test(n)) {
    const a = r.exec(n);
    e = a == null ? void 0 : a[1], r = new RegExp(xn), e && r.test(e) && (n = e + "i");
  }
  if (r = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/, r.test(n)) {
    const a = r.exec(n);
    e = a == null ? void 0 : a[1], t = a == null ? void 0 : a[2], r = new RegExp(Et), e && r.test(e) && (n = e + Bi[t]);
  }
  if (r = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/, r.test(n)) {
    const a = r.exec(n);
    e = a == null ? void 0 : a[1], t = a == null ? void 0 : a[2], r = new RegExp(Et), e && r.test(e) && (n = e + Fi[t]);
  }
  if (r = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/, s = /^(.+?)(s|t)(ion)$/, r.test(n)) {
    const a = r.exec(n);
    e = a == null ? void 0 : a[1], r = new RegExp(qe), e && r.test(e) && (n = e);
  } else if (s.test(n)) {
    const a = s.exec(n);
    e = (a == null ? void 0 : a[1]) ?? "" + (a == null ? void 0 : a[2]) ?? "", s = new RegExp(qe), s.test(e) && (n = e);
  }
  if (r = /^(.+?)e$/, r.test(n)) {
    const a = r.exec(n);
    e = a == null ? void 0 : a[1], r = new RegExp(qe), s = new RegExp(ji), i = new RegExp("^" + le + et + "[^aeiouwxy]$"), e && (r.test(e) || s.test(e) && !i.test(e)) && (n = e);
  }
  return r = /ll$/, s = new RegExp(qe), r.test(n) && s.test(n) && (r = /.$/, n = n.replace(r, "")), c == "y" && (n = c.toLowerCase() + n.substring(1)), n;
}
function vn(n, e, t = !0) {
  var s;
  const r = `${this.language}:${n}:${e}`;
  return t && this.normalizationCache.has(r) ? this.normalizationCache.get(r) : (s = this.stopWords) != null && s.includes(e) ? (t && this.normalizationCache.set(r, ""), "") : (this.stemmer && !this.stemmerSkipProperties.has(n) && (e = this.stemmer(e)), e = Li(e), t && this.normalizationCache.set(r, e), e);
}
function Wi(n) {
  for (; n[n.length - 1] === ""; )
    n.pop();
  for (; n[0] === ""; )
    n.shift();
  return n;
}
function An(n, e, t, r = !0) {
  if (e && e !== this.language)
    throw C("LANGUAGE_NOT_SUPPORTED", e);
  if (typeof n != "string")
    return [n];
  const s = this.normalizeToken.bind(this, t ?? "");
  let i;
  if (t && this.tokenizeSkipProperties.has(t))
    i = [s(n, r)];
  else {
    const c = ws[this.language];
    i = n.toLowerCase().split(c).map((a) => s(a, r)).filter(Boolean);
  }
  const o = Wi(i);
  return this.allowDuplicates ? o : Array.from(new Set(o));
}
function bn(n = {}) {
  if (!n.language)
    n.language = "english";
  else if (!kt.includes(n.language))
    throw C("LANGUAGE_NOT_SUPPORTED", n.language);
  let e;
  if (n.stemming || n.stemmer && !("stemming" in n))
    if (n.stemmer) {
      if (typeof n.stemmer != "function")
        throw C("INVALID_STEMMER_FUNCTION_TYPE");
      e = n.stemmer;
    } else if (n.language === "english")
      e = Hi;
    else
      throw C("MISSING_STEMMER", n.language);
  let t;
  if (n.stopWords !== !1) {
    if (t = [], Array.isArray(n.stopWords))
      t = n.stopWords;
    else if (typeof n.stopWords == "function")
      t = n.stopWords(t);
    else if (n.stopWords)
      throw C("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");
    if (!Array.isArray(t))
      throw C("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");
    for (const s of t)
      if (typeof s != "string")
        throw C("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");
  }
  const r = {
    tokenize: An,
    language: n.language,
    stemmer: e,
    stemmerSkipProperties: new Set(n.stemmerSkipProperties ? [n.stemmerSkipProperties].flat() : []),
    tokenizeSkipProperties: new Set(n.tokenizeSkipProperties ? [n.tokenizeSkipProperties].flat() : []),
    stopWords: t,
    allowDuplicates: !!n.allowDuplicates,
    normalizeToken: vn,
    normalizationCache: /* @__PURE__ */ new Map()
  };
  return r.tokenize = An.bind(r), r.normalizeToken = vn, r;
}
function Yi(n) {
  return {
    sharedInternalDocumentStore: n,
    rules: /* @__PURE__ */ new Map()
  };
}
function Ki(n, e) {
  if (n.rules.has(e.id))
    throw new Error(`PINNING_RULE_ALREADY_EXISTS: A pinning rule with id "${e.id}" already exists. Use updateRule to modify it.`);
  n.rules.set(e.id, e);
}
function Gi(n, e) {
  if (!n.rules.has(e.id))
    throw new Error(`PINNING_RULE_NOT_FOUND: Cannot update pinning rule with id "${e.id}" because it does not exist. Use addRule to create it.`);
  n.rules.set(e.id, e);
}
function qi(n, e) {
  return n.rules.delete(e);
}
function Ji(n, e) {
  return n.rules.get(e);
}
function Xi(n) {
  return Array.from(n.rules.values());
}
function Zi(n, e) {
  const t = n.toLowerCase().trim(), r = e.pattern.toLowerCase().trim();
  switch (e.anchoring) {
    case "is":
      return t === r;
    case "starts_with":
      return t.startsWith(r);
    case "contains":
      return t.includes(r);
    default:
      return !1;
  }
}
function Qi(n, e) {
  return n ? e.conditions.every((t) => Zi(n, t)) : !1;
}
function lr(n, e) {
  if (!e)
    return [];
  const t = [];
  for (const r of n.rules.values())
    Qi(e, r) && t.push(r);
  return t;
}
function eo(n, e) {
  const t = e;
  return {
    sharedInternalDocumentStore: n,
    rules: new Map((t == null ? void 0 : t.rules) ?? [])
  };
}
function to(n) {
  return {
    rules: Array.from(n.rules.entries())
  };
}
function no() {
  return {
    create: Yi,
    addRule: Ki,
    updateRule: Gi,
    removeRule: qi,
    getRule: Ji,
    getAllRules: Xi,
    getMatchingRules: lr,
    load: eo,
    save: to
  };
}
function ro(n) {
  const e = {
    formatElapsedTime: Us,
    getDocumentIndexId: Ps,
    getDocumentProperties: Zn,
    validateSchema: tr
  };
  for (const t of pn) {
    const r = t;
    if (n[r]) {
      if (typeof n[r] != "function")
        throw C("COMPONENT_MUST_BE_FUNCTION", r);
    } else
      n[r] = e[r];
  }
  for (const t of Object.keys(n))
    if (!Xs.includes(t) && !pn.includes(t))
      throw C("UNSUPPORTED_COMPONENT", t);
}
function so({ schema: n, sort: e, language: t, components: r, id: s, plugins: i }) {
  r || (r = {});
  for (const v of i ?? []) {
    if (!("getComponents" in v) || typeof v.getComponents != "function")
      continue;
    const w = v.getComponents(n), x = Object.keys(w);
    for (const N of x)
      if (r[N])
        throw C("PLUGIN_COMPONENT_CONFLICT", N, v.name);
    r = {
      ...r,
      ...w
    };
  }
  s || (s = Jn());
  let o = r.tokenizer, c = r.index, a = r.documentsStore, l = r.sorter, d = r.pinning;
  if (o ? o.tokenize ? o = o : o = bn(o) : o = bn({ language: t ?? "english" }), r.tokenizer && t)
    throw C("NO_LANGUAGE_WITH_CUSTOM_TOKENIZER");
  const u = zs();
  c || (c = Si()), l || (l = ki()), a || (a = Gs()), d || (d = no()), ro(r);
  const { getDocumentProperties: h, getDocumentIndexId: m, validateSchema: g, formatElapsedTime: y } = r, f = {
    data: {},
    caches: {},
    schema: n,
    tokenizer: o,
    index: c,
    sorter: l,
    documentsStore: a,
    pinning: d,
    internalDocumentIDStore: u,
    getDocumentProperties: h,
    getDocumentIndexId: m,
    validateSchema: g,
    beforeInsert: [],
    afterInsert: [],
    beforeRemove: [],
    afterRemove: [],
    beforeUpdate: [],
    afterUpdate: [],
    beforeUpsert: [],
    afterUpsert: [],
    beforeSearch: [],
    afterSearch: [],
    beforeInsertMultiple: [],
    afterInsertMultiple: [],
    beforeRemoveMultiple: [],
    afterRemoveMultiple: [],
    beforeUpdateMultiple: [],
    afterUpdateMultiple: [],
    beforeUpsertMultiple: [],
    afterUpsertMultiple: [],
    afterCreate: [],
    formatElapsedTime: y,
    id: s,
    plugins: i,
    version: io()
  };
  f.data = {
    index: f.index.create(f, u, n),
    docs: f.documentsStore.create(f, u),
    sorting: f.sorter.create(f, u, n, e),
    pinning: f.pinning.create(u)
  };
  for (const v of qs)
    f[v] = (f[v] ?? []).concat(Js(f, v));
  const p = f.afterCreate;
  return p && Zs(p, f), f;
}
function io() {
  return "{{VERSION}}";
}
function oo(n) {
  return n.documentsStore.count(n.data.docs);
}
const En = "fulltext", co = "hybrid", ao = "vector";
function lo(n, e) {
  return n[1] - e[1];
}
function fo(n, e) {
  return e[1] - n[1];
}
function uo(n = "desc") {
  return n.toLowerCase() === "asc" ? lo : fo;
}
function Vt(n, e, t) {
  const r = {}, s = e.map(([l]) => l), i = n.documentsStore.getMultiple(n.data.docs, s), o = Object.keys(t), c = n.index.getSearchablePropertiesWithTypes(n.data.index);
  for (const l of o) {
    let d;
    if (c[l] === "number") {
      const { ranges: u } = t[l], h = u.length, m = Array.from({ length: h });
      for (let g = 0; g < h; g++) {
        const y = u[g];
        m[g] = [`${y.from}-${y.to}`, 0];
      }
      d = Object.fromEntries(m);
    }
    r[l] = {
      count: 0,
      values: d ?? {}
    };
  }
  const a = i.length;
  for (let l = 0; l < a; l++) {
    const d = i[l];
    for (const u of o) {
      const h = u.includes(".") ? Mt(d, u) : d[u], m = c[u], g = r[u].values;
      switch (m) {
        case "number": {
          const y = t[u].ranges;
          _n(y, g)(h);
          break;
        }
        case "number[]": {
          const y = /* @__PURE__ */ new Set(), f = t[u].ranges, p = _n(f, g, y);
          for (const v of h)
            p(v);
          break;
        }
        case "boolean":
        case "enum":
        case "string": {
          In(g, m)(h);
          break;
        }
        case "boolean[]":
        case "enum[]":
        case "string[]": {
          const p = In(g, m === "boolean[]" ? "boolean" : "string", /* @__PURE__ */ new Set());
          for (const v of h)
            p(v);
          break;
        }
        default:
          throw C("FACET_NOT_SUPPORTED", m);
      }
    }
  }
  for (const l of o) {
    const d = r[l];
    if (d.count = Object.keys(d.values).length, c[l] === "string") {
      const u = t[l], h = uo(u.sort);
      d.values = Object.fromEntries(Object.entries(d.values).sort(h).slice(u.offset ?? 0, u.limit ?? 10));
    }
  }
  return r;
}
function _n(n, e, t) {
  return (r) => {
    for (const s of n) {
      const i = `${s.from}-${s.to}`;
      t != null && t.has(i) || r >= s.from && r <= s.to && (e[i] === void 0 ? e[i] = 1 : (e[i]++, t == null || t.add(i)));
    }
  };
}
function In(n, e, t) {
  const r = e === "boolean" ? "false" : "";
  return (s) => {
    const i = (s == null ? void 0 : s.toString()) ?? r;
    t != null && t.has(i) || (n[i] = (n[i] ?? 0) + 1, t == null || t.add(i));
  };
}
const ho = {
  reducer: (n, e, t, r) => (e[r] = t, e),
  getInitialValue: (n) => Array.from({ length: n })
}, Tn = ["string", "number", "boolean"];
function jt(n, e, t) {
  const r = t.properties, s = r.length, i = n.index.getSearchablePropertiesWithTypes(n.data.index);
  for (let p = 0; p < s; p++) {
    const v = r[p];
    if (typeof i[v] > "u")
      throw C("UNKNOWN_GROUP_BY_PROPERTY", v);
    if (!Tn.includes(i[v]))
      throw C("INVALID_GROUP_BY_PROPERTY", v, Tn.join(", "), i[v]);
  }
  const o = e.map(([p]) => st(n.internalDocumentIDStore, p)), c = n.documentsStore.getMultiple(n.data.docs, o), a = c.length, l = t.maxResult || Number.MAX_SAFE_INTEGER, d = [], u = {};
  for (let p = 0; p < s; p++) {
    const v = r[p], w = {
      property: v,
      perValue: {}
    }, x = /* @__PURE__ */ new Set();
    for (let N = 0; N < a; N++) {
      const T = c[N], A = Mt(T, v);
      if (typeof A > "u")
        continue;
      const U = typeof A != "boolean" ? A : "" + A, E = w.perValue[U] ?? {
        indexes: [],
        count: 0
      };
      E.count >= l || (E.indexes.push(N), E.count++, w.perValue[U] = E, x.add(A));
    }
    d.push(Array.from(x)), u[v] = w;
  }
  const h = fr(d), m = h.length, g = [];
  for (let p = 0; p < m; p++) {
    const v = h[p], w = v.length, x = {
      values: [],
      indexes: []
    }, N = [];
    for (let T = 0; T < w; T++) {
      const A = v[T], U = r[T];
      N.push(u[U].perValue[typeof A != "boolean" ? A : "" + A].indexes), x.values.push(A);
    }
    x.indexes = Is(N).sort((T, A) => T - A), x.indexes.length !== 0 && g.push(x);
  }
  const y = g.length, f = Array.from({ length: y });
  for (let p = 0; p < y; p++) {
    const v = g[p], w = t.reduce || ho, x = v.indexes.map((U) => ({
      id: o[U],
      score: e[U][1],
      document: c[U]
    })), N = w.reducer.bind(null, v.values), T = w.getInitialValue(v.indexes.length), A = x.reduce(N, T);
    f[p] = {
      values: v.values,
      result: A
    };
  }
  return f;
}
function fr(n, e = 0) {
  if (e + 1 === n.length)
    return n[e].map((i) => [i]);
  const t = n[e], r = fr(n, e + 1), s = [];
  for (const i of t)
    for (const o of r) {
      const c = [i];
      qn(c, o), s.push(c);
    }
  return s;
}
function Ht(n, e, t, r) {
  const s = lr(e, r);
  if (s.length === 0)
    return t;
  const i = s.flatMap((f) => f.consequence.promote);
  i.sort((f, p) => f.position - p.position);
  const o = /* @__PURE__ */ new Set(), c = /* @__PURE__ */ new Map(), a = /* @__PURE__ */ new Set();
  for (const f of i) {
    const p = re(n.internalDocumentIDStore, f.doc_id);
    if (p !== void 0) {
      if (c.has(p)) {
        const v = c.get(p);
        f.position < v && c.set(p, f.position);
        continue;
      }
      a.has(f.position) || (o.add(p), c.set(p, f.position), a.add(f.position));
    }
  }
  if (c.size === 0)
    return t;
  const l = t.filter(([f]) => !o.has(f)), d = 1e6, u = [];
  for (const [f, p] of c.entries())
    t.find(([w]) => w === f) ? u.push([f, d - p]) : n.documentsStore.get(n.data.docs, f) && u.push([f, 0]);
  u.sort((f, p) => {
    const v = c.get(f[0]) ?? 1 / 0, w = c.get(p[0]) ?? 1 / 0;
    return v - w;
  });
  const h = [], m = /* @__PURE__ */ new Map();
  for (const f of u) {
    const p = c.get(f[0]);
    m.set(p, f);
  }
  let g = 0, y = 0;
  for (; y < l.length + u.length; )
    if (m.has(y))
      h.push(m.get(y)), y++;
    else if (g < l.length)
      h.push(l[g]), g++, y++;
    else
      break;
  for (const [f, p] of m.entries())
    f >= h.length && h.push(p);
  return h;
}
function ur(n, e, t) {
  const { term: r, properties: s } = e, i = n.data.index;
  let o = n.caches.propertiesToSearch;
  if (!o) {
    const u = n.index.getSearchablePropertiesWithTypes(i);
    o = n.index.getSearchableProperties(i), o = o.filter((h) => u[h].startsWith("string")), n.caches.propertiesToSearch = o;
  }
  if (s && s !== "*") {
    for (const u of s)
      if (!o.includes(u))
        throw C("UNKNOWN_INDEX", u, o.join(", "));
    o = o.filter((u) => s.includes(u));
  }
  const c = Object.keys(e.where ?? {}).length > 0;
  let a;
  c && (a = n.index.searchByWhereClause(i, n.tokenizer, e.where, t));
  let l;
  const d = e.threshold !== void 0 && e.threshold !== null ? e.threshold : 1;
  if (r || s) {
    const u = oo(n);
    if (l = n.index.search(i, r || "", n.tokenizer, t, o, e.exact || !1, e.tolerance || 0, e.boost || {}, mo(e.relevance), u, a, d), e.exact && r) {
      const h = r.trim().split(/\s+/);
      l = l.filter(([m]) => {
        const g = n.documentsStore.get(n.data.docs, m);
        if (!g)
          return !1;
        for (const y of o) {
          const f = go(g, y);
          if (typeof f == "string" && h.every((v) => new RegExp(`\\b${po(v)}\\b`).test(f)))
            return !0;
        }
        return !1;
      });
    }
  } else if (c) {
    const u = xi(i, e.where);
    u ? l = u : l = (a ? Array.from(a) : []).map((m) => [+m, 0]);
  } else
    l = Object.keys(n.documentsStore.getAll(n.data.docs)).map((h) => [+h, 0]);
  return l;
}
function po(n) {
  return n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function go(n, e) {
  const t = e.split(".");
  let r = n;
  for (const s of t)
    if (r && typeof r == "object" && s in r)
      r = r[s];
    else
      return;
  return r;
}
function yo(n, e, t) {
  var c, a;
  const r = _e();
  function s() {
    const l = Object.keys(n.data.index.vectorIndexes), d = e.facets && Object.keys(e.facets).length > 0, { limit: u = 10, offset: h = 0, distinctOn: m, includeVectors: g = !1 } = e, y = e.preflight === !0;
    let f = ur(n, e, t);
    if (e.sortBy)
      if (typeof e.sortBy == "function") {
        const w = f.map(([T]) => T), N = n.documentsStore.getMultiple(n.data.docs, w).map((T, A) => [
          f[A][0],
          f[A][1],
          T
        ]);
        N.sort(e.sortBy), f = N.map(([T, A]) => [T, A]);
      } else
        f = n.sorter.sortBy(n.data.sorting, f, e.sortBy).map(([w, x]) => [re(n.internalDocumentIDStore, w), x]);
    else
      f = f.sort(Xn);
    f = Ht(n, n.data.pinning, f, e.term);
    let p;
    y || (p = m ? Io(n, f, h, u, m) : hr(n, f, h, u));
    const v = {
      elapsed: {
        formatted: "",
        raw: 0
      },
      hits: [],
      count: f.length
    };
    if (typeof p < "u" && (v.hits = p.filter(Boolean), g || er(v, l)), d) {
      const w = Vt(n, f, e.facets);
      v.facets = w;
    }
    return e.groupBy && (v.groups = jt(n, f, e.groupBy)), v.elapsed = n.formatElapsedTime(_e() - r), v;
  }
  async function i() {
    n.beforeSearch && await Bt(n.beforeSearch, n, e, t);
    const l = s();
    return n.afterSearch && await Lt(n.afterSearch, n, e, t, l), l;
  }
  return ((c = n.beforeSearch) == null ? void 0 : c.length) || ((a = n.afterSearch) == null ? void 0 : a.length) ? i() : s();
}
const _t = {
  k: 1.2,
  b: 0.75,
  d: 0.5
};
function mo(n) {
  const e = n ?? {};
  return e.k = e.k ?? _t.k, e.b = e.b ?? _t.b, e.d = e.d ?? _t.d, e;
}
function dr(n, e, t) {
  const r = e.vector;
  if (r && (!("value" in r) || !("property" in r)))
    throw C("INVALID_VECTOR_INPUT", Object.keys(r).join(", "));
  const s = n.data.index.vectorIndexes[r.property];
  if (!s)
    throw C("UNKNOWN_VECTOR_PROPERTY", r.property);
  const i = s.node.size;
  if ((r == null ? void 0 : r.value.length) !== i)
    throw (r == null ? void 0 : r.property) === void 0 || (r == null ? void 0 : r.value.length) === void 0 ? C("INVALID_INPUT_VECTOR", "undefined", i, "undefined") : C("INVALID_INPUT_VECTOR", r.property, i, r.value.length);
  const o = n.data.index;
  let c;
  return Object.keys(e.where ?? {}).length > 0 && (c = n.index.searchByWhereClause(o, n.tokenizer, e.where, t)), s.node.find(r.value, e.similarity ?? ri, c);
}
function So(n, e, t = "english") {
  var c, a;
  const r = _e();
  function s() {
    let l = dr(n, e, t).sort(Xn);
    l = Ht(n, n.data.pinning, l, void 0);
    let d = [];
    e.facets && Object.keys(e.facets).length > 0 && (d = Vt(n, l, e.facets));
    const h = e.vector.property, m = e.includeVectors ?? !1, g = e.limit ?? 10, y = e.offset ?? 0, f = Array.from({ length: g });
    for (let x = 0; x < g; x++) {
      const N = l[x + y];
      if (!N)
        break;
      const T = n.data.docs.docs[N[0]];
      if (T) {
        m || (T[h] = null);
        const A = {
          id: st(n.internalDocumentIDStore, N[0]),
          score: N[1],
          document: T
        };
        f[x] = A;
      }
    }
    let p = [];
    e.groupBy && (p = jt(n, l, e.groupBy));
    const w = _e() - r;
    return {
      count: l.length,
      hits: f.filter(Boolean),
      elapsed: {
        raw: Number(w),
        formatted: zt(w)
      },
      ...d ? { facets: d } : {},
      ...p ? { groups: p } : {}
    };
  }
  async function i() {
    n.beforeSearch && await Bt(n.beforeSearch, n, e, t);
    const l = s();
    return n.afterSearch && await Lt(n.afterSearch, n, e, t, l), l;
  }
  return ((c = n.beforeSearch) == null ? void 0 : c.length) || ((a = n.afterSearch) == null ? void 0 : a.length) ? i() : s();
}
function wo(n, e, t) {
  const r = vo(ur(n, e, t)), s = dr(n, e, t), i = e.hybridWeights;
  return bo(r, s, e.term ?? "", i);
}
function xo(n, e, t) {
  var c, a;
  const r = _e();
  function s() {
    let l = wo(n, e, t);
    l = Ht(n, n.data.pinning, l, e.term);
    let d;
    e.facets && Object.keys(e.facets).length > 0 && (d = Vt(n, l, e.facets));
    let h;
    e.groupBy && (h = jt(n, l, e.groupBy));
    const m = e.offset ?? 0, g = e.limit ?? 10, y = hr(n, l, m, g).filter(Boolean), f = _e(), p = {
      count: l.length,
      elapsed: {
        raw: Number(f - r),
        formatted: zt(f - r)
      },
      hits: y,
      ...d ? { facets: d } : {},
      ...h ? { groups: h } : {}
    };
    if (!(e.includeVectors ?? !1)) {
      const w = Object.keys(n.data.index.vectorIndexes);
      er(p, w);
    }
    return p;
  }
  async function i() {
    n.beforeSearch && await Bt(n.beforeSearch, n, e, t);
    const l = s();
    return n.afterSearch && await Lt(n.afterSearch, n, e, t, l), l;
  }
  return ((c = n.beforeSearch) == null ? void 0 : c.length) || ((a = n.afterSearch) == null ? void 0 : a.length) ? i() : s();
}
function Ot(n) {
  return n[1];
}
function vo(n) {
  const e = Math.max.apply(Math, n.map(Ot));
  return n.map(([t, r]) => [t, r / e]);
}
function On(n, e) {
  return n / e;
}
function Ao(n, e) {
  return (t, r) => t * n + r * e;
}
function bo(n, e, t, r) {
  const s = Math.max.apply(Math, n.map(Ot)), i = Math.max.apply(Math, e.map(Ot)), o = r && r.text && r.vector, { text: c, vector: a } = o ? r : Eo(), l = /* @__PURE__ */ new Map(), d = n.length, u = Ao(c, a);
  for (let m = 0; m < d; m++) {
    const [g, y] = n[m], f = On(y, s), p = u(f, 0);
    l.set(g, p);
  }
  const h = e.length;
  for (let m = 0; m < h; m++) {
    const [g, y] = e[m], f = On(y, i), p = l.get(g) ?? 0;
    l.set(g, p + u(0, f));
  }
  return [...l].sort((m, g) => g[1] - m[1]);
}
function Eo(n) {
  return {
    text: 0.5,
    vector: 0.5
  };
}
function _o(n, e, t) {
  const r = e.mode ?? En;
  if (r === En)
    return yo(n, e, t);
  if (r === ao)
    return So(n, e);
  if (r === co)
    return xo(n, e);
  throw C("INVALID_SEARCH_MODE", r);
}
function Io(n, e, t, r, s) {
  const i = n.data.docs, o = /* @__PURE__ */ new Map(), c = [], a = /* @__PURE__ */ new Set(), l = e.length;
  let d = 0;
  for (let u = 0; u < l; u++) {
    const h = e[u];
    if (typeof h > "u")
      continue;
    const [m, g] = h;
    if (a.has(m))
      continue;
    const y = n.documentsStore.get(i, m), f = Mt(y, s);
    if (!(typeof f > "u" || o.has(f)) && (o.set(f, !0), d++, !(d <= t) && (c.push({ id: st(n.internalDocumentIDStore, m), score: g, document: y }), a.add(m), d >= t + r)))
      break;
  }
  return c;
}
function hr(n, e, t, r) {
  const s = n.data.docs, i = Array.from({
    length: r
  }), o = /* @__PURE__ */ new Set();
  for (let c = t; c < r + t; c++) {
    const a = e[c];
    if (typeof a > "u")
      break;
    const [l, d] = a;
    if (!o.has(l)) {
      const u = n.documentsStore.get(s, l);
      i[c] = { id: st(n.internalDocumentIDStore, l), score: d, document: u }, o.add(l);
    }
  }
  return i;
}
function To(n, e) {
  n.internalDocumentIDStore.load(n, e.internalDocumentIDStore), n.data.index = n.index.load(n.internalDocumentIDStore, e.index), n.data.docs = n.documentsStore.load(n.internalDocumentIDStore, e.docs), n.data.sorting = n.sorter.load(n.internalDocumentIDStore, e.sorting), n.data.pinning = n.pinning.load(n.internalDocumentIDStore, e.pinning), n.tokenizer.language = e.language;
}
var tt = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
function Oo(n) {
  if (n.__esModule) return n;
  var e = n.default;
  if (typeof e == "function") {
    var t = function r() {
      return this instanceof r ? Reflect.construct(e, arguments, this.constructor) : e.apply(this, arguments);
    };
    t.prototype = e.prototype;
  } else t = {};
  return Object.defineProperty(t, "__esModule", { value: !0 }), Object.keys(n).forEach(function(r) {
    var s = Object.getOwnPropertyDescriptor(n, r);
    Object.defineProperty(t, r, s.get ? s : {
      enumerable: !0,
      get: function() {
        return n[r];
      }
    });
  }), t;
}
const Do = {}, No = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Do
}, Symbol.toStringTag, { value: "Module" })), pr = /* @__PURE__ */ Oo(No);
var Ie = {};
(function(n) {
  var e = 0, t = 3, r = 2, s = 1, i = 7, o = 0, c = 3, a = 4, l = 5, d = 6, u = 7, h = 8, m = 9, g = 11, y = 13, f = 500, p = 12, v = 14, w = 15, x = 1, N = typeof Symbol < "u" ? Symbol.iterator : "__iterator_symbol__";
  function T(P) {
    P || (P = {});
    var M = P.converterByConstructor;
    M || (M = /* @__PURE__ */ new Map()), M.set(Map, {
      name: "Map",
      toValue: G
    }), M.set(Set, {
      name: "Set",
      toValue: R
    }), M.set(Date, {
      name: "Date",
      toValue: W
    }), P.outlet || P.avoidShareUpdate;
    var z = typeof tt < "u" && tt.Buffer && !(P && P.encoding === "utf16le") ? n.nodeCharEncoder(P) : U(), F = z.writeString, _ = z.writeToken, O = z.startSequence, Y = z.endSequence, Te = z.writeBuffer;
    P.forProperty;
    var Q;
    P.shared && (Q = P.shared.propertyUsed, P.shared.propertyUsed);
    var se = [], b, Ye = n.bufferSymbol || "_bufferSymbol_", ft = n.targetSymbol || "_targetSymbol_", fe = x++, Oe = [
      0,
      1,
      2,
      3,
      4,
      5,
      ie,
      pt,
      ut,
      dt,
      vr
    ];
    function wr(S) {
      _(s, S);
    }
    function ue(S) {
      _(r, S.length), F(S);
    }
    function ut(S) {
      var k, I = b.values;
      if (I) {
        I.resetTo > -1 && I.serializer !== fe && (I.serializer = fe, I.resetTo < I.length && (I.length = I.resetTo), _(t, y), _(s, I.resetTo));
        var D = I.indexOf(S);
        if (D > -1)
          return wr(D);
      }
      if ((k = typeof S) == "string" || k === "object" && S) {
        if (b.writeSharedValue) {
          if (b.writeSharedValue(S, _, fe))
            return;
        } else if (I) {
          var B = I.length;
          B < 12 && (I[B] = S);
        }
      }
      k === "string" ? ue(S) : ie(S);
    }
    function dt(S) {
      var k = typeof S;
      if (k === "number")
        if (S >>> 0 === S || S > 0 && S < 70368744177664 && S % 1 === 0)
          _(s, S);
        else {
          var I = S.toString();
          ue(I);
        }
      else k === "object" ? ie(S) : De(S);
    }
    function De(S) {
      S === null ? _(t, o) : S === !1 ? _(t, c) : S === !0 ? _(t, a) : S === void 0 ? _(t, l) : xr(S);
    }
    function xr(S) {
      var k = typeof S, I;
      if (k === "object")
        if (S) {
          var D = S.constructor;
          if (D !== Object) if (D === Array)
            k = "array";
          else if (I = M.get(D), I && I.toValue) {
            if (S = I.toValue(S), k = typeof S, S && k === "object" && S.constructor === Array && (k = "array"), b.type === k)
              return b.extendedType !== I && (b.extendedType = I, _(t, g), ue(I.name)), Oe[b.code](S);
          } else
            I = !1;
        } else
          k = "undefined";
      else k === "boolean" ? k = "undefined" : k === "function" && (S = S.toString(), k = "string");
      b = oe(null, k, I), Oe[b.code](S);
    }
    function vr() {
      _(t, o);
    }
    function ie(S, k) {
      var I = typeof S;
      if (I === "object") {
        if (!S)
          return _(t, o);
      } else return I === "string" ? ue(S) : I === "number" && (S >>> 0 === S || S > 0 && S < 70368744177664 && S % 1 === 0) ? _(s, S) : De(S);
      var D = S, B = D.constructor, j;
      if (D[ft])
        return gt(S);
      if (B === Object)
        j = !1;
      else {
        if (B === Array)
          return b = oe(b.key, "array"), Oe[b.code](S);
        if (D.then)
          return gt(S);
        if (X = M.get(B), X) {
          if (X.toValue)
            return De(D);
        } else {
          if (D[N])
            return b = oe(b.key, "array"), ht(D, k);
          M.set(B, X = {
            name: B.name
          });
        }
        b.constructs !== B && (_(t, g), ue(X.name), b.constructs = B), j = !0;
      }
      var $ = b;
      $.resetTo < $.length && $.serializer != fe && ($.length = $.resetTo, $.serializer = fe), O();
      var L = 0, J = -2, H = 0;
      for (var ce in D)
        if (!(j && !D.hasOwnProperty(ce))) {
          var S = D[ce];
          I = typeof S, b = $[H];
          var B, X = !1;
          if (I === "object" && (S ? (B = S.constructor, B === Object || (B === Array ? I = "array" : (X = M.get(B), X && X.toValue ? (S = X.toValue(S), I = typeof S, S && I === "object" && S.constructor === Array && (I = "array")) : S[N] && !S.then ? I = "array" : X = !1))) : I = "undefined"), !b || b.key !== ce || b.type !== I && I !== "boolean" && I !== "undefined" && !(I === "string" && b.type !== "number") || X && b.extendedType !== B) {
            var ge = H;
            J > -2 && (H = J);
            do
              b = $[++H];
            while (b && (b.key !== ce || b.type !== I && I !== "boolean" && I !== "undefined" && !(I === "string" && b.type !== "number") || X && b.extendedType !== B));
            if (b)
              _(e, H), J === -2 && (J = ge - 1);
            else if ($.getProperty)
              b = $.getProperty(S, ce, I, X, oe, _, ge), H = b.index, ge !== H && J === -2 && (J = ge - 1);
            else {
              if (ge === $.length ? H = ge : (_(e, H = $.length), J === -2 && (J = ge - 1)), H < $.resetTo) {
                debugger;
                throw new Error("overwriting frozen property");
              }
              b = $[H] = oe(ce, I, X);
            }
          }
          Q && Q(b, D, fe, L);
          var yt = b.code;
          yt > 7 ? yt === 8 ? ut(S) : dt(S) : yt === 6 ? ie(S) : pt(S), H++, L++;
        }
      b = $, Y(L);
    }
    function oe(S, k, I) {
      var D;
      return D = [], D.key = S, D.type = k, k === "string" ? (_(t, h), D.values = [], D.code = h) : k === "number" ? (_(t, m), D.code = m) : k === "object" ? (_(t, d), D.code = d) : k === "array" ? (_(t, u), D.code = u) : k === "boolean" || k === "undefined" ? (D.type = "object", _(t, d), D.code = d) : (_(t, d), D.code = 10, console.error("Unable to write value of type " + k)), typeof S == "string" ? ue(S) : S === null && (k === "object" || k === "array") || ie(S), I && (D.extendedType = I, _(t, g), ue(I.name)), D;
    }
    function ht(S, k, I) {
      try {
        I || (_(i, p), I = S[N]());
        var D = b;
        b = D.child || (D.child = D);
        for (var B; !(B = I.next()).done; )
          if (Oe[b.code](B.value, D), k && z.hasWritten) {
            z.hasWritten = !1, b = D, se.unshift({
              then: function(j) {
                return ht(null, !0, I), j();
              }
            });
            return;
          }
      } catch (j) {
        throw _(t, g), _(s, f), ie(Object.assign(new (typeof j == "object" && j ? j.constructor : Error)(), {
          name: j && j.name,
          // make these enumerable so they will serialize
          message: j && j.message || j
        })), j;
      }
      b !== D.child && (D.child = b), b = D, _(i, v);
    }
    function pt(S) {
      if (!S)
        De(S);
      else {
        if (S[ft])
          return gt(S);
        if (S.constructor === Array) {
          var k = S.length, I;
          k > 11 ? (_(i, p), I = !0) : _(i, k);
          var D = b;
          b = D[0], D.resetTo < D.length && D.serializer != fe && (D.length = D.resetTo, D.serializer = fe);
          for (var B = 0, j = 0; j < k; j++) {
            var $ = S[j], L = typeof $;
            if (L === "object")
              if ($) {
                var J = $.constructor;
                if (J !== Object) if (J === Array)
                  L = "array";
                else {
                  var H = M.get(J);
                  H && H.toValue ? ($ = H.toValue($), L = typeof $, $ && L === "object" && $.constructor === Array && (L = "array")) : H = !1;
                }
              } else
                L = "undefined";
            if (!b)
              D.getProperty ? b = D.getProperty($, null, L, H, oe, _, 0) : (L === "string" || L === "number" || L === "array" ? b = oe(null, L, H) : (b = [], b.type = L, b.key = null, b.code = d), D[0] = b);
            else if (b.type !== L && L !== "boolean" && L !== "undefined" && !(L === "string" && b.type !== "number") || H && b.extendedType !== J) {
              B = -1;
              do
                b = D[++B];
              while (b && (b.type !== L && L !== "boolean" && L !== "undefined" && !(L === "string" && b.type !== "number") || H && b.extendedType !== J));
              b ? _(e, B) : D.getProperty ? b = D.getProperty($, null, L, H, oe, _, -1) : (_(e, B), b = oe(null, L, H), D[B] = b);
            }
            Q && Q(b, S, fe, j);
            var ce = b.code;
            ce > 7 ? ce === 8 ? ut($) : dt($) : ce === 6 ? ie($) : pt($);
          }
          I && _(i, v), b = D;
        } else {
          if (typeof S == "object" && S[N])
            return ht(S);
          if (L === "string")
            return ue($);
          if (L === "number" && ($ >>> 0 === $ || $ > 0 && $ < 70368744177664 && $ % 1 === 0))
            return _(s, $);
          De(S);
        }
      }
    }
    function gt(S, k) {
      _(i, w);
      var I = b, D = S[ft] ? {
        then: B
      } : {
        then: function(j) {
          return S.then(function($) {
            S = $, B(j);
          }, function($) {
            S = Object.assign(new (typeof $ == "object" && $ ? $.constructor : Error)(), {
              name: $ && $.name,
              // make these enumerable so they will serialize
              message: $ && $.message || $
            }), I.upgrade || (_(t, g), _(s, f)), B(j);
          });
        }
      };
      function B(j) {
        if (P.forBlock && S)
          P.forBlock(S, I);
        else {
          var $ = S && S[Ye] && S[Ye](I);
          if ($)
            Te($);
          else {
            b = I;
            var L = se;
            se = [], ie(S, !0), L.unshift.apply(L, se), se = L;
          }
        }
        j();
      }
      se.push(D);
    }
    var Gt = {
      serialize: function(S, k) {
        var I = S && S[Ye] && S[Ye](k);
        if (I) {
          z.writeBuffer(I);
          return;
        }
        k ? (b = k, Oe[b.code](S)) : (b = [], b.key = null, ie(S, !0));
      },
      getSerialized: function() {
        if (se.length > 0) {
          for (var S = []; se.length > 0; ) {
            var k = !1, I = se.shift().then(function() {
              k = !0;
            });
            k || S.push(I);
          }
          if (S.length > 0)
            return Promise.all(S).then(function() {
              return Gt.getSerialized();
            });
        }
        return P && P.encoding === "utf16le" ? Buffer.from(z.getSerialized(), "utf16le") : z.getSerialized();
      },
      flush: z.flush,
      setOffset: z.setOffset,
      finish: z.finish,
      pendingEncodings: se,
      getWriters: function() {
        return {
          writeProperty: oe,
          writeToken: _,
          writeAsDefault: ie,
          writeBuffer: Te
        };
      }
    };
    return Gt;
  }
  function A(P, M) {
    var z = T(M), F = M && M.shared, _;
    F && F.startWrite && F.startWrite(M.avoidShareUpdate, P), z.serialize(P, F), _ = z.getSerialized(), F && F.endWrite && F.endWrite(M.avoidShareUpdate, P), z.finish && z.finish();
    var O = P && P[n.sizeTableSymbol];
    return O && (_.sizeTable = O), M && M.lazy ? Buffer.concat([P[n.sizeTableSymbol], _]) : _;
  }
  n.serialize = A, n.createSerializer = T;
  function U() {
    var P = "";
    function M(_, O) {
      var Y;
      if (O < 16)
        Y = String.fromCharCode((_ << 4 | O) ^ 64);
      else if (O < 1024)
        Y = String.fromCharCode(
          (_ << 4) + (O >>> 6),
          (O & 63) + 64
        );
      else if (O < 65536)
        Y = String.fromCharCode(
          (_ << 4) + (O >>> 12),
          O >>> 6 & 63,
          (O & 63) + 64
        );
      else if (O < 4194304)
        Y = String.fromCharCode(
          (_ << 4) + (O >>> 18),
          O >>> 12 & 63,
          O >>> 6 & 63,
          (O & 63) + 64
        );
      else if (O < 268435456)
        Y = String.fromCharCode(
          (_ << 4) + (O >>> 24),
          O >>> 18 & 63,
          O >>> 12 & 63,
          O >>> 6 & 63,
          (O & 63) + 64
        );
      else if (O < 4294967296)
        Y = String.fromCharCode(
          (_ << 4) + (O >>> 30),
          O >>> 24 & 63,
          O >>> 18 & 63,
          O >>> 12 & 63,
          O >>> 6 & 63,
          (O & 63) + 64
        );
      else if (O < 17179869184)
        Y = String.fromCharCode(
          (_ << 4) + (O / 1073741824 >>> 0),
          O >>> 24 & 63,
          O >>> 18 & 63,
          O >>> 12 & 63,
          O >>> 6 & 63,
          (O & 63) + 64
        );
      else if (O < 1099511627776)
        Y = String.fromCharCode(
          (_ << 4) + (O / 68719476736 >>> 0),
          O / 1073741824 & 63,
          O >>> 24 & 63,
          O >>> 18 & 63,
          O >>> 12 & 63,
          O >>> 6 & 63,
          (O & 63) + 64
        );
      else if (O < 70368744177664)
        Y = String.fromCharCode(
          (_ << 4) + (O / 4398046511104 >>> 0),
          O / 68719476736 & 63,
          O / 1073741824 & 63,
          O >>> 24 & 63,
          O >>> 18 & 63,
          O >>> 12 & 63,
          O >>> 6 & 63,
          (O & 63) + 64
        );
      else
        throw new Error("Too big of number");
      P += Y;
    }
    function z(_) {
      P += _;
    }
    function F() {
      return P;
    }
    return {
      writeToken: M,
      writeString: z,
      //writeBuffer,
      getSerialized: F,
      //insertBuffer,
      //flush,
      startSequence: function() {
        M(i, p);
      },
      endSequence: function() {
        M(i, v);
      },
      getOffset: function() {
        return -1;
      }
    };
  }
  var E = Array.from || function(P, F) {
    var z = [], F = P.constructor === Map;
    return P.forEach(function(_, O) {
      F ? z.push([O, _]) : z.push(_);
    }), z;
  };
  function G(P) {
    for (var M = E(P), z = 0, F = M.length; z < F; z++) {
      var _ = M[z];
      M[z] = {
        key: _[0],
        value: _[1]
      };
    }
    return M;
  }
  function R(P) {
    return E(P);
  }
  function W(P) {
    return P.getTime();
  }
})(Ie);
const { Transform: Ec } = pr, { createSerializer: _c } = Ie;
var Wt = {}, $o = 3, Uo = 4, Dn = 6, Nn = 7, $n = 8, Un = 9, Pn = 11, Po = 13, Ro = 14, ko = 500, zo = 12, Mo = 14, Co = 15;
function gr(n) {
  n || (n = {});
  var e, t, r, s = n.classByName || /* @__PURE__ */ new Map();
  s.set("Map", Lo), s.set("Set", Bo), s.set("Date", Fo);
  var i, o;
  function c(g, y) {
    if (g.previous = i, g.resume = !0, i = g, !r)
      throw new Error("Unexpected end of dpack stream");
    return m.onResume || (m.onResume = function(f, p, v) {
      var w = i;
      return i = null, m.onResume = null, y < t.length ? t = t.slice(y) + f : v ? t = f.slice(0, 1) + f.slice(1) : t = f, r = p, u += y, e = 0, w.reader ? w.reader(w) : a(w.length, w);
    }), g.object;
  }
  function a(g, y) {
    var f = 0;
    y = y || [];
    var p, v, w, x, N = 0, T = 0;
    if (y.resume) {
      if (p = y.previous, p) {
        var x = p.reader ? p.reader(p) : a(p.length, p), A = p.values;
        A && (i ? i.values = A : x.nextPosition > -1 ? A[A.nextPosition++] = x : A.push(x));
      }
      y.code && y.code !== y.thisProperty.code ? y.resume = !1 : (N = y.i || 0, w = y.object, f = y.propertyState || 0, T = y.propertyIndex || 0, y = y.thisProperty);
    }
    for (v = y.code === Nn, w = w || (y.constructs ? new y.constructs() : v ? [] : {}); N < g; ) {
      var U, E, G = e, R = t.charCodeAt(e++);
      if (R >= 48)
        R > 12288 ? (U = R >>> 12 ^ 4, E = R & 4095) : (U = R >>> 4 ^ 4, E = R & 15);
      else if (U = R >>> 4 & 11, E = R & 15, R = t.charCodeAt(e++), E = (E << 6) + (R & 63), !(R >= 64) && (R = t.charCodeAt(e++), E = (E << 6) + (R & 63), !(R >= 64) && (R = t.charCodeAt(e++), E = (E << 6) + (R & 63), !(R >= 64) && (R = t.charCodeAt(e++), E = (E << 6) + (R & 63), !(R >= 64) && (R = t.charCodeAt(e++), E = E * 64 + (R & 63), !(R >= 64) && (R = t.charCodeAt(e++), E = E * 64 + (R & 63), !(R >= 64) && (R = t.charCodeAt(e++), E = E * 64 + (R & 63), !(R >= 0) && e > t.length)))))))
        return c({
          length: g,
          thisProperty: y,
          i: N,
          object: w,
          propertyIndex: T,
          propertyState: f
        }, G);
      if (U === 0) {
        T = E, f = 0;
        continue;
      }
      if (p = y[T], U === 3)
        if (E < 6)
          E < 3 ? E === 0 ? x = null : x = "Unknown token, type: " + U + " number: " + E : E === Uo ? x = !0 : E === $o ? x = !1 : x = void 0;
        else {
          if (E <= Un) {
            if (f === 1 && (T++, N++, p = y[T]), T < y.resetTo)
              throw new Error("Overwriting frozen property");
            p ? p.resume || (x = p.key, p = y[T] = [], p.key = x) : (p = y[T] = [], p.key = null), p.code = E, p.parent = y, f = 2, E === $n ? p.values = [] : E === Nn && (p[0] = [], p[0].key = null, p[0].code = Dn, p[0].parent = p);
          } else
            f = E;
          continue;
        }
      else if (U === 2) {
        if (x = t.slice(e, e += E), e > t.length)
          return c({
            length: g,
            thisProperty: y,
            i: N,
            object: w,
            propertyIndex: T,
            propertyState: f
          }, G);
        f < 2 && p.code === Un && (x = +x);
      } else if (U === 1)
        x = E;
      else if (E > 13) {
        if (E === Mo)
          return w;
        E === Co && (x = a(0, p), f = 0, n.forDeferred ? x = n.forDeferred(x, p) : (o || (o = [])).push({
          property: p,
          value: x
        }));
      } else if (E >= zo && (E = 2e9), f > 1 ? f === 2 ? (f = 0, x = a(E, p)) : f === Pn ? x = a(E, [{ key: null, code: 6 }]) : p.resume && (p.code || Dn) === p.thisProperty.code ? x = a(E, p.thisProperty) : x = a(E, p) : x = a(E, p), i) {
        if (x === void 0)
          return i = null, m.onResume = null, c({
            length: g,
            thisProperty: y,
            i: N,
            object: w,
            property: p,
            propertyIndex: T,
            previousProperty,
            propertyState: f
          }, G);
        i.values = p.values instanceof Array ? p.values : void 0;
      }
      if (!p)
        throw new Error("No property defined for slot" + (y.key ? " in " + y.key : ""));
      if (f < 2 && p && p.code === $n) {
        var A = p.values;
        if (typeof x == "number") {
          if (x = A[E], x === void 0 && !(E in A))
            throw new Error("Referencing value that has not been read yet");
        } else (U === 2 || U === 7) && A && (A.nextPosition > -1 ? (p.recordValueReference && p.recordValueReference(A), A[A.nextPosition++] = x) : A.push(x));
      }
      if (f > 1) {
        if (f === 2)
          p.key = x;
        else if (f === Pn)
          if (typeof x == "string") {
            var W = s.get(x);
            if (W)
              W.fromValue ? p.fromValue = W.fromValue : p.constructs = W;
            else if (n.errorOnUnknownClass)
              throw new Error("Attempt to deserialize to unknown class " + parameter);
            p.extendedType = W;
          } else
            p.metadata = x, x === ko && (p.fromValue = d);
        else if (f === Po) {
          var A = p.values || (p.values = []);
          A.nextPosition = x;
        } else if (f !== Ro) throw new Error("Unknown property type " + f);
        f = 1;
        continue;
      } else
        f = 0;
      p.fromValue && (x = p.fromValue(x)), v && p.key === null ? w.push(x) : x !== void 0 && (w[p.key] = x), N++, v || T++;
    }
    return w;
  }
  var l;
  function d(g) {
    var y = typeof tt < "u" ? tt : window;
    if (g && g.name && y[g.name] ? g = new y[g.name](g.message) : typeof g == "string" && (g = new Error(g)), n.onError)
      n.onError(g);
    else
      throw l = !0, g;
  }
  var u = 0;
  function h(g) {
    try {
      if (g && g.resume) {
        var y = g.previous;
        f = a(y.length, y), f = g.object || f, g = g.property;
      } else {
        g = g || [n && n.shared || {
          key: null,
          code: 6
        }];
        var f = a(1, g)[g[0].key];
      }
      for (; ; ) {
        if (i)
          return c({
            reader: h,
            object: f,
            property: g
          });
        if (!o)
          return f;
        var p = o.index || 0, v = o[p];
        if (o.index = p + 1, !v) {
          o = o.parent;
          continue;
        }
        var w = v.value, x = o;
        o = [], o.parent = x;
        var N = v.property, T = a(1, g = [{
          resume: !0,
          key: null,
          thisProperty: N,
          object: w
        }]);
        T = T.null || T[N.key], T != w && (Object.assign(w, T), i && i.object === T && (i.object = w), T && T.constructor === Array && (w.length = T.length, Object.setPrototypeOf(w, Object.getPrototypeOf(T))));
      }
    } catch (A) {
      throw l || (A.message = "DPack parsing error: " + A.message + " at position: " + (e + u) + " near: " + t.slice(e - 10, e + 10)), A;
    }
  }
  var m = {
    setSource: function(g, y, f) {
      return t = g, e = y || 0, u = 0, r = f, this;
    },
    hasMoreData: function() {
      return t.length > e;
    },
    isPaused: function() {
      return i;
    },
    hasUnfulfilledReferences: function() {
      return o && o.length > o.index;
    },
    getOffset: function() {
      return e + u;
    },
    read: h
  };
  return m;
}
Wt.parse = function(n, e) {
  var t;
  if (typeof n == "string")
    t = n;
  else if (n && n.toString)
    t = n.toString(e && e.encoding || "utf8");
  else
    return n;
  var r = gr(e).setSource(t);
  return e && e.shared ? r.read([e.shared]) : r.read();
};
Wt.createParser = gr;
var Lo = {
  fromValue: function(n) {
    for (var e = /* @__PURE__ */ new Map(), t = 0, r = n.length; t < r; t++) {
      var s = n[t];
      e.set(s.key, s.value);
    }
    return e;
  }
}, Bo = {
  fromValue: function(n) {
    var e = new Set(n);
    if (e.size === 0 && n.length > 0)
      for (var t = 0, r = n.length; t < r; t++)
        e.add(n[t]);
    return e;
  }
}, Fo = {
  fromValue: function(n) {
    return new Date(n);
  }
};
pr.Transform;
var yr = {}, Rn = 32768, kn = [];
function Vo(n) {
  var e = n.startOffset || 0, t, r = n.outlet, s = kn.pop();
  s && s.length > e + 128 ? t = s.length : (t = (e >> 12 << 12) + 8192, s = Buffer.allocUnsafeSlow(t));
  var i = n.encoding, o = [];
  function c(y) {
    if (r)
      r.writeBytes(s.slice(0, e)), (t < Rn || y > Rn) && (t = Math.max(t * 4, y)), s = Buffer.allocUnsafeSlow(t), e = 0, o = [], g.hasWritten = !0;
    else {
      t = Math.max(t * 4, t + y, 8192);
      var f = s;
      s = Buffer.allocUnsafeSlow(t), f.copy(s, 0, 0, e);
    }
  }
  function a(y) {
    (y || r).writeBytes(s.slice(0, e)), e + 128 > s.length ? s = Buffer.allocUnsafeSlow(t = Math.min(Math.max((e >> 10 << 10) + 8192, t), 32768)) : (s = s.slice(e), t = s.length), e = 0, o = [];
  }
  function l(y, f) {
    if (f < 16)
      s[e++] = (y << 4) + f ^ 64;
    else if (f < 1024)
      s[e++] = (y << 4) + (f >>> 6), s[e++] = (f & 63) + 64;
    else if (f < 65536)
      s[e++] = (y << 4) + (f >>> 12), s[e++] = f >>> 6 & 63, s[e++] = (f & 63) + 64;
    else if (f < 4194304)
      s[e++] = (y << 4) + (f >>> 18), s[e++] = f >>> 12 & 63, s[e++] = f >>> 6 & 63, s[e++] = (f & 63) + 64;
    else if (f < 268435456)
      s[e++] = (y << 4) + (f >>> 24), s[e++] = f >>> 18 & 63, s[e++] = f >>> 12 & 63, s[e++] = f >>> 6 & 63, s[e++] = (f & 63) + 64;
    else if (f < 4294967296)
      s[e++] = (y << 4) + (f >>> 30), s[e++] = f >>> 24 & 63, s[e++] = f >>> 18 & 63, s[e++] = f >>> 12 & 63, s[e++] = f >>> 6 & 63, s[e++] = (f & 63) + 64;
    else if (f < 17179869184)
      s[e++] = (y << 4) + (f / 1073741824 >>> 0), s[e++] = f >>> 24 & 63, s[e++] = f >>> 18 & 63, s[e++] = f >>> 12 & 63, s[e++] = f >>> 6 & 63, s[e++] = (f & 63) + 64;
    else if (f < 1099511627776)
      s[e++] = (y << 4) + (f / 68719476736 >>> 0), s[e++] = f / 1073741824 & 63, s[e++] = f >>> 24 & 63, s[e++] = f >>> 18 & 63, s[e++] = f >>> 12 & 63, s[e++] = f >>> 6 & 63, s[e++] = (f & 63) + 64;
    else if (f < 70368744177664)
      s[e++] = (y << 4) + (f / 4398046511104 >>> 0), s[e++] = f / 68719476736 & 63, s[e++] = f / 1073741824 & 63, s[e++] = f >>> 24 & 63, s[e++] = f >>> 18 & 63, s[e++] = f >>> 12 & 63, s[e++] = f >>> 6 & 63, s[e++] = (f & 63) + 64;
    else
      throw new Error("Invalid number " + f);
    e > t - 10 && c(0);
  }
  function d(y) {
    var f = y.length;
    f + e + 10 > t && c(f + 10), y.copy(s, e), e += f;
  }
  function u(y) {
    var f = y.length, p = f * 3 + 10;
    e + p > t && c(p + 10);
    var v = i ? s.write(y, e, s.length, i) : s.utf8Write(y, e, s.length);
    e += v;
  }
  function h() {
    return s.slice(0, e);
  }
  function m(y, f) {
    var p = y.length;
    e + p + 10 > t && c(p + 10), s.copy(s, p + f, f, e), y.copy(s, f), e += p;
  }
  var g = {
    writeToken: l,
    writeString: u,
    writeBuffer: d,
    getSerialized: h,
    insertBuffer: m,
    flush: a,
    startSequence() {
      var y = e;
      s[e++] = 60, o.push(y), e > t - 10 && c(0);
    },
    endSequence(y) {
      var f = o.pop();
      if (y < 12 && f > -1) {
        s[f] = 48 + y;
        return;
      }
      s[e++] = 62;
    },
    finish() {
      s.length - e > 144 && kn.push(s.slice(e));
    },
    getOffset() {
      return e;
    },
    setOffset(y) {
      e = y;
    }
  };
  return g;
}
yr.nodeCharEncoder = Vo;
function jo() {
  this.classByName = /* @__PURE__ */ new Map(), this.converterByConstructor = /* @__PURE__ */ new Map();
}
jo.prototype.addExtension = function(n, e, t) {
  e && n.name !== e && (n.name = e), this.classByName.set(n.name, t && t.fromArray ? t : n), this.converterByConstructor.set(n, t && t.toArray ? t : n);
};
Ie.createSerializer;
Ie.serialize;
var Yt = typeof Symbol < "u" ? Symbol : function(n) {
  return "symbol-" + n;
}, Ho = Yt("buffer"), Wo = Yt("sizeTable"), Yo = Yt("target"), We = Ie;
We.bufferSymbol = Ho;
We.targetSymbol = Yo;
We.sizeTableSymbol = Wo;
We.serialize;
We.createSerializer;
const Kt = Ie;
Kt.nodeCharEncoder = yr.nodeCharEncoder;
const Ko = Wt;
Kt.serialize;
var Go = Ko.parse;
Kt.createSerializer;
function qo(n) {
  return `Unsupported serialization format: ${n}`;
}
function Jo() {
  return typeof process < "u" && process.versions !== void 0 ? "node" : typeof Deno < "u" ? "deno" : typeof Bun < "u" ? "bun" : typeof window < "u" ? "browser" : "unknown";
}
const Xo = 0, Zo = 1, Qo = 2, ec = 2 ** 32;
function tc(n) {
  const e = Math.floor(n.byteLength / 4);
  return {
    index: 0,
    buffer: n,
    uint32Array: new Uint32Array(n, 0, e),
    float32Array: new Float32Array(n, 0, e),
    setBuffer: function(t, r, s) {
      if (typeof r == "number" && typeof s == "number") {
        this.index = Math.floor(r / 4);
        const o = this.index + Math.ceil(s / 4);
        this.buffer = t, this.uint32Array = new Uint32Array(t, 0, o), this.float32Array = new Float32Array(t, 0, o);
        return;
      }
      const i = Math.floor(t.byteLength / 4);
      this.buffer = t, this.index = 0, this.uint32Array = new Uint32Array(t, 0, i), this.float32Array = new Float32Array(t, 0, i);
    },
    deserializeBoolean: nc,
    deserializeUInt32: rc,
    deserializeFloat32: sc,
    deserializeNumber: ic,
    deserializeString: cc,
    deserializeArray: ac,
    deserializeIterable: lc,
    getArrayElements: uc,
    unsafeDeserializeUint32Array: fc
  };
}
function nc() {
  return this.uint32Array[this.index++] === 1;
}
function rc() {
  return this.uint32Array[this.index++];
}
function sc() {
  return this.float32Array[this.index++];
}
function ic() {
  const n = this.uint32Array[this.index++];
  if (n === Xo)
    return this.deserializeFloat32();
  if (n === Zo)
    return this.deserializeUInt32();
  if (n === Qo)
    return this.uint32Array[this.index++] - ec;
  throw new Error("Unknown type");
}
new TextEncoder();
const oc = new TextDecoder();
function cc() {
  const n = this.uint32Array[this.index++], e = oc.decode(new Uint8Array(this.buffer, this.index * 4, n));
  return this.index += Math.ceil(n / 4), e;
}
function ac(n) {
  const e = this.deserializeUInt32(), t = new Array(e);
  for (let r = 0; r < e; r++)
    t[r] = n(this);
  return t;
}
function lc(n) {
  const e = this.deserializeUInt32(), t = function* (r) {
    for (let s = 0; s < e; s++)
      yield n(r);
  }(this);
  return {
    [Symbol.iterator]() {
      return t;
    }
  };
}
function fc() {
  const n = this.uint32Array[this.index++], e = new Uint32Array(this.buffer, this.index * 4, n);
  return this.index += n, e;
}
function uc(n, e) {
  const t = this.index + 1, r = n.length, s = new Array(r);
  for (let i = 0; i < r; i++) {
    const o = t + n[i] * 2, c = this.uint32Array[o], a = this.uint32Array[o + 1];
    s[i] = e(this, c * 4, a);
  }
  return s;
}
function dc(n) {
  const e = n.deserializeUInt32(), t = new Array(e);
  for (let r = 0; r < e; r++)
    t[r] = n.deserializeString();
  return t;
}
function hc(n) {
  const e = n.deserializeUInt32(), t = new Array(e);
  for (let r = 0; r < e; r++)
    t[r] = n.deserializeNumber();
  return t;
}
function mr(n) {
  const e = n.deserializeUInt32();
  if (e === 1) {
    const t = n.deserializeString(), r = n.deserializeString(), s = n.deserializeBoolean(), i = n.deserializeString(), o = hc(n), c = n.deserializeUInt32(), a = [];
    for (let l = 0; l < c; l++) {
      const d = n.deserializeString(), u = mr(n);
      a.push([
        d,
        u
      ]);
    }
    return {
      w: t || "",
      s: r || "",
      e: s,
      k: i || "",
      d: o,
      c: a
    };
  } else if (e === 2) {
    const t = n.deserializeUInt32(), r = [];
    for (let s = 0; s < t; s++) {
      const i = n.deserializeString(), o = dc(n);
      r.push([
        i,
        o
      ]);
    }
    return {
      numberToDocumentId: r
    };
  } else
    return Fe(n);
}
function Sr(n) {
  const e = n.deserializeUInt32(), t = {};
  for (let r = 0; r < e; r++) {
    const s = n.deserializeString();
    t[s] = n.deserializeNumber();
  }
  return t;
}
function pc(n) {
  const e = n.deserializeUInt32(), t = {};
  for (let r = 0; r < e; r++) {
    const s = n.deserializeString(), i = n.deserializeUInt32(), o = {};
    for (let c = 0; c < i; c++) {
      const a = n.deserializeString();
      o[a] = Sr(n);
    }
    t[s] = o;
  }
  return t;
}
function gc(n) {
  const e = n.deserializeUInt32(), t = {};
  for (let r = 0; r < e; r++) {
    const s = n.deserializeString();
    t[s] = Sr(n);
  }
  return t;
}
function Fe(n) {
  const e = n.deserializeUInt32();
  if (e === 0) return null;
  if (e !== 1) {
    if (e === 2) return n.deserializeString();
    if (e === 3) return n.deserializeNumber();
    if (e === 4) return n.deserializeBoolean();
    if (e === 5) {
      const t = n.deserializeUInt32(), r = new Array(t);
      for (let s = 0; s < t; s++)
        r[s] = Fe(n);
      return r;
    }
    if (e === 6) {
      const t = n.deserializeUInt32(), r = {};
      for (let s = 0; s < t; s++) {
        const i = n.deserializeString();
        r[i] = Fe(n);
      }
      return r;
    }
    throw new Error(`Unknown type: ${e}`);
  }
}
function yc(n) {
  const e = tc(n), t = e.deserializeUInt32();
  if (t === 1)
    return Fe(e);
  if (t !== 2)
    throw new Error(`Unsupported seqproto Orama serialization version: ${t}`);
  const r = {}, s = e.deserializeUInt32(), i = new Array(s);
  for (let A = 0; A < s; A++)
    i[A] = e.deserializeString();
  r.internalDocumentIDStore = {
    internalIdToId: i
  };
  const o = e.deserializeUInt32(), c = e.deserializeUInt32(), a = {};
  for (let A = 0; A < c; A++) {
    const U = e.deserializeString(), E = {}, G = e.deserializeUInt32();
    for (let R = 0; R < G; R++) {
      const W = e.deserializeString(), P = e.deserializeUInt32();
      if (P & 2147483648) {
        const M = P & 2147483647, z = new Array(M);
        for (let F = 0; F < M; F++)
          z[F] = e.deserializeString();
        E[W] = z;
      } else
        E[W] = e.deserializeString();
    }
    a[U] = E;
  }
  r.docs = {
    docs: a,
    count: o
  };
  const l = e.deserializeUInt32(), d = {};
  for (let A = 0; A < l; A++) {
    const U = e.deserializeString(), E = e.deserializeString(), G = e.deserializeBoolean(), R = e.deserializeUInt32();
    let W;
    if (R === 1) {
      const P = e.deserializeString(), M = e.deserializeString(), z = e.deserializeBoolean(), F = e.deserializeString(), _ = e.deserializeUInt32(), O = new Array(_);
      for (let Q = 0; Q < _; Q++)
        O[Q] = e.deserializeNumber();
      const Y = e.deserializeUInt32(), Te = new Array(Y);
      for (let Q = 0; Q < Y; Q++) {
        const se = e.deserializeString(), b = mr(e);
        Te[Q] = [
          se,
          b
        ];
      }
      W = {
        w: P,
        s: M,
        e: z,
        k: F,
        d: O,
        c: Te
      };
    } else if (R === 2) {
      const P = e.deserializeUInt32(), M = new Array(P);
      for (let z = 0; z < P; z++) {
        const F = e.deserializeString(), _ = e.deserializeUInt32(), O = new Array(_);
        for (let Y = 0; Y < _; Y++)
          O[Y] = e.deserializeString();
        M[z] = [
          F,
          O
        ];
      }
      W = {
        numberToDocumentId: M
      };
    } else
      W = {};
    d[U] = {
      type: E,
      isArray: G,
      node: W
    };
  }
  const u = e.deserializeUInt32(), h = new Array(u);
  for (let A = 0; A < u; A++)
    h[A] = e.deserializeString();
  const m = e.deserializeUInt32(), g = {};
  for (let A = 0; A < m; A++) {
    const U = e.deserializeString(), E = e.deserializeString();
    g[U] = E;
  }
  const y = pc(e), f = gc(e), p = e.deserializeUInt32(), v = {};
  for (let A = 0; A < p; A++) {
    const U = e.deserializeString();
    v[U] = e.deserializeNumber();
  }
  const w = e.deserializeUInt32(), x = {};
  for (let A = 0; A < w; A++) {
    const U = e.deserializeString(), E = e.deserializeUInt32(), G = {};
    for (let R = 0; R < E; R++) {
      const W = e.deserializeString();
      G[W] = e.deserializeNumber();
    }
    x[U] = G;
  }
  r.index = {
    indexes: d,
    vectorIndexes: {},
    searchableProperties: h,
    searchablePropertiesWithTypes: g,
    frequencies: y,
    tokenOccurrences: f,
    avgFieldLength: v,
    fieldLengths: x
  }, r.language = e.deserializeString();
  const N = e.deserializeUInt32(), T = new Array(N);
  for (let A = 0; A < N; A++) {
    const U = e.deserializeString(), E = Fe(e);
    T[A] = [
      U,
      E
    ];
  }
  return r.pinning = {
    rules: T
  }, r.sorting = {}, r;
}
const zn = {
  0: 0,
  1: 1,
  2: 2,
  3: 3,
  4: 4,
  5: 5,
  6: 6,
  7: 7,
  8: 8,
  9: 9,
  a: 10,
  b: 11,
  c: 12,
  d: 13,
  e: 14,
  f: 15
};
function mc(n) {
  const e = new Uint8Array(Math.floor(n.length / 2));
  n = n.toLowerCase();
  for (let t = 0; t < n.length; t++) {
    const r = zn[n[t * 2]], s = zn[n[t * 2 + 1]];
    if (r === void 0 || s === void 0)
      break;
    e[t] = r << 4 | s;
  }
  return e;
}
async function Sc(n, e, t) {
  t || (t = Jo());
  const r = so({
    schema: {
      __placeholder: "string"
    }
  });
  let s;
  switch (n) {
    case "json":
      s = JSON.parse(e.toString());
      break;
    case "dpack":
      s = Go(e);
      break;
    case "binary": {
      t === "node" ? e = Buffer.from(e.toString(), "hex") : e = mc(e), s = Ss(e);
      break;
    }
    case "seqproto":
      {
        let i;
        if (e instanceof ArrayBuffer)
          i = e;
        else if (ArrayBuffer.isView(e)) {
          const o = e, c = o.buffer.slice(o.byteOffset, o.byteOffset + o.byteLength), a = new Uint8Array(o.byteLength);
          a.set(new Uint8Array(c)), i = a.buffer;
        } else if (typeof e == "string") {
          const o = Buffer.from(e, "binary"), c = o.buffer.slice(o.byteOffset, o.byteOffset + o.byteLength), a = new Uint8Array(o.byteLength);
          a.set(new Uint8Array(c)), i = a.buffer;
        } else
          throw new Error("Unsupported data type for seqproto restore");
        s = yc(i);
      }
      break;
    default:
      throw new Error(qo(n));
  }
  return To(r, s), r;
}
var wc = Object.defineProperty, xc = Object.getOwnPropertyDescriptor, Z = (n, e, t, r) => {
  for (var s = r > 1 ? void 0 : r ? xc(e, t) : e, i = n.length - 1, o; i >= 0; i--)
    (o = n[i]) && (s = (r ? o(e, t, s) : o(s)) || s);
  return r && s && wc(e, t, s), s;
};
const Mn = {
  chat: ae`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="24" height="24"><path d="M12 3l1.45 2.9L16.5 7l-2.05 2.1.5 3.4L12 11l-2.95 1.5.5-3.4L7.5 7l3.05-1.1L12 3z"/></svg>`,
  close: ae`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="24" height="24"><path d="M6 18L18 6M6 6l12 12"/></svg>`,
  send: ae`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="24" height="24"><path d="M5 12h14M12 5l7 7-7 7"/></svg>`,
  clear: ae`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="24" height="24"><path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2m3 0v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6h14z"/></svg>`
};
let q = class extends ke {
  constructor() {
    super(...arguments), this.apiEndpoint = "/api/chat", this.indexPath = "/search-index.json", this.title = "AI Assistant", this.accentColor = "#f97316", this.placeholder = "Ask a question...", this.position = "bottom-right", this.isOpen = !1, this.messages = [], this.input = "", this.loading = !1, this.isFocused = !1, this.oramaDB = null, this.indexLoaded = !1, this.handleGlobalKeydown = (n) => {
      (n.ctrlKey || n.metaKey) && n.key === "i" && (n.preventDefault(), this.isOpen = !this.isOpen), n.key === "Escape" && this.isOpen && (this.isOpen = !1);
    };
  }
  updated(n) {
    var e;
    n.has("isOpen") && this.isOpen && ((e = this.inputElement) == null || e.focus(), this.scrollToBottom()), n.has("messages") && this.scrollToBottom();
  }
  scrollToBottom() {
    this.messagesContainer && (this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight);
  }
  async connectedCallback() {
    super.connectedCallback(), this.loadIndex(), window.addEventListener("keydown", this.handleGlobalKeydown);
  }
  disconnectedCallback() {
    super.disconnectedCallback(), window.removeEventListener("keydown", this.handleGlobalKeydown);
  }
  async loadIndex() {
    if (!this.indexLoaded)
      try {
        const n = await fetch(this.indexPath);
        if (!n.ok) throw new Error("Index not found");
        const e = await n.text();
        this.oramaDB = await Sc("json", e), this.indexLoaded = !0;
      } catch (n) {
        console.error("Vetradocs: Failed to load index", n);
      }
  }
  async searchDocs(n) {
    if (!this.oramaDB) return [];
    try {
      return (await _o(this.oramaDB, { term: n, limit: 3 })).hits.map((t) => t.document);
    } catch {
      return [];
    }
  }
  async sendMessage() {
    const n = this.input.trim();
    if (!(!n || this.loading)) {
      this.messages = [...this.messages, { role: "user", content: n }], this.input = "", this.loading = !0;
      try {
        const t = (await this.searchDocs(n)).map((c) => `Title: ${c.title}
${c.content}`).join(`
---
`), r = await fetch(this.apiEndpoint, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            messages: this.messages,
            context: t
          })
        });
        if (!r.ok) throw new Error("API Error");
        const s = r.body.getReader(), i = new TextDecoder(), o = { role: "assistant", content: "" };
        for (this.messages = [...this.messages, o]; ; ) {
          const { done: c, value: a } = await s.read();
          if (c) break;
          o.content += i.decode(a, { stream: !0 }), this.messages = [...this.messages.slice(0, -1), { ...o }];
        }
      } catch {
        this.messages = [...this.messages, { role: "assistant", content: "Error occurred." }];
      } finally {
        this.loading = !1;
      }
    }
  }
  handleInputKeydown(n) {
    n.key === "Enter" && !n.shiftKey && (n.preventDefault(), this.sendMessage());
  }
  render() {
    return ae`
            <style>
                :host { --accent-color: ${this.accentColor}; }
            </style>
            
            ${this.isOpen ? ae`
                <div class="backdrop" @click=${() => this.isOpen = !1}></div>
                <div class="chat-window">
                    <div class="header">
                        <span>${this.title}</span>
                        <div class="actions">
                            <button class="icon-btn" @click=${() => this.messages = []}>${Mn.clear}</button>
                            <button class="icon-btn" @click=${() => this.isOpen = !1}>${Mn.close}</button>
                        </div>
                    </div>
                    <div class="messages">
                        ${this.messages.length === 0 ? ae`<div style="text-align:center; color: var(--text-secondary); margin-top: 40px;">How can I help you?</div>` : ""}
                        ${this.messages.map((n) => ae`
                            <div class="message ${n.role}">
                                <div class="content">${n.content}</div>
                            </div>
                        `)}
                        ${this.loading ? ae`<div style="font-size:12px; color: var(--text-secondary);">Thinking...</div>` : ""}
                    </div>
                    <div class="input-area">
                        <div class="input-wrapper">
                            <textarea
                                .value=${this.input}
                                @input=${(n) => this.input = n.target.value}
                                @keydown=${this.handleInputKeydown}
                                placeholder=${this.placeholder}
                                rows="1"
                            ></textarea>
                            <button class="send-btn" ?disabled=${!this.input.trim() || this.loading} @click=${this.sendMessage}>
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
                            </button>
                        </div>
                    </div>
                    <div class="branding">
                        Powered by <a href="https://vectra-docs.vercel.app" target="_blank" rel="noopener noreferrer">Vetradocs</a>
                    </div>
                </div>
            ` : ae`
                <button class="fab" @click=${() => this.isOpen = !0}>
                    Ask AI
                </button>
            `}
        `;
  }
};
q.styles = _r`
        :host {
            font-family: system-ui, -apple-system, sans-serif;
            --accent-color: #f97316;
            --bg-color: #1a1a1a;
            --text-color: #ffffff;
            --text-secondary: #a1a1aa;
            --border-color: #27272a;
            z-index: 9999;
        }

        .backdrop {
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(4px);
            z-index: 9998;
        }

        .chat-window {
            position: fixed;
            top: 20px;
            bottom: 100px;
            right: 20px;
            width: 400px;
            max-width: calc(100vw - 40px);
            background: var(--bg-color);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            display: flex;
            flex-direction: column;
            z-index: 9999;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            animation: slideIn 0.3s ease;
        }

        @keyframes slideIn {
            from { transform: translateY(20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        .header {
            padding: 16px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: var(--text-color);
            font-weight: 600;
        }

        .actions {
            display: flex;
            gap: 8px;
        }

        .icon-btn {
            background: none;
            border: none;
            color: var(--text-secondary);
            cursor: pointer;
            padding: 4px;
            border-radius: 4px;
        }
        .icon-btn:hover {
            color: var(--text-color);
            background: rgba(255,255,255,0.1);
        }

        .messages {
            flex: 1;
            overflow-y: auto;
            padding: 16px;
            display: flex;
            flex-direction: column;
            gap: 16px;
        }

        .message {
            display: flex;
            gap: 8px;
            color: var(--text-color);
            font-size: 14px;
            line-height: 1.5;
        }

        .message.user {
            justify-content: flex-end;
        }

        .message.user .content {
            background: #27272a;
            padding: 8px 12px;
            border-radius: 12px 12px 2px 12px;
        }

        .message.assistant .content {
            flex: 1;
        }

        .input-area {
            padding: 16px;
            border-top: 1px solid var(--border-color);
        }

        .input-wrapper {
            display: flex;
            align-items: flex-end;
            gap: 8px;
            background: #27272a;
            border-radius: 20px;
            padding: 8px 12px;
            border: 1px solid transparent;
        }

        .input-wrapper:focus-within {
            border-color: var(--accent-color);
        }

        textarea {
            flex: 1;
            background: transparent;
            border: none;
            color: var(--text-color);
            resize: none;
            font-family: inherit;
            outline: none;
            font-size: 14px;
            max-height: 100px;
        }

        .send-btn {
            background: var(--accent-color);
            border: none;
            border-radius: 50%;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            cursor: pointer;
        }
        .send-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* Floating Button / Bar */
        .fab {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: var(--accent-color);
            color: white;
            border: none;
            border-radius: 28px;
            padding: 12px 24px;
            font-weight: 600;
            cursor: pointer;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;
            gap: 8px;
            z-index: 9999;
            transition: transform 0.2s;
        }

        .fab:hover {
            transform: scale(1.05);
        }

        .branding {
            font-size: 11px;
            color: var(--text-secondary);
            text-align: center;
            padding: 8px;
            border-top: 1px solid var(--border-color);
        }

        .branding a {
            color: inherit;
            text-decoration: underline;
        }

        .branding a:hover {
            color: var(--accent-color);
        }
    `;
Z([
  xe({ type: String })
], q.prototype, "apiEndpoint", 2);
Z([
  xe({ type: String })
], q.prototype, "indexPath", 2);
Z([
  xe({ type: String })
], q.prototype, "title", 2);
Z([
  xe({ type: String })
], q.prototype, "accentColor", 2);
Z([
  xe({ type: String })
], q.prototype, "placeholder", 2);
Z([
  xe({ type: String })
], q.prototype, "position", 2);
Z([
  je()
], q.prototype, "isOpen", 2);
Z([
  je()
], q.prototype, "messages", 2);
Z([
  je()
], q.prototype, "input", 2);
Z([
  je()
], q.prototype, "loading", 2);
Z([
  je()
], q.prototype, "isFocused", 2);
Z([
  Hn("textarea")
], q.prototype, "inputElement", 2);
Z([
  Hn(".messages")
], q.prototype, "messagesContainer", 2);
q = Z([
  Hr("vetradocs-widget")
], q);
