var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod2) => function __require() {
  return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
  mod2
));

// node_modules/react/cjs/react.production.min.js
var require_react_production_min = __commonJS({
  "node_modules/react/cjs/react.production.min.js"(exports) {
    "use strict";
    var l2 = Symbol.for("react.element");
    var n3 = Symbol.for("react.portal");
    var p2 = Symbol.for("react.fragment");
    var q = Symbol.for("react.strict_mode");
    var r3 = Symbol.for("react.profiler");
    var t2 = Symbol.for("react.provider");
    var u2 = Symbol.for("react.context");
    var v = Symbol.for("react.forward_ref");
    var w2 = Symbol.for("react.suspense");
    var x = Symbol.for("react.memo");
    var y2 = Symbol.for("react.lazy");
    var z = Symbol.iterator;
    function A(a) {
      if (null === a || "object" !== typeof a) return null;
      a = z && a[z] || a["@@iterator"];
      return "function" === typeof a ? a : null;
    }
    var B2 = { isMounted: function() {
      return false;
    }, enqueueForceUpdate: function() {
    }, enqueueReplaceState: function() {
    }, enqueueSetState: function() {
    } };
    var C = Object.assign;
    var D = {};
    function E(a, b2, e3) {
      this.props = a;
      this.context = b2;
      this.refs = D;
      this.updater = e3 || B2;
    }
    E.prototype.isReactComponent = {};
    E.prototype.setState = function(a, b2) {
      if ("object" !== typeof a && "function" !== typeof a && null != a) throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");
      this.updater.enqueueSetState(this, a, b2, "setState");
    };
    E.prototype.forceUpdate = function(a) {
      this.updater.enqueueForceUpdate(this, a, "forceUpdate");
    };
    function F() {
    }
    F.prototype = E.prototype;
    function G3(a, b2, e3) {
      this.props = a;
      this.context = b2;
      this.refs = D;
      this.updater = e3 || B2;
    }
    var H = G3.prototype = new F();
    H.constructor = G3;
    C(H, E.prototype);
    H.isPureReactComponent = true;
    var I2 = Array.isArray;
    var J = Object.prototype.hasOwnProperty;
    var K = { current: null };
    var L = { key: true, ref: true, __self: true, __source: true };
    function M2(a, b2, e3) {
      var d2, c = {}, k = null, h2 = null;
      if (null != b2) for (d2 in void 0 !== b2.ref && (h2 = b2.ref), void 0 !== b2.key && (k = "" + b2.key), b2) J.call(b2, d2) && !L.hasOwnProperty(d2) && (c[d2] = b2[d2]);
      var g = arguments.length - 2;
      if (1 === g) c.children = e3;
      else if (1 < g) {
        for (var f = Array(g), m2 = 0; m2 < g; m2++) f[m2] = arguments[m2 + 2];
        c.children = f;
      }
      if (a && a.defaultProps) for (d2 in g = a.defaultProps, g) void 0 === c[d2] && (c[d2] = g[d2]);
      return { $$typeof: l2, type: a, key: k, ref: h2, props: c, _owner: K.current };
    }
    function N2(a, b2) {
      return { $$typeof: l2, type: a.type, key: b2, ref: a.ref, props: a.props, _owner: a._owner };
    }
    function O(a) {
      return "object" === typeof a && null !== a && a.$$typeof === l2;
    }
    function escape(a) {
      var b2 = { "=": "=0", ":": "=2" };
      return "$" + a.replace(/[=:]/g, function(a2) {
        return b2[a2];
      });
    }
    var P = /\/+/g;
    function Q(a, b2) {
      return "object" === typeof a && null !== a && null != a.key ? escape("" + a.key) : b2.toString(36);
    }
    function R2(a, b2, e3, d2, c) {
      var k = typeof a;
      if ("undefined" === k || "boolean" === k) a = null;
      var h2 = false;
      if (null === a) h2 = true;
      else switch (k) {
        case "string":
        case "number":
          h2 = true;
          break;
        case "object":
          switch (a.$$typeof) {
            case l2:
            case n3:
              h2 = true;
          }
      }
      if (h2) return h2 = a, c = c(h2), a = "" === d2 ? "." + Q(h2, 0) : d2, I2(c) ? (e3 = "", null != a && (e3 = a.replace(P, "$&/") + "/"), R2(c, b2, e3, "", function(a2) {
        return a2;
      })) : null != c && (O(c) && (c = N2(c, e3 + (!c.key || h2 && h2.key === c.key ? "" : ("" + c.key).replace(P, "$&/") + "/") + a)), b2.push(c)), 1;
      h2 = 0;
      d2 = "" === d2 ? "." : d2 + ":";
      if (I2(a)) for (var g = 0; g < a.length; g++) {
        k = a[g];
        var f = d2 + Q(k, g);
        h2 += R2(k, b2, e3, f, c);
      }
      else if (f = A(a), "function" === typeof f) for (a = f.call(a), g = 0; !(k = a.next()).done; ) k = k.value, f = d2 + Q(k, g++), h2 += R2(k, b2, e3, f, c);
      else if ("object" === k) throw b2 = String(a), Error("Objects are not valid as a React child (found: " + ("[object Object]" === b2 ? "object with keys {" + Object.keys(a).join(", ") + "}" : b2) + "). If you meant to render a collection of children, use an array instead.");
      return h2;
    }
    function S2(a, b2, e3) {
      if (null == a) return a;
      var d2 = [], c = 0;
      R2(a, d2, "", "", function(a2) {
        return b2.call(e3, a2, c++);
      });
      return d2;
    }
    function T(a) {
      if (-1 === a._status) {
        var b2 = a._result;
        b2 = b2();
        b2.then(function(b3) {
          if (0 === a._status || -1 === a._status) a._status = 1, a._result = b3;
        }, function(b3) {
          if (0 === a._status || -1 === a._status) a._status = 2, a._result = b3;
        });
        -1 === a._status && (a._status = 0, a._result = b2);
      }
      if (1 === a._status) return a._result.default;
      throw a._result;
    }
    var U = { current: null };
    var V = { transition: null };
    var W = { ReactCurrentDispatcher: U, ReactCurrentBatchConfig: V, ReactCurrentOwner: K };
    function X() {
      throw Error("act(...) is not supported in production builds of React.");
    }
    exports.Children = { map: S2, forEach: function(a, b2, e3) {
      S2(a, function() {
        b2.apply(this, arguments);
      }, e3);
    }, count: function(a) {
      var b2 = 0;
      S2(a, function() {
        b2++;
      });
      return b2;
    }, toArray: function(a) {
      return S2(a, function(a2) {
        return a2;
      }) || [];
    }, only: function(a) {
      if (!O(a)) throw Error("React.Children.only expected to receive a single React element child.");
      return a;
    } };
    exports.Component = E;
    exports.Fragment = p2;
    exports.Profiler = r3;
    exports.PureComponent = G3;
    exports.StrictMode = q;
    exports.Suspense = w2;
    exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = W;
    exports.act = X;
    exports.cloneElement = function(a, b2, e3) {
      if (null === a || void 0 === a) throw Error("React.cloneElement(...): The argument must be a React element, but you passed " + a + ".");
      var d2 = C({}, a.props), c = a.key, k = a.ref, h2 = a._owner;
      if (null != b2) {
        void 0 !== b2.ref && (k = b2.ref, h2 = K.current);
        void 0 !== b2.key && (c = "" + b2.key);
        if (a.type && a.type.defaultProps) var g = a.type.defaultProps;
        for (f in b2) J.call(b2, f) && !L.hasOwnProperty(f) && (d2[f] = void 0 === b2[f] && void 0 !== g ? g[f] : b2[f]);
      }
      var f = arguments.length - 2;
      if (1 === f) d2.children = e3;
      else if (1 < f) {
        g = Array(f);
        for (var m2 = 0; m2 < f; m2++) g[m2] = arguments[m2 + 2];
        d2.children = g;
      }
      return { $$typeof: l2, type: a.type, key: c, ref: k, props: d2, _owner: h2 };
    };
    exports.createContext = function(a) {
      a = { $$typeof: u2, _currentValue: a, _currentValue2: a, _threadCount: 0, Provider: null, Consumer: null, _defaultValue: null, _globalName: null };
      a.Provider = { $$typeof: t2, _context: a };
      return a.Consumer = a;
    };
    exports.createElement = M2;
    exports.createFactory = function(a) {
      var b2 = M2.bind(null, a);
      b2.type = a;
      return b2;
    };
    exports.createRef = function() {
      return { current: null };
    };
    exports.forwardRef = function(a) {
      return { $$typeof: v, render: a };
    };
    exports.isValidElement = O;
    exports.lazy = function(a) {
      return { $$typeof: y2, _payload: { _status: -1, _result: a }, _init: T };
    };
    exports.memo = function(a, b2) {
      return { $$typeof: x, type: a, compare: void 0 === b2 ? null : b2 };
    };
    exports.startTransition = function(a) {
      var b2 = V.transition;
      V.transition = {};
      try {
        a();
      } finally {
        V.transition = b2;
      }
    };
    exports.unstable_act = X;
    exports.useCallback = function(a, b2) {
      return U.current.useCallback(a, b2);
    };
    exports.useContext = function(a) {
      return U.current.useContext(a);
    };
    exports.useDebugValue = function() {
    };
    exports.useDeferredValue = function(a) {
      return U.current.useDeferredValue(a);
    };
    exports.useEffect = function(a, b2) {
      return U.current.useEffect(a, b2);
    };
    exports.useId = function() {
      return U.current.useId();
    };
    exports.useImperativeHandle = function(a, b2, e3) {
      return U.current.useImperativeHandle(a, b2, e3);
    };
    exports.useInsertionEffect = function(a, b2) {
      return U.current.useInsertionEffect(a, b2);
    };
    exports.useLayoutEffect = function(a, b2) {
      return U.current.useLayoutEffect(a, b2);
    };
    exports.useMemo = function(a, b2) {
      return U.current.useMemo(a, b2);
    };
    exports.useReducer = function(a, b2, e3) {
      return U.current.useReducer(a, b2, e3);
    };
    exports.useRef = function(a) {
      return U.current.useRef(a);
    };
    exports.useState = function(a) {
      return U.current.useState(a);
    };
    exports.useSyncExternalStore = function(a, b2, e3) {
      return U.current.useSyncExternalStore(a, b2, e3);
    };
    exports.useTransition = function() {
      return U.current.useTransition();
    };
    exports.version = "18.3.1";
  }
});

// node_modules/react/index.js
var require_react = __commonJS({
  "node_modules/react/index.js"(exports, module) {
    "use strict";
    if (true) {
      module.exports = require_react_production_min();
    } else {
      module.exports = null;
    }
  }
});

// node_modules/scheduler/cjs/scheduler.production.min.js
var require_scheduler_production_min = __commonJS({
  "node_modules/scheduler/cjs/scheduler.production.min.js"(exports) {
    "use strict";
    function f(a, b2) {
      var c = a.length;
      a.push(b2);
      a: for (; 0 < c; ) {
        var d2 = c - 1 >>> 1, e3 = a[d2];
        if (0 < g(e3, b2)) a[d2] = b2, a[c] = e3, c = d2;
        else break a;
      }
    }
    function h2(a) {
      return 0 === a.length ? null : a[0];
    }
    function k(a) {
      if (0 === a.length) return null;
      var b2 = a[0], c = a.pop();
      if (c !== b2) {
        a[0] = c;
        a: for (var d2 = 0, e3 = a.length, w2 = e3 >>> 1; d2 < w2; ) {
          var m2 = 2 * (d2 + 1) - 1, C = a[m2], n3 = m2 + 1, x = a[n3];
          if (0 > g(C, c)) n3 < e3 && 0 > g(x, C) ? (a[d2] = x, a[n3] = c, d2 = n3) : (a[d2] = C, a[m2] = c, d2 = m2);
          else if (n3 < e3 && 0 > g(x, c)) a[d2] = x, a[n3] = c, d2 = n3;
          else break a;
        }
      }
      return b2;
    }
    function g(a, b2) {
      var c = a.sortIndex - b2.sortIndex;
      return 0 !== c ? c : a.id - b2.id;
    }
    if ("object" === typeof performance && "function" === typeof performance.now) {
      l2 = performance;
      exports.unstable_now = function() {
        return l2.now();
      };
    } else {
      p2 = Date, q = p2.now();
      exports.unstable_now = function() {
        return p2.now() - q;
      };
    }
    var l2;
    var p2;
    var q;
    var r3 = [];
    var t2 = [];
    var u2 = 1;
    var v = null;
    var y2 = 3;
    var z = false;
    var A = false;
    var B2 = false;
    var D = "function" === typeof setTimeout ? setTimeout : null;
    var E = "function" === typeof clearTimeout ? clearTimeout : null;
    var F = "undefined" !== typeof setImmediate ? setImmediate : null;
    "undefined" !== typeof navigator && void 0 !== navigator.scheduling && void 0 !== navigator.scheduling.isInputPending && navigator.scheduling.isInputPending.bind(navigator.scheduling);
    function G3(a) {
      for (var b2 = h2(t2); null !== b2; ) {
        if (null === b2.callback) k(t2);
        else if (b2.startTime <= a) k(t2), b2.sortIndex = b2.expirationTime, f(r3, b2);
        else break;
        b2 = h2(t2);
      }
    }
    function H(a) {
      B2 = false;
      G3(a);
      if (!A) if (null !== h2(r3)) A = true, I2(J);
      else {
        var b2 = h2(t2);
        null !== b2 && K(H, b2.startTime - a);
      }
    }
    function J(a, b2) {
      A = false;
      B2 && (B2 = false, E(L), L = -1);
      z = true;
      var c = y2;
      try {
        G3(b2);
        for (v = h2(r3); null !== v && (!(v.expirationTime > b2) || a && !M2()); ) {
          var d2 = v.callback;
          if ("function" === typeof d2) {
            v.callback = null;
            y2 = v.priorityLevel;
            var e3 = d2(v.expirationTime <= b2);
            b2 = exports.unstable_now();
            "function" === typeof e3 ? v.callback = e3 : v === h2(r3) && k(r3);
            G3(b2);
          } else k(r3);
          v = h2(r3);
        }
        if (null !== v) var w2 = true;
        else {
          var m2 = h2(t2);
          null !== m2 && K(H, m2.startTime - b2);
          w2 = false;
        }
        return w2;
      } finally {
        v = null, y2 = c, z = false;
      }
    }
    var N2 = false;
    var O = null;
    var L = -1;
    var P = 5;
    var Q = -1;
    function M2() {
      return exports.unstable_now() - Q < P ? false : true;
    }
    function R2() {
      if (null !== O) {
        var a = exports.unstable_now();
        Q = a;
        var b2 = true;
        try {
          b2 = O(true, a);
        } finally {
          b2 ? S2() : (N2 = false, O = null);
        }
      } else N2 = false;
    }
    var S2;
    if ("function" === typeof F) S2 = function() {
      F(R2);
    };
    else if ("undefined" !== typeof MessageChannel) {
      T = new MessageChannel(), U = T.port2;
      T.port1.onmessage = R2;
      S2 = function() {
        U.postMessage(null);
      };
    } else S2 = function() {
      D(R2, 0);
    };
    var T;
    var U;
    function I2(a) {
      O = a;
      N2 || (N2 = true, S2());
    }
    function K(a, b2) {
      L = D(function() {
        a(exports.unstable_now());
      }, b2);
    }
    exports.unstable_IdlePriority = 5;
    exports.unstable_ImmediatePriority = 1;
    exports.unstable_LowPriority = 4;
    exports.unstable_NormalPriority = 3;
    exports.unstable_Profiling = null;
    exports.unstable_UserBlockingPriority = 2;
    exports.unstable_cancelCallback = function(a) {
      a.callback = null;
    };
    exports.unstable_continueExecution = function() {
      A || z || (A = true, I2(J));
    };
    exports.unstable_forceFrameRate = function(a) {
      0 > a || 125 < a ? console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported") : P = 0 < a ? Math.floor(1e3 / a) : 5;
    };
    exports.unstable_getCurrentPriorityLevel = function() {
      return y2;
    };
    exports.unstable_getFirstCallbackNode = function() {
      return h2(r3);
    };
    exports.unstable_next = function(a) {
      switch (y2) {
        case 1:
        case 2:
        case 3:
          var b2 = 3;
          break;
        default:
          b2 = y2;
      }
      var c = y2;
      y2 = b2;
      try {
        return a();
      } finally {
        y2 = c;
      }
    };
    exports.unstable_pauseExecution = function() {
    };
    exports.unstable_requestPaint = function() {
    };
    exports.unstable_runWithPriority = function(a, b2) {
      switch (a) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
          break;
        default:
          a = 3;
      }
      var c = y2;
      y2 = a;
      try {
        return b2();
      } finally {
        y2 = c;
      }
    };
    exports.unstable_scheduleCallback = function(a, b2, c) {
      var d2 = exports.unstable_now();
      "object" === typeof c && null !== c ? (c = c.delay, c = "number" === typeof c && 0 < c ? d2 + c : d2) : c = d2;
      switch (a) {
        case 1:
          var e3 = -1;
          break;
        case 2:
          e3 = 250;
          break;
        case 5:
          e3 = 1073741823;
          break;
        case 4:
          e3 = 1e4;
          break;
        default:
          e3 = 5e3;
      }
      e3 = c + e3;
      a = { id: u2++, callback: b2, priorityLevel: a, startTime: c, expirationTime: e3, sortIndex: -1 };
      c > d2 ? (a.sortIndex = c, f(t2, a), null === h2(r3) && a === h2(t2) && (B2 ? (E(L), L = -1) : B2 = true, K(H, c - d2))) : (a.sortIndex = e3, f(r3, a), A || z || (A = true, I2(J)));
      return a;
    };
    exports.unstable_shouldYield = M2;
    exports.unstable_wrapCallback = function(a) {
      var b2 = y2;
      return function() {
        var c = y2;
        y2 = b2;
        try {
          return a.apply(this, arguments);
        } finally {
          y2 = c;
        }
      };
    };
  }
});

// node_modules/scheduler/index.js
var require_scheduler = __commonJS({
  "node_modules/scheduler/index.js"(exports, module) {
    "use strict";
    if (true) {
      module.exports = require_scheduler_production_min();
    } else {
      module.exports = null;
    }
  }
});

// node_modules/react-dom/cjs/react-dom.production.min.js
var require_react_dom_production_min = __commonJS({
  "node_modules/react-dom/cjs/react-dom.production.min.js"(exports) {
    "use strict";
    var aa = require_react();
    var ca = require_scheduler();
    function p2(a) {
      for (var b2 = "https://reactjs.org/docs/error-decoder.html?invariant=" + a, c = 1; c < arguments.length; c++) b2 += "&args[]=" + encodeURIComponent(arguments[c]);
      return "Minified React error #" + a + "; visit " + b2 + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
    }
    var da = /* @__PURE__ */ new Set();
    var ea = {};
    function fa(a, b2) {
      ha(a, b2);
      ha(a + "Capture", b2);
    }
    function ha(a, b2) {
      ea[a] = b2;
      for (a = 0; a < b2.length; a++) da.add(b2[a]);
    }
    var ia = !("undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement);
    var ja = Object.prototype.hasOwnProperty;
    var ka = /^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/;
    var la = {};
    var ma = {};
    function oa(a) {
      if (ja.call(ma, a)) return true;
      if (ja.call(la, a)) return false;
      if (ka.test(a)) return ma[a] = true;
      la[a] = true;
      return false;
    }
    function pa(a, b2, c, d2) {
      if (null !== c && 0 === c.type) return false;
      switch (typeof b2) {
        case "function":
        case "symbol":
          return true;
        case "boolean":
          if (d2) return false;
          if (null !== c) return !c.acceptsBooleans;
          a = a.toLowerCase().slice(0, 5);
          return "data-" !== a && "aria-" !== a;
        default:
          return false;
      }
    }
    function qa(a, b2, c, d2) {
      if (null === b2 || "undefined" === typeof b2 || pa(a, b2, c, d2)) return true;
      if (d2) return false;
      if (null !== c) switch (c.type) {
        case 3:
          return !b2;
        case 4:
          return false === b2;
        case 5:
          return isNaN(b2);
        case 6:
          return isNaN(b2) || 1 > b2;
      }
      return false;
    }
    function v(a, b2, c, d2, e3, f, g) {
      this.acceptsBooleans = 2 === b2 || 3 === b2 || 4 === b2;
      this.attributeName = d2;
      this.attributeNamespace = e3;
      this.mustUseProperty = c;
      this.propertyName = a;
      this.type = b2;
      this.sanitizeURL = f;
      this.removeEmptyString = g;
    }
    var z = {};
    "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a) {
      z[a] = new v(a, 0, false, a, null, false, false);
    });
    [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(a) {
      var b2 = a[0];
      z[b2] = new v(b2, 1, false, a[1], null, false, false);
    });
    ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(a) {
      z[a] = new v(a, 2, false, a.toLowerCase(), null, false, false);
    });
    ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(a) {
      z[a] = new v(a, 2, false, a, null, false, false);
    });
    "allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a) {
      z[a] = new v(a, 3, false, a.toLowerCase(), null, false, false);
    });
    ["checked", "multiple", "muted", "selected"].forEach(function(a) {
      z[a] = new v(a, 3, true, a, null, false, false);
    });
    ["capture", "download"].forEach(function(a) {
      z[a] = new v(a, 4, false, a, null, false, false);
    });
    ["cols", "rows", "size", "span"].forEach(function(a) {
      z[a] = new v(a, 6, false, a, null, false, false);
    });
    ["rowSpan", "start"].forEach(function(a) {
      z[a] = new v(a, 5, false, a.toLowerCase(), null, false, false);
    });
    var ra = /[\-:]([a-z])/g;
    function sa(a) {
      return a[1].toUpperCase();
    }
    "accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a) {
      var b2 = a.replace(
        ra,
        sa
      );
      z[b2] = new v(b2, 1, false, a, null, false, false);
    });
    "xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a) {
      var b2 = a.replace(ra, sa);
      z[b2] = new v(b2, 1, false, a, "http://www.w3.org/1999/xlink", false, false);
    });
    ["xml:base", "xml:lang", "xml:space"].forEach(function(a) {
      var b2 = a.replace(ra, sa);
      z[b2] = new v(b2, 1, false, a, "http://www.w3.org/XML/1998/namespace", false, false);
    });
    ["tabIndex", "crossOrigin"].forEach(function(a) {
      z[a] = new v(a, 1, false, a.toLowerCase(), null, false, false);
    });
    z.xlinkHref = new v("xlinkHref", 1, false, "xlink:href", "http://www.w3.org/1999/xlink", true, false);
    ["src", "href", "action", "formAction"].forEach(function(a) {
      z[a] = new v(a, 1, false, a.toLowerCase(), null, true, true);
    });
    function ta(a, b2, c, d2) {
      var e3 = z.hasOwnProperty(b2) ? z[b2] : null;
      if (null !== e3 ? 0 !== e3.type : d2 || !(2 < b2.length) || "o" !== b2[0] && "O" !== b2[0] || "n" !== b2[1] && "N" !== b2[1]) qa(b2, c, e3, d2) && (c = null), d2 || null === e3 ? oa(b2) && (null === c ? a.removeAttribute(b2) : a.setAttribute(b2, "" + c)) : e3.mustUseProperty ? a[e3.propertyName] = null === c ? 3 === e3.type ? false : "" : c : (b2 = e3.attributeName, d2 = e3.attributeNamespace, null === c ? a.removeAttribute(b2) : (e3 = e3.type, c = 3 === e3 || 4 === e3 && true === c ? "" : "" + c, d2 ? a.setAttributeNS(d2, b2, c) : a.setAttribute(b2, c)));
    }
    var ua = aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
    var va = Symbol.for("react.element");
    var wa = Symbol.for("react.portal");
    var ya = Symbol.for("react.fragment");
    var za = Symbol.for("react.strict_mode");
    var Aa = Symbol.for("react.profiler");
    var Ba = Symbol.for("react.provider");
    var Ca = Symbol.for("react.context");
    var Da = Symbol.for("react.forward_ref");
    var Ea = Symbol.for("react.suspense");
    var Fa = Symbol.for("react.suspense_list");
    var Ga = Symbol.for("react.memo");
    var Ha = Symbol.for("react.lazy");
    Symbol.for("react.scope");
    Symbol.for("react.debug_trace_mode");
    var Ia = Symbol.for("react.offscreen");
    Symbol.for("react.legacy_hidden");
    Symbol.for("react.cache");
    Symbol.for("react.tracing_marker");
    var Ja = Symbol.iterator;
    function Ka(a) {
      if (null === a || "object" !== typeof a) return null;
      a = Ja && a[Ja] || a["@@iterator"];
      return "function" === typeof a ? a : null;
    }
    var A = Object.assign;
    var La;
    function Ma(a) {
      if (void 0 === La) try {
        throw Error();
      } catch (c) {
        var b2 = c.stack.trim().match(/\n( *(at )?)/);
        La = b2 && b2[1] || "";
      }
      return "\n" + La + a;
    }
    var Na = false;
    function Oa(a, b2) {
      if (!a || Na) return "";
      Na = true;
      var c = Error.prepareStackTrace;
      Error.prepareStackTrace = void 0;
      try {
        if (b2) if (b2 = function() {
          throw Error();
        }, Object.defineProperty(b2.prototype, "props", { set: function() {
          throw Error();
        } }), "object" === typeof Reflect && Reflect.construct) {
          try {
            Reflect.construct(b2, []);
          } catch (l2) {
            var d2 = l2;
          }
          Reflect.construct(a, [], b2);
        } else {
          try {
            b2.call();
          } catch (l2) {
            d2 = l2;
          }
          a.call(b2.prototype);
        }
        else {
          try {
            throw Error();
          } catch (l2) {
            d2 = l2;
          }
          a();
        }
      } catch (l2) {
        if (l2 && d2 && "string" === typeof l2.stack) {
          for (var e3 = l2.stack.split("\n"), f = d2.stack.split("\n"), g = e3.length - 1, h2 = f.length - 1; 1 <= g && 0 <= h2 && e3[g] !== f[h2]; ) h2--;
          for (; 1 <= g && 0 <= h2; g--, h2--) if (e3[g] !== f[h2]) {
            if (1 !== g || 1 !== h2) {
              do
                if (g--, h2--, 0 > h2 || e3[g] !== f[h2]) {
                  var k = "\n" + e3[g].replace(" at new ", " at ");
                  a.displayName && k.includes("<anonymous>") && (k = k.replace("<anonymous>", a.displayName));
                  return k;
                }
              while (1 <= g && 0 <= h2);
            }
            break;
          }
        }
      } finally {
        Na = false, Error.prepareStackTrace = c;
      }
      return (a = a ? a.displayName || a.name : "") ? Ma(a) : "";
    }
    function Pa(a) {
      switch (a.tag) {
        case 5:
          return Ma(a.type);
        case 16:
          return Ma("Lazy");
        case 13:
          return Ma("Suspense");
        case 19:
          return Ma("SuspenseList");
        case 0:
        case 2:
        case 15:
          return a = Oa(a.type, false), a;
        case 11:
          return a = Oa(a.type.render, false), a;
        case 1:
          return a = Oa(a.type, true), a;
        default:
          return "";
      }
    }
    function Qa(a) {
      if (null == a) return null;
      if ("function" === typeof a) return a.displayName || a.name || null;
      if ("string" === typeof a) return a;
      switch (a) {
        case ya:
          return "Fragment";
        case wa:
          return "Portal";
        case Aa:
          return "Profiler";
        case za:
          return "StrictMode";
        case Ea:
          return "Suspense";
        case Fa:
          return "SuspenseList";
      }
      if ("object" === typeof a) switch (a.$$typeof) {
        case Ca:
          return (a.displayName || "Context") + ".Consumer";
        case Ba:
          return (a._context.displayName || "Context") + ".Provider";
        case Da:
          var b2 = a.render;
          a = a.displayName;
          a || (a = b2.displayName || b2.name || "", a = "" !== a ? "ForwardRef(" + a + ")" : "ForwardRef");
          return a;
        case Ga:
          return b2 = a.displayName || null, null !== b2 ? b2 : Qa(a.type) || "Memo";
        case Ha:
          b2 = a._payload;
          a = a._init;
          try {
            return Qa(a(b2));
          } catch (c) {
          }
      }
      return null;
    }
    function Ra(a) {
      var b2 = a.type;
      switch (a.tag) {
        case 24:
          return "Cache";
        case 9:
          return (b2.displayName || "Context") + ".Consumer";
        case 10:
          return (b2._context.displayName || "Context") + ".Provider";
        case 18:
          return "DehydratedFragment";
        case 11:
          return a = b2.render, a = a.displayName || a.name || "", b2.displayName || ("" !== a ? "ForwardRef(" + a + ")" : "ForwardRef");
        case 7:
          return "Fragment";
        case 5:
          return b2;
        case 4:
          return "Portal";
        case 3:
          return "Root";
        case 6:
          return "Text";
        case 16:
          return Qa(b2);
        case 8:
          return b2 === za ? "StrictMode" : "Mode";
        case 22:
          return "Offscreen";
        case 12:
          return "Profiler";
        case 21:
          return "Scope";
        case 13:
          return "Suspense";
        case 19:
          return "SuspenseList";
        case 25:
          return "TracingMarker";
        case 1:
        case 0:
        case 17:
        case 2:
        case 14:
        case 15:
          if ("function" === typeof b2) return b2.displayName || b2.name || null;
          if ("string" === typeof b2) return b2;
      }
      return null;
    }
    function Sa(a) {
      switch (typeof a) {
        case "boolean":
        case "number":
        case "string":
        case "undefined":
          return a;
        case "object":
          return a;
        default:
          return "";
      }
    }
    function Ta(a) {
      var b2 = a.type;
      return (a = a.nodeName) && "input" === a.toLowerCase() && ("checkbox" === b2 || "radio" === b2);
    }
    function Ua(a) {
      var b2 = Ta(a) ? "checked" : "value", c = Object.getOwnPropertyDescriptor(a.constructor.prototype, b2), d2 = "" + a[b2];
      if (!a.hasOwnProperty(b2) && "undefined" !== typeof c && "function" === typeof c.get && "function" === typeof c.set) {
        var e3 = c.get, f = c.set;
        Object.defineProperty(a, b2, { configurable: true, get: function() {
          return e3.call(this);
        }, set: function(a2) {
          d2 = "" + a2;
          f.call(this, a2);
        } });
        Object.defineProperty(a, b2, { enumerable: c.enumerable });
        return { getValue: function() {
          return d2;
        }, setValue: function(a2) {
          d2 = "" + a2;
        }, stopTracking: function() {
          a._valueTracker = null;
          delete a[b2];
        } };
      }
    }
    function Va(a) {
      a._valueTracker || (a._valueTracker = Ua(a));
    }
    function Wa(a) {
      if (!a) return false;
      var b2 = a._valueTracker;
      if (!b2) return true;
      var c = b2.getValue();
      var d2 = "";
      a && (d2 = Ta(a) ? a.checked ? "true" : "false" : a.value);
      a = d2;
      return a !== c ? (b2.setValue(a), true) : false;
    }
    function Xa(a) {
      a = a || ("undefined" !== typeof document ? document : void 0);
      if ("undefined" === typeof a) return null;
      try {
        return a.activeElement || a.body;
      } catch (b2) {
        return a.body;
      }
    }
    function Ya(a, b2) {
      var c = b2.checked;
      return A({}, b2, { defaultChecked: void 0, defaultValue: void 0, value: void 0, checked: null != c ? c : a._wrapperState.initialChecked });
    }
    function Za(a, b2) {
      var c = null == b2.defaultValue ? "" : b2.defaultValue, d2 = null != b2.checked ? b2.checked : b2.defaultChecked;
      c = Sa(null != b2.value ? b2.value : c);
      a._wrapperState = { initialChecked: d2, initialValue: c, controlled: "checkbox" === b2.type || "radio" === b2.type ? null != b2.checked : null != b2.value };
    }
    function ab(a, b2) {
      b2 = b2.checked;
      null != b2 && ta(a, "checked", b2, false);
    }
    function bb(a, b2) {
      ab(a, b2);
      var c = Sa(b2.value), d2 = b2.type;
      if (null != c) if ("number" === d2) {
        if (0 === c && "" === a.value || a.value != c) a.value = "" + c;
      } else a.value !== "" + c && (a.value = "" + c);
      else if ("submit" === d2 || "reset" === d2) {
        a.removeAttribute("value");
        return;
      }
      b2.hasOwnProperty("value") ? cb(a, b2.type, c) : b2.hasOwnProperty("defaultValue") && cb(a, b2.type, Sa(b2.defaultValue));
      null == b2.checked && null != b2.defaultChecked && (a.defaultChecked = !!b2.defaultChecked);
    }
    function db(a, b2, c) {
      if (b2.hasOwnProperty("value") || b2.hasOwnProperty("defaultValue")) {
        var d2 = b2.type;
        if (!("submit" !== d2 && "reset" !== d2 || void 0 !== b2.value && null !== b2.value)) return;
        b2 = "" + a._wrapperState.initialValue;
        c || b2 === a.value || (a.value = b2);
        a.defaultValue = b2;
      }
      c = a.name;
      "" !== c && (a.name = "");
      a.defaultChecked = !!a._wrapperState.initialChecked;
      "" !== c && (a.name = c);
    }
    function cb(a, b2, c) {
      if ("number" !== b2 || Xa(a.ownerDocument) !== a) null == c ? a.defaultValue = "" + a._wrapperState.initialValue : a.defaultValue !== "" + c && (a.defaultValue = "" + c);
    }
    var eb = Array.isArray;
    function fb(a, b2, c, d2) {
      a = a.options;
      if (b2) {
        b2 = {};
        for (var e3 = 0; e3 < c.length; e3++) b2["$" + c[e3]] = true;
        for (c = 0; c < a.length; c++) e3 = b2.hasOwnProperty("$" + a[c].value), a[c].selected !== e3 && (a[c].selected = e3), e3 && d2 && (a[c].defaultSelected = true);
      } else {
        c = "" + Sa(c);
        b2 = null;
        for (e3 = 0; e3 < a.length; e3++) {
          if (a[e3].value === c) {
            a[e3].selected = true;
            d2 && (a[e3].defaultSelected = true);
            return;
          }
          null !== b2 || a[e3].disabled || (b2 = a[e3]);
        }
        null !== b2 && (b2.selected = true);
      }
    }
    function gb(a, b2) {
      if (null != b2.dangerouslySetInnerHTML) throw Error(p2(91));
      return A({}, b2, { value: void 0, defaultValue: void 0, children: "" + a._wrapperState.initialValue });
    }
    function hb(a, b2) {
      var c = b2.value;
      if (null == c) {
        c = b2.children;
        b2 = b2.defaultValue;
        if (null != c) {
          if (null != b2) throw Error(p2(92));
          if (eb(c)) {
            if (1 < c.length) throw Error(p2(93));
            c = c[0];
          }
          b2 = c;
        }
        null == b2 && (b2 = "");
        c = b2;
      }
      a._wrapperState = { initialValue: Sa(c) };
    }
    function ib(a, b2) {
      var c = Sa(b2.value), d2 = Sa(b2.defaultValue);
      null != c && (c = "" + c, c !== a.value && (a.value = c), null == b2.defaultValue && a.defaultValue !== c && (a.defaultValue = c));
      null != d2 && (a.defaultValue = "" + d2);
    }
    function jb(a) {
      var b2 = a.textContent;
      b2 === a._wrapperState.initialValue && "" !== b2 && null !== b2 && (a.value = b2);
    }
    function kb(a) {
      switch (a) {
        case "svg":
          return "http://www.w3.org/2000/svg";
        case "math":
          return "http://www.w3.org/1998/Math/MathML";
        default:
          return "http://www.w3.org/1999/xhtml";
      }
    }
    function lb(a, b2) {
      return null == a || "http://www.w3.org/1999/xhtml" === a ? kb(b2) : "http://www.w3.org/2000/svg" === a && "foreignObject" === b2 ? "http://www.w3.org/1999/xhtml" : a;
    }
    var mb;
    var nb = (function(a) {
      return "undefined" !== typeof MSApp && MSApp.execUnsafeLocalFunction ? function(b2, c, d2, e3) {
        MSApp.execUnsafeLocalFunction(function() {
          return a(b2, c, d2, e3);
        });
      } : a;
    })(function(a, b2) {
      if ("http://www.w3.org/2000/svg" !== a.namespaceURI || "innerHTML" in a) a.innerHTML = b2;
      else {
        mb = mb || document.createElement("div");
        mb.innerHTML = "<svg>" + b2.valueOf().toString() + "</svg>";
        for (b2 = mb.firstChild; a.firstChild; ) a.removeChild(a.firstChild);
        for (; b2.firstChild; ) a.appendChild(b2.firstChild);
      }
    });
    function ob(a, b2) {
      if (b2) {
        var c = a.firstChild;
        if (c && c === a.lastChild && 3 === c.nodeType) {
          c.nodeValue = b2;
          return;
        }
      }
      a.textContent = b2;
    }
    var pb = {
      animationIterationCount: true,
      aspectRatio: true,
      borderImageOutset: true,
      borderImageSlice: true,
      borderImageWidth: true,
      boxFlex: true,
      boxFlexGroup: true,
      boxOrdinalGroup: true,
      columnCount: true,
      columns: true,
      flex: true,
      flexGrow: true,
      flexPositive: true,
      flexShrink: true,
      flexNegative: true,
      flexOrder: true,
      gridArea: true,
      gridRow: true,
      gridRowEnd: true,
      gridRowSpan: true,
      gridRowStart: true,
      gridColumn: true,
      gridColumnEnd: true,
      gridColumnSpan: true,
      gridColumnStart: true,
      fontWeight: true,
      lineClamp: true,
      lineHeight: true,
      opacity: true,
      order: true,
      orphans: true,
      tabSize: true,
      widows: true,
      zIndex: true,
      zoom: true,
      fillOpacity: true,
      floodOpacity: true,
      stopOpacity: true,
      strokeDasharray: true,
      strokeDashoffset: true,
      strokeMiterlimit: true,
      strokeOpacity: true,
      strokeWidth: true
    };
    var qb = ["Webkit", "ms", "Moz", "O"];
    Object.keys(pb).forEach(function(a) {
      qb.forEach(function(b2) {
        b2 = b2 + a.charAt(0).toUpperCase() + a.substring(1);
        pb[b2] = pb[a];
      });
    });
    function rb(a, b2, c) {
      return null == b2 || "boolean" === typeof b2 || "" === b2 ? "" : c || "number" !== typeof b2 || 0 === b2 || pb.hasOwnProperty(a) && pb[a] ? ("" + b2).trim() : b2 + "px";
    }
    function sb(a, b2) {
      a = a.style;
      for (var c in b2) if (b2.hasOwnProperty(c)) {
        var d2 = 0 === c.indexOf("--"), e3 = rb(c, b2[c], d2);
        "float" === c && (c = "cssFloat");
        d2 ? a.setProperty(c, e3) : a[c] = e3;
      }
    }
    var tb = A({ menuitem: true }, { area: true, base: true, br: true, col: true, embed: true, hr: true, img: true, input: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true });
    function ub(a, b2) {
      if (b2) {
        if (tb[a] && (null != b2.children || null != b2.dangerouslySetInnerHTML)) throw Error(p2(137, a));
        if (null != b2.dangerouslySetInnerHTML) {
          if (null != b2.children) throw Error(p2(60));
          if ("object" !== typeof b2.dangerouslySetInnerHTML || !("__html" in b2.dangerouslySetInnerHTML)) throw Error(p2(61));
        }
        if (null != b2.style && "object" !== typeof b2.style) throw Error(p2(62));
      }
    }
    function vb(a, b2) {
      if (-1 === a.indexOf("-")) return "string" === typeof b2.is;
      switch (a) {
        case "annotation-xml":
        case "color-profile":
        case "font-face":
        case "font-face-src":
        case "font-face-uri":
        case "font-face-format":
        case "font-face-name":
        case "missing-glyph":
          return false;
        default:
          return true;
      }
    }
    var wb = null;
    function xb(a) {
      a = a.target || a.srcElement || window;
      a.correspondingUseElement && (a = a.correspondingUseElement);
      return 3 === a.nodeType ? a.parentNode : a;
    }
    var yb = null;
    var zb = null;
    var Ab = null;
    function Bb(a) {
      if (a = Cb(a)) {
        if ("function" !== typeof yb) throw Error(p2(280));
        var b2 = a.stateNode;
        b2 && (b2 = Db(b2), yb(a.stateNode, a.type, b2));
      }
    }
    function Eb(a) {
      zb ? Ab ? Ab.push(a) : Ab = [a] : zb = a;
    }
    function Fb() {
      if (zb) {
        var a = zb, b2 = Ab;
        Ab = zb = null;
        Bb(a);
        if (b2) for (a = 0; a < b2.length; a++) Bb(b2[a]);
      }
    }
    function Gb(a, b2) {
      return a(b2);
    }
    function Hb() {
    }
    var Ib = false;
    function Jb(a, b2, c) {
      if (Ib) return a(b2, c);
      Ib = true;
      try {
        return Gb(a, b2, c);
      } finally {
        if (Ib = false, null !== zb || null !== Ab) Hb(), Fb();
      }
    }
    function Kb(a, b2) {
      var c = a.stateNode;
      if (null === c) return null;
      var d2 = Db(c);
      if (null === d2) return null;
      c = d2[b2];
      a: switch (b2) {
        case "onClick":
        case "onClickCapture":
        case "onDoubleClick":
        case "onDoubleClickCapture":
        case "onMouseDown":
        case "onMouseDownCapture":
        case "onMouseMove":
        case "onMouseMoveCapture":
        case "onMouseUp":
        case "onMouseUpCapture":
        case "onMouseEnter":
          (d2 = !d2.disabled) || (a = a.type, d2 = !("button" === a || "input" === a || "select" === a || "textarea" === a));
          a = !d2;
          break a;
        default:
          a = false;
      }
      if (a) return null;
      if (c && "function" !== typeof c) throw Error(p2(231, b2, typeof c));
      return c;
    }
    var Lb = false;
    if (ia) try {
      Mb = {};
      Object.defineProperty(Mb, "passive", { get: function() {
        Lb = true;
      } });
      window.addEventListener("test", Mb, Mb);
      window.removeEventListener("test", Mb, Mb);
    } catch (a) {
      Lb = false;
    }
    var Mb;
    function Nb(a, b2, c, d2, e3, f, g, h2, k) {
      var l2 = Array.prototype.slice.call(arguments, 3);
      try {
        b2.apply(c, l2);
      } catch (m2) {
        this.onError(m2);
      }
    }
    var Ob = false;
    var Pb = null;
    var Qb = false;
    var Rb = null;
    var Sb = { onError: function(a) {
      Ob = true;
      Pb = a;
    } };
    function Tb(a, b2, c, d2, e3, f, g, h2, k) {
      Ob = false;
      Pb = null;
      Nb.apply(Sb, arguments);
    }
    function Ub(a, b2, c, d2, e3, f, g, h2, k) {
      Tb.apply(this, arguments);
      if (Ob) {
        if (Ob) {
          var l2 = Pb;
          Ob = false;
          Pb = null;
        } else throw Error(p2(198));
        Qb || (Qb = true, Rb = l2);
      }
    }
    function Vb(a) {
      var b2 = a, c = a;
      if (a.alternate) for (; b2.return; ) b2 = b2.return;
      else {
        a = b2;
        do
          b2 = a, 0 !== (b2.flags & 4098) && (c = b2.return), a = b2.return;
        while (a);
      }
      return 3 === b2.tag ? c : null;
    }
    function Wb(a) {
      if (13 === a.tag) {
        var b2 = a.memoizedState;
        null === b2 && (a = a.alternate, null !== a && (b2 = a.memoizedState));
        if (null !== b2) return b2.dehydrated;
      }
      return null;
    }
    function Xb(a) {
      if (Vb(a) !== a) throw Error(p2(188));
    }
    function Yb(a) {
      var b2 = a.alternate;
      if (!b2) {
        b2 = Vb(a);
        if (null === b2) throw Error(p2(188));
        return b2 !== a ? null : a;
      }
      for (var c = a, d2 = b2; ; ) {
        var e3 = c.return;
        if (null === e3) break;
        var f = e3.alternate;
        if (null === f) {
          d2 = e3.return;
          if (null !== d2) {
            c = d2;
            continue;
          }
          break;
        }
        if (e3.child === f.child) {
          for (f = e3.child; f; ) {
            if (f === c) return Xb(e3), a;
            if (f === d2) return Xb(e3), b2;
            f = f.sibling;
          }
          throw Error(p2(188));
        }
        if (c.return !== d2.return) c = e3, d2 = f;
        else {
          for (var g = false, h2 = e3.child; h2; ) {
            if (h2 === c) {
              g = true;
              c = e3;
              d2 = f;
              break;
            }
            if (h2 === d2) {
              g = true;
              d2 = e3;
              c = f;
              break;
            }
            h2 = h2.sibling;
          }
          if (!g) {
            for (h2 = f.child; h2; ) {
              if (h2 === c) {
                g = true;
                c = f;
                d2 = e3;
                break;
              }
              if (h2 === d2) {
                g = true;
                d2 = f;
                c = e3;
                break;
              }
              h2 = h2.sibling;
            }
            if (!g) throw Error(p2(189));
          }
        }
        if (c.alternate !== d2) throw Error(p2(190));
      }
      if (3 !== c.tag) throw Error(p2(188));
      return c.stateNode.current === c ? a : b2;
    }
    function Zb(a) {
      a = Yb(a);
      return null !== a ? $b(a) : null;
    }
    function $b(a) {
      if (5 === a.tag || 6 === a.tag) return a;
      for (a = a.child; null !== a; ) {
        var b2 = $b(a);
        if (null !== b2) return b2;
        a = a.sibling;
      }
      return null;
    }
    var ac = ca.unstable_scheduleCallback;
    var bc = ca.unstable_cancelCallback;
    var cc = ca.unstable_shouldYield;
    var dc = ca.unstable_requestPaint;
    var B2 = ca.unstable_now;
    var ec = ca.unstable_getCurrentPriorityLevel;
    var fc = ca.unstable_ImmediatePriority;
    var gc = ca.unstable_UserBlockingPriority;
    var hc = ca.unstable_NormalPriority;
    var ic = ca.unstable_LowPriority;
    var jc = ca.unstable_IdlePriority;
    var kc = null;
    var lc = null;
    function mc(a) {
      if (lc && "function" === typeof lc.onCommitFiberRoot) try {
        lc.onCommitFiberRoot(kc, a, void 0, 128 === (a.current.flags & 128));
      } catch (b2) {
      }
    }
    var oc = Math.clz32 ? Math.clz32 : nc;
    var pc = Math.log;
    var qc = Math.LN2;
    function nc(a) {
      a >>>= 0;
      return 0 === a ? 32 : 31 - (pc(a) / qc | 0) | 0;
    }
    var rc = 64;
    var sc = 4194304;
    function tc(a) {
      switch (a & -a) {
        case 1:
          return 1;
        case 2:
          return 2;
        case 4:
          return 4;
        case 8:
          return 8;
        case 16:
          return 16;
        case 32:
          return 32;
        case 64:
        case 128:
        case 256:
        case 512:
        case 1024:
        case 2048:
        case 4096:
        case 8192:
        case 16384:
        case 32768:
        case 65536:
        case 131072:
        case 262144:
        case 524288:
        case 1048576:
        case 2097152:
          return a & 4194240;
        case 4194304:
        case 8388608:
        case 16777216:
        case 33554432:
        case 67108864:
          return a & 130023424;
        case 134217728:
          return 134217728;
        case 268435456:
          return 268435456;
        case 536870912:
          return 536870912;
        case 1073741824:
          return 1073741824;
        default:
          return a;
      }
    }
    function uc(a, b2) {
      var c = a.pendingLanes;
      if (0 === c) return 0;
      var d2 = 0, e3 = a.suspendedLanes, f = a.pingedLanes, g = c & 268435455;
      if (0 !== g) {
        var h2 = g & ~e3;
        0 !== h2 ? d2 = tc(h2) : (f &= g, 0 !== f && (d2 = tc(f)));
      } else g = c & ~e3, 0 !== g ? d2 = tc(g) : 0 !== f && (d2 = tc(f));
      if (0 === d2) return 0;
      if (0 !== b2 && b2 !== d2 && 0 === (b2 & e3) && (e3 = d2 & -d2, f = b2 & -b2, e3 >= f || 16 === e3 && 0 !== (f & 4194240))) return b2;
      0 !== (d2 & 4) && (d2 |= c & 16);
      b2 = a.entangledLanes;
      if (0 !== b2) for (a = a.entanglements, b2 &= d2; 0 < b2; ) c = 31 - oc(b2), e3 = 1 << c, d2 |= a[c], b2 &= ~e3;
      return d2;
    }
    function vc(a, b2) {
      switch (a) {
        case 1:
        case 2:
        case 4:
          return b2 + 250;
        case 8:
        case 16:
        case 32:
        case 64:
        case 128:
        case 256:
        case 512:
        case 1024:
        case 2048:
        case 4096:
        case 8192:
        case 16384:
        case 32768:
        case 65536:
        case 131072:
        case 262144:
        case 524288:
        case 1048576:
        case 2097152:
          return b2 + 5e3;
        case 4194304:
        case 8388608:
        case 16777216:
        case 33554432:
        case 67108864:
          return -1;
        case 134217728:
        case 268435456:
        case 536870912:
        case 1073741824:
          return -1;
        default:
          return -1;
      }
    }
    function wc(a, b2) {
      for (var c = a.suspendedLanes, d2 = a.pingedLanes, e3 = a.expirationTimes, f = a.pendingLanes; 0 < f; ) {
        var g = 31 - oc(f), h2 = 1 << g, k = e3[g];
        if (-1 === k) {
          if (0 === (h2 & c) || 0 !== (h2 & d2)) e3[g] = vc(h2, b2);
        } else k <= b2 && (a.expiredLanes |= h2);
        f &= ~h2;
      }
    }
    function xc(a) {
      a = a.pendingLanes & -1073741825;
      return 0 !== a ? a : a & 1073741824 ? 1073741824 : 0;
    }
    function yc() {
      var a = rc;
      rc <<= 1;
      0 === (rc & 4194240) && (rc = 64);
      return a;
    }
    function zc(a) {
      for (var b2 = [], c = 0; 31 > c; c++) b2.push(a);
      return b2;
    }
    function Ac(a, b2, c) {
      a.pendingLanes |= b2;
      536870912 !== b2 && (a.suspendedLanes = 0, a.pingedLanes = 0);
      a = a.eventTimes;
      b2 = 31 - oc(b2);
      a[b2] = c;
    }
    function Bc(a, b2) {
      var c = a.pendingLanes & ~b2;
      a.pendingLanes = b2;
      a.suspendedLanes = 0;
      a.pingedLanes = 0;
      a.expiredLanes &= b2;
      a.mutableReadLanes &= b2;
      a.entangledLanes &= b2;
      b2 = a.entanglements;
      var d2 = a.eventTimes;
      for (a = a.expirationTimes; 0 < c; ) {
        var e3 = 31 - oc(c), f = 1 << e3;
        b2[e3] = 0;
        d2[e3] = -1;
        a[e3] = -1;
        c &= ~f;
      }
    }
    function Cc(a, b2) {
      var c = a.entangledLanes |= b2;
      for (a = a.entanglements; c; ) {
        var d2 = 31 - oc(c), e3 = 1 << d2;
        e3 & b2 | a[d2] & b2 && (a[d2] |= b2);
        c &= ~e3;
      }
    }
    var C = 0;
    function Dc(a) {
      a &= -a;
      return 1 < a ? 4 < a ? 0 !== (a & 268435455) ? 16 : 536870912 : 4 : 1;
    }
    var Ec;
    var Fc;
    var Gc;
    var Hc;
    var Ic;
    var Jc = false;
    var Kc = [];
    var Lc = null;
    var Mc = null;
    var Nc = null;
    var Oc = /* @__PURE__ */ new Map();
    var Pc = /* @__PURE__ */ new Map();
    var Qc = [];
    var Rc = "mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");
    function Sc(a, b2) {
      switch (a) {
        case "focusin":
        case "focusout":
          Lc = null;
          break;
        case "dragenter":
        case "dragleave":
          Mc = null;
          break;
        case "mouseover":
        case "mouseout":
          Nc = null;
          break;
        case "pointerover":
        case "pointerout":
          Oc.delete(b2.pointerId);
          break;
        case "gotpointercapture":
        case "lostpointercapture":
          Pc.delete(b2.pointerId);
      }
    }
    function Tc(a, b2, c, d2, e3, f) {
      if (null === a || a.nativeEvent !== f) return a = { blockedOn: b2, domEventName: c, eventSystemFlags: d2, nativeEvent: f, targetContainers: [e3] }, null !== b2 && (b2 = Cb(b2), null !== b2 && Fc(b2)), a;
      a.eventSystemFlags |= d2;
      b2 = a.targetContainers;
      null !== e3 && -1 === b2.indexOf(e3) && b2.push(e3);
      return a;
    }
    function Uc(a, b2, c, d2, e3) {
      switch (b2) {
        case "focusin":
          return Lc = Tc(Lc, a, b2, c, d2, e3), true;
        case "dragenter":
          return Mc = Tc(Mc, a, b2, c, d2, e3), true;
        case "mouseover":
          return Nc = Tc(Nc, a, b2, c, d2, e3), true;
        case "pointerover":
          var f = e3.pointerId;
          Oc.set(f, Tc(Oc.get(f) || null, a, b2, c, d2, e3));
          return true;
        case "gotpointercapture":
          return f = e3.pointerId, Pc.set(f, Tc(Pc.get(f) || null, a, b2, c, d2, e3)), true;
      }
      return false;
    }
    function Vc(a) {
      var b2 = Wc(a.target);
      if (null !== b2) {
        var c = Vb(b2);
        if (null !== c) {
          if (b2 = c.tag, 13 === b2) {
            if (b2 = Wb(c), null !== b2) {
              a.blockedOn = b2;
              Ic(a.priority, function() {
                Gc(c);
              });
              return;
            }
          } else if (3 === b2 && c.stateNode.current.memoizedState.isDehydrated) {
            a.blockedOn = 3 === c.tag ? c.stateNode.containerInfo : null;
            return;
          }
        }
      }
      a.blockedOn = null;
    }
    function Xc(a) {
      if (null !== a.blockedOn) return false;
      for (var b2 = a.targetContainers; 0 < b2.length; ) {
        var c = Yc(a.domEventName, a.eventSystemFlags, b2[0], a.nativeEvent);
        if (null === c) {
          c = a.nativeEvent;
          var d2 = new c.constructor(c.type, c);
          wb = d2;
          c.target.dispatchEvent(d2);
          wb = null;
        } else return b2 = Cb(c), null !== b2 && Fc(b2), a.blockedOn = c, false;
        b2.shift();
      }
      return true;
    }
    function Zc(a, b2, c) {
      Xc(a) && c.delete(b2);
    }
    function $c() {
      Jc = false;
      null !== Lc && Xc(Lc) && (Lc = null);
      null !== Mc && Xc(Mc) && (Mc = null);
      null !== Nc && Xc(Nc) && (Nc = null);
      Oc.forEach(Zc);
      Pc.forEach(Zc);
    }
    function ad(a, b2) {
      a.blockedOn === b2 && (a.blockedOn = null, Jc || (Jc = true, ca.unstable_scheduleCallback(ca.unstable_NormalPriority, $c)));
    }
    function bd(a) {
      function b2(b3) {
        return ad(b3, a);
      }
      if (0 < Kc.length) {
        ad(Kc[0], a);
        for (var c = 1; c < Kc.length; c++) {
          var d2 = Kc[c];
          d2.blockedOn === a && (d2.blockedOn = null);
        }
      }
      null !== Lc && ad(Lc, a);
      null !== Mc && ad(Mc, a);
      null !== Nc && ad(Nc, a);
      Oc.forEach(b2);
      Pc.forEach(b2);
      for (c = 0; c < Qc.length; c++) d2 = Qc[c], d2.blockedOn === a && (d2.blockedOn = null);
      for (; 0 < Qc.length && (c = Qc[0], null === c.blockedOn); ) Vc(c), null === c.blockedOn && Qc.shift();
    }
    var cd = ua.ReactCurrentBatchConfig;
    var dd = true;
    function ed(a, b2, c, d2) {
      var e3 = C, f = cd.transition;
      cd.transition = null;
      try {
        C = 1, fd(a, b2, c, d2);
      } finally {
        C = e3, cd.transition = f;
      }
    }
    function gd(a, b2, c, d2) {
      var e3 = C, f = cd.transition;
      cd.transition = null;
      try {
        C = 4, fd(a, b2, c, d2);
      } finally {
        C = e3, cd.transition = f;
      }
    }
    function fd(a, b2, c, d2) {
      if (dd) {
        var e3 = Yc(a, b2, c, d2);
        if (null === e3) hd(a, b2, d2, id, c), Sc(a, d2);
        else if (Uc(e3, a, b2, c, d2)) d2.stopPropagation();
        else if (Sc(a, d2), b2 & 4 && -1 < Rc.indexOf(a)) {
          for (; null !== e3; ) {
            var f = Cb(e3);
            null !== f && Ec(f);
            f = Yc(a, b2, c, d2);
            null === f && hd(a, b2, d2, id, c);
            if (f === e3) break;
            e3 = f;
          }
          null !== e3 && d2.stopPropagation();
        } else hd(a, b2, d2, null, c);
      }
    }
    var id = null;
    function Yc(a, b2, c, d2) {
      id = null;
      a = xb(d2);
      a = Wc(a);
      if (null !== a) if (b2 = Vb(a), null === b2) a = null;
      else if (c = b2.tag, 13 === c) {
        a = Wb(b2);
        if (null !== a) return a;
        a = null;
      } else if (3 === c) {
        if (b2.stateNode.current.memoizedState.isDehydrated) return 3 === b2.tag ? b2.stateNode.containerInfo : null;
        a = null;
      } else b2 !== a && (a = null);
      id = a;
      return null;
    }
    function jd(a) {
      switch (a) {
        case "cancel":
        case "click":
        case "close":
        case "contextmenu":
        case "copy":
        case "cut":
        case "auxclick":
        case "dblclick":
        case "dragend":
        case "dragstart":
        case "drop":
        case "focusin":
        case "focusout":
        case "input":
        case "invalid":
        case "keydown":
        case "keypress":
        case "keyup":
        case "mousedown":
        case "mouseup":
        case "paste":
        case "pause":
        case "play":
        case "pointercancel":
        case "pointerdown":
        case "pointerup":
        case "ratechange":
        case "reset":
        case "resize":
        case "seeked":
        case "submit":
        case "touchcancel":
        case "touchend":
        case "touchstart":
        case "volumechange":
        case "change":
        case "selectionchange":
        case "textInput":
        case "compositionstart":
        case "compositionend":
        case "compositionupdate":
        case "beforeblur":
        case "afterblur":
        case "beforeinput":
        case "blur":
        case "fullscreenchange":
        case "focus":
        case "hashchange":
        case "popstate":
        case "select":
        case "selectstart":
          return 1;
        case "drag":
        case "dragenter":
        case "dragexit":
        case "dragleave":
        case "dragover":
        case "mousemove":
        case "mouseout":
        case "mouseover":
        case "pointermove":
        case "pointerout":
        case "pointerover":
        case "scroll":
        case "toggle":
        case "touchmove":
        case "wheel":
        case "mouseenter":
        case "mouseleave":
        case "pointerenter":
        case "pointerleave":
          return 4;
        case "message":
          switch (ec()) {
            case fc:
              return 1;
            case gc:
              return 4;
            case hc:
            case ic:
              return 16;
            case jc:
              return 536870912;
            default:
              return 16;
          }
        default:
          return 16;
      }
    }
    var kd = null;
    var ld = null;
    var md = null;
    function nd() {
      if (md) return md;
      var a, b2 = ld, c = b2.length, d2, e3 = "value" in kd ? kd.value : kd.textContent, f = e3.length;
      for (a = 0; a < c && b2[a] === e3[a]; a++) ;
      var g = c - a;
      for (d2 = 1; d2 <= g && b2[c - d2] === e3[f - d2]; d2++) ;
      return md = e3.slice(a, 1 < d2 ? 1 - d2 : void 0);
    }
    function od(a) {
      var b2 = a.keyCode;
      "charCode" in a ? (a = a.charCode, 0 === a && 13 === b2 && (a = 13)) : a = b2;
      10 === a && (a = 13);
      return 32 <= a || 13 === a ? a : 0;
    }
    function pd() {
      return true;
    }
    function qd() {
      return false;
    }
    function rd(a) {
      function b2(b3, d2, e3, f, g) {
        this._reactName = b3;
        this._targetInst = e3;
        this.type = d2;
        this.nativeEvent = f;
        this.target = g;
        this.currentTarget = null;
        for (var c in a) a.hasOwnProperty(c) && (b3 = a[c], this[c] = b3 ? b3(f) : f[c]);
        this.isDefaultPrevented = (null != f.defaultPrevented ? f.defaultPrevented : false === f.returnValue) ? pd : qd;
        this.isPropagationStopped = qd;
        return this;
      }
      A(b2.prototype, { preventDefault: function() {
        this.defaultPrevented = true;
        var a2 = this.nativeEvent;
        a2 && (a2.preventDefault ? a2.preventDefault() : "unknown" !== typeof a2.returnValue && (a2.returnValue = false), this.isDefaultPrevented = pd);
      }, stopPropagation: function() {
        var a2 = this.nativeEvent;
        a2 && (a2.stopPropagation ? a2.stopPropagation() : "unknown" !== typeof a2.cancelBubble && (a2.cancelBubble = true), this.isPropagationStopped = pd);
      }, persist: function() {
      }, isPersistent: pd });
      return b2;
    }
    var sd = { eventPhase: 0, bubbles: 0, cancelable: 0, timeStamp: function(a) {
      return a.timeStamp || Date.now();
    }, defaultPrevented: 0, isTrusted: 0 };
    var td = rd(sd);
    var ud = A({}, sd, { view: 0, detail: 0 });
    var vd = rd(ud);
    var wd;
    var xd;
    var yd;
    var Ad = A({}, ud, { screenX: 0, screenY: 0, clientX: 0, clientY: 0, pageX: 0, pageY: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, getModifierState: zd, button: 0, buttons: 0, relatedTarget: function(a) {
      return void 0 === a.relatedTarget ? a.fromElement === a.srcElement ? a.toElement : a.fromElement : a.relatedTarget;
    }, movementX: function(a) {
      if ("movementX" in a) return a.movementX;
      a !== yd && (yd && "mousemove" === a.type ? (wd = a.screenX - yd.screenX, xd = a.screenY - yd.screenY) : xd = wd = 0, yd = a);
      return wd;
    }, movementY: function(a) {
      return "movementY" in a ? a.movementY : xd;
    } });
    var Bd = rd(Ad);
    var Cd = A({}, Ad, { dataTransfer: 0 });
    var Dd = rd(Cd);
    var Ed = A({}, ud, { relatedTarget: 0 });
    var Fd = rd(Ed);
    var Gd = A({}, sd, { animationName: 0, elapsedTime: 0, pseudoElement: 0 });
    var Hd = rd(Gd);
    var Id = A({}, sd, { clipboardData: function(a) {
      return "clipboardData" in a ? a.clipboardData : window.clipboardData;
    } });
    var Jd = rd(Id);
    var Kd = A({}, sd, { data: 0 });
    var Ld = rd(Kd);
    var Md = {
      Esc: "Escape",
      Spacebar: " ",
      Left: "ArrowLeft",
      Up: "ArrowUp",
      Right: "ArrowRight",
      Down: "ArrowDown",
      Del: "Delete",
      Win: "OS",
      Menu: "ContextMenu",
      Apps: "ContextMenu",
      Scroll: "ScrollLock",
      MozPrintableKey: "Unidentified"
    };
    var Nd = {
      8: "Backspace",
      9: "Tab",
      12: "Clear",
      13: "Enter",
      16: "Shift",
      17: "Control",
      18: "Alt",
      19: "Pause",
      20: "CapsLock",
      27: "Escape",
      32: " ",
      33: "PageUp",
      34: "PageDown",
      35: "End",
      36: "Home",
      37: "ArrowLeft",
      38: "ArrowUp",
      39: "ArrowRight",
      40: "ArrowDown",
      45: "Insert",
      46: "Delete",
      112: "F1",
      113: "F2",
      114: "F3",
      115: "F4",
      116: "F5",
      117: "F6",
      118: "F7",
      119: "F8",
      120: "F9",
      121: "F10",
      122: "F11",
      123: "F12",
      144: "NumLock",
      145: "ScrollLock",
      224: "Meta"
    };
    var Od = { Alt: "altKey", Control: "ctrlKey", Meta: "metaKey", Shift: "shiftKey" };
    function Pd(a) {
      var b2 = this.nativeEvent;
      return b2.getModifierState ? b2.getModifierState(a) : (a = Od[a]) ? !!b2[a] : false;
    }
    function zd() {
      return Pd;
    }
    var Qd = A({}, ud, { key: function(a) {
      if (a.key) {
        var b2 = Md[a.key] || a.key;
        if ("Unidentified" !== b2) return b2;
      }
      return "keypress" === a.type ? (a = od(a), 13 === a ? "Enter" : String.fromCharCode(a)) : "keydown" === a.type || "keyup" === a.type ? Nd[a.keyCode] || "Unidentified" : "";
    }, code: 0, location: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, repeat: 0, locale: 0, getModifierState: zd, charCode: function(a) {
      return "keypress" === a.type ? od(a) : 0;
    }, keyCode: function(a) {
      return "keydown" === a.type || "keyup" === a.type ? a.keyCode : 0;
    }, which: function(a) {
      return "keypress" === a.type ? od(a) : "keydown" === a.type || "keyup" === a.type ? a.keyCode : 0;
    } });
    var Rd = rd(Qd);
    var Sd = A({}, Ad, { pointerId: 0, width: 0, height: 0, pressure: 0, tangentialPressure: 0, tiltX: 0, tiltY: 0, twist: 0, pointerType: 0, isPrimary: 0 });
    var Td = rd(Sd);
    var Ud = A({}, ud, { touches: 0, targetTouches: 0, changedTouches: 0, altKey: 0, metaKey: 0, ctrlKey: 0, shiftKey: 0, getModifierState: zd });
    var Vd = rd(Ud);
    var Wd = A({}, sd, { propertyName: 0, elapsedTime: 0, pseudoElement: 0 });
    var Xd = rd(Wd);
    var Yd = A({}, Ad, {
      deltaX: function(a) {
        return "deltaX" in a ? a.deltaX : "wheelDeltaX" in a ? -a.wheelDeltaX : 0;
      },
      deltaY: function(a) {
        return "deltaY" in a ? a.deltaY : "wheelDeltaY" in a ? -a.wheelDeltaY : "wheelDelta" in a ? -a.wheelDelta : 0;
      },
      deltaZ: 0,
      deltaMode: 0
    });
    var Zd = rd(Yd);
    var $d = [9, 13, 27, 32];
    var ae = ia && "CompositionEvent" in window;
    var be = null;
    ia && "documentMode" in document && (be = document.documentMode);
    var ce = ia && "TextEvent" in window && !be;
    var de = ia && (!ae || be && 8 < be && 11 >= be);
    var ee = String.fromCharCode(32);
    var fe = false;
    function ge(a, b2) {
      switch (a) {
        case "keyup":
          return -1 !== $d.indexOf(b2.keyCode);
        case "keydown":
          return 229 !== b2.keyCode;
        case "keypress":
        case "mousedown":
        case "focusout":
          return true;
        default:
          return false;
      }
    }
    function he(a) {
      a = a.detail;
      return "object" === typeof a && "data" in a ? a.data : null;
    }
    var ie = false;
    function je(a, b2) {
      switch (a) {
        case "compositionend":
          return he(b2);
        case "keypress":
          if (32 !== b2.which) return null;
          fe = true;
          return ee;
        case "textInput":
          return a = b2.data, a === ee && fe ? null : a;
        default:
          return null;
      }
    }
    function ke(a, b2) {
      if (ie) return "compositionend" === a || !ae && ge(a, b2) ? (a = nd(), md = ld = kd = null, ie = false, a) : null;
      switch (a) {
        case "paste":
          return null;
        case "keypress":
          if (!(b2.ctrlKey || b2.altKey || b2.metaKey) || b2.ctrlKey && b2.altKey) {
            if (b2.char && 1 < b2.char.length) return b2.char;
            if (b2.which) return String.fromCharCode(b2.which);
          }
          return null;
        case "compositionend":
          return de && "ko" !== b2.locale ? null : b2.data;
        default:
          return null;
      }
    }
    var le = { color: true, date: true, datetime: true, "datetime-local": true, email: true, month: true, number: true, password: true, range: true, search: true, tel: true, text: true, time: true, url: true, week: true };
    function me(a) {
      var b2 = a && a.nodeName && a.nodeName.toLowerCase();
      return "input" === b2 ? !!le[a.type] : "textarea" === b2 ? true : false;
    }
    function ne(a, b2, c, d2) {
      Eb(d2);
      b2 = oe(b2, "onChange");
      0 < b2.length && (c = new td("onChange", "change", null, c, d2), a.push({ event: c, listeners: b2 }));
    }
    var pe = null;
    var qe = null;
    function re(a) {
      se(a, 0);
    }
    function te(a) {
      var b2 = ue(a);
      if (Wa(b2)) return a;
    }
    function ve(a, b2) {
      if ("change" === a) return b2;
    }
    var we = false;
    if (ia) {
      if (ia) {
        ye = "oninput" in document;
        if (!ye) {
          ze = document.createElement("div");
          ze.setAttribute("oninput", "return;");
          ye = "function" === typeof ze.oninput;
        }
        xe = ye;
      } else xe = false;
      we = xe && (!document.documentMode || 9 < document.documentMode);
    }
    var xe;
    var ye;
    var ze;
    function Ae() {
      pe && (pe.detachEvent("onpropertychange", Be), qe = pe = null);
    }
    function Be(a) {
      if ("value" === a.propertyName && te(qe)) {
        var b2 = [];
        ne(b2, qe, a, xb(a));
        Jb(re, b2);
      }
    }
    function Ce(a, b2, c) {
      "focusin" === a ? (Ae(), pe = b2, qe = c, pe.attachEvent("onpropertychange", Be)) : "focusout" === a && Ae();
    }
    function De(a) {
      if ("selectionchange" === a || "keyup" === a || "keydown" === a) return te(qe);
    }
    function Ee(a, b2) {
      if ("click" === a) return te(b2);
    }
    function Fe(a, b2) {
      if ("input" === a || "change" === a) return te(b2);
    }
    function Ge(a, b2) {
      return a === b2 && (0 !== a || 1 / a === 1 / b2) || a !== a && b2 !== b2;
    }
    var He = "function" === typeof Object.is ? Object.is : Ge;
    function Ie(a, b2) {
      if (He(a, b2)) return true;
      if ("object" !== typeof a || null === a || "object" !== typeof b2 || null === b2) return false;
      var c = Object.keys(a), d2 = Object.keys(b2);
      if (c.length !== d2.length) return false;
      for (d2 = 0; d2 < c.length; d2++) {
        var e3 = c[d2];
        if (!ja.call(b2, e3) || !He(a[e3], b2[e3])) return false;
      }
      return true;
    }
    function Je(a) {
      for (; a && a.firstChild; ) a = a.firstChild;
      return a;
    }
    function Ke(a, b2) {
      var c = Je(a);
      a = 0;
      for (var d2; c; ) {
        if (3 === c.nodeType) {
          d2 = a + c.textContent.length;
          if (a <= b2 && d2 >= b2) return { node: c, offset: b2 - a };
          a = d2;
        }
        a: {
          for (; c; ) {
            if (c.nextSibling) {
              c = c.nextSibling;
              break a;
            }
            c = c.parentNode;
          }
          c = void 0;
        }
        c = Je(c);
      }
    }
    function Le(a, b2) {
      return a && b2 ? a === b2 ? true : a && 3 === a.nodeType ? false : b2 && 3 === b2.nodeType ? Le(a, b2.parentNode) : "contains" in a ? a.contains(b2) : a.compareDocumentPosition ? !!(a.compareDocumentPosition(b2) & 16) : false : false;
    }
    function Me() {
      for (var a = window, b2 = Xa(); b2 instanceof a.HTMLIFrameElement; ) {
        try {
          var c = "string" === typeof b2.contentWindow.location.href;
        } catch (d2) {
          c = false;
        }
        if (c) a = b2.contentWindow;
        else break;
        b2 = Xa(a.document);
      }
      return b2;
    }
    function Ne(a) {
      var b2 = a && a.nodeName && a.nodeName.toLowerCase();
      return b2 && ("input" === b2 && ("text" === a.type || "search" === a.type || "tel" === a.type || "url" === a.type || "password" === a.type) || "textarea" === b2 || "true" === a.contentEditable);
    }
    function Oe(a) {
      var b2 = Me(), c = a.focusedElem, d2 = a.selectionRange;
      if (b2 !== c && c && c.ownerDocument && Le(c.ownerDocument.documentElement, c)) {
        if (null !== d2 && Ne(c)) {
          if (b2 = d2.start, a = d2.end, void 0 === a && (a = b2), "selectionStart" in c) c.selectionStart = b2, c.selectionEnd = Math.min(a, c.value.length);
          else if (a = (b2 = c.ownerDocument || document) && b2.defaultView || window, a.getSelection) {
            a = a.getSelection();
            var e3 = c.textContent.length, f = Math.min(d2.start, e3);
            d2 = void 0 === d2.end ? f : Math.min(d2.end, e3);
            !a.extend && f > d2 && (e3 = d2, d2 = f, f = e3);
            e3 = Ke(c, f);
            var g = Ke(
              c,
              d2
            );
            e3 && g && (1 !== a.rangeCount || a.anchorNode !== e3.node || a.anchorOffset !== e3.offset || a.focusNode !== g.node || a.focusOffset !== g.offset) && (b2 = b2.createRange(), b2.setStart(e3.node, e3.offset), a.removeAllRanges(), f > d2 ? (a.addRange(b2), a.extend(g.node, g.offset)) : (b2.setEnd(g.node, g.offset), a.addRange(b2)));
          }
        }
        b2 = [];
        for (a = c; a = a.parentNode; ) 1 === a.nodeType && b2.push({ element: a, left: a.scrollLeft, top: a.scrollTop });
        "function" === typeof c.focus && c.focus();
        for (c = 0; c < b2.length; c++) a = b2[c], a.element.scrollLeft = a.left, a.element.scrollTop = a.top;
      }
    }
    var Pe = ia && "documentMode" in document && 11 >= document.documentMode;
    var Qe = null;
    var Re = null;
    var Se = null;
    var Te = false;
    function Ue(a, b2, c) {
      var d2 = c.window === c ? c.document : 9 === c.nodeType ? c : c.ownerDocument;
      Te || null == Qe || Qe !== Xa(d2) || (d2 = Qe, "selectionStart" in d2 && Ne(d2) ? d2 = { start: d2.selectionStart, end: d2.selectionEnd } : (d2 = (d2.ownerDocument && d2.ownerDocument.defaultView || window).getSelection(), d2 = { anchorNode: d2.anchorNode, anchorOffset: d2.anchorOffset, focusNode: d2.focusNode, focusOffset: d2.focusOffset }), Se && Ie(Se, d2) || (Se = d2, d2 = oe(Re, "onSelect"), 0 < d2.length && (b2 = new td("onSelect", "select", null, b2, c), a.push({ event: b2, listeners: d2 }), b2.target = Qe)));
    }
    function Ve(a, b2) {
      var c = {};
      c[a.toLowerCase()] = b2.toLowerCase();
      c["Webkit" + a] = "webkit" + b2;
      c["Moz" + a] = "moz" + b2;
      return c;
    }
    var We = { animationend: Ve("Animation", "AnimationEnd"), animationiteration: Ve("Animation", "AnimationIteration"), animationstart: Ve("Animation", "AnimationStart"), transitionend: Ve("Transition", "TransitionEnd") };
    var Xe = {};
    var Ye = {};
    ia && (Ye = document.createElement("div").style, "AnimationEvent" in window || (delete We.animationend.animation, delete We.animationiteration.animation, delete We.animationstart.animation), "TransitionEvent" in window || delete We.transitionend.transition);
    function Ze(a) {
      if (Xe[a]) return Xe[a];
      if (!We[a]) return a;
      var b2 = We[a], c;
      for (c in b2) if (b2.hasOwnProperty(c) && c in Ye) return Xe[a] = b2[c];
      return a;
    }
    var $e = Ze("animationend");
    var af = Ze("animationiteration");
    var bf = Ze("animationstart");
    var cf = Ze("transitionend");
    var df = /* @__PURE__ */ new Map();
    var ef = "abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");
    function ff(a, b2) {
      df.set(a, b2);
      fa(b2, [a]);
    }
    for (gf = 0; gf < ef.length; gf++) {
      hf = ef[gf], jf = hf.toLowerCase(), kf = hf[0].toUpperCase() + hf.slice(1);
      ff(jf, "on" + kf);
    }
    var hf;
    var jf;
    var kf;
    var gf;
    ff($e, "onAnimationEnd");
    ff(af, "onAnimationIteration");
    ff(bf, "onAnimationStart");
    ff("dblclick", "onDoubleClick");
    ff("focusin", "onFocus");
    ff("focusout", "onBlur");
    ff(cf, "onTransitionEnd");
    ha("onMouseEnter", ["mouseout", "mouseover"]);
    ha("onMouseLeave", ["mouseout", "mouseover"]);
    ha("onPointerEnter", ["pointerout", "pointerover"]);
    ha("onPointerLeave", ["pointerout", "pointerover"]);
    fa("onChange", "change click focusin focusout input keydown keyup selectionchange".split(" "));
    fa("onSelect", "focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));
    fa("onBeforeInput", ["compositionend", "keypress", "textInput", "paste"]);
    fa("onCompositionEnd", "compositionend focusout keydown keypress keyup mousedown".split(" "));
    fa("onCompositionStart", "compositionstart focusout keydown keypress keyup mousedown".split(" "));
    fa("onCompositionUpdate", "compositionupdate focusout keydown keypress keyup mousedown".split(" "));
    var lf = "abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" ");
    var mf = new Set("cancel close invalid load scroll toggle".split(" ").concat(lf));
    function nf(a, b2, c) {
      var d2 = a.type || "unknown-event";
      a.currentTarget = c;
      Ub(d2, b2, void 0, a);
      a.currentTarget = null;
    }
    function se(a, b2) {
      b2 = 0 !== (b2 & 4);
      for (var c = 0; c < a.length; c++) {
        var d2 = a[c], e3 = d2.event;
        d2 = d2.listeners;
        a: {
          var f = void 0;
          if (b2) for (var g = d2.length - 1; 0 <= g; g--) {
            var h2 = d2[g], k = h2.instance, l2 = h2.currentTarget;
            h2 = h2.listener;
            if (k !== f && e3.isPropagationStopped()) break a;
            nf(e3, h2, l2);
            f = k;
          }
          else for (g = 0; g < d2.length; g++) {
            h2 = d2[g];
            k = h2.instance;
            l2 = h2.currentTarget;
            h2 = h2.listener;
            if (k !== f && e3.isPropagationStopped()) break a;
            nf(e3, h2, l2);
            f = k;
          }
        }
      }
      if (Qb) throw a = Rb, Qb = false, Rb = null, a;
    }
    function D(a, b2) {
      var c = b2[of];
      void 0 === c && (c = b2[of] = /* @__PURE__ */ new Set());
      var d2 = a + "__bubble";
      c.has(d2) || (pf(b2, a, 2, false), c.add(d2));
    }
    function qf(a, b2, c) {
      var d2 = 0;
      b2 && (d2 |= 4);
      pf(c, a, d2, b2);
    }
    var rf = "_reactListening" + Math.random().toString(36).slice(2);
    function sf(a) {
      if (!a[rf]) {
        a[rf] = true;
        da.forEach(function(b3) {
          "selectionchange" !== b3 && (mf.has(b3) || qf(b3, false, a), qf(b3, true, a));
        });
        var b2 = 9 === a.nodeType ? a : a.ownerDocument;
        null === b2 || b2[rf] || (b2[rf] = true, qf("selectionchange", false, b2));
      }
    }
    function pf(a, b2, c, d2) {
      switch (jd(b2)) {
        case 1:
          var e3 = ed;
          break;
        case 4:
          e3 = gd;
          break;
        default:
          e3 = fd;
      }
      c = e3.bind(null, b2, c, a);
      e3 = void 0;
      !Lb || "touchstart" !== b2 && "touchmove" !== b2 && "wheel" !== b2 || (e3 = true);
      d2 ? void 0 !== e3 ? a.addEventListener(b2, c, { capture: true, passive: e3 }) : a.addEventListener(b2, c, true) : void 0 !== e3 ? a.addEventListener(b2, c, { passive: e3 }) : a.addEventListener(b2, c, false);
    }
    function hd(a, b2, c, d2, e3) {
      var f = d2;
      if (0 === (b2 & 1) && 0 === (b2 & 2) && null !== d2) a: for (; ; ) {
        if (null === d2) return;
        var g = d2.tag;
        if (3 === g || 4 === g) {
          var h2 = d2.stateNode.containerInfo;
          if (h2 === e3 || 8 === h2.nodeType && h2.parentNode === e3) break;
          if (4 === g) for (g = d2.return; null !== g; ) {
            var k = g.tag;
            if (3 === k || 4 === k) {
              if (k = g.stateNode.containerInfo, k === e3 || 8 === k.nodeType && k.parentNode === e3) return;
            }
            g = g.return;
          }
          for (; null !== h2; ) {
            g = Wc(h2);
            if (null === g) return;
            k = g.tag;
            if (5 === k || 6 === k) {
              d2 = f = g;
              continue a;
            }
            h2 = h2.parentNode;
          }
        }
        d2 = d2.return;
      }
      Jb(function() {
        var d3 = f, e4 = xb(c), g2 = [];
        a: {
          var h3 = df.get(a);
          if (void 0 !== h3) {
            var k2 = td, n3 = a;
            switch (a) {
              case "keypress":
                if (0 === od(c)) break a;
              case "keydown":
              case "keyup":
                k2 = Rd;
                break;
              case "focusin":
                n3 = "focus";
                k2 = Fd;
                break;
              case "focusout":
                n3 = "blur";
                k2 = Fd;
                break;
              case "beforeblur":
              case "afterblur":
                k2 = Fd;
                break;
              case "click":
                if (2 === c.button) break a;
              case "auxclick":
              case "dblclick":
              case "mousedown":
              case "mousemove":
              case "mouseup":
              case "mouseout":
              case "mouseover":
              case "contextmenu":
                k2 = Bd;
                break;
              case "drag":
              case "dragend":
              case "dragenter":
              case "dragexit":
              case "dragleave":
              case "dragover":
              case "dragstart":
              case "drop":
                k2 = Dd;
                break;
              case "touchcancel":
              case "touchend":
              case "touchmove":
              case "touchstart":
                k2 = Vd;
                break;
              case $e:
              case af:
              case bf:
                k2 = Hd;
                break;
              case cf:
                k2 = Xd;
                break;
              case "scroll":
                k2 = vd;
                break;
              case "wheel":
                k2 = Zd;
                break;
              case "copy":
              case "cut":
              case "paste":
                k2 = Jd;
                break;
              case "gotpointercapture":
              case "lostpointercapture":
              case "pointercancel":
              case "pointerdown":
              case "pointermove":
              case "pointerout":
              case "pointerover":
              case "pointerup":
                k2 = Td;
            }
            var t2 = 0 !== (b2 & 4), J = !t2 && "scroll" === a, x = t2 ? null !== h3 ? h3 + "Capture" : null : h3;
            t2 = [];
            for (var w2 = d3, u2; null !== w2; ) {
              u2 = w2;
              var F = u2.stateNode;
              5 === u2.tag && null !== F && (u2 = F, null !== x && (F = Kb(w2, x), null != F && t2.push(tf(w2, F, u2))));
              if (J) break;
              w2 = w2.return;
            }
            0 < t2.length && (h3 = new k2(h3, n3, null, c, e4), g2.push({ event: h3, listeners: t2 }));
          }
        }
        if (0 === (b2 & 7)) {
          a: {
            h3 = "mouseover" === a || "pointerover" === a;
            k2 = "mouseout" === a || "pointerout" === a;
            if (h3 && c !== wb && (n3 = c.relatedTarget || c.fromElement) && (Wc(n3) || n3[uf])) break a;
            if (k2 || h3) {
              h3 = e4.window === e4 ? e4 : (h3 = e4.ownerDocument) ? h3.defaultView || h3.parentWindow : window;
              if (k2) {
                if (n3 = c.relatedTarget || c.toElement, k2 = d3, n3 = n3 ? Wc(n3) : null, null !== n3 && (J = Vb(n3), n3 !== J || 5 !== n3.tag && 6 !== n3.tag)) n3 = null;
              } else k2 = null, n3 = d3;
              if (k2 !== n3) {
                t2 = Bd;
                F = "onMouseLeave";
                x = "onMouseEnter";
                w2 = "mouse";
                if ("pointerout" === a || "pointerover" === a) t2 = Td, F = "onPointerLeave", x = "onPointerEnter", w2 = "pointer";
                J = null == k2 ? h3 : ue(k2);
                u2 = null == n3 ? h3 : ue(n3);
                h3 = new t2(F, w2 + "leave", k2, c, e4);
                h3.target = J;
                h3.relatedTarget = u2;
                F = null;
                Wc(e4) === d3 && (t2 = new t2(x, w2 + "enter", n3, c, e4), t2.target = u2, t2.relatedTarget = J, F = t2);
                J = F;
                if (k2 && n3) b: {
                  t2 = k2;
                  x = n3;
                  w2 = 0;
                  for (u2 = t2; u2; u2 = vf(u2)) w2++;
                  u2 = 0;
                  for (F = x; F; F = vf(F)) u2++;
                  for (; 0 < w2 - u2; ) t2 = vf(t2), w2--;
                  for (; 0 < u2 - w2; ) x = vf(x), u2--;
                  for (; w2--; ) {
                    if (t2 === x || null !== x && t2 === x.alternate) break b;
                    t2 = vf(t2);
                    x = vf(x);
                  }
                  t2 = null;
                }
                else t2 = null;
                null !== k2 && wf(g2, h3, k2, t2, false);
                null !== n3 && null !== J && wf(g2, J, n3, t2, true);
              }
            }
          }
          a: {
            h3 = d3 ? ue(d3) : window;
            k2 = h3.nodeName && h3.nodeName.toLowerCase();
            if ("select" === k2 || "input" === k2 && "file" === h3.type) var na = ve;
            else if (me(h3)) if (we) na = Fe;
            else {
              na = De;
              var xa = Ce;
            }
            else (k2 = h3.nodeName) && "input" === k2.toLowerCase() && ("checkbox" === h3.type || "radio" === h3.type) && (na = Ee);
            if (na && (na = na(a, d3))) {
              ne(g2, na, c, e4);
              break a;
            }
            xa && xa(a, h3, d3);
            "focusout" === a && (xa = h3._wrapperState) && xa.controlled && "number" === h3.type && cb(h3, "number", h3.value);
          }
          xa = d3 ? ue(d3) : window;
          switch (a) {
            case "focusin":
              if (me(xa) || "true" === xa.contentEditable) Qe = xa, Re = d3, Se = null;
              break;
            case "focusout":
              Se = Re = Qe = null;
              break;
            case "mousedown":
              Te = true;
              break;
            case "contextmenu":
            case "mouseup":
            case "dragend":
              Te = false;
              Ue(g2, c, e4);
              break;
            case "selectionchange":
              if (Pe) break;
            case "keydown":
            case "keyup":
              Ue(g2, c, e4);
          }
          var $a;
          if (ae) b: {
            switch (a) {
              case "compositionstart":
                var ba = "onCompositionStart";
                break b;
              case "compositionend":
                ba = "onCompositionEnd";
                break b;
              case "compositionupdate":
                ba = "onCompositionUpdate";
                break b;
            }
            ba = void 0;
          }
          else ie ? ge(a, c) && (ba = "onCompositionEnd") : "keydown" === a && 229 === c.keyCode && (ba = "onCompositionStart");
          ba && (de && "ko" !== c.locale && (ie || "onCompositionStart" !== ba ? "onCompositionEnd" === ba && ie && ($a = nd()) : (kd = e4, ld = "value" in kd ? kd.value : kd.textContent, ie = true)), xa = oe(d3, ba), 0 < xa.length && (ba = new Ld(ba, a, null, c, e4), g2.push({ event: ba, listeners: xa }), $a ? ba.data = $a : ($a = he(c), null !== $a && (ba.data = $a))));
          if ($a = ce ? je(a, c) : ke(a, c)) d3 = oe(d3, "onBeforeInput"), 0 < d3.length && (e4 = new Ld("onBeforeInput", "beforeinput", null, c, e4), g2.push({ event: e4, listeners: d3 }), e4.data = $a);
        }
        se(g2, b2);
      });
    }
    function tf(a, b2, c) {
      return { instance: a, listener: b2, currentTarget: c };
    }
    function oe(a, b2) {
      for (var c = b2 + "Capture", d2 = []; null !== a; ) {
        var e3 = a, f = e3.stateNode;
        5 === e3.tag && null !== f && (e3 = f, f = Kb(a, c), null != f && d2.unshift(tf(a, f, e3)), f = Kb(a, b2), null != f && d2.push(tf(a, f, e3)));
        a = a.return;
      }
      return d2;
    }
    function vf(a) {
      if (null === a) return null;
      do
        a = a.return;
      while (a && 5 !== a.tag);
      return a ? a : null;
    }
    function wf(a, b2, c, d2, e3) {
      for (var f = b2._reactName, g = []; null !== c && c !== d2; ) {
        var h2 = c, k = h2.alternate, l2 = h2.stateNode;
        if (null !== k && k === d2) break;
        5 === h2.tag && null !== l2 && (h2 = l2, e3 ? (k = Kb(c, f), null != k && g.unshift(tf(c, k, h2))) : e3 || (k = Kb(c, f), null != k && g.push(tf(c, k, h2))));
        c = c.return;
      }
      0 !== g.length && a.push({ event: b2, listeners: g });
    }
    var xf = /\r\n?/g;
    var yf = /\u0000|\uFFFD/g;
    function zf(a) {
      return ("string" === typeof a ? a : "" + a).replace(xf, "\n").replace(yf, "");
    }
    function Af(a, b2, c) {
      b2 = zf(b2);
      if (zf(a) !== b2 && c) throw Error(p2(425));
    }
    function Bf() {
    }
    var Cf = null;
    var Df = null;
    function Ef(a, b2) {
      return "textarea" === a || "noscript" === a || "string" === typeof b2.children || "number" === typeof b2.children || "object" === typeof b2.dangerouslySetInnerHTML && null !== b2.dangerouslySetInnerHTML && null != b2.dangerouslySetInnerHTML.__html;
    }
    var Ff = "function" === typeof setTimeout ? setTimeout : void 0;
    var Gf = "function" === typeof clearTimeout ? clearTimeout : void 0;
    var Hf = "function" === typeof Promise ? Promise : void 0;
    var Jf = "function" === typeof queueMicrotask ? queueMicrotask : "undefined" !== typeof Hf ? function(a) {
      return Hf.resolve(null).then(a).catch(If);
    } : Ff;
    function If(a) {
      setTimeout(function() {
        throw a;
      });
    }
    function Kf(a, b2) {
      var c = b2, d2 = 0;
      do {
        var e3 = c.nextSibling;
        a.removeChild(c);
        if (e3 && 8 === e3.nodeType) if (c = e3.data, "/$" === c) {
          if (0 === d2) {
            a.removeChild(e3);
            bd(b2);
            return;
          }
          d2--;
        } else "$" !== c && "$?" !== c && "$!" !== c || d2++;
        c = e3;
      } while (c);
      bd(b2);
    }
    function Lf(a) {
      for (; null != a; a = a.nextSibling) {
        var b2 = a.nodeType;
        if (1 === b2 || 3 === b2) break;
        if (8 === b2) {
          b2 = a.data;
          if ("$" === b2 || "$!" === b2 || "$?" === b2) break;
          if ("/$" === b2) return null;
        }
      }
      return a;
    }
    function Mf(a) {
      a = a.previousSibling;
      for (var b2 = 0; a; ) {
        if (8 === a.nodeType) {
          var c = a.data;
          if ("$" === c || "$!" === c || "$?" === c) {
            if (0 === b2) return a;
            b2--;
          } else "/$" === c && b2++;
        }
        a = a.previousSibling;
      }
      return null;
    }
    var Nf = Math.random().toString(36).slice(2);
    var Of = "__reactFiber$" + Nf;
    var Pf = "__reactProps$" + Nf;
    var uf = "__reactContainer$" + Nf;
    var of = "__reactEvents$" + Nf;
    var Qf = "__reactListeners$" + Nf;
    var Rf = "__reactHandles$" + Nf;
    function Wc(a) {
      var b2 = a[Of];
      if (b2) return b2;
      for (var c = a.parentNode; c; ) {
        if (b2 = c[uf] || c[Of]) {
          c = b2.alternate;
          if (null !== b2.child || null !== c && null !== c.child) for (a = Mf(a); null !== a; ) {
            if (c = a[Of]) return c;
            a = Mf(a);
          }
          return b2;
        }
        a = c;
        c = a.parentNode;
      }
      return null;
    }
    function Cb(a) {
      a = a[Of] || a[uf];
      return !a || 5 !== a.tag && 6 !== a.tag && 13 !== a.tag && 3 !== a.tag ? null : a;
    }
    function ue(a) {
      if (5 === a.tag || 6 === a.tag) return a.stateNode;
      throw Error(p2(33));
    }
    function Db(a) {
      return a[Pf] || null;
    }
    var Sf = [];
    var Tf = -1;
    function Uf(a) {
      return { current: a };
    }
    function E(a) {
      0 > Tf || (a.current = Sf[Tf], Sf[Tf] = null, Tf--);
    }
    function G3(a, b2) {
      Tf++;
      Sf[Tf] = a.current;
      a.current = b2;
    }
    var Vf = {};
    var H = Uf(Vf);
    var Wf = Uf(false);
    var Xf = Vf;
    function Yf(a, b2) {
      var c = a.type.contextTypes;
      if (!c) return Vf;
      var d2 = a.stateNode;
      if (d2 && d2.__reactInternalMemoizedUnmaskedChildContext === b2) return d2.__reactInternalMemoizedMaskedChildContext;
      var e3 = {}, f;
      for (f in c) e3[f] = b2[f];
      d2 && (a = a.stateNode, a.__reactInternalMemoizedUnmaskedChildContext = b2, a.__reactInternalMemoizedMaskedChildContext = e3);
      return e3;
    }
    function Zf(a) {
      a = a.childContextTypes;
      return null !== a && void 0 !== a;
    }
    function $f() {
      E(Wf);
      E(H);
    }
    function ag(a, b2, c) {
      if (H.current !== Vf) throw Error(p2(168));
      G3(H, b2);
      G3(Wf, c);
    }
    function bg(a, b2, c) {
      var d2 = a.stateNode;
      b2 = b2.childContextTypes;
      if ("function" !== typeof d2.getChildContext) return c;
      d2 = d2.getChildContext();
      for (var e3 in d2) if (!(e3 in b2)) throw Error(p2(108, Ra(a) || "Unknown", e3));
      return A({}, c, d2);
    }
    function cg(a) {
      a = (a = a.stateNode) && a.__reactInternalMemoizedMergedChildContext || Vf;
      Xf = H.current;
      G3(H, a);
      G3(Wf, Wf.current);
      return true;
    }
    function dg(a, b2, c) {
      var d2 = a.stateNode;
      if (!d2) throw Error(p2(169));
      c ? (a = bg(a, b2, Xf), d2.__reactInternalMemoizedMergedChildContext = a, E(Wf), E(H), G3(H, a)) : E(Wf);
      G3(Wf, c);
    }
    var eg = null;
    var fg = false;
    var gg = false;
    function hg(a) {
      null === eg ? eg = [a] : eg.push(a);
    }
    function ig(a) {
      fg = true;
      hg(a);
    }
    function jg() {
      if (!gg && null !== eg) {
        gg = true;
        var a = 0, b2 = C;
        try {
          var c = eg;
          for (C = 1; a < c.length; a++) {
            var d2 = c[a];
            do
              d2 = d2(true);
            while (null !== d2);
          }
          eg = null;
          fg = false;
        } catch (e3) {
          throw null !== eg && (eg = eg.slice(a + 1)), ac(fc, jg), e3;
        } finally {
          C = b2, gg = false;
        }
      }
      return null;
    }
    var kg = [];
    var lg = 0;
    var mg = null;
    var ng = 0;
    var og = [];
    var pg = 0;
    var qg = null;
    var rg = 1;
    var sg = "";
    function tg(a, b2) {
      kg[lg++] = ng;
      kg[lg++] = mg;
      mg = a;
      ng = b2;
    }
    function ug(a, b2, c) {
      og[pg++] = rg;
      og[pg++] = sg;
      og[pg++] = qg;
      qg = a;
      var d2 = rg;
      a = sg;
      var e3 = 32 - oc(d2) - 1;
      d2 &= ~(1 << e3);
      c += 1;
      var f = 32 - oc(b2) + e3;
      if (30 < f) {
        var g = e3 - e3 % 5;
        f = (d2 & (1 << g) - 1).toString(32);
        d2 >>= g;
        e3 -= g;
        rg = 1 << 32 - oc(b2) + e3 | c << e3 | d2;
        sg = f + a;
      } else rg = 1 << f | c << e3 | d2, sg = a;
    }
    function vg(a) {
      null !== a.return && (tg(a, 1), ug(a, 1, 0));
    }
    function wg(a) {
      for (; a === mg; ) mg = kg[--lg], kg[lg] = null, ng = kg[--lg], kg[lg] = null;
      for (; a === qg; ) qg = og[--pg], og[pg] = null, sg = og[--pg], og[pg] = null, rg = og[--pg], og[pg] = null;
    }
    var xg = null;
    var yg = null;
    var I2 = false;
    var zg = null;
    function Ag(a, b2) {
      var c = Bg(5, null, null, 0);
      c.elementType = "DELETED";
      c.stateNode = b2;
      c.return = a;
      b2 = a.deletions;
      null === b2 ? (a.deletions = [c], a.flags |= 16) : b2.push(c);
    }
    function Cg(a, b2) {
      switch (a.tag) {
        case 5:
          var c = a.type;
          b2 = 1 !== b2.nodeType || c.toLowerCase() !== b2.nodeName.toLowerCase() ? null : b2;
          return null !== b2 ? (a.stateNode = b2, xg = a, yg = Lf(b2.firstChild), true) : false;
        case 6:
          return b2 = "" === a.pendingProps || 3 !== b2.nodeType ? null : b2, null !== b2 ? (a.stateNode = b2, xg = a, yg = null, true) : false;
        case 13:
          return b2 = 8 !== b2.nodeType ? null : b2, null !== b2 ? (c = null !== qg ? { id: rg, overflow: sg } : null, a.memoizedState = { dehydrated: b2, treeContext: c, retryLane: 1073741824 }, c = Bg(18, null, null, 0), c.stateNode = b2, c.return = a, a.child = c, xg = a, yg = null, true) : false;
        default:
          return false;
      }
    }
    function Dg(a) {
      return 0 !== (a.mode & 1) && 0 === (a.flags & 128);
    }
    function Eg(a) {
      if (I2) {
        var b2 = yg;
        if (b2) {
          var c = b2;
          if (!Cg(a, b2)) {
            if (Dg(a)) throw Error(p2(418));
            b2 = Lf(c.nextSibling);
            var d2 = xg;
            b2 && Cg(a, b2) ? Ag(d2, c) : (a.flags = a.flags & -4097 | 2, I2 = false, xg = a);
          }
        } else {
          if (Dg(a)) throw Error(p2(418));
          a.flags = a.flags & -4097 | 2;
          I2 = false;
          xg = a;
        }
      }
    }
    function Fg(a) {
      for (a = a.return; null !== a && 5 !== a.tag && 3 !== a.tag && 13 !== a.tag; ) a = a.return;
      xg = a;
    }
    function Gg(a) {
      if (a !== xg) return false;
      if (!I2) return Fg(a), I2 = true, false;
      var b2;
      (b2 = 3 !== a.tag) && !(b2 = 5 !== a.tag) && (b2 = a.type, b2 = "head" !== b2 && "body" !== b2 && !Ef(a.type, a.memoizedProps));
      if (b2 && (b2 = yg)) {
        if (Dg(a)) throw Hg(), Error(p2(418));
        for (; b2; ) Ag(a, b2), b2 = Lf(b2.nextSibling);
      }
      Fg(a);
      if (13 === a.tag) {
        a = a.memoizedState;
        a = null !== a ? a.dehydrated : null;
        if (!a) throw Error(p2(317));
        a: {
          a = a.nextSibling;
          for (b2 = 0; a; ) {
            if (8 === a.nodeType) {
              var c = a.data;
              if ("/$" === c) {
                if (0 === b2) {
                  yg = Lf(a.nextSibling);
                  break a;
                }
                b2--;
              } else "$" !== c && "$!" !== c && "$?" !== c || b2++;
            }
            a = a.nextSibling;
          }
          yg = null;
        }
      } else yg = xg ? Lf(a.stateNode.nextSibling) : null;
      return true;
    }
    function Hg() {
      for (var a = yg; a; ) a = Lf(a.nextSibling);
    }
    function Ig() {
      yg = xg = null;
      I2 = false;
    }
    function Jg(a) {
      null === zg ? zg = [a] : zg.push(a);
    }
    var Kg = ua.ReactCurrentBatchConfig;
    function Lg(a, b2, c) {
      a = c.ref;
      if (null !== a && "function" !== typeof a && "object" !== typeof a) {
        if (c._owner) {
          c = c._owner;
          if (c) {
            if (1 !== c.tag) throw Error(p2(309));
            var d2 = c.stateNode;
          }
          if (!d2) throw Error(p2(147, a));
          var e3 = d2, f = "" + a;
          if (null !== b2 && null !== b2.ref && "function" === typeof b2.ref && b2.ref._stringRef === f) return b2.ref;
          b2 = function(a2) {
            var b3 = e3.refs;
            null === a2 ? delete b3[f] : b3[f] = a2;
          };
          b2._stringRef = f;
          return b2;
        }
        if ("string" !== typeof a) throw Error(p2(284));
        if (!c._owner) throw Error(p2(290, a));
      }
      return a;
    }
    function Mg(a, b2) {
      a = Object.prototype.toString.call(b2);
      throw Error(p2(31, "[object Object]" === a ? "object with keys {" + Object.keys(b2).join(", ") + "}" : a));
    }
    function Ng(a) {
      var b2 = a._init;
      return b2(a._payload);
    }
    function Og(a) {
      function b2(b3, c2) {
        if (a) {
          var d3 = b3.deletions;
          null === d3 ? (b3.deletions = [c2], b3.flags |= 16) : d3.push(c2);
        }
      }
      function c(c2, d3) {
        if (!a) return null;
        for (; null !== d3; ) b2(c2, d3), d3 = d3.sibling;
        return null;
      }
      function d2(a2, b3) {
        for (a2 = /* @__PURE__ */ new Map(); null !== b3; ) null !== b3.key ? a2.set(b3.key, b3) : a2.set(b3.index, b3), b3 = b3.sibling;
        return a2;
      }
      function e3(a2, b3) {
        a2 = Pg(a2, b3);
        a2.index = 0;
        a2.sibling = null;
        return a2;
      }
      function f(b3, c2, d3) {
        b3.index = d3;
        if (!a) return b3.flags |= 1048576, c2;
        d3 = b3.alternate;
        if (null !== d3) return d3 = d3.index, d3 < c2 ? (b3.flags |= 2, c2) : d3;
        b3.flags |= 2;
        return c2;
      }
      function g(b3) {
        a && null === b3.alternate && (b3.flags |= 2);
        return b3;
      }
      function h2(a2, b3, c2, d3) {
        if (null === b3 || 6 !== b3.tag) return b3 = Qg(c2, a2.mode, d3), b3.return = a2, b3;
        b3 = e3(b3, c2);
        b3.return = a2;
        return b3;
      }
      function k(a2, b3, c2, d3) {
        var f2 = c2.type;
        if (f2 === ya) return m2(a2, b3, c2.props.children, d3, c2.key);
        if (null !== b3 && (b3.elementType === f2 || "object" === typeof f2 && null !== f2 && f2.$$typeof === Ha && Ng(f2) === b3.type)) return d3 = e3(b3, c2.props), d3.ref = Lg(a2, b3, c2), d3.return = a2, d3;
        d3 = Rg(c2.type, c2.key, c2.props, null, a2.mode, d3);
        d3.ref = Lg(a2, b3, c2);
        d3.return = a2;
        return d3;
      }
      function l2(a2, b3, c2, d3) {
        if (null === b3 || 4 !== b3.tag || b3.stateNode.containerInfo !== c2.containerInfo || b3.stateNode.implementation !== c2.implementation) return b3 = Sg(c2, a2.mode, d3), b3.return = a2, b3;
        b3 = e3(b3, c2.children || []);
        b3.return = a2;
        return b3;
      }
      function m2(a2, b3, c2, d3, f2) {
        if (null === b3 || 7 !== b3.tag) return b3 = Tg(c2, a2.mode, d3, f2), b3.return = a2, b3;
        b3 = e3(b3, c2);
        b3.return = a2;
        return b3;
      }
      function q(a2, b3, c2) {
        if ("string" === typeof b3 && "" !== b3 || "number" === typeof b3) return b3 = Qg("" + b3, a2.mode, c2), b3.return = a2, b3;
        if ("object" === typeof b3 && null !== b3) {
          switch (b3.$$typeof) {
            case va:
              return c2 = Rg(b3.type, b3.key, b3.props, null, a2.mode, c2), c2.ref = Lg(a2, null, b3), c2.return = a2, c2;
            case wa:
              return b3 = Sg(b3, a2.mode, c2), b3.return = a2, b3;
            case Ha:
              var d3 = b3._init;
              return q(a2, d3(b3._payload), c2);
          }
          if (eb(b3) || Ka(b3)) return b3 = Tg(b3, a2.mode, c2, null), b3.return = a2, b3;
          Mg(a2, b3);
        }
        return null;
      }
      function r3(a2, b3, c2, d3) {
        var e4 = null !== b3 ? b3.key : null;
        if ("string" === typeof c2 && "" !== c2 || "number" === typeof c2) return null !== e4 ? null : h2(a2, b3, "" + c2, d3);
        if ("object" === typeof c2 && null !== c2) {
          switch (c2.$$typeof) {
            case va:
              return c2.key === e4 ? k(a2, b3, c2, d3) : null;
            case wa:
              return c2.key === e4 ? l2(a2, b3, c2, d3) : null;
            case Ha:
              return e4 = c2._init, r3(
                a2,
                b3,
                e4(c2._payload),
                d3
              );
          }
          if (eb(c2) || Ka(c2)) return null !== e4 ? null : m2(a2, b3, c2, d3, null);
          Mg(a2, c2);
        }
        return null;
      }
      function y2(a2, b3, c2, d3, e4) {
        if ("string" === typeof d3 && "" !== d3 || "number" === typeof d3) return a2 = a2.get(c2) || null, h2(b3, a2, "" + d3, e4);
        if ("object" === typeof d3 && null !== d3) {
          switch (d3.$$typeof) {
            case va:
              return a2 = a2.get(null === d3.key ? c2 : d3.key) || null, k(b3, a2, d3, e4);
            case wa:
              return a2 = a2.get(null === d3.key ? c2 : d3.key) || null, l2(b3, a2, d3, e4);
            case Ha:
              var f2 = d3._init;
              return y2(a2, b3, c2, f2(d3._payload), e4);
          }
          if (eb(d3) || Ka(d3)) return a2 = a2.get(c2) || null, m2(b3, a2, d3, e4, null);
          Mg(b3, d3);
        }
        return null;
      }
      function n3(e4, g2, h3, k2) {
        for (var l3 = null, m3 = null, u2 = g2, w2 = g2 = 0, x = null; null !== u2 && w2 < h3.length; w2++) {
          u2.index > w2 ? (x = u2, u2 = null) : x = u2.sibling;
          var n4 = r3(e4, u2, h3[w2], k2);
          if (null === n4) {
            null === u2 && (u2 = x);
            break;
          }
          a && u2 && null === n4.alternate && b2(e4, u2);
          g2 = f(n4, g2, w2);
          null === m3 ? l3 = n4 : m3.sibling = n4;
          m3 = n4;
          u2 = x;
        }
        if (w2 === h3.length) return c(e4, u2), I2 && tg(e4, w2), l3;
        if (null === u2) {
          for (; w2 < h3.length; w2++) u2 = q(e4, h3[w2], k2), null !== u2 && (g2 = f(u2, g2, w2), null === m3 ? l3 = u2 : m3.sibling = u2, m3 = u2);
          I2 && tg(e4, w2);
          return l3;
        }
        for (u2 = d2(e4, u2); w2 < h3.length; w2++) x = y2(u2, e4, w2, h3[w2], k2), null !== x && (a && null !== x.alternate && u2.delete(null === x.key ? w2 : x.key), g2 = f(x, g2, w2), null === m3 ? l3 = x : m3.sibling = x, m3 = x);
        a && u2.forEach(function(a2) {
          return b2(e4, a2);
        });
        I2 && tg(e4, w2);
        return l3;
      }
      function t2(e4, g2, h3, k2) {
        var l3 = Ka(h3);
        if ("function" !== typeof l3) throw Error(p2(150));
        h3 = l3.call(h3);
        if (null == h3) throw Error(p2(151));
        for (var u2 = l3 = null, m3 = g2, w2 = g2 = 0, x = null, n4 = h3.next(); null !== m3 && !n4.done; w2++, n4 = h3.next()) {
          m3.index > w2 ? (x = m3, m3 = null) : x = m3.sibling;
          var t3 = r3(e4, m3, n4.value, k2);
          if (null === t3) {
            null === m3 && (m3 = x);
            break;
          }
          a && m3 && null === t3.alternate && b2(e4, m3);
          g2 = f(t3, g2, w2);
          null === u2 ? l3 = t3 : u2.sibling = t3;
          u2 = t3;
          m3 = x;
        }
        if (n4.done) return c(
          e4,
          m3
        ), I2 && tg(e4, w2), l3;
        if (null === m3) {
          for (; !n4.done; w2++, n4 = h3.next()) n4 = q(e4, n4.value, k2), null !== n4 && (g2 = f(n4, g2, w2), null === u2 ? l3 = n4 : u2.sibling = n4, u2 = n4);
          I2 && tg(e4, w2);
          return l3;
        }
        for (m3 = d2(e4, m3); !n4.done; w2++, n4 = h3.next()) n4 = y2(m3, e4, w2, n4.value, k2), null !== n4 && (a && null !== n4.alternate && m3.delete(null === n4.key ? w2 : n4.key), g2 = f(n4, g2, w2), null === u2 ? l3 = n4 : u2.sibling = n4, u2 = n4);
        a && m3.forEach(function(a2) {
          return b2(e4, a2);
        });
        I2 && tg(e4, w2);
        return l3;
      }
      function J(a2, d3, f2, h3) {
        "object" === typeof f2 && null !== f2 && f2.type === ya && null === f2.key && (f2 = f2.props.children);
        if ("object" === typeof f2 && null !== f2) {
          switch (f2.$$typeof) {
            case va:
              a: {
                for (var k2 = f2.key, l3 = d3; null !== l3; ) {
                  if (l3.key === k2) {
                    k2 = f2.type;
                    if (k2 === ya) {
                      if (7 === l3.tag) {
                        c(a2, l3.sibling);
                        d3 = e3(l3, f2.props.children);
                        d3.return = a2;
                        a2 = d3;
                        break a;
                      }
                    } else if (l3.elementType === k2 || "object" === typeof k2 && null !== k2 && k2.$$typeof === Ha && Ng(k2) === l3.type) {
                      c(a2, l3.sibling);
                      d3 = e3(l3, f2.props);
                      d3.ref = Lg(a2, l3, f2);
                      d3.return = a2;
                      a2 = d3;
                      break a;
                    }
                    c(a2, l3);
                    break;
                  } else b2(a2, l3);
                  l3 = l3.sibling;
                }
                f2.type === ya ? (d3 = Tg(f2.props.children, a2.mode, h3, f2.key), d3.return = a2, a2 = d3) : (h3 = Rg(f2.type, f2.key, f2.props, null, a2.mode, h3), h3.ref = Lg(a2, d3, f2), h3.return = a2, a2 = h3);
              }
              return g(a2);
            case wa:
              a: {
                for (l3 = f2.key; null !== d3; ) {
                  if (d3.key === l3) if (4 === d3.tag && d3.stateNode.containerInfo === f2.containerInfo && d3.stateNode.implementation === f2.implementation) {
                    c(a2, d3.sibling);
                    d3 = e3(d3, f2.children || []);
                    d3.return = a2;
                    a2 = d3;
                    break a;
                  } else {
                    c(a2, d3);
                    break;
                  }
                  else b2(a2, d3);
                  d3 = d3.sibling;
                }
                d3 = Sg(f2, a2.mode, h3);
                d3.return = a2;
                a2 = d3;
              }
              return g(a2);
            case Ha:
              return l3 = f2._init, J(a2, d3, l3(f2._payload), h3);
          }
          if (eb(f2)) return n3(a2, d3, f2, h3);
          if (Ka(f2)) return t2(a2, d3, f2, h3);
          Mg(a2, f2);
        }
        return "string" === typeof f2 && "" !== f2 || "number" === typeof f2 ? (f2 = "" + f2, null !== d3 && 6 === d3.tag ? (c(a2, d3.sibling), d3 = e3(d3, f2), d3.return = a2, a2 = d3) : (c(a2, d3), d3 = Qg(f2, a2.mode, h3), d3.return = a2, a2 = d3), g(a2)) : c(a2, d3);
      }
      return J;
    }
    var Ug = Og(true);
    var Vg = Og(false);
    var Wg = Uf(null);
    var Xg = null;
    var Yg = null;
    var Zg = null;
    function $g() {
      Zg = Yg = Xg = null;
    }
    function ah(a) {
      var b2 = Wg.current;
      E(Wg);
      a._currentValue = b2;
    }
    function bh(a, b2, c) {
      for (; null !== a; ) {
        var d2 = a.alternate;
        (a.childLanes & b2) !== b2 ? (a.childLanes |= b2, null !== d2 && (d2.childLanes |= b2)) : null !== d2 && (d2.childLanes & b2) !== b2 && (d2.childLanes |= b2);
        if (a === c) break;
        a = a.return;
      }
    }
    function ch(a, b2) {
      Xg = a;
      Zg = Yg = null;
      a = a.dependencies;
      null !== a && null !== a.firstContext && (0 !== (a.lanes & b2) && (dh = true), a.firstContext = null);
    }
    function eh(a) {
      var b2 = a._currentValue;
      if (Zg !== a) if (a = { context: a, memoizedValue: b2, next: null }, null === Yg) {
        if (null === Xg) throw Error(p2(308));
        Yg = a;
        Xg.dependencies = { lanes: 0, firstContext: a };
      } else Yg = Yg.next = a;
      return b2;
    }
    var fh = null;
    function gh(a) {
      null === fh ? fh = [a] : fh.push(a);
    }
    function hh(a, b2, c, d2) {
      var e3 = b2.interleaved;
      null === e3 ? (c.next = c, gh(b2)) : (c.next = e3.next, e3.next = c);
      b2.interleaved = c;
      return ih(a, d2);
    }
    function ih(a, b2) {
      a.lanes |= b2;
      var c = a.alternate;
      null !== c && (c.lanes |= b2);
      c = a;
      for (a = a.return; null !== a; ) a.childLanes |= b2, c = a.alternate, null !== c && (c.childLanes |= b2), c = a, a = a.return;
      return 3 === c.tag ? c.stateNode : null;
    }
    var jh = false;
    function kh(a) {
      a.updateQueue = { baseState: a.memoizedState, firstBaseUpdate: null, lastBaseUpdate: null, shared: { pending: null, interleaved: null, lanes: 0 }, effects: null };
    }
    function lh(a, b2) {
      a = a.updateQueue;
      b2.updateQueue === a && (b2.updateQueue = { baseState: a.baseState, firstBaseUpdate: a.firstBaseUpdate, lastBaseUpdate: a.lastBaseUpdate, shared: a.shared, effects: a.effects });
    }
    function mh(a, b2) {
      return { eventTime: a, lane: b2, tag: 0, payload: null, callback: null, next: null };
    }
    function nh(a, b2, c) {
      var d2 = a.updateQueue;
      if (null === d2) return null;
      d2 = d2.shared;
      if (0 !== (K & 2)) {
        var e3 = d2.pending;
        null === e3 ? b2.next = b2 : (b2.next = e3.next, e3.next = b2);
        d2.pending = b2;
        return ih(a, c);
      }
      e3 = d2.interleaved;
      null === e3 ? (b2.next = b2, gh(d2)) : (b2.next = e3.next, e3.next = b2);
      d2.interleaved = b2;
      return ih(a, c);
    }
    function oh(a, b2, c) {
      b2 = b2.updateQueue;
      if (null !== b2 && (b2 = b2.shared, 0 !== (c & 4194240))) {
        var d2 = b2.lanes;
        d2 &= a.pendingLanes;
        c |= d2;
        b2.lanes = c;
        Cc(a, c);
      }
    }
    function ph(a, b2) {
      var c = a.updateQueue, d2 = a.alternate;
      if (null !== d2 && (d2 = d2.updateQueue, c === d2)) {
        var e3 = null, f = null;
        c = c.firstBaseUpdate;
        if (null !== c) {
          do {
            var g = { eventTime: c.eventTime, lane: c.lane, tag: c.tag, payload: c.payload, callback: c.callback, next: null };
            null === f ? e3 = f = g : f = f.next = g;
            c = c.next;
          } while (null !== c);
          null === f ? e3 = f = b2 : f = f.next = b2;
        } else e3 = f = b2;
        c = { baseState: d2.baseState, firstBaseUpdate: e3, lastBaseUpdate: f, shared: d2.shared, effects: d2.effects };
        a.updateQueue = c;
        return;
      }
      a = c.lastBaseUpdate;
      null === a ? c.firstBaseUpdate = b2 : a.next = b2;
      c.lastBaseUpdate = b2;
    }
    function qh(a, b2, c, d2) {
      var e3 = a.updateQueue;
      jh = false;
      var f = e3.firstBaseUpdate, g = e3.lastBaseUpdate, h2 = e3.shared.pending;
      if (null !== h2) {
        e3.shared.pending = null;
        var k = h2, l2 = k.next;
        k.next = null;
        null === g ? f = l2 : g.next = l2;
        g = k;
        var m2 = a.alternate;
        null !== m2 && (m2 = m2.updateQueue, h2 = m2.lastBaseUpdate, h2 !== g && (null === h2 ? m2.firstBaseUpdate = l2 : h2.next = l2, m2.lastBaseUpdate = k));
      }
      if (null !== f) {
        var q = e3.baseState;
        g = 0;
        m2 = l2 = k = null;
        h2 = f;
        do {
          var r3 = h2.lane, y2 = h2.eventTime;
          if ((d2 & r3) === r3) {
            null !== m2 && (m2 = m2.next = {
              eventTime: y2,
              lane: 0,
              tag: h2.tag,
              payload: h2.payload,
              callback: h2.callback,
              next: null
            });
            a: {
              var n3 = a, t2 = h2;
              r3 = b2;
              y2 = c;
              switch (t2.tag) {
                case 1:
                  n3 = t2.payload;
                  if ("function" === typeof n3) {
                    q = n3.call(y2, q, r3);
                    break a;
                  }
                  q = n3;
                  break a;
                case 3:
                  n3.flags = n3.flags & -65537 | 128;
                case 0:
                  n3 = t2.payload;
                  r3 = "function" === typeof n3 ? n3.call(y2, q, r3) : n3;
                  if (null === r3 || void 0 === r3) break a;
                  q = A({}, q, r3);
                  break a;
                case 2:
                  jh = true;
              }
            }
            null !== h2.callback && 0 !== h2.lane && (a.flags |= 64, r3 = e3.effects, null === r3 ? e3.effects = [h2] : r3.push(h2));
          } else y2 = { eventTime: y2, lane: r3, tag: h2.tag, payload: h2.payload, callback: h2.callback, next: null }, null === m2 ? (l2 = m2 = y2, k = q) : m2 = m2.next = y2, g |= r3;
          h2 = h2.next;
          if (null === h2) if (h2 = e3.shared.pending, null === h2) break;
          else r3 = h2, h2 = r3.next, r3.next = null, e3.lastBaseUpdate = r3, e3.shared.pending = null;
        } while (1);
        null === m2 && (k = q);
        e3.baseState = k;
        e3.firstBaseUpdate = l2;
        e3.lastBaseUpdate = m2;
        b2 = e3.shared.interleaved;
        if (null !== b2) {
          e3 = b2;
          do
            g |= e3.lane, e3 = e3.next;
          while (e3 !== b2);
        } else null === f && (e3.shared.lanes = 0);
        rh |= g;
        a.lanes = g;
        a.memoizedState = q;
      }
    }
    function sh(a, b2, c) {
      a = b2.effects;
      b2.effects = null;
      if (null !== a) for (b2 = 0; b2 < a.length; b2++) {
        var d2 = a[b2], e3 = d2.callback;
        if (null !== e3) {
          d2.callback = null;
          d2 = c;
          if ("function" !== typeof e3) throw Error(p2(191, e3));
          e3.call(d2);
        }
      }
    }
    var th = {};
    var uh = Uf(th);
    var vh = Uf(th);
    var wh = Uf(th);
    function xh(a) {
      if (a === th) throw Error(p2(174));
      return a;
    }
    function yh(a, b2) {
      G3(wh, b2);
      G3(vh, a);
      G3(uh, th);
      a = b2.nodeType;
      switch (a) {
        case 9:
        case 11:
          b2 = (b2 = b2.documentElement) ? b2.namespaceURI : lb(null, "");
          break;
        default:
          a = 8 === a ? b2.parentNode : b2, b2 = a.namespaceURI || null, a = a.tagName, b2 = lb(b2, a);
      }
      E(uh);
      G3(uh, b2);
    }
    function zh() {
      E(uh);
      E(vh);
      E(wh);
    }
    function Ah(a) {
      xh(wh.current);
      var b2 = xh(uh.current);
      var c = lb(b2, a.type);
      b2 !== c && (G3(vh, a), G3(uh, c));
    }
    function Bh(a) {
      vh.current === a && (E(uh), E(vh));
    }
    var L = Uf(0);
    function Ch(a) {
      for (var b2 = a; null !== b2; ) {
        if (13 === b2.tag) {
          var c = b2.memoizedState;
          if (null !== c && (c = c.dehydrated, null === c || "$?" === c.data || "$!" === c.data)) return b2;
        } else if (19 === b2.tag && void 0 !== b2.memoizedProps.revealOrder) {
          if (0 !== (b2.flags & 128)) return b2;
        } else if (null !== b2.child) {
          b2.child.return = b2;
          b2 = b2.child;
          continue;
        }
        if (b2 === a) break;
        for (; null === b2.sibling; ) {
          if (null === b2.return || b2.return === a) return null;
          b2 = b2.return;
        }
        b2.sibling.return = b2.return;
        b2 = b2.sibling;
      }
      return null;
    }
    var Dh = [];
    function Eh() {
      for (var a = 0; a < Dh.length; a++) Dh[a]._workInProgressVersionPrimary = null;
      Dh.length = 0;
    }
    var Fh = ua.ReactCurrentDispatcher;
    var Gh = ua.ReactCurrentBatchConfig;
    var Hh = 0;
    var M2 = null;
    var N2 = null;
    var O = null;
    var Ih = false;
    var Jh = false;
    var Kh = 0;
    var Lh = 0;
    function P() {
      throw Error(p2(321));
    }
    function Mh(a, b2) {
      if (null === b2) return false;
      for (var c = 0; c < b2.length && c < a.length; c++) if (!He(a[c], b2[c])) return false;
      return true;
    }
    function Nh(a, b2, c, d2, e3, f) {
      Hh = f;
      M2 = b2;
      b2.memoizedState = null;
      b2.updateQueue = null;
      b2.lanes = 0;
      Fh.current = null === a || null === a.memoizedState ? Oh : Ph;
      a = c(d2, e3);
      if (Jh) {
        f = 0;
        do {
          Jh = false;
          Kh = 0;
          if (25 <= f) throw Error(p2(301));
          f += 1;
          O = N2 = null;
          b2.updateQueue = null;
          Fh.current = Qh;
          a = c(d2, e3);
        } while (Jh);
      }
      Fh.current = Rh;
      b2 = null !== N2 && null !== N2.next;
      Hh = 0;
      O = N2 = M2 = null;
      Ih = false;
      if (b2) throw Error(p2(300));
      return a;
    }
    function Sh() {
      var a = 0 !== Kh;
      Kh = 0;
      return a;
    }
    function Th() {
      var a = { memoizedState: null, baseState: null, baseQueue: null, queue: null, next: null };
      null === O ? M2.memoizedState = O = a : O = O.next = a;
      return O;
    }
    function Uh() {
      if (null === N2) {
        var a = M2.alternate;
        a = null !== a ? a.memoizedState : null;
      } else a = N2.next;
      var b2 = null === O ? M2.memoizedState : O.next;
      if (null !== b2) O = b2, N2 = a;
      else {
        if (null === a) throw Error(p2(310));
        N2 = a;
        a = { memoizedState: N2.memoizedState, baseState: N2.baseState, baseQueue: N2.baseQueue, queue: N2.queue, next: null };
        null === O ? M2.memoizedState = O = a : O = O.next = a;
      }
      return O;
    }
    function Vh(a, b2) {
      return "function" === typeof b2 ? b2(a) : b2;
    }
    function Wh(a) {
      var b2 = Uh(), c = b2.queue;
      if (null === c) throw Error(p2(311));
      c.lastRenderedReducer = a;
      var d2 = N2, e3 = d2.baseQueue, f = c.pending;
      if (null !== f) {
        if (null !== e3) {
          var g = e3.next;
          e3.next = f.next;
          f.next = g;
        }
        d2.baseQueue = e3 = f;
        c.pending = null;
      }
      if (null !== e3) {
        f = e3.next;
        d2 = d2.baseState;
        var h2 = g = null, k = null, l2 = f;
        do {
          var m2 = l2.lane;
          if ((Hh & m2) === m2) null !== k && (k = k.next = { lane: 0, action: l2.action, hasEagerState: l2.hasEagerState, eagerState: l2.eagerState, next: null }), d2 = l2.hasEagerState ? l2.eagerState : a(d2, l2.action);
          else {
            var q = {
              lane: m2,
              action: l2.action,
              hasEagerState: l2.hasEagerState,
              eagerState: l2.eagerState,
              next: null
            };
            null === k ? (h2 = k = q, g = d2) : k = k.next = q;
            M2.lanes |= m2;
            rh |= m2;
          }
          l2 = l2.next;
        } while (null !== l2 && l2 !== f);
        null === k ? g = d2 : k.next = h2;
        He(d2, b2.memoizedState) || (dh = true);
        b2.memoizedState = d2;
        b2.baseState = g;
        b2.baseQueue = k;
        c.lastRenderedState = d2;
      }
      a = c.interleaved;
      if (null !== a) {
        e3 = a;
        do
          f = e3.lane, M2.lanes |= f, rh |= f, e3 = e3.next;
        while (e3 !== a);
      } else null === e3 && (c.lanes = 0);
      return [b2.memoizedState, c.dispatch];
    }
    function Xh(a) {
      var b2 = Uh(), c = b2.queue;
      if (null === c) throw Error(p2(311));
      c.lastRenderedReducer = a;
      var d2 = c.dispatch, e3 = c.pending, f = b2.memoizedState;
      if (null !== e3) {
        c.pending = null;
        var g = e3 = e3.next;
        do
          f = a(f, g.action), g = g.next;
        while (g !== e3);
        He(f, b2.memoizedState) || (dh = true);
        b2.memoizedState = f;
        null === b2.baseQueue && (b2.baseState = f);
        c.lastRenderedState = f;
      }
      return [f, d2];
    }
    function Yh() {
    }
    function Zh(a, b2) {
      var c = M2, d2 = Uh(), e3 = b2(), f = !He(d2.memoizedState, e3);
      f && (d2.memoizedState = e3, dh = true);
      d2 = d2.queue;
      $h(ai.bind(null, c, d2, a), [a]);
      if (d2.getSnapshot !== b2 || f || null !== O && O.memoizedState.tag & 1) {
        c.flags |= 2048;
        bi(9, ci.bind(null, c, d2, e3, b2), void 0, null);
        if (null === Q) throw Error(p2(349));
        0 !== (Hh & 30) || di(c, b2, e3);
      }
      return e3;
    }
    function di(a, b2, c) {
      a.flags |= 16384;
      a = { getSnapshot: b2, value: c };
      b2 = M2.updateQueue;
      null === b2 ? (b2 = { lastEffect: null, stores: null }, M2.updateQueue = b2, b2.stores = [a]) : (c = b2.stores, null === c ? b2.stores = [a] : c.push(a));
    }
    function ci(a, b2, c, d2) {
      b2.value = c;
      b2.getSnapshot = d2;
      ei(b2) && fi(a);
    }
    function ai(a, b2, c) {
      return c(function() {
        ei(b2) && fi(a);
      });
    }
    function ei(a) {
      var b2 = a.getSnapshot;
      a = a.value;
      try {
        var c = b2();
        return !He(a, c);
      } catch (d2) {
        return true;
      }
    }
    function fi(a) {
      var b2 = ih(a, 1);
      null !== b2 && gi(b2, a, 1, -1);
    }
    function hi(a) {
      var b2 = Th();
      "function" === typeof a && (a = a());
      b2.memoizedState = b2.baseState = a;
      a = { pending: null, interleaved: null, lanes: 0, dispatch: null, lastRenderedReducer: Vh, lastRenderedState: a };
      b2.queue = a;
      a = a.dispatch = ii.bind(null, M2, a);
      return [b2.memoizedState, a];
    }
    function bi(a, b2, c, d2) {
      a = { tag: a, create: b2, destroy: c, deps: d2, next: null };
      b2 = M2.updateQueue;
      null === b2 ? (b2 = { lastEffect: null, stores: null }, M2.updateQueue = b2, b2.lastEffect = a.next = a) : (c = b2.lastEffect, null === c ? b2.lastEffect = a.next = a : (d2 = c.next, c.next = a, a.next = d2, b2.lastEffect = a));
      return a;
    }
    function ji() {
      return Uh().memoizedState;
    }
    function ki(a, b2, c, d2) {
      var e3 = Th();
      M2.flags |= a;
      e3.memoizedState = bi(1 | b2, c, void 0, void 0 === d2 ? null : d2);
    }
    function li(a, b2, c, d2) {
      var e3 = Uh();
      d2 = void 0 === d2 ? null : d2;
      var f = void 0;
      if (null !== N2) {
        var g = N2.memoizedState;
        f = g.destroy;
        if (null !== d2 && Mh(d2, g.deps)) {
          e3.memoizedState = bi(b2, c, f, d2);
          return;
        }
      }
      M2.flags |= a;
      e3.memoizedState = bi(1 | b2, c, f, d2);
    }
    function mi(a, b2) {
      return ki(8390656, 8, a, b2);
    }
    function $h(a, b2) {
      return li(2048, 8, a, b2);
    }
    function ni(a, b2) {
      return li(4, 2, a, b2);
    }
    function oi(a, b2) {
      return li(4, 4, a, b2);
    }
    function pi(a, b2) {
      if ("function" === typeof b2) return a = a(), b2(a), function() {
        b2(null);
      };
      if (null !== b2 && void 0 !== b2) return a = a(), b2.current = a, function() {
        b2.current = null;
      };
    }
    function qi(a, b2, c) {
      c = null !== c && void 0 !== c ? c.concat([a]) : null;
      return li(4, 4, pi.bind(null, b2, a), c);
    }
    function ri() {
    }
    function si(a, b2) {
      var c = Uh();
      b2 = void 0 === b2 ? null : b2;
      var d2 = c.memoizedState;
      if (null !== d2 && null !== b2 && Mh(b2, d2[1])) return d2[0];
      c.memoizedState = [a, b2];
      return a;
    }
    function ti(a, b2) {
      var c = Uh();
      b2 = void 0 === b2 ? null : b2;
      var d2 = c.memoizedState;
      if (null !== d2 && null !== b2 && Mh(b2, d2[1])) return d2[0];
      a = a();
      c.memoizedState = [a, b2];
      return a;
    }
    function ui(a, b2, c) {
      if (0 === (Hh & 21)) return a.baseState && (a.baseState = false, dh = true), a.memoizedState = c;
      He(c, b2) || (c = yc(), M2.lanes |= c, rh |= c, a.baseState = true);
      return b2;
    }
    function vi(a, b2) {
      var c = C;
      C = 0 !== c && 4 > c ? c : 4;
      a(true);
      var d2 = Gh.transition;
      Gh.transition = {};
      try {
        a(false), b2();
      } finally {
        C = c, Gh.transition = d2;
      }
    }
    function wi() {
      return Uh().memoizedState;
    }
    function xi(a, b2, c) {
      var d2 = yi(a);
      c = { lane: d2, action: c, hasEagerState: false, eagerState: null, next: null };
      if (zi(a)) Ai(b2, c);
      else if (c = hh(a, b2, c, d2), null !== c) {
        var e3 = R2();
        gi(c, a, d2, e3);
        Bi(c, b2, d2);
      }
    }
    function ii(a, b2, c) {
      var d2 = yi(a), e3 = { lane: d2, action: c, hasEagerState: false, eagerState: null, next: null };
      if (zi(a)) Ai(b2, e3);
      else {
        var f = a.alternate;
        if (0 === a.lanes && (null === f || 0 === f.lanes) && (f = b2.lastRenderedReducer, null !== f)) try {
          var g = b2.lastRenderedState, h2 = f(g, c);
          e3.hasEagerState = true;
          e3.eagerState = h2;
          if (He(h2, g)) {
            var k = b2.interleaved;
            null === k ? (e3.next = e3, gh(b2)) : (e3.next = k.next, k.next = e3);
            b2.interleaved = e3;
            return;
          }
        } catch (l2) {
        } finally {
        }
        c = hh(a, b2, e3, d2);
        null !== c && (e3 = R2(), gi(c, a, d2, e3), Bi(c, b2, d2));
      }
    }
    function zi(a) {
      var b2 = a.alternate;
      return a === M2 || null !== b2 && b2 === M2;
    }
    function Ai(a, b2) {
      Jh = Ih = true;
      var c = a.pending;
      null === c ? b2.next = b2 : (b2.next = c.next, c.next = b2);
      a.pending = b2;
    }
    function Bi(a, b2, c) {
      if (0 !== (c & 4194240)) {
        var d2 = b2.lanes;
        d2 &= a.pendingLanes;
        c |= d2;
        b2.lanes = c;
        Cc(a, c);
      }
    }
    var Rh = { readContext: eh, useCallback: P, useContext: P, useEffect: P, useImperativeHandle: P, useInsertionEffect: P, useLayoutEffect: P, useMemo: P, useReducer: P, useRef: P, useState: P, useDebugValue: P, useDeferredValue: P, useTransition: P, useMutableSource: P, useSyncExternalStore: P, useId: P, unstable_isNewReconciler: false };
    var Oh = { readContext: eh, useCallback: function(a, b2) {
      Th().memoizedState = [a, void 0 === b2 ? null : b2];
      return a;
    }, useContext: eh, useEffect: mi, useImperativeHandle: function(a, b2, c) {
      c = null !== c && void 0 !== c ? c.concat([a]) : null;
      return ki(
        4194308,
        4,
        pi.bind(null, b2, a),
        c
      );
    }, useLayoutEffect: function(a, b2) {
      return ki(4194308, 4, a, b2);
    }, useInsertionEffect: function(a, b2) {
      return ki(4, 2, a, b2);
    }, useMemo: function(a, b2) {
      var c = Th();
      b2 = void 0 === b2 ? null : b2;
      a = a();
      c.memoizedState = [a, b2];
      return a;
    }, useReducer: function(a, b2, c) {
      var d2 = Th();
      b2 = void 0 !== c ? c(b2) : b2;
      d2.memoizedState = d2.baseState = b2;
      a = { pending: null, interleaved: null, lanes: 0, dispatch: null, lastRenderedReducer: a, lastRenderedState: b2 };
      d2.queue = a;
      a = a.dispatch = xi.bind(null, M2, a);
      return [d2.memoizedState, a];
    }, useRef: function(a) {
      var b2 = Th();
      a = { current: a };
      return b2.memoizedState = a;
    }, useState: hi, useDebugValue: ri, useDeferredValue: function(a) {
      return Th().memoizedState = a;
    }, useTransition: function() {
      var a = hi(false), b2 = a[0];
      a = vi.bind(null, a[1]);
      Th().memoizedState = a;
      return [b2, a];
    }, useMutableSource: function() {
    }, useSyncExternalStore: function(a, b2, c) {
      var d2 = M2, e3 = Th();
      if (I2) {
        if (void 0 === c) throw Error(p2(407));
        c = c();
      } else {
        c = b2();
        if (null === Q) throw Error(p2(349));
        0 !== (Hh & 30) || di(d2, b2, c);
      }
      e3.memoizedState = c;
      var f = { value: c, getSnapshot: b2 };
      e3.queue = f;
      mi(ai.bind(
        null,
        d2,
        f,
        a
      ), [a]);
      d2.flags |= 2048;
      bi(9, ci.bind(null, d2, f, c, b2), void 0, null);
      return c;
    }, useId: function() {
      var a = Th(), b2 = Q.identifierPrefix;
      if (I2) {
        var c = sg;
        var d2 = rg;
        c = (d2 & ~(1 << 32 - oc(d2) - 1)).toString(32) + c;
        b2 = ":" + b2 + "R" + c;
        c = Kh++;
        0 < c && (b2 += "H" + c.toString(32));
        b2 += ":";
      } else c = Lh++, b2 = ":" + b2 + "r" + c.toString(32) + ":";
      return a.memoizedState = b2;
    }, unstable_isNewReconciler: false };
    var Ph = {
      readContext: eh,
      useCallback: si,
      useContext: eh,
      useEffect: $h,
      useImperativeHandle: qi,
      useInsertionEffect: ni,
      useLayoutEffect: oi,
      useMemo: ti,
      useReducer: Wh,
      useRef: ji,
      useState: function() {
        return Wh(Vh);
      },
      useDebugValue: ri,
      useDeferredValue: function(a) {
        var b2 = Uh();
        return ui(b2, N2.memoizedState, a);
      },
      useTransition: function() {
        var a = Wh(Vh)[0], b2 = Uh().memoizedState;
        return [a, b2];
      },
      useMutableSource: Yh,
      useSyncExternalStore: Zh,
      useId: wi,
      unstable_isNewReconciler: false
    };
    var Qh = { readContext: eh, useCallback: si, useContext: eh, useEffect: $h, useImperativeHandle: qi, useInsertionEffect: ni, useLayoutEffect: oi, useMemo: ti, useReducer: Xh, useRef: ji, useState: function() {
      return Xh(Vh);
    }, useDebugValue: ri, useDeferredValue: function(a) {
      var b2 = Uh();
      return null === N2 ? b2.memoizedState = a : ui(b2, N2.memoizedState, a);
    }, useTransition: function() {
      var a = Xh(Vh)[0], b2 = Uh().memoizedState;
      return [a, b2];
    }, useMutableSource: Yh, useSyncExternalStore: Zh, useId: wi, unstable_isNewReconciler: false };
    function Ci(a, b2) {
      if (a && a.defaultProps) {
        b2 = A({}, b2);
        a = a.defaultProps;
        for (var c in a) void 0 === b2[c] && (b2[c] = a[c]);
        return b2;
      }
      return b2;
    }
    function Di(a, b2, c, d2) {
      b2 = a.memoizedState;
      c = c(d2, b2);
      c = null === c || void 0 === c ? b2 : A({}, b2, c);
      a.memoizedState = c;
      0 === a.lanes && (a.updateQueue.baseState = c);
    }
    var Ei = { isMounted: function(a) {
      return (a = a._reactInternals) ? Vb(a) === a : false;
    }, enqueueSetState: function(a, b2, c) {
      a = a._reactInternals;
      var d2 = R2(), e3 = yi(a), f = mh(d2, e3);
      f.payload = b2;
      void 0 !== c && null !== c && (f.callback = c);
      b2 = nh(a, f, e3);
      null !== b2 && (gi(b2, a, e3, d2), oh(b2, a, e3));
    }, enqueueReplaceState: function(a, b2, c) {
      a = a._reactInternals;
      var d2 = R2(), e3 = yi(a), f = mh(d2, e3);
      f.tag = 1;
      f.payload = b2;
      void 0 !== c && null !== c && (f.callback = c);
      b2 = nh(a, f, e3);
      null !== b2 && (gi(b2, a, e3, d2), oh(b2, a, e3));
    }, enqueueForceUpdate: function(a, b2) {
      a = a._reactInternals;
      var c = R2(), d2 = yi(a), e3 = mh(c, d2);
      e3.tag = 2;
      void 0 !== b2 && null !== b2 && (e3.callback = b2);
      b2 = nh(a, e3, d2);
      null !== b2 && (gi(b2, a, d2, c), oh(b2, a, d2));
    } };
    function Fi(a, b2, c, d2, e3, f, g) {
      a = a.stateNode;
      return "function" === typeof a.shouldComponentUpdate ? a.shouldComponentUpdate(d2, f, g) : b2.prototype && b2.prototype.isPureReactComponent ? !Ie(c, d2) || !Ie(e3, f) : true;
    }
    function Gi(a, b2, c) {
      var d2 = false, e3 = Vf;
      var f = b2.contextType;
      "object" === typeof f && null !== f ? f = eh(f) : (e3 = Zf(b2) ? Xf : H.current, d2 = b2.contextTypes, f = (d2 = null !== d2 && void 0 !== d2) ? Yf(a, e3) : Vf);
      b2 = new b2(c, f);
      a.memoizedState = null !== b2.state && void 0 !== b2.state ? b2.state : null;
      b2.updater = Ei;
      a.stateNode = b2;
      b2._reactInternals = a;
      d2 && (a = a.stateNode, a.__reactInternalMemoizedUnmaskedChildContext = e3, a.__reactInternalMemoizedMaskedChildContext = f);
      return b2;
    }
    function Hi(a, b2, c, d2) {
      a = b2.state;
      "function" === typeof b2.componentWillReceiveProps && b2.componentWillReceiveProps(c, d2);
      "function" === typeof b2.UNSAFE_componentWillReceiveProps && b2.UNSAFE_componentWillReceiveProps(c, d2);
      b2.state !== a && Ei.enqueueReplaceState(b2, b2.state, null);
    }
    function Ii(a, b2, c, d2) {
      var e3 = a.stateNode;
      e3.props = c;
      e3.state = a.memoizedState;
      e3.refs = {};
      kh(a);
      var f = b2.contextType;
      "object" === typeof f && null !== f ? e3.context = eh(f) : (f = Zf(b2) ? Xf : H.current, e3.context = Yf(a, f));
      e3.state = a.memoizedState;
      f = b2.getDerivedStateFromProps;
      "function" === typeof f && (Di(a, b2, f, c), e3.state = a.memoizedState);
      "function" === typeof b2.getDerivedStateFromProps || "function" === typeof e3.getSnapshotBeforeUpdate || "function" !== typeof e3.UNSAFE_componentWillMount && "function" !== typeof e3.componentWillMount || (b2 = e3.state, "function" === typeof e3.componentWillMount && e3.componentWillMount(), "function" === typeof e3.UNSAFE_componentWillMount && e3.UNSAFE_componentWillMount(), b2 !== e3.state && Ei.enqueueReplaceState(e3, e3.state, null), qh(a, c, e3, d2), e3.state = a.memoizedState);
      "function" === typeof e3.componentDidMount && (a.flags |= 4194308);
    }
    function Ji(a, b2) {
      try {
        var c = "", d2 = b2;
        do
          c += Pa(d2), d2 = d2.return;
        while (d2);
        var e3 = c;
      } catch (f) {
        e3 = "\nError generating stack: " + f.message + "\n" + f.stack;
      }
      return { value: a, source: b2, stack: e3, digest: null };
    }
    function Ki(a, b2, c) {
      return { value: a, source: null, stack: null != c ? c : null, digest: null != b2 ? b2 : null };
    }
    function Li(a, b2) {
      try {
        console.error(b2.value);
      } catch (c) {
        setTimeout(function() {
          throw c;
        });
      }
    }
    var Mi = "function" === typeof WeakMap ? WeakMap : Map;
    function Ni(a, b2, c) {
      c = mh(-1, c);
      c.tag = 3;
      c.payload = { element: null };
      var d2 = b2.value;
      c.callback = function() {
        Oi || (Oi = true, Pi = d2);
        Li(a, b2);
      };
      return c;
    }
    function Qi(a, b2, c) {
      c = mh(-1, c);
      c.tag = 3;
      var d2 = a.type.getDerivedStateFromError;
      if ("function" === typeof d2) {
        var e3 = b2.value;
        c.payload = function() {
          return d2(e3);
        };
        c.callback = function() {
          Li(a, b2);
        };
      }
      var f = a.stateNode;
      null !== f && "function" === typeof f.componentDidCatch && (c.callback = function() {
        Li(a, b2);
        "function" !== typeof d2 && (null === Ri ? Ri = /* @__PURE__ */ new Set([this]) : Ri.add(this));
        var c2 = b2.stack;
        this.componentDidCatch(b2.value, { componentStack: null !== c2 ? c2 : "" });
      });
      return c;
    }
    function Si(a, b2, c) {
      var d2 = a.pingCache;
      if (null === d2) {
        d2 = a.pingCache = new Mi();
        var e3 = /* @__PURE__ */ new Set();
        d2.set(b2, e3);
      } else e3 = d2.get(b2), void 0 === e3 && (e3 = /* @__PURE__ */ new Set(), d2.set(b2, e3));
      e3.has(c) || (e3.add(c), a = Ti.bind(null, a, b2, c), b2.then(a, a));
    }
    function Ui(a) {
      do {
        var b2;
        if (b2 = 13 === a.tag) b2 = a.memoizedState, b2 = null !== b2 ? null !== b2.dehydrated ? true : false : true;
        if (b2) return a;
        a = a.return;
      } while (null !== a);
      return null;
    }
    function Vi(a, b2, c, d2, e3) {
      if (0 === (a.mode & 1)) return a === b2 ? a.flags |= 65536 : (a.flags |= 128, c.flags |= 131072, c.flags &= -52805, 1 === c.tag && (null === c.alternate ? c.tag = 17 : (b2 = mh(-1, 1), b2.tag = 2, nh(c, b2, 1))), c.lanes |= 1), a;
      a.flags |= 65536;
      a.lanes = e3;
      return a;
    }
    var Wi = ua.ReactCurrentOwner;
    var dh = false;
    function Xi(a, b2, c, d2) {
      b2.child = null === a ? Vg(b2, null, c, d2) : Ug(b2, a.child, c, d2);
    }
    function Yi(a, b2, c, d2, e3) {
      c = c.render;
      var f = b2.ref;
      ch(b2, e3);
      d2 = Nh(a, b2, c, d2, f, e3);
      c = Sh();
      if (null !== a && !dh) return b2.updateQueue = a.updateQueue, b2.flags &= -2053, a.lanes &= ~e3, Zi(a, b2, e3);
      I2 && c && vg(b2);
      b2.flags |= 1;
      Xi(a, b2, d2, e3);
      return b2.child;
    }
    function $i(a, b2, c, d2, e3) {
      if (null === a) {
        var f = c.type;
        if ("function" === typeof f && !aj(f) && void 0 === f.defaultProps && null === c.compare && void 0 === c.defaultProps) return b2.tag = 15, b2.type = f, bj(a, b2, f, d2, e3);
        a = Rg(c.type, null, d2, b2, b2.mode, e3);
        a.ref = b2.ref;
        a.return = b2;
        return b2.child = a;
      }
      f = a.child;
      if (0 === (a.lanes & e3)) {
        var g = f.memoizedProps;
        c = c.compare;
        c = null !== c ? c : Ie;
        if (c(g, d2) && a.ref === b2.ref) return Zi(a, b2, e3);
      }
      b2.flags |= 1;
      a = Pg(f, d2);
      a.ref = b2.ref;
      a.return = b2;
      return b2.child = a;
    }
    function bj(a, b2, c, d2, e3) {
      if (null !== a) {
        var f = a.memoizedProps;
        if (Ie(f, d2) && a.ref === b2.ref) if (dh = false, b2.pendingProps = d2 = f, 0 !== (a.lanes & e3)) 0 !== (a.flags & 131072) && (dh = true);
        else return b2.lanes = a.lanes, Zi(a, b2, e3);
      }
      return cj(a, b2, c, d2, e3);
    }
    function dj(a, b2, c) {
      var d2 = b2.pendingProps, e3 = d2.children, f = null !== a ? a.memoizedState : null;
      if ("hidden" === d2.mode) if (0 === (b2.mode & 1)) b2.memoizedState = { baseLanes: 0, cachePool: null, transitions: null }, G3(ej, fj), fj |= c;
      else {
        if (0 === (c & 1073741824)) return a = null !== f ? f.baseLanes | c : c, b2.lanes = b2.childLanes = 1073741824, b2.memoizedState = { baseLanes: a, cachePool: null, transitions: null }, b2.updateQueue = null, G3(ej, fj), fj |= a, null;
        b2.memoizedState = { baseLanes: 0, cachePool: null, transitions: null };
        d2 = null !== f ? f.baseLanes : c;
        G3(ej, fj);
        fj |= d2;
      }
      else null !== f ? (d2 = f.baseLanes | c, b2.memoizedState = null) : d2 = c, G3(ej, fj), fj |= d2;
      Xi(a, b2, e3, c);
      return b2.child;
    }
    function gj(a, b2) {
      var c = b2.ref;
      if (null === a && null !== c || null !== a && a.ref !== c) b2.flags |= 512, b2.flags |= 2097152;
    }
    function cj(a, b2, c, d2, e3) {
      var f = Zf(c) ? Xf : H.current;
      f = Yf(b2, f);
      ch(b2, e3);
      c = Nh(a, b2, c, d2, f, e3);
      d2 = Sh();
      if (null !== a && !dh) return b2.updateQueue = a.updateQueue, b2.flags &= -2053, a.lanes &= ~e3, Zi(a, b2, e3);
      I2 && d2 && vg(b2);
      b2.flags |= 1;
      Xi(a, b2, c, e3);
      return b2.child;
    }
    function hj(a, b2, c, d2, e3) {
      if (Zf(c)) {
        var f = true;
        cg(b2);
      } else f = false;
      ch(b2, e3);
      if (null === b2.stateNode) ij(a, b2), Gi(b2, c, d2), Ii(b2, c, d2, e3), d2 = true;
      else if (null === a) {
        var g = b2.stateNode, h2 = b2.memoizedProps;
        g.props = h2;
        var k = g.context, l2 = c.contextType;
        "object" === typeof l2 && null !== l2 ? l2 = eh(l2) : (l2 = Zf(c) ? Xf : H.current, l2 = Yf(b2, l2));
        var m2 = c.getDerivedStateFromProps, q = "function" === typeof m2 || "function" === typeof g.getSnapshotBeforeUpdate;
        q || "function" !== typeof g.UNSAFE_componentWillReceiveProps && "function" !== typeof g.componentWillReceiveProps || (h2 !== d2 || k !== l2) && Hi(b2, g, d2, l2);
        jh = false;
        var r3 = b2.memoizedState;
        g.state = r3;
        qh(b2, d2, g, e3);
        k = b2.memoizedState;
        h2 !== d2 || r3 !== k || Wf.current || jh ? ("function" === typeof m2 && (Di(b2, c, m2, d2), k = b2.memoizedState), (h2 = jh || Fi(b2, c, h2, d2, r3, k, l2)) ? (q || "function" !== typeof g.UNSAFE_componentWillMount && "function" !== typeof g.componentWillMount || ("function" === typeof g.componentWillMount && g.componentWillMount(), "function" === typeof g.UNSAFE_componentWillMount && g.UNSAFE_componentWillMount()), "function" === typeof g.componentDidMount && (b2.flags |= 4194308)) : ("function" === typeof g.componentDidMount && (b2.flags |= 4194308), b2.memoizedProps = d2, b2.memoizedState = k), g.props = d2, g.state = k, g.context = l2, d2 = h2) : ("function" === typeof g.componentDidMount && (b2.flags |= 4194308), d2 = false);
      } else {
        g = b2.stateNode;
        lh(a, b2);
        h2 = b2.memoizedProps;
        l2 = b2.type === b2.elementType ? h2 : Ci(b2.type, h2);
        g.props = l2;
        q = b2.pendingProps;
        r3 = g.context;
        k = c.contextType;
        "object" === typeof k && null !== k ? k = eh(k) : (k = Zf(c) ? Xf : H.current, k = Yf(b2, k));
        var y2 = c.getDerivedStateFromProps;
        (m2 = "function" === typeof y2 || "function" === typeof g.getSnapshotBeforeUpdate) || "function" !== typeof g.UNSAFE_componentWillReceiveProps && "function" !== typeof g.componentWillReceiveProps || (h2 !== q || r3 !== k) && Hi(b2, g, d2, k);
        jh = false;
        r3 = b2.memoizedState;
        g.state = r3;
        qh(b2, d2, g, e3);
        var n3 = b2.memoizedState;
        h2 !== q || r3 !== n3 || Wf.current || jh ? ("function" === typeof y2 && (Di(b2, c, y2, d2), n3 = b2.memoizedState), (l2 = jh || Fi(b2, c, l2, d2, r3, n3, k) || false) ? (m2 || "function" !== typeof g.UNSAFE_componentWillUpdate && "function" !== typeof g.componentWillUpdate || ("function" === typeof g.componentWillUpdate && g.componentWillUpdate(d2, n3, k), "function" === typeof g.UNSAFE_componentWillUpdate && g.UNSAFE_componentWillUpdate(d2, n3, k)), "function" === typeof g.componentDidUpdate && (b2.flags |= 4), "function" === typeof g.getSnapshotBeforeUpdate && (b2.flags |= 1024)) : ("function" !== typeof g.componentDidUpdate || h2 === a.memoizedProps && r3 === a.memoizedState || (b2.flags |= 4), "function" !== typeof g.getSnapshotBeforeUpdate || h2 === a.memoizedProps && r3 === a.memoizedState || (b2.flags |= 1024), b2.memoizedProps = d2, b2.memoizedState = n3), g.props = d2, g.state = n3, g.context = k, d2 = l2) : ("function" !== typeof g.componentDidUpdate || h2 === a.memoizedProps && r3 === a.memoizedState || (b2.flags |= 4), "function" !== typeof g.getSnapshotBeforeUpdate || h2 === a.memoizedProps && r3 === a.memoizedState || (b2.flags |= 1024), d2 = false);
      }
      return jj(a, b2, c, d2, f, e3);
    }
    function jj(a, b2, c, d2, e3, f) {
      gj(a, b2);
      var g = 0 !== (b2.flags & 128);
      if (!d2 && !g) return e3 && dg(b2, c, false), Zi(a, b2, f);
      d2 = b2.stateNode;
      Wi.current = b2;
      var h2 = g && "function" !== typeof c.getDerivedStateFromError ? null : d2.render();
      b2.flags |= 1;
      null !== a && g ? (b2.child = Ug(b2, a.child, null, f), b2.child = Ug(b2, null, h2, f)) : Xi(a, b2, h2, f);
      b2.memoizedState = d2.state;
      e3 && dg(b2, c, true);
      return b2.child;
    }
    function kj(a) {
      var b2 = a.stateNode;
      b2.pendingContext ? ag(a, b2.pendingContext, b2.pendingContext !== b2.context) : b2.context && ag(a, b2.context, false);
      yh(a, b2.containerInfo);
    }
    function lj(a, b2, c, d2, e3) {
      Ig();
      Jg(e3);
      b2.flags |= 256;
      Xi(a, b2, c, d2);
      return b2.child;
    }
    var mj = { dehydrated: null, treeContext: null, retryLane: 0 };
    function nj(a) {
      return { baseLanes: a, cachePool: null, transitions: null };
    }
    function oj(a, b2, c) {
      var d2 = b2.pendingProps, e3 = L.current, f = false, g = 0 !== (b2.flags & 128), h2;
      (h2 = g) || (h2 = null !== a && null === a.memoizedState ? false : 0 !== (e3 & 2));
      if (h2) f = true, b2.flags &= -129;
      else if (null === a || null !== a.memoizedState) e3 |= 1;
      G3(L, e3 & 1);
      if (null === a) {
        Eg(b2);
        a = b2.memoizedState;
        if (null !== a && (a = a.dehydrated, null !== a)) return 0 === (b2.mode & 1) ? b2.lanes = 1 : "$!" === a.data ? b2.lanes = 8 : b2.lanes = 1073741824, null;
        g = d2.children;
        a = d2.fallback;
        return f ? (d2 = b2.mode, f = b2.child, g = { mode: "hidden", children: g }, 0 === (d2 & 1) && null !== f ? (f.childLanes = 0, f.pendingProps = g) : f = pj(g, d2, 0, null), a = Tg(a, d2, c, null), f.return = b2, a.return = b2, f.sibling = a, b2.child = f, b2.child.memoizedState = nj(c), b2.memoizedState = mj, a) : qj(b2, g);
      }
      e3 = a.memoizedState;
      if (null !== e3 && (h2 = e3.dehydrated, null !== h2)) return rj(a, b2, g, d2, h2, e3, c);
      if (f) {
        f = d2.fallback;
        g = b2.mode;
        e3 = a.child;
        h2 = e3.sibling;
        var k = { mode: "hidden", children: d2.children };
        0 === (g & 1) && b2.child !== e3 ? (d2 = b2.child, d2.childLanes = 0, d2.pendingProps = k, b2.deletions = null) : (d2 = Pg(e3, k), d2.subtreeFlags = e3.subtreeFlags & 14680064);
        null !== h2 ? f = Pg(h2, f) : (f = Tg(f, g, c, null), f.flags |= 2);
        f.return = b2;
        d2.return = b2;
        d2.sibling = f;
        b2.child = d2;
        d2 = f;
        f = b2.child;
        g = a.child.memoizedState;
        g = null === g ? nj(c) : { baseLanes: g.baseLanes | c, cachePool: null, transitions: g.transitions };
        f.memoizedState = g;
        f.childLanes = a.childLanes & ~c;
        b2.memoizedState = mj;
        return d2;
      }
      f = a.child;
      a = f.sibling;
      d2 = Pg(f, { mode: "visible", children: d2.children });
      0 === (b2.mode & 1) && (d2.lanes = c);
      d2.return = b2;
      d2.sibling = null;
      null !== a && (c = b2.deletions, null === c ? (b2.deletions = [a], b2.flags |= 16) : c.push(a));
      b2.child = d2;
      b2.memoizedState = null;
      return d2;
    }
    function qj(a, b2) {
      b2 = pj({ mode: "visible", children: b2 }, a.mode, 0, null);
      b2.return = a;
      return a.child = b2;
    }
    function sj(a, b2, c, d2) {
      null !== d2 && Jg(d2);
      Ug(b2, a.child, null, c);
      a = qj(b2, b2.pendingProps.children);
      a.flags |= 2;
      b2.memoizedState = null;
      return a;
    }
    function rj(a, b2, c, d2, e3, f, g) {
      if (c) {
        if (b2.flags & 256) return b2.flags &= -257, d2 = Ki(Error(p2(422))), sj(a, b2, g, d2);
        if (null !== b2.memoizedState) return b2.child = a.child, b2.flags |= 128, null;
        f = d2.fallback;
        e3 = b2.mode;
        d2 = pj({ mode: "visible", children: d2.children }, e3, 0, null);
        f = Tg(f, e3, g, null);
        f.flags |= 2;
        d2.return = b2;
        f.return = b2;
        d2.sibling = f;
        b2.child = d2;
        0 !== (b2.mode & 1) && Ug(b2, a.child, null, g);
        b2.child.memoizedState = nj(g);
        b2.memoizedState = mj;
        return f;
      }
      if (0 === (b2.mode & 1)) return sj(a, b2, g, null);
      if ("$!" === e3.data) {
        d2 = e3.nextSibling && e3.nextSibling.dataset;
        if (d2) var h2 = d2.dgst;
        d2 = h2;
        f = Error(p2(419));
        d2 = Ki(f, d2, void 0);
        return sj(a, b2, g, d2);
      }
      h2 = 0 !== (g & a.childLanes);
      if (dh || h2) {
        d2 = Q;
        if (null !== d2) {
          switch (g & -g) {
            case 4:
              e3 = 2;
              break;
            case 16:
              e3 = 8;
              break;
            case 64:
            case 128:
            case 256:
            case 512:
            case 1024:
            case 2048:
            case 4096:
            case 8192:
            case 16384:
            case 32768:
            case 65536:
            case 131072:
            case 262144:
            case 524288:
            case 1048576:
            case 2097152:
            case 4194304:
            case 8388608:
            case 16777216:
            case 33554432:
            case 67108864:
              e3 = 32;
              break;
            case 536870912:
              e3 = 268435456;
              break;
            default:
              e3 = 0;
          }
          e3 = 0 !== (e3 & (d2.suspendedLanes | g)) ? 0 : e3;
          0 !== e3 && e3 !== f.retryLane && (f.retryLane = e3, ih(a, e3), gi(d2, a, e3, -1));
        }
        tj();
        d2 = Ki(Error(p2(421)));
        return sj(a, b2, g, d2);
      }
      if ("$?" === e3.data) return b2.flags |= 128, b2.child = a.child, b2 = uj.bind(null, a), e3._reactRetry = b2, null;
      a = f.treeContext;
      yg = Lf(e3.nextSibling);
      xg = b2;
      I2 = true;
      zg = null;
      null !== a && (og[pg++] = rg, og[pg++] = sg, og[pg++] = qg, rg = a.id, sg = a.overflow, qg = b2);
      b2 = qj(b2, d2.children);
      b2.flags |= 4096;
      return b2;
    }
    function vj(a, b2, c) {
      a.lanes |= b2;
      var d2 = a.alternate;
      null !== d2 && (d2.lanes |= b2);
      bh(a.return, b2, c);
    }
    function wj(a, b2, c, d2, e3) {
      var f = a.memoizedState;
      null === f ? a.memoizedState = { isBackwards: b2, rendering: null, renderingStartTime: 0, last: d2, tail: c, tailMode: e3 } : (f.isBackwards = b2, f.rendering = null, f.renderingStartTime = 0, f.last = d2, f.tail = c, f.tailMode = e3);
    }
    function xj(a, b2, c) {
      var d2 = b2.pendingProps, e3 = d2.revealOrder, f = d2.tail;
      Xi(a, b2, d2.children, c);
      d2 = L.current;
      if (0 !== (d2 & 2)) d2 = d2 & 1 | 2, b2.flags |= 128;
      else {
        if (null !== a && 0 !== (a.flags & 128)) a: for (a = b2.child; null !== a; ) {
          if (13 === a.tag) null !== a.memoizedState && vj(a, c, b2);
          else if (19 === a.tag) vj(a, c, b2);
          else if (null !== a.child) {
            a.child.return = a;
            a = a.child;
            continue;
          }
          if (a === b2) break a;
          for (; null === a.sibling; ) {
            if (null === a.return || a.return === b2) break a;
            a = a.return;
          }
          a.sibling.return = a.return;
          a = a.sibling;
        }
        d2 &= 1;
      }
      G3(L, d2);
      if (0 === (b2.mode & 1)) b2.memoizedState = null;
      else switch (e3) {
        case "forwards":
          c = b2.child;
          for (e3 = null; null !== c; ) a = c.alternate, null !== a && null === Ch(a) && (e3 = c), c = c.sibling;
          c = e3;
          null === c ? (e3 = b2.child, b2.child = null) : (e3 = c.sibling, c.sibling = null);
          wj(b2, false, e3, c, f);
          break;
        case "backwards":
          c = null;
          e3 = b2.child;
          for (b2.child = null; null !== e3; ) {
            a = e3.alternate;
            if (null !== a && null === Ch(a)) {
              b2.child = e3;
              break;
            }
            a = e3.sibling;
            e3.sibling = c;
            c = e3;
            e3 = a;
          }
          wj(b2, true, c, null, f);
          break;
        case "together":
          wj(b2, false, null, null, void 0);
          break;
        default:
          b2.memoizedState = null;
      }
      return b2.child;
    }
    function ij(a, b2) {
      0 === (b2.mode & 1) && null !== a && (a.alternate = null, b2.alternate = null, b2.flags |= 2);
    }
    function Zi(a, b2, c) {
      null !== a && (b2.dependencies = a.dependencies);
      rh |= b2.lanes;
      if (0 === (c & b2.childLanes)) return null;
      if (null !== a && b2.child !== a.child) throw Error(p2(153));
      if (null !== b2.child) {
        a = b2.child;
        c = Pg(a, a.pendingProps);
        b2.child = c;
        for (c.return = b2; null !== a.sibling; ) a = a.sibling, c = c.sibling = Pg(a, a.pendingProps), c.return = b2;
        c.sibling = null;
      }
      return b2.child;
    }
    function yj(a, b2, c) {
      switch (b2.tag) {
        case 3:
          kj(b2);
          Ig();
          break;
        case 5:
          Ah(b2);
          break;
        case 1:
          Zf(b2.type) && cg(b2);
          break;
        case 4:
          yh(b2, b2.stateNode.containerInfo);
          break;
        case 10:
          var d2 = b2.type._context, e3 = b2.memoizedProps.value;
          G3(Wg, d2._currentValue);
          d2._currentValue = e3;
          break;
        case 13:
          d2 = b2.memoizedState;
          if (null !== d2) {
            if (null !== d2.dehydrated) return G3(L, L.current & 1), b2.flags |= 128, null;
            if (0 !== (c & b2.child.childLanes)) return oj(a, b2, c);
            G3(L, L.current & 1);
            a = Zi(a, b2, c);
            return null !== a ? a.sibling : null;
          }
          G3(L, L.current & 1);
          break;
        case 19:
          d2 = 0 !== (c & b2.childLanes);
          if (0 !== (a.flags & 128)) {
            if (d2) return xj(a, b2, c);
            b2.flags |= 128;
          }
          e3 = b2.memoizedState;
          null !== e3 && (e3.rendering = null, e3.tail = null, e3.lastEffect = null);
          G3(L, L.current);
          if (d2) break;
          else return null;
        case 22:
        case 23:
          return b2.lanes = 0, dj(a, b2, c);
      }
      return Zi(a, b2, c);
    }
    var zj;
    var Aj;
    var Bj;
    var Cj;
    zj = function(a, b2) {
      for (var c = b2.child; null !== c; ) {
        if (5 === c.tag || 6 === c.tag) a.appendChild(c.stateNode);
        else if (4 !== c.tag && null !== c.child) {
          c.child.return = c;
          c = c.child;
          continue;
        }
        if (c === b2) break;
        for (; null === c.sibling; ) {
          if (null === c.return || c.return === b2) return;
          c = c.return;
        }
        c.sibling.return = c.return;
        c = c.sibling;
      }
    };
    Aj = function() {
    };
    Bj = function(a, b2, c, d2) {
      var e3 = a.memoizedProps;
      if (e3 !== d2) {
        a = b2.stateNode;
        xh(uh.current);
        var f = null;
        switch (c) {
          case "input":
            e3 = Ya(a, e3);
            d2 = Ya(a, d2);
            f = [];
            break;
          case "select":
            e3 = A({}, e3, { value: void 0 });
            d2 = A({}, d2, { value: void 0 });
            f = [];
            break;
          case "textarea":
            e3 = gb(a, e3);
            d2 = gb(a, d2);
            f = [];
            break;
          default:
            "function" !== typeof e3.onClick && "function" === typeof d2.onClick && (a.onclick = Bf);
        }
        ub(c, d2);
        var g;
        c = null;
        for (l2 in e3) if (!d2.hasOwnProperty(l2) && e3.hasOwnProperty(l2) && null != e3[l2]) if ("style" === l2) {
          var h2 = e3[l2];
          for (g in h2) h2.hasOwnProperty(g) && (c || (c = {}), c[g] = "");
        } else "dangerouslySetInnerHTML" !== l2 && "children" !== l2 && "suppressContentEditableWarning" !== l2 && "suppressHydrationWarning" !== l2 && "autoFocus" !== l2 && (ea.hasOwnProperty(l2) ? f || (f = []) : (f = f || []).push(l2, null));
        for (l2 in d2) {
          var k = d2[l2];
          h2 = null != e3 ? e3[l2] : void 0;
          if (d2.hasOwnProperty(l2) && k !== h2 && (null != k || null != h2)) if ("style" === l2) if (h2) {
            for (g in h2) !h2.hasOwnProperty(g) || k && k.hasOwnProperty(g) || (c || (c = {}), c[g] = "");
            for (g in k) k.hasOwnProperty(g) && h2[g] !== k[g] && (c || (c = {}), c[g] = k[g]);
          } else c || (f || (f = []), f.push(
            l2,
            c
          )), c = k;
          else "dangerouslySetInnerHTML" === l2 ? (k = k ? k.__html : void 0, h2 = h2 ? h2.__html : void 0, null != k && h2 !== k && (f = f || []).push(l2, k)) : "children" === l2 ? "string" !== typeof k && "number" !== typeof k || (f = f || []).push(l2, "" + k) : "suppressContentEditableWarning" !== l2 && "suppressHydrationWarning" !== l2 && (ea.hasOwnProperty(l2) ? (null != k && "onScroll" === l2 && D("scroll", a), f || h2 === k || (f = [])) : (f = f || []).push(l2, k));
        }
        c && (f = f || []).push("style", c);
        var l2 = f;
        if (b2.updateQueue = l2) b2.flags |= 4;
      }
    };
    Cj = function(a, b2, c, d2) {
      c !== d2 && (b2.flags |= 4);
    };
    function Dj(a, b2) {
      if (!I2) switch (a.tailMode) {
        case "hidden":
          b2 = a.tail;
          for (var c = null; null !== b2; ) null !== b2.alternate && (c = b2), b2 = b2.sibling;
          null === c ? a.tail = null : c.sibling = null;
          break;
        case "collapsed":
          c = a.tail;
          for (var d2 = null; null !== c; ) null !== c.alternate && (d2 = c), c = c.sibling;
          null === d2 ? b2 || null === a.tail ? a.tail = null : a.tail.sibling = null : d2.sibling = null;
      }
    }
    function S2(a) {
      var b2 = null !== a.alternate && a.alternate.child === a.child, c = 0, d2 = 0;
      if (b2) for (var e3 = a.child; null !== e3; ) c |= e3.lanes | e3.childLanes, d2 |= e3.subtreeFlags & 14680064, d2 |= e3.flags & 14680064, e3.return = a, e3 = e3.sibling;
      else for (e3 = a.child; null !== e3; ) c |= e3.lanes | e3.childLanes, d2 |= e3.subtreeFlags, d2 |= e3.flags, e3.return = a, e3 = e3.sibling;
      a.subtreeFlags |= d2;
      a.childLanes = c;
      return b2;
    }
    function Ej(a, b2, c) {
      var d2 = b2.pendingProps;
      wg(b2);
      switch (b2.tag) {
        case 2:
        case 16:
        case 15:
        case 0:
        case 11:
        case 7:
        case 8:
        case 12:
        case 9:
        case 14:
          return S2(b2), null;
        case 1:
          return Zf(b2.type) && $f(), S2(b2), null;
        case 3:
          d2 = b2.stateNode;
          zh();
          E(Wf);
          E(H);
          Eh();
          d2.pendingContext && (d2.context = d2.pendingContext, d2.pendingContext = null);
          if (null === a || null === a.child) Gg(b2) ? b2.flags |= 4 : null === a || a.memoizedState.isDehydrated && 0 === (b2.flags & 256) || (b2.flags |= 1024, null !== zg && (Fj(zg), zg = null));
          Aj(a, b2);
          S2(b2);
          return null;
        case 5:
          Bh(b2);
          var e3 = xh(wh.current);
          c = b2.type;
          if (null !== a && null != b2.stateNode) Bj(a, b2, c, d2, e3), a.ref !== b2.ref && (b2.flags |= 512, b2.flags |= 2097152);
          else {
            if (!d2) {
              if (null === b2.stateNode) throw Error(p2(166));
              S2(b2);
              return null;
            }
            a = xh(uh.current);
            if (Gg(b2)) {
              d2 = b2.stateNode;
              c = b2.type;
              var f = b2.memoizedProps;
              d2[Of] = b2;
              d2[Pf] = f;
              a = 0 !== (b2.mode & 1);
              switch (c) {
                case "dialog":
                  D("cancel", d2);
                  D("close", d2);
                  break;
                case "iframe":
                case "object":
                case "embed":
                  D("load", d2);
                  break;
                case "video":
                case "audio":
                  for (e3 = 0; e3 < lf.length; e3++) D(lf[e3], d2);
                  break;
                case "source":
                  D("error", d2);
                  break;
                case "img":
                case "image":
                case "link":
                  D(
                    "error",
                    d2
                  );
                  D("load", d2);
                  break;
                case "details":
                  D("toggle", d2);
                  break;
                case "input":
                  Za(d2, f);
                  D("invalid", d2);
                  break;
                case "select":
                  d2._wrapperState = { wasMultiple: !!f.multiple };
                  D("invalid", d2);
                  break;
                case "textarea":
                  hb(d2, f), D("invalid", d2);
              }
              ub(c, f);
              e3 = null;
              for (var g in f) if (f.hasOwnProperty(g)) {
                var h2 = f[g];
                "children" === g ? "string" === typeof h2 ? d2.textContent !== h2 && (true !== f.suppressHydrationWarning && Af(d2.textContent, h2, a), e3 = ["children", h2]) : "number" === typeof h2 && d2.textContent !== "" + h2 && (true !== f.suppressHydrationWarning && Af(
                  d2.textContent,
                  h2,
                  a
                ), e3 = ["children", "" + h2]) : ea.hasOwnProperty(g) && null != h2 && "onScroll" === g && D("scroll", d2);
              }
              switch (c) {
                case "input":
                  Va(d2);
                  db(d2, f, true);
                  break;
                case "textarea":
                  Va(d2);
                  jb(d2);
                  break;
                case "select":
                case "option":
                  break;
                default:
                  "function" === typeof f.onClick && (d2.onclick = Bf);
              }
              d2 = e3;
              b2.updateQueue = d2;
              null !== d2 && (b2.flags |= 4);
            } else {
              g = 9 === e3.nodeType ? e3 : e3.ownerDocument;
              "http://www.w3.org/1999/xhtml" === a && (a = kb(c));
              "http://www.w3.org/1999/xhtml" === a ? "script" === c ? (a = g.createElement("div"), a.innerHTML = "<script><\/script>", a = a.removeChild(a.firstChild)) : "string" === typeof d2.is ? a = g.createElement(c, { is: d2.is }) : (a = g.createElement(c), "select" === c && (g = a, d2.multiple ? g.multiple = true : d2.size && (g.size = d2.size))) : a = g.createElementNS(a, c);
              a[Of] = b2;
              a[Pf] = d2;
              zj(a, b2, false, false);
              b2.stateNode = a;
              a: {
                g = vb(c, d2);
                switch (c) {
                  case "dialog":
                    D("cancel", a);
                    D("close", a);
                    e3 = d2;
                    break;
                  case "iframe":
                  case "object":
                  case "embed":
                    D("load", a);
                    e3 = d2;
                    break;
                  case "video":
                  case "audio":
                    for (e3 = 0; e3 < lf.length; e3++) D(lf[e3], a);
                    e3 = d2;
                    break;
                  case "source":
                    D("error", a);
                    e3 = d2;
                    break;
                  case "img":
                  case "image":
                  case "link":
                    D(
                      "error",
                      a
                    );
                    D("load", a);
                    e3 = d2;
                    break;
                  case "details":
                    D("toggle", a);
                    e3 = d2;
                    break;
                  case "input":
                    Za(a, d2);
                    e3 = Ya(a, d2);
                    D("invalid", a);
                    break;
                  case "option":
                    e3 = d2;
                    break;
                  case "select":
                    a._wrapperState = { wasMultiple: !!d2.multiple };
                    e3 = A({}, d2, { value: void 0 });
                    D("invalid", a);
                    break;
                  case "textarea":
                    hb(a, d2);
                    e3 = gb(a, d2);
                    D("invalid", a);
                    break;
                  default:
                    e3 = d2;
                }
                ub(c, e3);
                h2 = e3;
                for (f in h2) if (h2.hasOwnProperty(f)) {
                  var k = h2[f];
                  "style" === f ? sb(a, k) : "dangerouslySetInnerHTML" === f ? (k = k ? k.__html : void 0, null != k && nb(a, k)) : "children" === f ? "string" === typeof k ? ("textarea" !== c || "" !== k) && ob(a, k) : "number" === typeof k && ob(a, "" + k) : "suppressContentEditableWarning" !== f && "suppressHydrationWarning" !== f && "autoFocus" !== f && (ea.hasOwnProperty(f) ? null != k && "onScroll" === f && D("scroll", a) : null != k && ta(a, f, k, g));
                }
                switch (c) {
                  case "input":
                    Va(a);
                    db(a, d2, false);
                    break;
                  case "textarea":
                    Va(a);
                    jb(a);
                    break;
                  case "option":
                    null != d2.value && a.setAttribute("value", "" + Sa(d2.value));
                    break;
                  case "select":
                    a.multiple = !!d2.multiple;
                    f = d2.value;
                    null != f ? fb(a, !!d2.multiple, f, false) : null != d2.defaultValue && fb(
                      a,
                      !!d2.multiple,
                      d2.defaultValue,
                      true
                    );
                    break;
                  default:
                    "function" === typeof e3.onClick && (a.onclick = Bf);
                }
                switch (c) {
                  case "button":
                  case "input":
                  case "select":
                  case "textarea":
                    d2 = !!d2.autoFocus;
                    break a;
                  case "img":
                    d2 = true;
                    break a;
                  default:
                    d2 = false;
                }
              }
              d2 && (b2.flags |= 4);
            }
            null !== b2.ref && (b2.flags |= 512, b2.flags |= 2097152);
          }
          S2(b2);
          return null;
        case 6:
          if (a && null != b2.stateNode) Cj(a, b2, a.memoizedProps, d2);
          else {
            if ("string" !== typeof d2 && null === b2.stateNode) throw Error(p2(166));
            c = xh(wh.current);
            xh(uh.current);
            if (Gg(b2)) {
              d2 = b2.stateNode;
              c = b2.memoizedProps;
              d2[Of] = b2;
              if (f = d2.nodeValue !== c) {
                if (a = xg, null !== a) switch (a.tag) {
                  case 3:
                    Af(d2.nodeValue, c, 0 !== (a.mode & 1));
                    break;
                  case 5:
                    true !== a.memoizedProps.suppressHydrationWarning && Af(d2.nodeValue, c, 0 !== (a.mode & 1));
                }
              }
              f && (b2.flags |= 4);
            } else d2 = (9 === c.nodeType ? c : c.ownerDocument).createTextNode(d2), d2[Of] = b2, b2.stateNode = d2;
          }
          S2(b2);
          return null;
        case 13:
          E(L);
          d2 = b2.memoizedState;
          if (null === a || null !== a.memoizedState && null !== a.memoizedState.dehydrated) {
            if (I2 && null !== yg && 0 !== (b2.mode & 1) && 0 === (b2.flags & 128)) Hg(), Ig(), b2.flags |= 98560, f = false;
            else if (f = Gg(b2), null !== d2 && null !== d2.dehydrated) {
              if (null === a) {
                if (!f) throw Error(p2(318));
                f = b2.memoizedState;
                f = null !== f ? f.dehydrated : null;
                if (!f) throw Error(p2(317));
                f[Of] = b2;
              } else Ig(), 0 === (b2.flags & 128) && (b2.memoizedState = null), b2.flags |= 4;
              S2(b2);
              f = false;
            } else null !== zg && (Fj(zg), zg = null), f = true;
            if (!f) return b2.flags & 65536 ? b2 : null;
          }
          if (0 !== (b2.flags & 128)) return b2.lanes = c, b2;
          d2 = null !== d2;
          d2 !== (null !== a && null !== a.memoizedState) && d2 && (b2.child.flags |= 8192, 0 !== (b2.mode & 1) && (null === a || 0 !== (L.current & 1) ? 0 === T && (T = 3) : tj()));
          null !== b2.updateQueue && (b2.flags |= 4);
          S2(b2);
          return null;
        case 4:
          return zh(), Aj(a, b2), null === a && sf(b2.stateNode.containerInfo), S2(b2), null;
        case 10:
          return ah(b2.type._context), S2(b2), null;
        case 17:
          return Zf(b2.type) && $f(), S2(b2), null;
        case 19:
          E(L);
          f = b2.memoizedState;
          if (null === f) return S2(b2), null;
          d2 = 0 !== (b2.flags & 128);
          g = f.rendering;
          if (null === g) if (d2) Dj(f, false);
          else {
            if (0 !== T || null !== a && 0 !== (a.flags & 128)) for (a = b2.child; null !== a; ) {
              g = Ch(a);
              if (null !== g) {
                b2.flags |= 128;
                Dj(f, false);
                d2 = g.updateQueue;
                null !== d2 && (b2.updateQueue = d2, b2.flags |= 4);
                b2.subtreeFlags = 0;
                d2 = c;
                for (c = b2.child; null !== c; ) f = c, a = d2, f.flags &= 14680066, g = f.alternate, null === g ? (f.childLanes = 0, f.lanes = a, f.child = null, f.subtreeFlags = 0, f.memoizedProps = null, f.memoizedState = null, f.updateQueue = null, f.dependencies = null, f.stateNode = null) : (f.childLanes = g.childLanes, f.lanes = g.lanes, f.child = g.child, f.subtreeFlags = 0, f.deletions = null, f.memoizedProps = g.memoizedProps, f.memoizedState = g.memoizedState, f.updateQueue = g.updateQueue, f.type = g.type, a = g.dependencies, f.dependencies = null === a ? null : { lanes: a.lanes, firstContext: a.firstContext }), c = c.sibling;
                G3(L, L.current & 1 | 2);
                return b2.child;
              }
              a = a.sibling;
            }
            null !== f.tail && B2() > Gj && (b2.flags |= 128, d2 = true, Dj(f, false), b2.lanes = 4194304);
          }
          else {
            if (!d2) if (a = Ch(g), null !== a) {
              if (b2.flags |= 128, d2 = true, c = a.updateQueue, null !== c && (b2.updateQueue = c, b2.flags |= 4), Dj(f, true), null === f.tail && "hidden" === f.tailMode && !g.alternate && !I2) return S2(b2), null;
            } else 2 * B2() - f.renderingStartTime > Gj && 1073741824 !== c && (b2.flags |= 128, d2 = true, Dj(f, false), b2.lanes = 4194304);
            f.isBackwards ? (g.sibling = b2.child, b2.child = g) : (c = f.last, null !== c ? c.sibling = g : b2.child = g, f.last = g);
          }
          if (null !== f.tail) return b2 = f.tail, f.rendering = b2, f.tail = b2.sibling, f.renderingStartTime = B2(), b2.sibling = null, c = L.current, G3(L, d2 ? c & 1 | 2 : c & 1), b2;
          S2(b2);
          return null;
        case 22:
        case 23:
          return Hj(), d2 = null !== b2.memoizedState, null !== a && null !== a.memoizedState !== d2 && (b2.flags |= 8192), d2 && 0 !== (b2.mode & 1) ? 0 !== (fj & 1073741824) && (S2(b2), b2.subtreeFlags & 6 && (b2.flags |= 8192)) : S2(b2), null;
        case 24:
          return null;
        case 25:
          return null;
      }
      throw Error(p2(156, b2.tag));
    }
    function Ij(a, b2) {
      wg(b2);
      switch (b2.tag) {
        case 1:
          return Zf(b2.type) && $f(), a = b2.flags, a & 65536 ? (b2.flags = a & -65537 | 128, b2) : null;
        case 3:
          return zh(), E(Wf), E(H), Eh(), a = b2.flags, 0 !== (a & 65536) && 0 === (a & 128) ? (b2.flags = a & -65537 | 128, b2) : null;
        case 5:
          return Bh(b2), null;
        case 13:
          E(L);
          a = b2.memoizedState;
          if (null !== a && null !== a.dehydrated) {
            if (null === b2.alternate) throw Error(p2(340));
            Ig();
          }
          a = b2.flags;
          return a & 65536 ? (b2.flags = a & -65537 | 128, b2) : null;
        case 19:
          return E(L), null;
        case 4:
          return zh(), null;
        case 10:
          return ah(b2.type._context), null;
        case 22:
        case 23:
          return Hj(), null;
        case 24:
          return null;
        default:
          return null;
      }
    }
    var Jj = false;
    var U = false;
    var Kj = "function" === typeof WeakSet ? WeakSet : Set;
    var V = null;
    function Lj(a, b2) {
      var c = a.ref;
      if (null !== c) if ("function" === typeof c) try {
        c(null);
      } catch (d2) {
        W(a, b2, d2);
      }
      else c.current = null;
    }
    function Mj(a, b2, c) {
      try {
        c();
      } catch (d2) {
        W(a, b2, d2);
      }
    }
    var Nj = false;
    function Oj(a, b2) {
      Cf = dd;
      a = Me();
      if (Ne(a)) {
        if ("selectionStart" in a) var c = { start: a.selectionStart, end: a.selectionEnd };
        else a: {
          c = (c = a.ownerDocument) && c.defaultView || window;
          var d2 = c.getSelection && c.getSelection();
          if (d2 && 0 !== d2.rangeCount) {
            c = d2.anchorNode;
            var e3 = d2.anchorOffset, f = d2.focusNode;
            d2 = d2.focusOffset;
            try {
              c.nodeType, f.nodeType;
            } catch (F) {
              c = null;
              break a;
            }
            var g = 0, h2 = -1, k = -1, l2 = 0, m2 = 0, q = a, r3 = null;
            b: for (; ; ) {
              for (var y2; ; ) {
                q !== c || 0 !== e3 && 3 !== q.nodeType || (h2 = g + e3);
                q !== f || 0 !== d2 && 3 !== q.nodeType || (k = g + d2);
                3 === q.nodeType && (g += q.nodeValue.length);
                if (null === (y2 = q.firstChild)) break;
                r3 = q;
                q = y2;
              }
              for (; ; ) {
                if (q === a) break b;
                r3 === c && ++l2 === e3 && (h2 = g);
                r3 === f && ++m2 === d2 && (k = g);
                if (null !== (y2 = q.nextSibling)) break;
                q = r3;
                r3 = q.parentNode;
              }
              q = y2;
            }
            c = -1 === h2 || -1 === k ? null : { start: h2, end: k };
          } else c = null;
        }
        c = c || { start: 0, end: 0 };
      } else c = null;
      Df = { focusedElem: a, selectionRange: c };
      dd = false;
      for (V = b2; null !== V; ) if (b2 = V, a = b2.child, 0 !== (b2.subtreeFlags & 1028) && null !== a) a.return = b2, V = a;
      else for (; null !== V; ) {
        b2 = V;
        try {
          var n3 = b2.alternate;
          if (0 !== (b2.flags & 1024)) switch (b2.tag) {
            case 0:
            case 11:
            case 15:
              break;
            case 1:
              if (null !== n3) {
                var t2 = n3.memoizedProps, J = n3.memoizedState, x = b2.stateNode, w2 = x.getSnapshotBeforeUpdate(b2.elementType === b2.type ? t2 : Ci(b2.type, t2), J);
                x.__reactInternalSnapshotBeforeUpdate = w2;
              }
              break;
            case 3:
              var u2 = b2.stateNode.containerInfo;
              1 === u2.nodeType ? u2.textContent = "" : 9 === u2.nodeType && u2.documentElement && u2.removeChild(u2.documentElement);
              break;
            case 5:
            case 6:
            case 4:
            case 17:
              break;
            default:
              throw Error(p2(163));
          }
        } catch (F) {
          W(b2, b2.return, F);
        }
        a = b2.sibling;
        if (null !== a) {
          a.return = b2.return;
          V = a;
          break;
        }
        V = b2.return;
      }
      n3 = Nj;
      Nj = false;
      return n3;
    }
    function Pj(a, b2, c) {
      var d2 = b2.updateQueue;
      d2 = null !== d2 ? d2.lastEffect : null;
      if (null !== d2) {
        var e3 = d2 = d2.next;
        do {
          if ((e3.tag & a) === a) {
            var f = e3.destroy;
            e3.destroy = void 0;
            void 0 !== f && Mj(b2, c, f);
          }
          e3 = e3.next;
        } while (e3 !== d2);
      }
    }
    function Qj(a, b2) {
      b2 = b2.updateQueue;
      b2 = null !== b2 ? b2.lastEffect : null;
      if (null !== b2) {
        var c = b2 = b2.next;
        do {
          if ((c.tag & a) === a) {
            var d2 = c.create;
            c.destroy = d2();
          }
          c = c.next;
        } while (c !== b2);
      }
    }
    function Rj(a) {
      var b2 = a.ref;
      if (null !== b2) {
        var c = a.stateNode;
        switch (a.tag) {
          case 5:
            a = c;
            break;
          default:
            a = c;
        }
        "function" === typeof b2 ? b2(a) : b2.current = a;
      }
    }
    function Sj(a) {
      var b2 = a.alternate;
      null !== b2 && (a.alternate = null, Sj(b2));
      a.child = null;
      a.deletions = null;
      a.sibling = null;
      5 === a.tag && (b2 = a.stateNode, null !== b2 && (delete b2[Of], delete b2[Pf], delete b2[of], delete b2[Qf], delete b2[Rf]));
      a.stateNode = null;
      a.return = null;
      a.dependencies = null;
      a.memoizedProps = null;
      a.memoizedState = null;
      a.pendingProps = null;
      a.stateNode = null;
      a.updateQueue = null;
    }
    function Tj(a) {
      return 5 === a.tag || 3 === a.tag || 4 === a.tag;
    }
    function Uj(a) {
      a: for (; ; ) {
        for (; null === a.sibling; ) {
          if (null === a.return || Tj(a.return)) return null;
          a = a.return;
        }
        a.sibling.return = a.return;
        for (a = a.sibling; 5 !== a.tag && 6 !== a.tag && 18 !== a.tag; ) {
          if (a.flags & 2) continue a;
          if (null === a.child || 4 === a.tag) continue a;
          else a.child.return = a, a = a.child;
        }
        if (!(a.flags & 2)) return a.stateNode;
      }
    }
    function Vj(a, b2, c) {
      var d2 = a.tag;
      if (5 === d2 || 6 === d2) a = a.stateNode, b2 ? 8 === c.nodeType ? c.parentNode.insertBefore(a, b2) : c.insertBefore(a, b2) : (8 === c.nodeType ? (b2 = c.parentNode, b2.insertBefore(a, c)) : (b2 = c, b2.appendChild(a)), c = c._reactRootContainer, null !== c && void 0 !== c || null !== b2.onclick || (b2.onclick = Bf));
      else if (4 !== d2 && (a = a.child, null !== a)) for (Vj(a, b2, c), a = a.sibling; null !== a; ) Vj(a, b2, c), a = a.sibling;
    }
    function Wj(a, b2, c) {
      var d2 = a.tag;
      if (5 === d2 || 6 === d2) a = a.stateNode, b2 ? c.insertBefore(a, b2) : c.appendChild(a);
      else if (4 !== d2 && (a = a.child, null !== a)) for (Wj(a, b2, c), a = a.sibling; null !== a; ) Wj(a, b2, c), a = a.sibling;
    }
    var X = null;
    var Xj = false;
    function Yj(a, b2, c) {
      for (c = c.child; null !== c; ) Zj(a, b2, c), c = c.sibling;
    }
    function Zj(a, b2, c) {
      if (lc && "function" === typeof lc.onCommitFiberUnmount) try {
        lc.onCommitFiberUnmount(kc, c);
      } catch (h2) {
      }
      switch (c.tag) {
        case 5:
          U || Lj(c, b2);
        case 6:
          var d2 = X, e3 = Xj;
          X = null;
          Yj(a, b2, c);
          X = d2;
          Xj = e3;
          null !== X && (Xj ? (a = X, c = c.stateNode, 8 === a.nodeType ? a.parentNode.removeChild(c) : a.removeChild(c)) : X.removeChild(c.stateNode));
          break;
        case 18:
          null !== X && (Xj ? (a = X, c = c.stateNode, 8 === a.nodeType ? Kf(a.parentNode, c) : 1 === a.nodeType && Kf(a, c), bd(a)) : Kf(X, c.stateNode));
          break;
        case 4:
          d2 = X;
          e3 = Xj;
          X = c.stateNode.containerInfo;
          Xj = true;
          Yj(a, b2, c);
          X = d2;
          Xj = e3;
          break;
        case 0:
        case 11:
        case 14:
        case 15:
          if (!U && (d2 = c.updateQueue, null !== d2 && (d2 = d2.lastEffect, null !== d2))) {
            e3 = d2 = d2.next;
            do {
              var f = e3, g = f.destroy;
              f = f.tag;
              void 0 !== g && (0 !== (f & 2) ? Mj(c, b2, g) : 0 !== (f & 4) && Mj(c, b2, g));
              e3 = e3.next;
            } while (e3 !== d2);
          }
          Yj(a, b2, c);
          break;
        case 1:
          if (!U && (Lj(c, b2), d2 = c.stateNode, "function" === typeof d2.componentWillUnmount)) try {
            d2.props = c.memoizedProps, d2.state = c.memoizedState, d2.componentWillUnmount();
          } catch (h2) {
            W(c, b2, h2);
          }
          Yj(a, b2, c);
          break;
        case 21:
          Yj(a, b2, c);
          break;
        case 22:
          c.mode & 1 ? (U = (d2 = U) || null !== c.memoizedState, Yj(a, b2, c), U = d2) : Yj(a, b2, c);
          break;
        default:
          Yj(a, b2, c);
      }
    }
    function ak(a) {
      var b2 = a.updateQueue;
      if (null !== b2) {
        a.updateQueue = null;
        var c = a.stateNode;
        null === c && (c = a.stateNode = new Kj());
        b2.forEach(function(b3) {
          var d2 = bk.bind(null, a, b3);
          c.has(b3) || (c.add(b3), b3.then(d2, d2));
        });
      }
    }
    function ck(a, b2) {
      var c = b2.deletions;
      if (null !== c) for (var d2 = 0; d2 < c.length; d2++) {
        var e3 = c[d2];
        try {
          var f = a, g = b2, h2 = g;
          a: for (; null !== h2; ) {
            switch (h2.tag) {
              case 5:
                X = h2.stateNode;
                Xj = false;
                break a;
              case 3:
                X = h2.stateNode.containerInfo;
                Xj = true;
                break a;
              case 4:
                X = h2.stateNode.containerInfo;
                Xj = true;
                break a;
            }
            h2 = h2.return;
          }
          if (null === X) throw Error(p2(160));
          Zj(f, g, e3);
          X = null;
          Xj = false;
          var k = e3.alternate;
          null !== k && (k.return = null);
          e3.return = null;
        } catch (l2) {
          W(e3, b2, l2);
        }
      }
      if (b2.subtreeFlags & 12854) for (b2 = b2.child; null !== b2; ) dk(b2, a), b2 = b2.sibling;
    }
    function dk(a, b2) {
      var c = a.alternate, d2 = a.flags;
      switch (a.tag) {
        case 0:
        case 11:
        case 14:
        case 15:
          ck(b2, a);
          ek(a);
          if (d2 & 4) {
            try {
              Pj(3, a, a.return), Qj(3, a);
            } catch (t2) {
              W(a, a.return, t2);
            }
            try {
              Pj(5, a, a.return);
            } catch (t2) {
              W(a, a.return, t2);
            }
          }
          break;
        case 1:
          ck(b2, a);
          ek(a);
          d2 & 512 && null !== c && Lj(c, c.return);
          break;
        case 5:
          ck(b2, a);
          ek(a);
          d2 & 512 && null !== c && Lj(c, c.return);
          if (a.flags & 32) {
            var e3 = a.stateNode;
            try {
              ob(e3, "");
            } catch (t2) {
              W(a, a.return, t2);
            }
          }
          if (d2 & 4 && (e3 = a.stateNode, null != e3)) {
            var f = a.memoizedProps, g = null !== c ? c.memoizedProps : f, h2 = a.type, k = a.updateQueue;
            a.updateQueue = null;
            if (null !== k) try {
              "input" === h2 && "radio" === f.type && null != f.name && ab(e3, f);
              vb(h2, g);
              var l2 = vb(h2, f);
              for (g = 0; g < k.length; g += 2) {
                var m2 = k[g], q = k[g + 1];
                "style" === m2 ? sb(e3, q) : "dangerouslySetInnerHTML" === m2 ? nb(e3, q) : "children" === m2 ? ob(e3, q) : ta(e3, m2, q, l2);
              }
              switch (h2) {
                case "input":
                  bb(e3, f);
                  break;
                case "textarea":
                  ib(e3, f);
                  break;
                case "select":
                  var r3 = e3._wrapperState.wasMultiple;
                  e3._wrapperState.wasMultiple = !!f.multiple;
                  var y2 = f.value;
                  null != y2 ? fb(e3, !!f.multiple, y2, false) : r3 !== !!f.multiple && (null != f.defaultValue ? fb(
                    e3,
                    !!f.multiple,
                    f.defaultValue,
                    true
                  ) : fb(e3, !!f.multiple, f.multiple ? [] : "", false));
              }
              e3[Pf] = f;
            } catch (t2) {
              W(a, a.return, t2);
            }
          }
          break;
        case 6:
          ck(b2, a);
          ek(a);
          if (d2 & 4) {
            if (null === a.stateNode) throw Error(p2(162));
            e3 = a.stateNode;
            f = a.memoizedProps;
            try {
              e3.nodeValue = f;
            } catch (t2) {
              W(a, a.return, t2);
            }
          }
          break;
        case 3:
          ck(b2, a);
          ek(a);
          if (d2 & 4 && null !== c && c.memoizedState.isDehydrated) try {
            bd(b2.containerInfo);
          } catch (t2) {
            W(a, a.return, t2);
          }
          break;
        case 4:
          ck(b2, a);
          ek(a);
          break;
        case 13:
          ck(b2, a);
          ek(a);
          e3 = a.child;
          e3.flags & 8192 && (f = null !== e3.memoizedState, e3.stateNode.isHidden = f, !f || null !== e3.alternate && null !== e3.alternate.memoizedState || (fk = B2()));
          d2 & 4 && ak(a);
          break;
        case 22:
          m2 = null !== c && null !== c.memoizedState;
          a.mode & 1 ? (U = (l2 = U) || m2, ck(b2, a), U = l2) : ck(b2, a);
          ek(a);
          if (d2 & 8192) {
            l2 = null !== a.memoizedState;
            if ((a.stateNode.isHidden = l2) && !m2 && 0 !== (a.mode & 1)) for (V = a, m2 = a.child; null !== m2; ) {
              for (q = V = m2; null !== V; ) {
                r3 = V;
                y2 = r3.child;
                switch (r3.tag) {
                  case 0:
                  case 11:
                  case 14:
                  case 15:
                    Pj(4, r3, r3.return);
                    break;
                  case 1:
                    Lj(r3, r3.return);
                    var n3 = r3.stateNode;
                    if ("function" === typeof n3.componentWillUnmount) {
                      d2 = r3;
                      c = r3.return;
                      try {
                        b2 = d2, n3.props = b2.memoizedProps, n3.state = b2.memoizedState, n3.componentWillUnmount();
                      } catch (t2) {
                        W(d2, c, t2);
                      }
                    }
                    break;
                  case 5:
                    Lj(r3, r3.return);
                    break;
                  case 22:
                    if (null !== r3.memoizedState) {
                      gk(q);
                      continue;
                    }
                }
                null !== y2 ? (y2.return = r3, V = y2) : gk(q);
              }
              m2 = m2.sibling;
            }
            a: for (m2 = null, q = a; ; ) {
              if (5 === q.tag) {
                if (null === m2) {
                  m2 = q;
                  try {
                    e3 = q.stateNode, l2 ? (f = e3.style, "function" === typeof f.setProperty ? f.setProperty("display", "none", "important") : f.display = "none") : (h2 = q.stateNode, k = q.memoizedProps.style, g = void 0 !== k && null !== k && k.hasOwnProperty("display") ? k.display : null, h2.style.display = rb("display", g));
                  } catch (t2) {
                    W(a, a.return, t2);
                  }
                }
              } else if (6 === q.tag) {
                if (null === m2) try {
                  q.stateNode.nodeValue = l2 ? "" : q.memoizedProps;
                } catch (t2) {
                  W(a, a.return, t2);
                }
              } else if ((22 !== q.tag && 23 !== q.tag || null === q.memoizedState || q === a) && null !== q.child) {
                q.child.return = q;
                q = q.child;
                continue;
              }
              if (q === a) break a;
              for (; null === q.sibling; ) {
                if (null === q.return || q.return === a) break a;
                m2 === q && (m2 = null);
                q = q.return;
              }
              m2 === q && (m2 = null);
              q.sibling.return = q.return;
              q = q.sibling;
            }
          }
          break;
        case 19:
          ck(b2, a);
          ek(a);
          d2 & 4 && ak(a);
          break;
        case 21:
          break;
        default:
          ck(
            b2,
            a
          ), ek(a);
      }
    }
    function ek(a) {
      var b2 = a.flags;
      if (b2 & 2) {
        try {
          a: {
            for (var c = a.return; null !== c; ) {
              if (Tj(c)) {
                var d2 = c;
                break a;
              }
              c = c.return;
            }
            throw Error(p2(160));
          }
          switch (d2.tag) {
            case 5:
              var e3 = d2.stateNode;
              d2.flags & 32 && (ob(e3, ""), d2.flags &= -33);
              var f = Uj(a);
              Wj(a, f, e3);
              break;
            case 3:
            case 4:
              var g = d2.stateNode.containerInfo, h2 = Uj(a);
              Vj(a, h2, g);
              break;
            default:
              throw Error(p2(161));
          }
        } catch (k) {
          W(a, a.return, k);
        }
        a.flags &= -3;
      }
      b2 & 4096 && (a.flags &= -4097);
    }
    function hk(a, b2, c) {
      V = a;
      ik(a, b2, c);
    }
    function ik(a, b2, c) {
      for (var d2 = 0 !== (a.mode & 1); null !== V; ) {
        var e3 = V, f = e3.child;
        if (22 === e3.tag && d2) {
          var g = null !== e3.memoizedState || Jj;
          if (!g) {
            var h2 = e3.alternate, k = null !== h2 && null !== h2.memoizedState || U;
            h2 = Jj;
            var l2 = U;
            Jj = g;
            if ((U = k) && !l2) for (V = e3; null !== V; ) g = V, k = g.child, 22 === g.tag && null !== g.memoizedState ? jk(e3) : null !== k ? (k.return = g, V = k) : jk(e3);
            for (; null !== f; ) V = f, ik(f, b2, c), f = f.sibling;
            V = e3;
            Jj = h2;
            U = l2;
          }
          kk(a, b2, c);
        } else 0 !== (e3.subtreeFlags & 8772) && null !== f ? (f.return = e3, V = f) : kk(a, b2, c);
      }
    }
    function kk(a) {
      for (; null !== V; ) {
        var b2 = V;
        if (0 !== (b2.flags & 8772)) {
          var c = b2.alternate;
          try {
            if (0 !== (b2.flags & 8772)) switch (b2.tag) {
              case 0:
              case 11:
              case 15:
                U || Qj(5, b2);
                break;
              case 1:
                var d2 = b2.stateNode;
                if (b2.flags & 4 && !U) if (null === c) d2.componentDidMount();
                else {
                  var e3 = b2.elementType === b2.type ? c.memoizedProps : Ci(b2.type, c.memoizedProps);
                  d2.componentDidUpdate(e3, c.memoizedState, d2.__reactInternalSnapshotBeforeUpdate);
                }
                var f = b2.updateQueue;
                null !== f && sh(b2, f, d2);
                break;
              case 3:
                var g = b2.updateQueue;
                if (null !== g) {
                  c = null;
                  if (null !== b2.child) switch (b2.child.tag) {
                    case 5:
                      c = b2.child.stateNode;
                      break;
                    case 1:
                      c = b2.child.stateNode;
                  }
                  sh(b2, g, c);
                }
                break;
              case 5:
                var h2 = b2.stateNode;
                if (null === c && b2.flags & 4) {
                  c = h2;
                  var k = b2.memoizedProps;
                  switch (b2.type) {
                    case "button":
                    case "input":
                    case "select":
                    case "textarea":
                      k.autoFocus && c.focus();
                      break;
                    case "img":
                      k.src && (c.src = k.src);
                  }
                }
                break;
              case 6:
                break;
              case 4:
                break;
              case 12:
                break;
              case 13:
                if (null === b2.memoizedState) {
                  var l2 = b2.alternate;
                  if (null !== l2) {
                    var m2 = l2.memoizedState;
                    if (null !== m2) {
                      var q = m2.dehydrated;
                      null !== q && bd(q);
                    }
                  }
                }
                break;
              case 19:
              case 17:
              case 21:
              case 22:
              case 23:
              case 25:
                break;
              default:
                throw Error(p2(163));
            }
            U || b2.flags & 512 && Rj(b2);
          } catch (r3) {
            W(b2, b2.return, r3);
          }
        }
        if (b2 === a) {
          V = null;
          break;
        }
        c = b2.sibling;
        if (null !== c) {
          c.return = b2.return;
          V = c;
          break;
        }
        V = b2.return;
      }
    }
    function gk(a) {
      for (; null !== V; ) {
        var b2 = V;
        if (b2 === a) {
          V = null;
          break;
        }
        var c = b2.sibling;
        if (null !== c) {
          c.return = b2.return;
          V = c;
          break;
        }
        V = b2.return;
      }
    }
    function jk(a) {
      for (; null !== V; ) {
        var b2 = V;
        try {
          switch (b2.tag) {
            case 0:
            case 11:
            case 15:
              var c = b2.return;
              try {
                Qj(4, b2);
              } catch (k) {
                W(b2, c, k);
              }
              break;
            case 1:
              var d2 = b2.stateNode;
              if ("function" === typeof d2.componentDidMount) {
                var e3 = b2.return;
                try {
                  d2.componentDidMount();
                } catch (k) {
                  W(b2, e3, k);
                }
              }
              var f = b2.return;
              try {
                Rj(b2);
              } catch (k) {
                W(b2, f, k);
              }
              break;
            case 5:
              var g = b2.return;
              try {
                Rj(b2);
              } catch (k) {
                W(b2, g, k);
              }
          }
        } catch (k) {
          W(b2, b2.return, k);
        }
        if (b2 === a) {
          V = null;
          break;
        }
        var h2 = b2.sibling;
        if (null !== h2) {
          h2.return = b2.return;
          V = h2;
          break;
        }
        V = b2.return;
      }
    }
    var lk = Math.ceil;
    var mk = ua.ReactCurrentDispatcher;
    var nk = ua.ReactCurrentOwner;
    var ok = ua.ReactCurrentBatchConfig;
    var K = 0;
    var Q = null;
    var Y = null;
    var Z = 0;
    var fj = 0;
    var ej = Uf(0);
    var T = 0;
    var pk = null;
    var rh = 0;
    var qk = 0;
    var rk = 0;
    var sk = null;
    var tk = null;
    var fk = 0;
    var Gj = Infinity;
    var uk = null;
    var Oi = false;
    var Pi = null;
    var Ri = null;
    var vk = false;
    var wk = null;
    var xk = 0;
    var yk = 0;
    var zk = null;
    var Ak = -1;
    var Bk = 0;
    function R2() {
      return 0 !== (K & 6) ? B2() : -1 !== Ak ? Ak : Ak = B2();
    }
    function yi(a) {
      if (0 === (a.mode & 1)) return 1;
      if (0 !== (K & 2) && 0 !== Z) return Z & -Z;
      if (null !== Kg.transition) return 0 === Bk && (Bk = yc()), Bk;
      a = C;
      if (0 !== a) return a;
      a = window.event;
      a = void 0 === a ? 16 : jd(a.type);
      return a;
    }
    function gi(a, b2, c, d2) {
      if (50 < yk) throw yk = 0, zk = null, Error(p2(185));
      Ac(a, c, d2);
      if (0 === (K & 2) || a !== Q) a === Q && (0 === (K & 2) && (qk |= c), 4 === T && Ck(a, Z)), Dk(a, d2), 1 === c && 0 === K && 0 === (b2.mode & 1) && (Gj = B2() + 500, fg && jg());
    }
    function Dk(a, b2) {
      var c = a.callbackNode;
      wc(a, b2);
      var d2 = uc(a, a === Q ? Z : 0);
      if (0 === d2) null !== c && bc(c), a.callbackNode = null, a.callbackPriority = 0;
      else if (b2 = d2 & -d2, a.callbackPriority !== b2) {
        null != c && bc(c);
        if (1 === b2) 0 === a.tag ? ig(Ek.bind(null, a)) : hg(Ek.bind(null, a)), Jf(function() {
          0 === (K & 6) && jg();
        }), c = null;
        else {
          switch (Dc(d2)) {
            case 1:
              c = fc;
              break;
            case 4:
              c = gc;
              break;
            case 16:
              c = hc;
              break;
            case 536870912:
              c = jc;
              break;
            default:
              c = hc;
          }
          c = Fk(c, Gk.bind(null, a));
        }
        a.callbackPriority = b2;
        a.callbackNode = c;
      }
    }
    function Gk(a, b2) {
      Ak = -1;
      Bk = 0;
      if (0 !== (K & 6)) throw Error(p2(327));
      var c = a.callbackNode;
      if (Hk() && a.callbackNode !== c) return null;
      var d2 = uc(a, a === Q ? Z : 0);
      if (0 === d2) return null;
      if (0 !== (d2 & 30) || 0 !== (d2 & a.expiredLanes) || b2) b2 = Ik(a, d2);
      else {
        b2 = d2;
        var e3 = K;
        K |= 2;
        var f = Jk();
        if (Q !== a || Z !== b2) uk = null, Gj = B2() + 500, Kk(a, b2);
        do
          try {
            Lk();
            break;
          } catch (h2) {
            Mk(a, h2);
          }
        while (1);
        $g();
        mk.current = f;
        K = e3;
        null !== Y ? b2 = 0 : (Q = null, Z = 0, b2 = T);
      }
      if (0 !== b2) {
        2 === b2 && (e3 = xc(a), 0 !== e3 && (d2 = e3, b2 = Nk(a, e3)));
        if (1 === b2) throw c = pk, Kk(a, 0), Ck(a, d2), Dk(a, B2()), c;
        if (6 === b2) Ck(a, d2);
        else {
          e3 = a.current.alternate;
          if (0 === (d2 & 30) && !Ok(e3) && (b2 = Ik(a, d2), 2 === b2 && (f = xc(a), 0 !== f && (d2 = f, b2 = Nk(a, f))), 1 === b2)) throw c = pk, Kk(a, 0), Ck(a, d2), Dk(a, B2()), c;
          a.finishedWork = e3;
          a.finishedLanes = d2;
          switch (b2) {
            case 0:
            case 1:
              throw Error(p2(345));
            case 2:
              Pk(a, tk, uk);
              break;
            case 3:
              Ck(a, d2);
              if ((d2 & 130023424) === d2 && (b2 = fk + 500 - B2(), 10 < b2)) {
                if (0 !== uc(a, 0)) break;
                e3 = a.suspendedLanes;
                if ((e3 & d2) !== d2) {
                  R2();
                  a.pingedLanes |= a.suspendedLanes & e3;
                  break;
                }
                a.timeoutHandle = Ff(Pk.bind(null, a, tk, uk), b2);
                break;
              }
              Pk(a, tk, uk);
              break;
            case 4:
              Ck(a, d2);
              if ((d2 & 4194240) === d2) break;
              b2 = a.eventTimes;
              for (e3 = -1; 0 < d2; ) {
                var g = 31 - oc(d2);
                f = 1 << g;
                g = b2[g];
                g > e3 && (e3 = g);
                d2 &= ~f;
              }
              d2 = e3;
              d2 = B2() - d2;
              d2 = (120 > d2 ? 120 : 480 > d2 ? 480 : 1080 > d2 ? 1080 : 1920 > d2 ? 1920 : 3e3 > d2 ? 3e3 : 4320 > d2 ? 4320 : 1960 * lk(d2 / 1960)) - d2;
              if (10 < d2) {
                a.timeoutHandle = Ff(Pk.bind(null, a, tk, uk), d2);
                break;
              }
              Pk(a, tk, uk);
              break;
            case 5:
              Pk(a, tk, uk);
              break;
            default:
              throw Error(p2(329));
          }
        }
      }
      Dk(a, B2());
      return a.callbackNode === c ? Gk.bind(null, a) : null;
    }
    function Nk(a, b2) {
      var c = sk;
      a.current.memoizedState.isDehydrated && (Kk(a, b2).flags |= 256);
      a = Ik(a, b2);
      2 !== a && (b2 = tk, tk = c, null !== b2 && Fj(b2));
      return a;
    }
    function Fj(a) {
      null === tk ? tk = a : tk.push.apply(tk, a);
    }
    function Ok(a) {
      for (var b2 = a; ; ) {
        if (b2.flags & 16384) {
          var c = b2.updateQueue;
          if (null !== c && (c = c.stores, null !== c)) for (var d2 = 0; d2 < c.length; d2++) {
            var e3 = c[d2], f = e3.getSnapshot;
            e3 = e3.value;
            try {
              if (!He(f(), e3)) return false;
            } catch (g) {
              return false;
            }
          }
        }
        c = b2.child;
        if (b2.subtreeFlags & 16384 && null !== c) c.return = b2, b2 = c;
        else {
          if (b2 === a) break;
          for (; null === b2.sibling; ) {
            if (null === b2.return || b2.return === a) return true;
            b2 = b2.return;
          }
          b2.sibling.return = b2.return;
          b2 = b2.sibling;
        }
      }
      return true;
    }
    function Ck(a, b2) {
      b2 &= ~rk;
      b2 &= ~qk;
      a.suspendedLanes |= b2;
      a.pingedLanes &= ~b2;
      for (a = a.expirationTimes; 0 < b2; ) {
        var c = 31 - oc(b2), d2 = 1 << c;
        a[c] = -1;
        b2 &= ~d2;
      }
    }
    function Ek(a) {
      if (0 !== (K & 6)) throw Error(p2(327));
      Hk();
      var b2 = uc(a, 0);
      if (0 === (b2 & 1)) return Dk(a, B2()), null;
      var c = Ik(a, b2);
      if (0 !== a.tag && 2 === c) {
        var d2 = xc(a);
        0 !== d2 && (b2 = d2, c = Nk(a, d2));
      }
      if (1 === c) throw c = pk, Kk(a, 0), Ck(a, b2), Dk(a, B2()), c;
      if (6 === c) throw Error(p2(345));
      a.finishedWork = a.current.alternate;
      a.finishedLanes = b2;
      Pk(a, tk, uk);
      Dk(a, B2());
      return null;
    }
    function Qk(a, b2) {
      var c = K;
      K |= 1;
      try {
        return a(b2);
      } finally {
        K = c, 0 === K && (Gj = B2() + 500, fg && jg());
      }
    }
    function Rk(a) {
      null !== wk && 0 === wk.tag && 0 === (K & 6) && Hk();
      var b2 = K;
      K |= 1;
      var c = ok.transition, d2 = C;
      try {
        if (ok.transition = null, C = 1, a) return a();
      } finally {
        C = d2, ok.transition = c, K = b2, 0 === (K & 6) && jg();
      }
    }
    function Hj() {
      fj = ej.current;
      E(ej);
    }
    function Kk(a, b2) {
      a.finishedWork = null;
      a.finishedLanes = 0;
      var c = a.timeoutHandle;
      -1 !== c && (a.timeoutHandle = -1, Gf(c));
      if (null !== Y) for (c = Y.return; null !== c; ) {
        var d2 = c;
        wg(d2);
        switch (d2.tag) {
          case 1:
            d2 = d2.type.childContextTypes;
            null !== d2 && void 0 !== d2 && $f();
            break;
          case 3:
            zh();
            E(Wf);
            E(H);
            Eh();
            break;
          case 5:
            Bh(d2);
            break;
          case 4:
            zh();
            break;
          case 13:
            E(L);
            break;
          case 19:
            E(L);
            break;
          case 10:
            ah(d2.type._context);
            break;
          case 22:
          case 23:
            Hj();
        }
        c = c.return;
      }
      Q = a;
      Y = a = Pg(a.current, null);
      Z = fj = b2;
      T = 0;
      pk = null;
      rk = qk = rh = 0;
      tk = sk = null;
      if (null !== fh) {
        for (b2 = 0; b2 < fh.length; b2++) if (c = fh[b2], d2 = c.interleaved, null !== d2) {
          c.interleaved = null;
          var e3 = d2.next, f = c.pending;
          if (null !== f) {
            var g = f.next;
            f.next = e3;
            d2.next = g;
          }
          c.pending = d2;
        }
        fh = null;
      }
      return a;
    }
    function Mk(a, b2) {
      do {
        var c = Y;
        try {
          $g();
          Fh.current = Rh;
          if (Ih) {
            for (var d2 = M2.memoizedState; null !== d2; ) {
              var e3 = d2.queue;
              null !== e3 && (e3.pending = null);
              d2 = d2.next;
            }
            Ih = false;
          }
          Hh = 0;
          O = N2 = M2 = null;
          Jh = false;
          Kh = 0;
          nk.current = null;
          if (null === c || null === c.return) {
            T = 1;
            pk = b2;
            Y = null;
            break;
          }
          a: {
            var f = a, g = c.return, h2 = c, k = b2;
            b2 = Z;
            h2.flags |= 32768;
            if (null !== k && "object" === typeof k && "function" === typeof k.then) {
              var l2 = k, m2 = h2, q = m2.tag;
              if (0 === (m2.mode & 1) && (0 === q || 11 === q || 15 === q)) {
                var r3 = m2.alternate;
                r3 ? (m2.updateQueue = r3.updateQueue, m2.memoizedState = r3.memoizedState, m2.lanes = r3.lanes) : (m2.updateQueue = null, m2.memoizedState = null);
              }
              var y2 = Ui(g);
              if (null !== y2) {
                y2.flags &= -257;
                Vi(y2, g, h2, f, b2);
                y2.mode & 1 && Si(f, l2, b2);
                b2 = y2;
                k = l2;
                var n3 = b2.updateQueue;
                if (null === n3) {
                  var t2 = /* @__PURE__ */ new Set();
                  t2.add(k);
                  b2.updateQueue = t2;
                } else n3.add(k);
                break a;
              } else {
                if (0 === (b2 & 1)) {
                  Si(f, l2, b2);
                  tj();
                  break a;
                }
                k = Error(p2(426));
              }
            } else if (I2 && h2.mode & 1) {
              var J = Ui(g);
              if (null !== J) {
                0 === (J.flags & 65536) && (J.flags |= 256);
                Vi(J, g, h2, f, b2);
                Jg(Ji(k, h2));
                break a;
              }
            }
            f = k = Ji(k, h2);
            4 !== T && (T = 2);
            null === sk ? sk = [f] : sk.push(f);
            f = g;
            do {
              switch (f.tag) {
                case 3:
                  f.flags |= 65536;
                  b2 &= -b2;
                  f.lanes |= b2;
                  var x = Ni(f, k, b2);
                  ph(f, x);
                  break a;
                case 1:
                  h2 = k;
                  var w2 = f.type, u2 = f.stateNode;
                  if (0 === (f.flags & 128) && ("function" === typeof w2.getDerivedStateFromError || null !== u2 && "function" === typeof u2.componentDidCatch && (null === Ri || !Ri.has(u2)))) {
                    f.flags |= 65536;
                    b2 &= -b2;
                    f.lanes |= b2;
                    var F = Qi(f, h2, b2);
                    ph(f, F);
                    break a;
                  }
              }
              f = f.return;
            } while (null !== f);
          }
          Sk(c);
        } catch (na) {
          b2 = na;
          Y === c && null !== c && (Y = c = c.return);
          continue;
        }
        break;
      } while (1);
    }
    function Jk() {
      var a = mk.current;
      mk.current = Rh;
      return null === a ? Rh : a;
    }
    function tj() {
      if (0 === T || 3 === T || 2 === T) T = 4;
      null === Q || 0 === (rh & 268435455) && 0 === (qk & 268435455) || Ck(Q, Z);
    }
    function Ik(a, b2) {
      var c = K;
      K |= 2;
      var d2 = Jk();
      if (Q !== a || Z !== b2) uk = null, Kk(a, b2);
      do
        try {
          Tk();
          break;
        } catch (e3) {
          Mk(a, e3);
        }
      while (1);
      $g();
      K = c;
      mk.current = d2;
      if (null !== Y) throw Error(p2(261));
      Q = null;
      Z = 0;
      return T;
    }
    function Tk() {
      for (; null !== Y; ) Uk(Y);
    }
    function Lk() {
      for (; null !== Y && !cc(); ) Uk(Y);
    }
    function Uk(a) {
      var b2 = Vk(a.alternate, a, fj);
      a.memoizedProps = a.pendingProps;
      null === b2 ? Sk(a) : Y = b2;
      nk.current = null;
    }
    function Sk(a) {
      var b2 = a;
      do {
        var c = b2.alternate;
        a = b2.return;
        if (0 === (b2.flags & 32768)) {
          if (c = Ej(c, b2, fj), null !== c) {
            Y = c;
            return;
          }
        } else {
          c = Ij(c, b2);
          if (null !== c) {
            c.flags &= 32767;
            Y = c;
            return;
          }
          if (null !== a) a.flags |= 32768, a.subtreeFlags = 0, a.deletions = null;
          else {
            T = 6;
            Y = null;
            return;
          }
        }
        b2 = b2.sibling;
        if (null !== b2) {
          Y = b2;
          return;
        }
        Y = b2 = a;
      } while (null !== b2);
      0 === T && (T = 5);
    }
    function Pk(a, b2, c) {
      var d2 = C, e3 = ok.transition;
      try {
        ok.transition = null, C = 1, Wk(a, b2, c, d2);
      } finally {
        ok.transition = e3, C = d2;
      }
      return null;
    }
    function Wk(a, b2, c, d2) {
      do
        Hk();
      while (null !== wk);
      if (0 !== (K & 6)) throw Error(p2(327));
      c = a.finishedWork;
      var e3 = a.finishedLanes;
      if (null === c) return null;
      a.finishedWork = null;
      a.finishedLanes = 0;
      if (c === a.current) throw Error(p2(177));
      a.callbackNode = null;
      a.callbackPriority = 0;
      var f = c.lanes | c.childLanes;
      Bc(a, f);
      a === Q && (Y = Q = null, Z = 0);
      0 === (c.subtreeFlags & 2064) && 0 === (c.flags & 2064) || vk || (vk = true, Fk(hc, function() {
        Hk();
        return null;
      }));
      f = 0 !== (c.flags & 15990);
      if (0 !== (c.subtreeFlags & 15990) || f) {
        f = ok.transition;
        ok.transition = null;
        var g = C;
        C = 1;
        var h2 = K;
        K |= 4;
        nk.current = null;
        Oj(a, c);
        dk(c, a);
        Oe(Df);
        dd = !!Cf;
        Df = Cf = null;
        a.current = c;
        hk(c, a, e3);
        dc();
        K = h2;
        C = g;
        ok.transition = f;
      } else a.current = c;
      vk && (vk = false, wk = a, xk = e3);
      f = a.pendingLanes;
      0 === f && (Ri = null);
      mc(c.stateNode, d2);
      Dk(a, B2());
      if (null !== b2) for (d2 = a.onRecoverableError, c = 0; c < b2.length; c++) e3 = b2[c], d2(e3.value, { componentStack: e3.stack, digest: e3.digest });
      if (Oi) throw Oi = false, a = Pi, Pi = null, a;
      0 !== (xk & 1) && 0 !== a.tag && Hk();
      f = a.pendingLanes;
      0 !== (f & 1) ? a === zk ? yk++ : (yk = 0, zk = a) : yk = 0;
      jg();
      return null;
    }
    function Hk() {
      if (null !== wk) {
        var a = Dc(xk), b2 = ok.transition, c = C;
        try {
          ok.transition = null;
          C = 16 > a ? 16 : a;
          if (null === wk) var d2 = false;
          else {
            a = wk;
            wk = null;
            xk = 0;
            if (0 !== (K & 6)) throw Error(p2(331));
            var e3 = K;
            K |= 4;
            for (V = a.current; null !== V; ) {
              var f = V, g = f.child;
              if (0 !== (V.flags & 16)) {
                var h2 = f.deletions;
                if (null !== h2) {
                  for (var k = 0; k < h2.length; k++) {
                    var l2 = h2[k];
                    for (V = l2; null !== V; ) {
                      var m2 = V;
                      switch (m2.tag) {
                        case 0:
                        case 11:
                        case 15:
                          Pj(8, m2, f);
                      }
                      var q = m2.child;
                      if (null !== q) q.return = m2, V = q;
                      else for (; null !== V; ) {
                        m2 = V;
                        var r3 = m2.sibling, y2 = m2.return;
                        Sj(m2);
                        if (m2 === l2) {
                          V = null;
                          break;
                        }
                        if (null !== r3) {
                          r3.return = y2;
                          V = r3;
                          break;
                        }
                        V = y2;
                      }
                    }
                  }
                  var n3 = f.alternate;
                  if (null !== n3) {
                    var t2 = n3.child;
                    if (null !== t2) {
                      n3.child = null;
                      do {
                        var J = t2.sibling;
                        t2.sibling = null;
                        t2 = J;
                      } while (null !== t2);
                    }
                  }
                  V = f;
                }
              }
              if (0 !== (f.subtreeFlags & 2064) && null !== g) g.return = f, V = g;
              else b: for (; null !== V; ) {
                f = V;
                if (0 !== (f.flags & 2048)) switch (f.tag) {
                  case 0:
                  case 11:
                  case 15:
                    Pj(9, f, f.return);
                }
                var x = f.sibling;
                if (null !== x) {
                  x.return = f.return;
                  V = x;
                  break b;
                }
                V = f.return;
              }
            }
            var w2 = a.current;
            for (V = w2; null !== V; ) {
              g = V;
              var u2 = g.child;
              if (0 !== (g.subtreeFlags & 2064) && null !== u2) u2.return = g, V = u2;
              else b: for (g = w2; null !== V; ) {
                h2 = V;
                if (0 !== (h2.flags & 2048)) try {
                  switch (h2.tag) {
                    case 0:
                    case 11:
                    case 15:
                      Qj(9, h2);
                  }
                } catch (na) {
                  W(h2, h2.return, na);
                }
                if (h2 === g) {
                  V = null;
                  break b;
                }
                var F = h2.sibling;
                if (null !== F) {
                  F.return = h2.return;
                  V = F;
                  break b;
                }
                V = h2.return;
              }
            }
            K = e3;
            jg();
            if (lc && "function" === typeof lc.onPostCommitFiberRoot) try {
              lc.onPostCommitFiberRoot(kc, a);
            } catch (na) {
            }
            d2 = true;
          }
          return d2;
        } finally {
          C = c, ok.transition = b2;
        }
      }
      return false;
    }
    function Xk(a, b2, c) {
      b2 = Ji(c, b2);
      b2 = Ni(a, b2, 1);
      a = nh(a, b2, 1);
      b2 = R2();
      null !== a && (Ac(a, 1, b2), Dk(a, b2));
    }
    function W(a, b2, c) {
      if (3 === a.tag) Xk(a, a, c);
      else for (; null !== b2; ) {
        if (3 === b2.tag) {
          Xk(b2, a, c);
          break;
        } else if (1 === b2.tag) {
          var d2 = b2.stateNode;
          if ("function" === typeof b2.type.getDerivedStateFromError || "function" === typeof d2.componentDidCatch && (null === Ri || !Ri.has(d2))) {
            a = Ji(c, a);
            a = Qi(b2, a, 1);
            b2 = nh(b2, a, 1);
            a = R2();
            null !== b2 && (Ac(b2, 1, a), Dk(b2, a));
            break;
          }
        }
        b2 = b2.return;
      }
    }
    function Ti(a, b2, c) {
      var d2 = a.pingCache;
      null !== d2 && d2.delete(b2);
      b2 = R2();
      a.pingedLanes |= a.suspendedLanes & c;
      Q === a && (Z & c) === c && (4 === T || 3 === T && (Z & 130023424) === Z && 500 > B2() - fk ? Kk(a, 0) : rk |= c);
      Dk(a, b2);
    }
    function Yk(a, b2) {
      0 === b2 && (0 === (a.mode & 1) ? b2 = 1 : (b2 = sc, sc <<= 1, 0 === (sc & 130023424) && (sc = 4194304)));
      var c = R2();
      a = ih(a, b2);
      null !== a && (Ac(a, b2, c), Dk(a, c));
    }
    function uj(a) {
      var b2 = a.memoizedState, c = 0;
      null !== b2 && (c = b2.retryLane);
      Yk(a, c);
    }
    function bk(a, b2) {
      var c = 0;
      switch (a.tag) {
        case 13:
          var d2 = a.stateNode;
          var e3 = a.memoizedState;
          null !== e3 && (c = e3.retryLane);
          break;
        case 19:
          d2 = a.stateNode;
          break;
        default:
          throw Error(p2(314));
      }
      null !== d2 && d2.delete(b2);
      Yk(a, c);
    }
    var Vk;
    Vk = function(a, b2, c) {
      if (null !== a) if (a.memoizedProps !== b2.pendingProps || Wf.current) dh = true;
      else {
        if (0 === (a.lanes & c) && 0 === (b2.flags & 128)) return dh = false, yj(a, b2, c);
        dh = 0 !== (a.flags & 131072) ? true : false;
      }
      else dh = false, I2 && 0 !== (b2.flags & 1048576) && ug(b2, ng, b2.index);
      b2.lanes = 0;
      switch (b2.tag) {
        case 2:
          var d2 = b2.type;
          ij(a, b2);
          a = b2.pendingProps;
          var e3 = Yf(b2, H.current);
          ch(b2, c);
          e3 = Nh(null, b2, d2, a, e3, c);
          var f = Sh();
          b2.flags |= 1;
          "object" === typeof e3 && null !== e3 && "function" === typeof e3.render && void 0 === e3.$$typeof ? (b2.tag = 1, b2.memoizedState = null, b2.updateQueue = null, Zf(d2) ? (f = true, cg(b2)) : f = false, b2.memoizedState = null !== e3.state && void 0 !== e3.state ? e3.state : null, kh(b2), e3.updater = Ei, b2.stateNode = e3, e3._reactInternals = b2, Ii(b2, d2, a, c), b2 = jj(null, b2, d2, true, f, c)) : (b2.tag = 0, I2 && f && vg(b2), Xi(null, b2, e3, c), b2 = b2.child);
          return b2;
        case 16:
          d2 = b2.elementType;
          a: {
            ij(a, b2);
            a = b2.pendingProps;
            e3 = d2._init;
            d2 = e3(d2._payload);
            b2.type = d2;
            e3 = b2.tag = Zk(d2);
            a = Ci(d2, a);
            switch (e3) {
              case 0:
                b2 = cj(null, b2, d2, a, c);
                break a;
              case 1:
                b2 = hj(null, b2, d2, a, c);
                break a;
              case 11:
                b2 = Yi(null, b2, d2, a, c);
                break a;
              case 14:
                b2 = $i(null, b2, d2, Ci(d2.type, a), c);
                break a;
            }
            throw Error(p2(
              306,
              d2,
              ""
            ));
          }
          return b2;
        case 0:
          return d2 = b2.type, e3 = b2.pendingProps, e3 = b2.elementType === d2 ? e3 : Ci(d2, e3), cj(a, b2, d2, e3, c);
        case 1:
          return d2 = b2.type, e3 = b2.pendingProps, e3 = b2.elementType === d2 ? e3 : Ci(d2, e3), hj(a, b2, d2, e3, c);
        case 3:
          a: {
            kj(b2);
            if (null === a) throw Error(p2(387));
            d2 = b2.pendingProps;
            f = b2.memoizedState;
            e3 = f.element;
            lh(a, b2);
            qh(b2, d2, null, c);
            var g = b2.memoizedState;
            d2 = g.element;
            if (f.isDehydrated) if (f = { element: d2, isDehydrated: false, cache: g.cache, pendingSuspenseBoundaries: g.pendingSuspenseBoundaries, transitions: g.transitions }, b2.updateQueue.baseState = f, b2.memoizedState = f, b2.flags & 256) {
              e3 = Ji(Error(p2(423)), b2);
              b2 = lj(a, b2, d2, c, e3);
              break a;
            } else if (d2 !== e3) {
              e3 = Ji(Error(p2(424)), b2);
              b2 = lj(a, b2, d2, c, e3);
              break a;
            } else for (yg = Lf(b2.stateNode.containerInfo.firstChild), xg = b2, I2 = true, zg = null, c = Vg(b2, null, d2, c), b2.child = c; c; ) c.flags = c.flags & -3 | 4096, c = c.sibling;
            else {
              Ig();
              if (d2 === e3) {
                b2 = Zi(a, b2, c);
                break a;
              }
              Xi(a, b2, d2, c);
            }
            b2 = b2.child;
          }
          return b2;
        case 5:
          return Ah(b2), null === a && Eg(b2), d2 = b2.type, e3 = b2.pendingProps, f = null !== a ? a.memoizedProps : null, g = e3.children, Ef(d2, e3) ? g = null : null !== f && Ef(d2, f) && (b2.flags |= 32), gj(a, b2), Xi(a, b2, g, c), b2.child;
        case 6:
          return null === a && Eg(b2), null;
        case 13:
          return oj(a, b2, c);
        case 4:
          return yh(b2, b2.stateNode.containerInfo), d2 = b2.pendingProps, null === a ? b2.child = Ug(b2, null, d2, c) : Xi(a, b2, d2, c), b2.child;
        case 11:
          return d2 = b2.type, e3 = b2.pendingProps, e3 = b2.elementType === d2 ? e3 : Ci(d2, e3), Yi(a, b2, d2, e3, c);
        case 7:
          return Xi(a, b2, b2.pendingProps, c), b2.child;
        case 8:
          return Xi(a, b2, b2.pendingProps.children, c), b2.child;
        case 12:
          return Xi(a, b2, b2.pendingProps.children, c), b2.child;
        case 10:
          a: {
            d2 = b2.type._context;
            e3 = b2.pendingProps;
            f = b2.memoizedProps;
            g = e3.value;
            G3(Wg, d2._currentValue);
            d2._currentValue = g;
            if (null !== f) if (He(f.value, g)) {
              if (f.children === e3.children && !Wf.current) {
                b2 = Zi(a, b2, c);
                break a;
              }
            } else for (f = b2.child, null !== f && (f.return = b2); null !== f; ) {
              var h2 = f.dependencies;
              if (null !== h2) {
                g = f.child;
                for (var k = h2.firstContext; null !== k; ) {
                  if (k.context === d2) {
                    if (1 === f.tag) {
                      k = mh(-1, c & -c);
                      k.tag = 2;
                      var l2 = f.updateQueue;
                      if (null !== l2) {
                        l2 = l2.shared;
                        var m2 = l2.pending;
                        null === m2 ? k.next = k : (k.next = m2.next, m2.next = k);
                        l2.pending = k;
                      }
                    }
                    f.lanes |= c;
                    k = f.alternate;
                    null !== k && (k.lanes |= c);
                    bh(
                      f.return,
                      c,
                      b2
                    );
                    h2.lanes |= c;
                    break;
                  }
                  k = k.next;
                }
              } else if (10 === f.tag) g = f.type === b2.type ? null : f.child;
              else if (18 === f.tag) {
                g = f.return;
                if (null === g) throw Error(p2(341));
                g.lanes |= c;
                h2 = g.alternate;
                null !== h2 && (h2.lanes |= c);
                bh(g, c, b2);
                g = f.sibling;
              } else g = f.child;
              if (null !== g) g.return = f;
              else for (g = f; null !== g; ) {
                if (g === b2) {
                  g = null;
                  break;
                }
                f = g.sibling;
                if (null !== f) {
                  f.return = g.return;
                  g = f;
                  break;
                }
                g = g.return;
              }
              f = g;
            }
            Xi(a, b2, e3.children, c);
            b2 = b2.child;
          }
          return b2;
        case 9:
          return e3 = b2.type, d2 = b2.pendingProps.children, ch(b2, c), e3 = eh(e3), d2 = d2(e3), b2.flags |= 1, Xi(a, b2, d2, c), b2.child;
        case 14:
          return d2 = b2.type, e3 = Ci(d2, b2.pendingProps), e3 = Ci(d2.type, e3), $i(a, b2, d2, e3, c);
        case 15:
          return bj(a, b2, b2.type, b2.pendingProps, c);
        case 17:
          return d2 = b2.type, e3 = b2.pendingProps, e3 = b2.elementType === d2 ? e3 : Ci(d2, e3), ij(a, b2), b2.tag = 1, Zf(d2) ? (a = true, cg(b2)) : a = false, ch(b2, c), Gi(b2, d2, e3), Ii(b2, d2, e3, c), jj(null, b2, d2, true, a, c);
        case 19:
          return xj(a, b2, c);
        case 22:
          return dj(a, b2, c);
      }
      throw Error(p2(156, b2.tag));
    };
    function Fk(a, b2) {
      return ac(a, b2);
    }
    function $k(a, b2, c, d2) {
      this.tag = a;
      this.key = c;
      this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null;
      this.index = 0;
      this.ref = null;
      this.pendingProps = b2;
      this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null;
      this.mode = d2;
      this.subtreeFlags = this.flags = 0;
      this.deletions = null;
      this.childLanes = this.lanes = 0;
      this.alternate = null;
    }
    function Bg(a, b2, c, d2) {
      return new $k(a, b2, c, d2);
    }
    function aj(a) {
      a = a.prototype;
      return !(!a || !a.isReactComponent);
    }
    function Zk(a) {
      if ("function" === typeof a) return aj(a) ? 1 : 0;
      if (void 0 !== a && null !== a) {
        a = a.$$typeof;
        if (a === Da) return 11;
        if (a === Ga) return 14;
      }
      return 2;
    }
    function Pg(a, b2) {
      var c = a.alternate;
      null === c ? (c = Bg(a.tag, b2, a.key, a.mode), c.elementType = a.elementType, c.type = a.type, c.stateNode = a.stateNode, c.alternate = a, a.alternate = c) : (c.pendingProps = b2, c.type = a.type, c.flags = 0, c.subtreeFlags = 0, c.deletions = null);
      c.flags = a.flags & 14680064;
      c.childLanes = a.childLanes;
      c.lanes = a.lanes;
      c.child = a.child;
      c.memoizedProps = a.memoizedProps;
      c.memoizedState = a.memoizedState;
      c.updateQueue = a.updateQueue;
      b2 = a.dependencies;
      c.dependencies = null === b2 ? null : { lanes: b2.lanes, firstContext: b2.firstContext };
      c.sibling = a.sibling;
      c.index = a.index;
      c.ref = a.ref;
      return c;
    }
    function Rg(a, b2, c, d2, e3, f) {
      var g = 2;
      d2 = a;
      if ("function" === typeof a) aj(a) && (g = 1);
      else if ("string" === typeof a) g = 5;
      else a: switch (a) {
        case ya:
          return Tg(c.children, e3, f, b2);
        case za:
          g = 8;
          e3 |= 8;
          break;
        case Aa:
          return a = Bg(12, c, b2, e3 | 2), a.elementType = Aa, a.lanes = f, a;
        case Ea:
          return a = Bg(13, c, b2, e3), a.elementType = Ea, a.lanes = f, a;
        case Fa:
          return a = Bg(19, c, b2, e3), a.elementType = Fa, a.lanes = f, a;
        case Ia:
          return pj(c, e3, f, b2);
        default:
          if ("object" === typeof a && null !== a) switch (a.$$typeof) {
            case Ba:
              g = 10;
              break a;
            case Ca:
              g = 9;
              break a;
            case Da:
              g = 11;
              break a;
            case Ga:
              g = 14;
              break a;
            case Ha:
              g = 16;
              d2 = null;
              break a;
          }
          throw Error(p2(130, null == a ? a : typeof a, ""));
      }
      b2 = Bg(g, c, b2, e3);
      b2.elementType = a;
      b2.type = d2;
      b2.lanes = f;
      return b2;
    }
    function Tg(a, b2, c, d2) {
      a = Bg(7, a, d2, b2);
      a.lanes = c;
      return a;
    }
    function pj(a, b2, c, d2) {
      a = Bg(22, a, d2, b2);
      a.elementType = Ia;
      a.lanes = c;
      a.stateNode = { isHidden: false };
      return a;
    }
    function Qg(a, b2, c) {
      a = Bg(6, a, null, b2);
      a.lanes = c;
      return a;
    }
    function Sg(a, b2, c) {
      b2 = Bg(4, null !== a.children ? a.children : [], a.key, b2);
      b2.lanes = c;
      b2.stateNode = { containerInfo: a.containerInfo, pendingChildren: null, implementation: a.implementation };
      return b2;
    }
    function al(a, b2, c, d2, e3) {
      this.tag = b2;
      this.containerInfo = a;
      this.finishedWork = this.pingCache = this.current = this.pendingChildren = null;
      this.timeoutHandle = -1;
      this.callbackNode = this.pendingContext = this.context = null;
      this.callbackPriority = 0;
      this.eventTimes = zc(0);
      this.expirationTimes = zc(-1);
      this.entangledLanes = this.finishedLanes = this.mutableReadLanes = this.expiredLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0;
      this.entanglements = zc(0);
      this.identifierPrefix = d2;
      this.onRecoverableError = e3;
      this.mutableSourceEagerHydrationData = null;
    }
    function bl(a, b2, c, d2, e3, f, g, h2, k) {
      a = new al(a, b2, c, h2, k);
      1 === b2 ? (b2 = 1, true === f && (b2 |= 8)) : b2 = 0;
      f = Bg(3, null, null, b2);
      a.current = f;
      f.stateNode = a;
      f.memoizedState = { element: d2, isDehydrated: c, cache: null, transitions: null, pendingSuspenseBoundaries: null };
      kh(f);
      return a;
    }
    function cl(a, b2, c) {
      var d2 = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null;
      return { $$typeof: wa, key: null == d2 ? null : "" + d2, children: a, containerInfo: b2, implementation: c };
    }
    function dl(a) {
      if (!a) return Vf;
      a = a._reactInternals;
      a: {
        if (Vb(a) !== a || 1 !== a.tag) throw Error(p2(170));
        var b2 = a;
        do {
          switch (b2.tag) {
            case 3:
              b2 = b2.stateNode.context;
              break a;
            case 1:
              if (Zf(b2.type)) {
                b2 = b2.stateNode.__reactInternalMemoizedMergedChildContext;
                break a;
              }
          }
          b2 = b2.return;
        } while (null !== b2);
        throw Error(p2(171));
      }
      if (1 === a.tag) {
        var c = a.type;
        if (Zf(c)) return bg(a, c, b2);
      }
      return b2;
    }
    function el(a, b2, c, d2, e3, f, g, h2, k) {
      a = bl(c, d2, true, a, e3, f, g, h2, k);
      a.context = dl(null);
      c = a.current;
      d2 = R2();
      e3 = yi(c);
      f = mh(d2, e3);
      f.callback = void 0 !== b2 && null !== b2 ? b2 : null;
      nh(c, f, e3);
      a.current.lanes = e3;
      Ac(a, e3, d2);
      Dk(a, d2);
      return a;
    }
    function fl(a, b2, c, d2) {
      var e3 = b2.current, f = R2(), g = yi(e3);
      c = dl(c);
      null === b2.context ? b2.context = c : b2.pendingContext = c;
      b2 = mh(f, g);
      b2.payload = { element: a };
      d2 = void 0 === d2 ? null : d2;
      null !== d2 && (b2.callback = d2);
      a = nh(e3, b2, g);
      null !== a && (gi(a, e3, g, f), oh(a, e3, g));
      return g;
    }
    function gl(a) {
      a = a.current;
      if (!a.child) return null;
      switch (a.child.tag) {
        case 5:
          return a.child.stateNode;
        default:
          return a.child.stateNode;
      }
    }
    function hl(a, b2) {
      a = a.memoizedState;
      if (null !== a && null !== a.dehydrated) {
        var c = a.retryLane;
        a.retryLane = 0 !== c && c < b2 ? c : b2;
      }
    }
    function il(a, b2) {
      hl(a, b2);
      (a = a.alternate) && hl(a, b2);
    }
    function jl() {
      return null;
    }
    var kl = "function" === typeof reportError ? reportError : function(a) {
      console.error(a);
    };
    function ll(a) {
      this._internalRoot = a;
    }
    ml.prototype.render = ll.prototype.render = function(a) {
      var b2 = this._internalRoot;
      if (null === b2) throw Error(p2(409));
      fl(a, b2, null, null);
    };
    ml.prototype.unmount = ll.prototype.unmount = function() {
      var a = this._internalRoot;
      if (null !== a) {
        this._internalRoot = null;
        var b2 = a.containerInfo;
        Rk(function() {
          fl(null, a, null, null);
        });
        b2[uf] = null;
      }
    };
    function ml(a) {
      this._internalRoot = a;
    }
    ml.prototype.unstable_scheduleHydration = function(a) {
      if (a) {
        var b2 = Hc();
        a = { blockedOn: null, target: a, priority: b2 };
        for (var c = 0; c < Qc.length && 0 !== b2 && b2 < Qc[c].priority; c++) ;
        Qc.splice(c, 0, a);
        0 === c && Vc(a);
      }
    };
    function nl(a) {
      return !(!a || 1 !== a.nodeType && 9 !== a.nodeType && 11 !== a.nodeType);
    }
    function ol(a) {
      return !(!a || 1 !== a.nodeType && 9 !== a.nodeType && 11 !== a.nodeType && (8 !== a.nodeType || " react-mount-point-unstable " !== a.nodeValue));
    }
    function pl() {
    }
    function ql(a, b2, c, d2, e3) {
      if (e3) {
        if ("function" === typeof d2) {
          var f = d2;
          d2 = function() {
            var a2 = gl(g);
            f.call(a2);
          };
        }
        var g = el(b2, d2, a, 0, null, false, false, "", pl);
        a._reactRootContainer = g;
        a[uf] = g.current;
        sf(8 === a.nodeType ? a.parentNode : a);
        Rk();
        return g;
      }
      for (; e3 = a.lastChild; ) a.removeChild(e3);
      if ("function" === typeof d2) {
        var h2 = d2;
        d2 = function() {
          var a2 = gl(k);
          h2.call(a2);
        };
      }
      var k = bl(a, 0, false, null, null, false, false, "", pl);
      a._reactRootContainer = k;
      a[uf] = k.current;
      sf(8 === a.nodeType ? a.parentNode : a);
      Rk(function() {
        fl(b2, k, c, d2);
      });
      return k;
    }
    function rl(a, b2, c, d2, e3) {
      var f = c._reactRootContainer;
      if (f) {
        var g = f;
        if ("function" === typeof e3) {
          var h2 = e3;
          e3 = function() {
            var a2 = gl(g);
            h2.call(a2);
          };
        }
        fl(b2, g, a, e3);
      } else g = ql(c, b2, a, e3, d2);
      return gl(g);
    }
    Ec = function(a) {
      switch (a.tag) {
        case 3:
          var b2 = a.stateNode;
          if (b2.current.memoizedState.isDehydrated) {
            var c = tc(b2.pendingLanes);
            0 !== c && (Cc(b2, c | 1), Dk(b2, B2()), 0 === (K & 6) && (Gj = B2() + 500, jg()));
          }
          break;
        case 13:
          Rk(function() {
            var b3 = ih(a, 1);
            if (null !== b3) {
              var c2 = R2();
              gi(b3, a, 1, c2);
            }
          }), il(a, 1);
      }
    };
    Fc = function(a) {
      if (13 === a.tag) {
        var b2 = ih(a, 134217728);
        if (null !== b2) {
          var c = R2();
          gi(b2, a, 134217728, c);
        }
        il(a, 134217728);
      }
    };
    Gc = function(a) {
      if (13 === a.tag) {
        var b2 = yi(a), c = ih(a, b2);
        if (null !== c) {
          var d2 = R2();
          gi(c, a, b2, d2);
        }
        il(a, b2);
      }
    };
    Hc = function() {
      return C;
    };
    Ic = function(a, b2) {
      var c = C;
      try {
        return C = a, b2();
      } finally {
        C = c;
      }
    };
    yb = function(a, b2, c) {
      switch (b2) {
        case "input":
          bb(a, c);
          b2 = c.name;
          if ("radio" === c.type && null != b2) {
            for (c = a; c.parentNode; ) c = c.parentNode;
            c = c.querySelectorAll("input[name=" + JSON.stringify("" + b2) + '][type="radio"]');
            for (b2 = 0; b2 < c.length; b2++) {
              var d2 = c[b2];
              if (d2 !== a && d2.form === a.form) {
                var e3 = Db(d2);
                if (!e3) throw Error(p2(90));
                Wa(d2);
                bb(d2, e3);
              }
            }
          }
          break;
        case "textarea":
          ib(a, c);
          break;
        case "select":
          b2 = c.value, null != b2 && fb(a, !!c.multiple, b2, false);
      }
    };
    Gb = Qk;
    Hb = Rk;
    var sl = { usingClientEntryPoint: false, Events: [Cb, ue, Db, Eb, Fb, Qk] };
    var tl = { findFiberByHostInstance: Wc, bundleType: 0, version: "18.3.1", rendererPackageName: "react-dom" };
    var ul = { bundleType: tl.bundleType, version: tl.version, rendererPackageName: tl.rendererPackageName, rendererConfig: tl.rendererConfig, overrideHookState: null, overrideHookStateDeletePath: null, overrideHookStateRenamePath: null, overrideProps: null, overridePropsDeletePath: null, overridePropsRenamePath: null, setErrorHandler: null, setSuspenseHandler: null, scheduleUpdate: null, currentDispatcherRef: ua.ReactCurrentDispatcher, findHostInstanceByFiber: function(a) {
      a = Zb(a);
      return null === a ? null : a.stateNode;
    }, findFiberByHostInstance: tl.findFiberByHostInstance || jl, findHostInstancesForRefresh: null, scheduleRefresh: null, scheduleRoot: null, setRefreshHandler: null, getCurrentFiber: null, reconcilerVersion: "18.3.1-next-f1338f8080-20240426" };
    if ("undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) {
      vl = __REACT_DEVTOOLS_GLOBAL_HOOK__;
      if (!vl.isDisabled && vl.supportsFiber) try {
        kc = vl.inject(ul), lc = vl;
      } catch (a) {
      }
    }
    var vl;
    exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = sl;
    exports.createPortal = function(a, b2) {
      var c = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null;
      if (!nl(b2)) throw Error(p2(200));
      return cl(a, b2, null, c);
    };
    exports.createRoot = function(a, b2) {
      if (!nl(a)) throw Error(p2(299));
      var c = false, d2 = "", e3 = kl;
      null !== b2 && void 0 !== b2 && (true === b2.unstable_strictMode && (c = true), void 0 !== b2.identifierPrefix && (d2 = b2.identifierPrefix), void 0 !== b2.onRecoverableError && (e3 = b2.onRecoverableError));
      b2 = bl(a, 1, false, null, null, c, false, d2, e3);
      a[uf] = b2.current;
      sf(8 === a.nodeType ? a.parentNode : a);
      return new ll(b2);
    };
    exports.findDOMNode = function(a) {
      if (null == a) return null;
      if (1 === a.nodeType) return a;
      var b2 = a._reactInternals;
      if (void 0 === b2) {
        if ("function" === typeof a.render) throw Error(p2(188));
        a = Object.keys(a).join(",");
        throw Error(p2(268, a));
      }
      a = Zb(b2);
      a = null === a ? null : a.stateNode;
      return a;
    };
    exports.flushSync = function(a) {
      return Rk(a);
    };
    exports.hydrate = function(a, b2, c) {
      if (!ol(b2)) throw Error(p2(200));
      return rl(null, a, b2, true, c);
    };
    exports.hydrateRoot = function(a, b2, c) {
      if (!nl(a)) throw Error(p2(405));
      var d2 = null != c && c.hydratedSources || null, e3 = false, f = "", g = kl;
      null !== c && void 0 !== c && (true === c.unstable_strictMode && (e3 = true), void 0 !== c.identifierPrefix && (f = c.identifierPrefix), void 0 !== c.onRecoverableError && (g = c.onRecoverableError));
      b2 = el(b2, null, a, 1, null != c ? c : null, e3, false, f, g);
      a[uf] = b2.current;
      sf(a);
      if (d2) for (a = 0; a < d2.length; a++) c = d2[a], e3 = c._getVersion, e3 = e3(c._source), null == b2.mutableSourceEagerHydrationData ? b2.mutableSourceEagerHydrationData = [c, e3] : b2.mutableSourceEagerHydrationData.push(
        c,
        e3
      );
      return new ml(b2);
    };
    exports.render = function(a, b2, c) {
      if (!ol(b2)) throw Error(p2(200));
      return rl(null, a, b2, false, c);
    };
    exports.unmountComponentAtNode = function(a) {
      if (!ol(a)) throw Error(p2(40));
      return a._reactRootContainer ? (Rk(function() {
        rl(null, null, a, false, function() {
          a._reactRootContainer = null;
          a[uf] = null;
        });
      }), true) : false;
    };
    exports.unstable_batchedUpdates = Qk;
    exports.unstable_renderSubtreeIntoContainer = function(a, b2, c, d2) {
      if (!ol(c)) throw Error(p2(200));
      if (null == a || void 0 === a._reactInternals) throw Error(p2(38));
      return rl(a, b2, c, false, d2);
    };
    exports.version = "18.3.1-next-f1338f8080-20240426";
  }
});

// node_modules/react-dom/index.js
var require_react_dom = __commonJS({
  "node_modules/react-dom/index.js"(exports, module) {
    "use strict";
    function checkDCE() {
      if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined" || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== "function") {
        return;
      }
      if (false) {
        throw new Error("^_^");
      }
      try {
        __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
      } catch (err) {
        console.error(err);
      }
    }
    if (true) {
      checkDCE();
      module.exports = require_react_dom_production_min();
    } else {
      module.exports = null;
    }
  }
});

// node_modules/react-dom/client.js
var require_client = __commonJS({
  "node_modules/react-dom/client.js"(exports) {
    "use strict";
    var m2 = require_react_dom();
    if (true) {
      exports.createRoot = m2.createRoot;
      exports.hydrateRoot = m2.hydrateRoot;
    } else {
      i3 = m2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
      exports.createRoot = function(c, o3) {
        i3.usingClientEntryPoint = true;
        try {
          return m2.createRoot(c, o3);
        } finally {
          i3.usingClientEntryPoint = false;
        }
      };
      exports.hydrateRoot = function(c, h2, o3) {
        i3.usingClientEntryPoint = true;
        try {
          return m2.hydrateRoot(c, h2, o3);
        } finally {
          i3.usingClientEntryPoint = false;
        }
      };
    }
    var i3;
  }
});

// node_modules/@noble/hashes/esm/crypto.js
var crypto2;
var init_crypto = __esm({
  "node_modules/@noble/hashes/esm/crypto.js"() {
    crypto2 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
  }
});

// node_modules/@noble/hashes/esm/utils.js
function isBytes(a) {
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
function anumber(n3) {
  if (!Number.isSafeInteger(n3) || n3 < 0)
    throw new Error("positive integer expected, got " + n3);
}
function abytes(b2, ...lengths) {
  if (!isBytes(b2))
    throw new Error("Uint8Array expected");
  if (lengths.length > 0 && !lengths.includes(b2.length))
    throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b2.length);
}
function ahash(h2) {
  if (typeof h2 !== "function" || typeof h2.create !== "function")
    throw new Error("Hash should be wrapped by utils.createHasher");
  anumber(h2.outputLen);
  anumber(h2.blockLen);
}
function aexists(instance, checkFinished = true) {
  if (instance.destroyed)
    throw new Error("Hash instance has been destroyed");
  if (checkFinished && instance.finished)
    throw new Error("Hash#digest() has already been called");
}
function aoutput(out, instance) {
  abytes(out);
  const min = instance.outputLen;
  if (out.length < min) {
    throw new Error("digestInto() expects output buffer of length at least " + min);
  }
}
function u32(arr) {
  return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
function clean(...arrays) {
  for (let i3 = 0; i3 < arrays.length; i3++) {
    arrays[i3].fill(0);
  }
}
function createView(arr) {
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
function rotr(word2, shift) {
  return word2 << 32 - shift | word2 >>> shift;
}
function byteSwap(word2) {
  return word2 << 24 & 4278190080 | word2 << 8 & 16711680 | word2 >>> 8 & 65280 | word2 >>> 24 & 255;
}
function byteSwap32(arr) {
  for (let i3 = 0; i3 < arr.length; i3++) {
    arr[i3] = byteSwap(arr[i3]);
  }
  return arr;
}
function bytesToHex(bytes) {
  abytes(bytes);
  if (hasHexBuiltin)
    return bytes.toHex();
  let hex = "";
  for (let i3 = 0; i3 < bytes.length; i3++) {
    hex += hexes[bytes[i3]];
  }
  return hex;
}
function asciiToBase16(ch) {
  if (ch >= asciis._0 && ch <= asciis._9)
    return ch - asciis._0;
  if (ch >= asciis.A && ch <= asciis.F)
    return ch - (asciis.A - 10);
  if (ch >= asciis.a && ch <= asciis.f)
    return ch - (asciis.a - 10);
  return;
}
function hexToBytes(hex) {
  if (typeof hex !== "string")
    throw new Error("hex string expected, got " + typeof hex);
  if (hasHexBuiltin)
    return Uint8Array.fromHex(hex);
  const hl = hex.length;
  const al = hl / 2;
  if (hl % 2)
    throw new Error("hex string expected, got unpadded hex of length " + hl);
  const array = new Uint8Array(al);
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
    const n1 = asciiToBase16(hex.charCodeAt(hi));
    const n22 = asciiToBase16(hex.charCodeAt(hi + 1));
    if (n1 === void 0 || n22 === void 0) {
      const char = hex[hi] + hex[hi + 1];
      throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
    }
    array[ai] = n1 * 16 + n22;
  }
  return array;
}
function utf8ToBytes(str) {
  if (typeof str !== "string")
    throw new Error("string expected");
  return new Uint8Array(new TextEncoder().encode(str));
}
function toBytes(data) {
  if (typeof data === "string")
    data = utf8ToBytes(data);
  abytes(data);
  return data;
}
function concatBytes(...arrays) {
  let sum = 0;
  for (let i3 = 0; i3 < arrays.length; i3++) {
    const a = arrays[i3];
    abytes(a);
    sum += a.length;
  }
  const res = new Uint8Array(sum);
  for (let i3 = 0, pad = 0; i3 < arrays.length; i3++) {
    const a = arrays[i3];
    res.set(a, pad);
    pad += a.length;
  }
  return res;
}
function createHasher(hashCons) {
  const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
  const tmp = hashCons();
  hashC.outputLen = tmp.outputLen;
  hashC.blockLen = tmp.blockLen;
  hashC.create = () => hashCons();
  return hashC;
}
function randomBytes(bytesLength = 32) {
  if (crypto2 && typeof crypto2.getRandomValues === "function") {
    return crypto2.getRandomValues(new Uint8Array(bytesLength));
  }
  if (crypto2 && typeof crypto2.randomBytes === "function") {
    return Uint8Array.from(crypto2.randomBytes(bytesLength));
  }
  throw new Error("crypto.getRandomValues must be defined");
}
var isLE, swap32IfBE, hasHexBuiltin, hexes, asciis, Hash;
var init_utils = __esm({
  "node_modules/@noble/hashes/esm/utils.js"() {
    init_crypto();
    isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
    swap32IfBE = isLE ? (u2) => u2 : byteSwap32;
    hasHexBuiltin = /* @__PURE__ */ (() => (
      // @ts-ignore
      typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
    ))();
    hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i3) => i3.toString(16).padStart(2, "0"));
    asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
    Hash = class {
    };
  }
});

// node_modules/@noble/hashes/esm/_md.js
function setBigUint64(view, byteOffset, value, isLE2) {
  if (typeof view.setBigUint64 === "function")
    return view.setBigUint64(byteOffset, value, isLE2);
  const _32n2 = BigInt(32);
  const _u32_max = BigInt(4294967295);
  const wh = Number(value >> _32n2 & _u32_max);
  const wl = Number(value & _u32_max);
  const h2 = isLE2 ? 4 : 0;
  const l2 = isLE2 ? 0 : 4;
  view.setUint32(byteOffset + h2, wh, isLE2);
  view.setUint32(byteOffset + l2, wl, isLE2);
}
function Chi(a, b2, c) {
  return a & b2 ^ ~a & c;
}
function Maj(a, b2, c) {
  return a & b2 ^ a & c ^ b2 & c;
}
var HashMD, SHA256_IV;
var init_md = __esm({
  "node_modules/@noble/hashes/esm/_md.js"() {
    init_utils();
    HashMD = class extends Hash {
      constructor(blockLen, outputLen, padOffset, isLE2) {
        super();
        this.finished = false;
        this.length = 0;
        this.pos = 0;
        this.destroyed = false;
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE2;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView(this.buffer);
      }
      update(data) {
        aexists(this);
        data = toBytes(data);
        abytes(data);
        const { view, buffer, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len; ) {
          const take = Math.min(blockLen - this.pos, len - pos);
          if (take === blockLen) {
            const dataView = createView(data);
            for (; blockLen <= len - pos; pos += blockLen)
              this.process(dataView, pos);
            continue;
          }
          buffer.set(data.subarray(pos, pos + take), this.pos);
          this.pos += take;
          pos += take;
          if (this.pos === blockLen) {
            this.process(view, 0);
            this.pos = 0;
          }
        }
        this.length += data.length;
        this.roundClean();
        return this;
      }
      digestInto(out) {
        aexists(this);
        aoutput(out, this);
        this.finished = true;
        const { buffer, view, blockLen, isLE: isLE2 } = this;
        let { pos } = this;
        buffer[pos++] = 128;
        clean(this.buffer.subarray(pos));
        if (this.padOffset > blockLen - pos) {
          this.process(view, 0);
          pos = 0;
        }
        for (let i3 = pos; i3 < blockLen; i3++)
          buffer[i3] = 0;
        setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2);
        this.process(view, 0);
        const oview = createView(out);
        const len = this.outputLen;
        if (len % 4)
          throw new Error("_sha2: outputLen should be aligned to 32bit");
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
          throw new Error("_sha2: outputLen bigger than state");
        for (let i3 = 0; i3 < outLen; i3++)
          oview.setUint32(4 * i3, state[i3], isLE2);
      }
      digest() {
        const { buffer, outputLen } = this;
        this.digestInto(buffer);
        const res = buffer.slice(0, outputLen);
        this.destroy();
        return res;
      }
      _cloneInto(to) {
        to || (to = new this.constructor());
        to.set(...this.get());
        const { blockLen, buffer, length, finished, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
          to.buffer.set(buffer);
        return to;
      }
      clone() {
        return this._cloneInto();
      }
    };
    SHA256_IV = /* @__PURE__ */ Uint32Array.from([
      1779033703,
      3144134277,
      1013904242,
      2773480762,
      1359893119,
      2600822924,
      528734635,
      1541459225
    ]);
  }
});

// node_modules/@noble/hashes/esm/_u64.js
function fromBig(n3, le = false) {
  if (le)
    return { h: Number(n3 & U32_MASK64), l: Number(n3 >> _32n & U32_MASK64) };
  return { h: Number(n3 >> _32n & U32_MASK64) | 0, l: Number(n3 & U32_MASK64) | 0 };
}
function split(lst, le = false) {
  const len = lst.length;
  let Ah = new Uint32Array(len);
  let Al = new Uint32Array(len);
  for (let i3 = 0; i3 < len; i3++) {
    const { h: h2, l: l2 } = fromBig(lst[i3], le);
    [Ah[i3], Al[i3]] = [h2, l2];
  }
  return [Ah, Al];
}
var U32_MASK64, _32n, rotlSH, rotlSL, rotlBH, rotlBL;
var init_u64 = __esm({
  "node_modules/@noble/hashes/esm/_u64.js"() {
    U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
    _32n = /* @__PURE__ */ BigInt(32);
    rotlSH = (h2, l2, s3) => h2 << s3 | l2 >>> 32 - s3;
    rotlSL = (h2, l2, s3) => l2 << s3 | h2 >>> 32 - s3;
    rotlBH = (h2, l2, s3) => l2 << s3 - 32 | h2 >>> 64 - s3;
    rotlBL = (h2, l2, s3) => h2 << s3 - 32 | l2 >>> 64 - s3;
  }
});

// node_modules/@noble/hashes/esm/sha2.js
var SHA256_K, SHA256_W, SHA256, sha256;
var init_sha2 = __esm({
  "node_modules/@noble/hashes/esm/sha2.js"() {
    init_md();
    init_utils();
    SHA256_K = /* @__PURE__ */ Uint32Array.from([
      1116352408,
      1899447441,
      3049323471,
      3921009573,
      961987163,
      1508970993,
      2453635748,
      2870763221,
      3624381080,
      310598401,
      607225278,
      1426881987,
      1925078388,
      2162078206,
      2614888103,
      3248222580,
      3835390401,
      4022224774,
      264347078,
      604807628,
      770255983,
      1249150122,
      1555081692,
      1996064986,
      2554220882,
      2821834349,
      2952996808,
      3210313671,
      3336571891,
      3584528711,
      113926993,
      338241895,
      666307205,
      773529912,
      1294757372,
      1396182291,
      1695183700,
      1986661051,
      2177026350,
      2456956037,
      2730485921,
      2820302411,
      3259730800,
      3345764771,
      3516065817,
      3600352804,
      4094571909,
      275423344,
      430227734,
      506948616,
      659060556,
      883997877,
      958139571,
      1322822218,
      1537002063,
      1747873779,
      1955562222,
      2024104815,
      2227730452,
      2361852424,
      2428436474,
      2756734187,
      3204031479,
      3329325298
    ]);
    SHA256_W = /* @__PURE__ */ new Uint32Array(64);
    SHA256 = class extends HashMD {
      constructor(outputLen = 32) {
        super(64, outputLen, 8, false);
        this.A = SHA256_IV[0] | 0;
        this.B = SHA256_IV[1] | 0;
        this.C = SHA256_IV[2] | 0;
        this.D = SHA256_IV[3] | 0;
        this.E = SHA256_IV[4] | 0;
        this.F = SHA256_IV[5] | 0;
        this.G = SHA256_IV[6] | 0;
        this.H = SHA256_IV[7] | 0;
      }
      get() {
        const { A, B: B2, C, D, E, F, G: G3, H } = this;
        return [A, B2, C, D, E, F, G3, H];
      }
      // prettier-ignore
      set(A, B2, C, D, E, F, G3, H) {
        this.A = A | 0;
        this.B = B2 | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G3 | 0;
        this.H = H | 0;
      }
      process(view, offset) {
        for (let i3 = 0; i3 < 16; i3++, offset += 4)
          SHA256_W[i3] = view.getUint32(offset, false);
        for (let i3 = 16; i3 < 64; i3++) {
          const W15 = SHA256_W[i3 - 15];
          const W2 = SHA256_W[i3 - 2];
          const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
          const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
          SHA256_W[i3] = s1 + SHA256_W[i3 - 7] + s0 + SHA256_W[i3 - 16] | 0;
        }
        let { A, B: B2, C, D, E, F, G: G3, H } = this;
        for (let i3 = 0; i3 < 64; i3++) {
          const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
          const T1 = H + sigma1 + Chi(E, F, G3) + SHA256_K[i3] + SHA256_W[i3] | 0;
          const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
          const T2 = sigma0 + Maj(A, B2, C) | 0;
          H = G3;
          G3 = F;
          F = E;
          E = D + T1 | 0;
          D = C;
          C = B2;
          B2 = A;
          A = T1 + T2 | 0;
        }
        A = A + this.A | 0;
        B2 = B2 + this.B | 0;
        C = C + this.C | 0;
        D = D + this.D | 0;
        E = E + this.E | 0;
        F = F + this.F | 0;
        G3 = G3 + this.G | 0;
        H = H + this.H | 0;
        this.set(A, B2, C, D, E, F, G3, H);
      }
      roundClean() {
        clean(SHA256_W);
      }
      destroy() {
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean(this.buffer);
      }
    };
    sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
  }
});

// node_modules/@noble/hashes/esm/hmac.js
var HMAC, hmac;
var init_hmac = __esm({
  "node_modules/@noble/hashes/esm/hmac.js"() {
    init_utils();
    HMAC = class extends Hash {
      constructor(hash, _key) {
        super();
        this.finished = false;
        this.destroyed = false;
        ahash(hash);
        const key = toBytes(_key);
        this.iHash = hash.create();
        if (typeof this.iHash.update !== "function")
          throw new Error("Expected instance of class which extends utils.Hash");
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad = new Uint8Array(blockLen);
        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
        for (let i3 = 0; i3 < pad.length; i3++)
          pad[i3] ^= 54;
        this.iHash.update(pad);
        this.oHash = hash.create();
        for (let i3 = 0; i3 < pad.length; i3++)
          pad[i3] ^= 54 ^ 92;
        this.oHash.update(pad);
        clean(pad);
      }
      update(buf) {
        aexists(this);
        this.iHash.update(buf);
        return this;
      }
      digestInto(out) {
        aexists(this);
        abytes(out, this.outputLen);
        this.finished = true;
        this.iHash.digestInto(out);
        this.oHash.update(out);
        this.oHash.digestInto(out);
        this.destroy();
      }
      digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
      }
      _cloneInto(to) {
        to || (to = Object.create(Object.getPrototypeOf(this), {}));
        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
      }
      clone() {
        return this._cloneInto();
      }
      destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
      }
    };
    hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
    hmac.create = (hash, key) => new HMAC(hash, key);
  }
});

// node_modules/@noble/curves/esm/utils.js
function _abool2(value, title = "") {
  if (typeof value !== "boolean") {
    const prefix = title && `"${title}"`;
    throw new Error(prefix + "expected boolean, got type=" + typeof value);
  }
  return value;
}
function _abytes2(value, length, title = "") {
  const bytes = isBytes(value);
  const len = value?.length;
  const needsLen = length !== void 0;
  if (!bytes || needsLen && len !== length) {
    const prefix = title && `"${title}" `;
    const ofLen = needsLen ? ` of length ${length}` : "";
    const got = bytes ? `length=${len}` : `type=${typeof value}`;
    throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
  }
  return value;
}
function numberToHexUnpadded(num2) {
  const hex = num2.toString(16);
  return hex.length & 1 ? "0" + hex : hex;
}
function hexToNumber(hex) {
  if (typeof hex !== "string")
    throw new Error("hex string expected, got " + typeof hex);
  return hex === "" ? _0n : BigInt("0x" + hex);
}
function bytesToNumberBE(bytes) {
  return hexToNumber(bytesToHex(bytes));
}
function bytesToNumberLE(bytes) {
  abytes(bytes);
  return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
}
function numberToBytesBE(n3, len) {
  return hexToBytes(n3.toString(16).padStart(len * 2, "0"));
}
function numberToBytesLE(n3, len) {
  return numberToBytesBE(n3, len).reverse();
}
function ensureBytes(title, hex, expectedLength) {
  let res;
  if (typeof hex === "string") {
    try {
      res = hexToBytes(hex);
    } catch (e3) {
      throw new Error(title + " must be hex string or Uint8Array, cause: " + e3);
    }
  } else if (isBytes(hex)) {
    res = Uint8Array.from(hex);
  } else {
    throw new Error(title + " must be hex string or Uint8Array");
  }
  const len = res.length;
  if (typeof expectedLength === "number" && len !== expectedLength)
    throw new Error(title + " of length " + expectedLength + " expected, got " + len);
  return res;
}
function inRange(n3, min, max) {
  return isPosBig(n3) && isPosBig(min) && isPosBig(max) && min <= n3 && n3 < max;
}
function aInRange(title, n3, min, max) {
  if (!inRange(n3, min, max))
    throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n3);
}
function bitLen(n3) {
  let len;
  for (len = 0; n3 > _0n; n3 >>= _1n, len += 1)
    ;
  return len;
}
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
  if (typeof hashLen !== "number" || hashLen < 2)
    throw new Error("hashLen must be a number");
  if (typeof qByteLen !== "number" || qByteLen < 2)
    throw new Error("qByteLen must be a number");
  if (typeof hmacFn !== "function")
    throw new Error("hmacFn must be a function");
  const u8n = (len) => new Uint8Array(len);
  const u8of = (byte) => Uint8Array.of(byte);
  let v = u8n(hashLen);
  let k = u8n(hashLen);
  let i3 = 0;
  const reset = () => {
    v.fill(1);
    k.fill(0);
    i3 = 0;
  };
  const h2 = (...b2) => hmacFn(k, v, ...b2);
  const reseed = (seed = u8n(0)) => {
    k = h2(u8of(0), seed);
    v = h2();
    if (seed.length === 0)
      return;
    k = h2(u8of(1), seed);
    v = h2();
  };
  const gen2 = () => {
    if (i3++ >= 1e3)
      throw new Error("drbg: tried 1000 values");
    let len = 0;
    const out = [];
    while (len < qByteLen) {
      v = h2();
      const sl = v.slice();
      out.push(sl);
      len += v.length;
    }
    return concatBytes(...out);
  };
  const genUntil = (seed, pred) => {
    reset();
    reseed(seed);
    let res = void 0;
    while (!(res = pred(gen2())))
      reseed();
    reset();
    return res;
  };
  return genUntil;
}
function isHash(val) {
  return typeof val === "function" && Number.isSafeInteger(val.outputLen);
}
function _validateObject(object, fields, optFields = {}) {
  if (!object || typeof object !== "object")
    throw new Error("expected valid options object");
  function checkField(fieldName, expectedType, isOpt) {
    const val = object[fieldName];
    if (isOpt && val === void 0)
      return;
    const current = typeof val;
    if (current !== expectedType || val === null)
      throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
  }
  Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
  Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
}
function memoized(fn) {
  const map = /* @__PURE__ */ new WeakMap();
  return (arg, ...args) => {
    const val = map.get(arg);
    if (val !== void 0)
      return val;
    const computed = fn(arg, ...args);
    map.set(arg, computed);
    return computed;
  };
}
var _0n, _1n, isPosBig, bitMask;
var init_utils2 = __esm({
  "node_modules/@noble/curves/esm/utils.js"() {
    init_utils();
    init_utils();
    _0n = /* @__PURE__ */ BigInt(0);
    _1n = /* @__PURE__ */ BigInt(1);
    isPosBig = (n3) => typeof n3 === "bigint" && _0n <= n3;
    bitMask = (n3) => (_1n << BigInt(n3)) - _1n;
  }
});

// node_modules/@noble/curves/esm/abstract/modular.js
function mod(a, b2) {
  const result = a % b2;
  return result >= _0n2 ? result : b2 + result;
}
function pow2(x, power, modulo) {
  let res = x;
  while (power-- > _0n2) {
    res *= res;
    res %= modulo;
  }
  return res;
}
function invert(number, modulo) {
  if (number === _0n2)
    throw new Error("invert: expected non-zero number");
  if (modulo <= _0n2)
    throw new Error("invert: expected positive modulus, got " + modulo);
  let a = mod(number, modulo);
  let b2 = modulo;
  let x = _0n2, y2 = _1n2, u2 = _1n2, v = _0n2;
  while (a !== _0n2) {
    const q = b2 / a;
    const r3 = b2 % a;
    const m2 = x - u2 * q;
    const n3 = y2 - v * q;
    b2 = a, a = r3, x = u2, y2 = v, u2 = m2, v = n3;
  }
  const gcd2 = b2;
  if (gcd2 !== _1n2)
    throw new Error("invert: does not exist");
  return mod(x, modulo);
}
function assertIsSquare(Fp, root2, n3) {
  if (!Fp.eql(Fp.sqr(root2), n3))
    throw new Error("Cannot find square root");
}
function sqrt3mod4(Fp, n3) {
  const p1div4 = (Fp.ORDER + _1n2) / _4n;
  const root2 = Fp.pow(n3, p1div4);
  assertIsSquare(Fp, root2, n3);
  return root2;
}
function sqrt5mod8(Fp, n3) {
  const p5div8 = (Fp.ORDER - _5n) / _8n;
  const n22 = Fp.mul(n3, _2n);
  const v = Fp.pow(n22, p5div8);
  const nv = Fp.mul(n3, v);
  const i3 = Fp.mul(Fp.mul(nv, _2n), v);
  const root2 = Fp.mul(nv, Fp.sub(i3, Fp.ONE));
  assertIsSquare(Fp, root2, n3);
  return root2;
}
function sqrt9mod16(P) {
  const Fp_ = Field(P);
  const tn = tonelliShanks(P);
  const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
  const c2 = tn(Fp_, c1);
  const c3 = tn(Fp_, Fp_.neg(c1));
  const c4 = (P + _7n) / _16n;
  return (Fp, n3) => {
    let tv1 = Fp.pow(n3, c4);
    let tv2 = Fp.mul(tv1, c1);
    const tv3 = Fp.mul(tv1, c2);
    const tv4 = Fp.mul(tv1, c3);
    const e1 = Fp.eql(Fp.sqr(tv2), n3);
    const e22 = Fp.eql(Fp.sqr(tv3), n3);
    tv1 = Fp.cmov(tv1, tv2, e1);
    tv2 = Fp.cmov(tv4, tv3, e22);
    const e3 = Fp.eql(Fp.sqr(tv2), n3);
    const root2 = Fp.cmov(tv1, tv2, e3);
    assertIsSquare(Fp, root2, n3);
    return root2;
  };
}
function tonelliShanks(P) {
  if (P < _3n)
    throw new Error("sqrt is not defined for small field");
  let Q = P - _1n2;
  let S2 = 0;
  while (Q % _2n === _0n2) {
    Q /= _2n;
    S2++;
  }
  let Z = _2n;
  const _Fp = Field(P);
  while (FpLegendre(_Fp, Z) === 1) {
    if (Z++ > 1e3)
      throw new Error("Cannot find square root: probably non-prime P");
  }
  if (S2 === 1)
    return sqrt3mod4;
  let cc = _Fp.pow(Z, Q);
  const Q1div2 = (Q + _1n2) / _2n;
  return function tonelliSlow(Fp, n3) {
    if (Fp.is0(n3))
      return n3;
    if (FpLegendre(Fp, n3) !== 1)
      throw new Error("Cannot find square root");
    let M2 = S2;
    let c = Fp.mul(Fp.ONE, cc);
    let t2 = Fp.pow(n3, Q);
    let R2 = Fp.pow(n3, Q1div2);
    while (!Fp.eql(t2, Fp.ONE)) {
      if (Fp.is0(t2))
        return Fp.ZERO;
      let i3 = 1;
      let t_tmp = Fp.sqr(t2);
      while (!Fp.eql(t_tmp, Fp.ONE)) {
        i3++;
        t_tmp = Fp.sqr(t_tmp);
        if (i3 === M2)
          throw new Error("Cannot find square root");
      }
      const exponent = _1n2 << BigInt(M2 - i3 - 1);
      const b2 = Fp.pow(c, exponent);
      M2 = i3;
      c = Fp.sqr(b2);
      t2 = Fp.mul(t2, c);
      R2 = Fp.mul(R2, b2);
    }
    return R2;
  };
}
function FpSqrt(P) {
  if (P % _4n === _3n)
    return sqrt3mod4;
  if (P % _8n === _5n)
    return sqrt5mod8;
  if (P % _16n === _9n)
    return sqrt9mod16(P);
  return tonelliShanks(P);
}
function validateField(field) {
  const initial = {
    ORDER: "bigint",
    MASK: "bigint",
    BYTES: "number",
    BITS: "number"
  };
  const opts = FIELD_FIELDS.reduce((map, val) => {
    map[val] = "function";
    return map;
  }, initial);
  _validateObject(field, opts);
  return field;
}
function FpPow(Fp, num2, power) {
  if (power < _0n2)
    throw new Error("invalid exponent, negatives unsupported");
  if (power === _0n2)
    return Fp.ONE;
  if (power === _1n2)
    return num2;
  let p2 = Fp.ONE;
  let d2 = num2;
  while (power > _0n2) {
    if (power & _1n2)
      p2 = Fp.mul(p2, d2);
    d2 = Fp.sqr(d2);
    power >>= _1n2;
  }
  return p2;
}
function FpInvertBatch(Fp, nums, passZero = false) {
  const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
  const multipliedAcc = nums.reduce((acc, num2, i3) => {
    if (Fp.is0(num2))
      return acc;
    inverted[i3] = acc;
    return Fp.mul(acc, num2);
  }, Fp.ONE);
  const invertedAcc = Fp.inv(multipliedAcc);
  nums.reduceRight((acc, num2, i3) => {
    if (Fp.is0(num2))
      return acc;
    inverted[i3] = Fp.mul(acc, inverted[i3]);
    return Fp.mul(acc, num2);
  }, invertedAcc);
  return inverted;
}
function FpLegendre(Fp, n3) {
  const p1mod2 = (Fp.ORDER - _1n2) / _2n;
  const powered = Fp.pow(n3, p1mod2);
  const yes = Fp.eql(powered, Fp.ONE);
  const zero = Fp.eql(powered, Fp.ZERO);
  const no = Fp.eql(powered, Fp.neg(Fp.ONE));
  if (!yes && !zero && !no)
    throw new Error("invalid Legendre symbol result");
  return yes ? 1 : zero ? 0 : -1;
}
function nLength(n3, nBitLength) {
  if (nBitLength !== void 0)
    anumber(nBitLength);
  const _nBitLength = nBitLength !== void 0 ? nBitLength : n3.toString(2).length;
  const nByteLength = Math.ceil(_nBitLength / 8);
  return { nBitLength: _nBitLength, nByteLength };
}
function Field(ORDER, bitLenOrOpts, isLE2 = false, opts = {}) {
  if (ORDER <= _0n2)
    throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
  let _nbitLength = void 0;
  let _sqrt = void 0;
  let modFromBytes = false;
  let allowedLengths = void 0;
  if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) {
    if (opts.sqrt || isLE2)
      throw new Error("cannot specify opts in two arguments");
    const _opts = bitLenOrOpts;
    if (_opts.BITS)
      _nbitLength = _opts.BITS;
    if (_opts.sqrt)
      _sqrt = _opts.sqrt;
    if (typeof _opts.isLE === "boolean")
      isLE2 = _opts.isLE;
    if (typeof _opts.modFromBytes === "boolean")
      modFromBytes = _opts.modFromBytes;
    allowedLengths = _opts.allowedLengths;
  } else {
    if (typeof bitLenOrOpts === "number")
      _nbitLength = bitLenOrOpts;
    if (opts.sqrt)
      _sqrt = opts.sqrt;
  }
  const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
  if (BYTES > 2048)
    throw new Error("invalid field: expected ORDER of <= 2048 bytes");
  let sqrtP;
  const f = Object.freeze({
    ORDER,
    isLE: isLE2,
    BITS,
    BYTES,
    MASK: bitMask(BITS),
    ZERO: _0n2,
    ONE: _1n2,
    allowedLengths,
    create: (num2) => mod(num2, ORDER),
    isValid: (num2) => {
      if (typeof num2 !== "bigint")
        throw new Error("invalid field element: expected bigint, got " + typeof num2);
      return _0n2 <= num2 && num2 < ORDER;
    },
    is0: (num2) => num2 === _0n2,
    // is valid and invertible
    isValidNot0: (num2) => !f.is0(num2) && f.isValid(num2),
    isOdd: (num2) => (num2 & _1n2) === _1n2,
    neg: (num2) => mod(-num2, ORDER),
    eql: (lhs, rhs) => lhs === rhs,
    sqr: (num2) => mod(num2 * num2, ORDER),
    add: (lhs, rhs) => mod(lhs + rhs, ORDER),
    sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
    mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
    pow: (num2, power) => FpPow(f, num2, power),
    div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
    // Same as above, but doesn't normalize
    sqrN: (num2) => num2 * num2,
    addN: (lhs, rhs) => lhs + rhs,
    subN: (lhs, rhs) => lhs - rhs,
    mulN: (lhs, rhs) => lhs * rhs,
    inv: (num2) => invert(num2, ORDER),
    sqrt: _sqrt || ((n3) => {
      if (!sqrtP)
        sqrtP = FpSqrt(ORDER);
      return sqrtP(f, n3);
    }),
    toBytes: (num2) => isLE2 ? numberToBytesLE(num2, BYTES) : numberToBytesBE(num2, BYTES),
    fromBytes: (bytes, skipValidation = true) => {
      if (allowedLengths) {
        if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
          throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
        }
        const padded = new Uint8Array(BYTES);
        padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
        bytes = padded;
      }
      if (bytes.length !== BYTES)
        throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
      let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
      if (modFromBytes)
        scalar = mod(scalar, ORDER);
      if (!skipValidation) {
        if (!f.isValid(scalar))
          throw new Error("invalid field element: outside of range 0..ORDER");
      }
      return scalar;
    },
    // TODO: we don't need it here, move out to separate fn
    invertBatch: (lst) => FpInvertBatch(f, lst),
    // We can't move this out because Fp6, Fp12 implement it
    // and it's unclear what to return in there.
    cmov: (a, b2, c) => c ? b2 : a
  });
  return Object.freeze(f);
}
function getFieldBytesLength(fieldOrder) {
  if (typeof fieldOrder !== "bigint")
    throw new Error("field order must be bigint");
  const bitLength = fieldOrder.toString(2).length;
  return Math.ceil(bitLength / 8);
}
function getMinHashLength(fieldOrder) {
  const length = getFieldBytesLength(fieldOrder);
  return length + Math.ceil(length / 2);
}
function mapHashToField(key, fieldOrder, isLE2 = false) {
  const len = key.length;
  const fieldLen = getFieldBytesLength(fieldOrder);
  const minLen = getMinHashLength(fieldOrder);
  if (len < 16 || len < minLen || len > 1024)
    throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
  const num2 = isLE2 ? bytesToNumberLE(key) : bytesToNumberBE(key);
  const reduced = mod(num2, fieldOrder - _1n2) + _1n2;
  return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
var _0n2, _1n2, _2n, _3n, _4n, _5n, _7n, _8n, _9n, _16n, FIELD_FIELDS;
var init_modular = __esm({
  "node_modules/@noble/curves/esm/abstract/modular.js"() {
    init_utils2();
    _0n2 = BigInt(0);
    _1n2 = BigInt(1);
    _2n = /* @__PURE__ */ BigInt(2);
    _3n = /* @__PURE__ */ BigInt(3);
    _4n = /* @__PURE__ */ BigInt(4);
    _5n = /* @__PURE__ */ BigInt(5);
    _7n = /* @__PURE__ */ BigInt(7);
    _8n = /* @__PURE__ */ BigInt(8);
    _9n = /* @__PURE__ */ BigInt(9);
    _16n = /* @__PURE__ */ BigInt(16);
    FIELD_FIELDS = [
      "create",
      "isValid",
      "is0",
      "neg",
      "inv",
      "sqrt",
      "sqr",
      "eql",
      "add",
      "sub",
      "mul",
      "pow",
      "div",
      "addN",
      "subN",
      "mulN",
      "sqrN"
    ];
  }
});

// node_modules/@noble/curves/esm/abstract/curve.js
function negateCt(condition, item) {
  const neg = item.negate();
  return condition ? neg : item;
}
function normalizeZ(c, points) {
  const invertedZs = FpInvertBatch(c.Fp, points.map((p2) => p2.Z));
  return points.map((p2, i3) => c.fromAffine(p2.toAffine(invertedZs[i3])));
}
function validateW(W, bits) {
  if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
    throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
}
function calcWOpts(W, scalarBits) {
  validateW(W, scalarBits);
  const windows = Math.ceil(scalarBits / W) + 1;
  const windowSize = 2 ** (W - 1);
  const maxNumber = 2 ** W;
  const mask = bitMask(W);
  const shiftBy = BigInt(W);
  return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets(n3, window2, wOpts) {
  const { windowSize, mask, maxNumber, shiftBy } = wOpts;
  let wbits = Number(n3 & mask);
  let nextN = n3 >> shiftBy;
  if (wbits > windowSize) {
    wbits -= maxNumber;
    nextN += _1n3;
  }
  const offsetStart = window2 * windowSize;
  const offset = offsetStart + Math.abs(wbits) - 1;
  const isZero = wbits === 0;
  const isNeg = wbits < 0;
  const isNegF = window2 % 2 !== 0;
  const offsetF = offsetStart;
  return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
function validateMSMPoints(points, c) {
  if (!Array.isArray(points))
    throw new Error("array expected");
  points.forEach((p2, i3) => {
    if (!(p2 instanceof c))
      throw new Error("invalid point at index " + i3);
  });
}
function validateMSMScalars(scalars, field) {
  if (!Array.isArray(scalars))
    throw new Error("array of scalars expected");
  scalars.forEach((s3, i3) => {
    if (!field.isValid(s3))
      throw new Error("invalid scalar at index " + i3);
  });
}
function getW(P) {
  return pointWindowSizes.get(P) || 1;
}
function assert0(n3) {
  if (n3 !== _0n3)
    throw new Error("invalid wNAF");
}
function mulEndoUnsafe(Point, point, k1, k2) {
  let acc = point;
  let p1 = Point.ZERO;
  let p2 = Point.ZERO;
  while (k1 > _0n3 || k2 > _0n3) {
    if (k1 & _1n3)
      p1 = p1.add(acc);
    if (k2 & _1n3)
      p2 = p2.add(acc);
    acc = acc.double();
    k1 >>= _1n3;
    k2 >>= _1n3;
  }
  return { p1, p2 };
}
function pippenger(c, fieldN, points, scalars) {
  validateMSMPoints(points, c);
  validateMSMScalars(scalars, fieldN);
  const plength = points.length;
  const slength = scalars.length;
  if (plength !== slength)
    throw new Error("arrays of points and scalars must have equal length");
  const zero = c.ZERO;
  const wbits = bitLen(BigInt(plength));
  let windowSize = 1;
  if (wbits > 12)
    windowSize = wbits - 3;
  else if (wbits > 4)
    windowSize = wbits - 2;
  else if (wbits > 0)
    windowSize = 2;
  const MASK = bitMask(windowSize);
  const buckets = new Array(Number(MASK) + 1).fill(zero);
  const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
  let sum = zero;
  for (let i3 = lastBits; i3 >= 0; i3 -= windowSize) {
    buckets.fill(zero);
    for (let j = 0; j < slength; j++) {
      const scalar = scalars[j];
      const wbits2 = Number(scalar >> BigInt(i3) & MASK);
      buckets[wbits2] = buckets[wbits2].add(points[j]);
    }
    let resI = zero;
    for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
      sumI = sumI.add(buckets[j]);
      resI = resI.add(sumI);
    }
    sum = sum.add(resI);
    if (i3 !== 0)
      for (let j = 0; j < windowSize; j++)
        sum = sum.double();
  }
  return sum;
}
function createField(order, field, isLE2) {
  if (field) {
    if (field.ORDER !== order)
      throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
    validateField(field);
    return field;
  } else {
    return Field(order, { isLE: isLE2 });
  }
}
function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
  if (FpFnLE === void 0)
    FpFnLE = type === "edwards";
  if (!CURVE || typeof CURVE !== "object")
    throw new Error(`expected valid ${type} CURVE object`);
  for (const p2 of ["p", "n", "h"]) {
    const val = CURVE[p2];
    if (!(typeof val === "bigint" && val > _0n3))
      throw new Error(`CURVE.${p2} must be positive bigint`);
  }
  const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
  const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
  const _b = type === "weierstrass" ? "b" : "d";
  const params = ["Gx", "Gy", "a", _b];
  for (const p2 of params) {
    if (!Fp.isValid(CURVE[p2]))
      throw new Error(`CURVE.${p2} must be valid field element of CURVE.Fp`);
  }
  CURVE = Object.freeze(Object.assign({}, CURVE));
  return { CURVE, Fp, Fn };
}
var _0n3, _1n3, pointPrecomputes, pointWindowSizes, wNAF;
var init_curve = __esm({
  "node_modules/@noble/curves/esm/abstract/curve.js"() {
    init_utils2();
    init_modular();
    _0n3 = BigInt(0);
    _1n3 = BigInt(1);
    pointPrecomputes = /* @__PURE__ */ new WeakMap();
    pointWindowSizes = /* @__PURE__ */ new WeakMap();
    wNAF = class {
      // Parametrized with a given Point class (not individual point)
      constructor(Point, bits) {
        this.BASE = Point.BASE;
        this.ZERO = Point.ZERO;
        this.Fn = Point.Fn;
        this.bits = bits;
      }
      // non-const time multiplication ladder
      _unsafeLadder(elm, n3, p2 = this.ZERO) {
        let d2 = elm;
        while (n3 > _0n3) {
          if (n3 & _1n3)
            p2 = p2.add(d2);
          d2 = d2.double();
          n3 >>= _1n3;
        }
        return p2;
      }
      /**
       * Creates a wNAF precomputation window. Used for caching.
       * Default window size is set by `utils.precompute()` and is equal to 8.
       * Number of precomputed points depends on the curve size:
       * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
       * - 𝑊 is the window size
       * - 𝑛 is the bitlength of the curve order.
       * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
       * @param point Point instance
       * @param W window size
       * @returns precomputed point tables flattened to a single array
       */
      precomputeWindow(point, W) {
        const { windows, windowSize } = calcWOpts(W, this.bits);
        const points = [];
        let p2 = point;
        let base = p2;
        for (let window2 = 0; window2 < windows; window2++) {
          base = p2;
          points.push(base);
          for (let i3 = 1; i3 < windowSize; i3++) {
            base = base.add(p2);
            points.push(base);
          }
          p2 = base.double();
        }
        return points;
      }
      /**
       * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
       * More compact implementation:
       * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
       * @returns real and fake (for const-time) points
       */
      wNAF(W, precomputes, n3) {
        if (!this.Fn.isValid(n3))
          throw new Error("invalid scalar");
        let p2 = this.ZERO;
        let f = this.BASE;
        const wo = calcWOpts(W, this.bits);
        for (let window2 = 0; window2 < wo.windows; window2++) {
          const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n3, window2, wo);
          n3 = nextN;
          if (isZero) {
            f = f.add(negateCt(isNegF, precomputes[offsetF]));
          } else {
            p2 = p2.add(negateCt(isNeg, precomputes[offset]));
          }
        }
        assert0(n3);
        return { p: p2, f };
      }
      /**
       * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
       * @param acc accumulator point to add result of multiplication
       * @returns point
       */
      wNAFUnsafe(W, precomputes, n3, acc = this.ZERO) {
        const wo = calcWOpts(W, this.bits);
        for (let window2 = 0; window2 < wo.windows; window2++) {
          if (n3 === _0n3)
            break;
          const { nextN, offset, isZero, isNeg } = calcOffsets(n3, window2, wo);
          n3 = nextN;
          if (isZero) {
            continue;
          } else {
            const item = precomputes[offset];
            acc = acc.add(isNeg ? item.negate() : item);
          }
        }
        assert0(n3);
        return acc;
      }
      getPrecomputes(W, point, transform) {
        let comp = pointPrecomputes.get(point);
        if (!comp) {
          comp = this.precomputeWindow(point, W);
          if (W !== 1) {
            if (typeof transform === "function")
              comp = transform(comp);
            pointPrecomputes.set(point, comp);
          }
        }
        return comp;
      }
      cached(point, scalar, transform) {
        const W = getW(point);
        return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
      }
      unsafe(point, scalar, transform, prev) {
        const W = getW(point);
        if (W === 1)
          return this._unsafeLadder(point, scalar, prev);
        return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
      }
      // We calculate precomputes for elliptic curve point multiplication
      // using windowed method. This specifies window size and
      // stores precomputed values. Usually only base point would be precomputed.
      createCache(P, W) {
        validateW(W, this.bits);
        pointWindowSizes.set(P, W);
        pointPrecomputes.delete(P);
      }
      hasCache(elm) {
        return getW(elm) !== 1;
      }
    };
  }
});

// node_modules/@noble/curves/esm/abstract/weierstrass.js
function _splitEndoScalar(k, basis, n3) {
  const [[a1, b1], [a2, b2]] = basis;
  const c1 = divNearest(b2 * k, n3);
  const c2 = divNearest(-b1 * k, n3);
  let k1 = k - c1 * a1 - c2 * a2;
  let k2 = -c1 * b1 - c2 * b2;
  const k1neg = k1 < _0n4;
  const k2neg = k2 < _0n4;
  if (k1neg)
    k1 = -k1;
  if (k2neg)
    k2 = -k2;
  const MAX_NUM = bitMask(Math.ceil(bitLen(n3) / 2)) + _1n4;
  if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
    throw new Error("splitScalar (endomorphism): failed, k=" + k);
  }
  return { k1neg, k1, k2neg, k2 };
}
function validateSigFormat(format) {
  if (!["compact", "recovered", "der"].includes(format))
    throw new Error('Signature format must be "compact", "recovered", or "der"');
  return format;
}
function validateSigOpts(opts, def) {
  const optsn = {};
  for (let optName of Object.keys(def)) {
    optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
  }
  _abool2(optsn.lowS, "lowS");
  _abool2(optsn.prehash, "prehash");
  if (optsn.format !== void 0)
    validateSigFormat(optsn.format);
  return optsn;
}
function _normFnElement(Fn, key) {
  const { BYTES: expected } = Fn;
  let num2;
  if (typeof key === "bigint") {
    num2 = key;
  } else {
    let bytes = ensureBytes("private key", key);
    try {
      num2 = Fn.fromBytes(bytes);
    } catch (error) {
      throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
    }
  }
  if (!Fn.isValidNot0(num2))
    throw new Error("invalid private key: out of range [1..N-1]");
  return num2;
}
function weierstrassN(params, extraOpts = {}) {
  const validated = _createCurveFields("weierstrass", params, extraOpts);
  const { Fp, Fn } = validated;
  let CURVE = validated.CURVE;
  const { h: cofactor, n: CURVE_ORDER } = CURVE;
  _validateObject(extraOpts, {}, {
    allowInfinityPoint: "boolean",
    clearCofactor: "function",
    isTorsionFree: "function",
    fromBytes: "function",
    toBytes: "function",
    endo: "object",
    wrapPrivateKey: "boolean"
  });
  const { endo } = extraOpts;
  if (endo) {
    if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
      throw new Error('invalid endo: expected "beta": bigint and "basises": array');
    }
  }
  const lengths = getWLengths(Fp, Fn);
  function assertCompressionIsSupported() {
    if (!Fp.isOdd)
      throw new Error("compression is not supported: Field does not have .isOdd()");
  }
  function pointToBytes2(_c, point, isCompressed) {
    const { x, y: y2 } = point.toAffine();
    const bx = Fp.toBytes(x);
    _abool2(isCompressed, "isCompressed");
    if (isCompressed) {
      assertCompressionIsSupported();
      const hasEvenY = !Fp.isOdd(y2);
      return concatBytes(pprefix(hasEvenY), bx);
    } else {
      return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y2));
    }
  }
  function pointFromBytes(bytes) {
    _abytes2(bytes, void 0, "Point");
    const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
    const length = bytes.length;
    const head = bytes[0];
    const tail = bytes.subarray(1);
    if (length === comp && (head === 2 || head === 3)) {
      const x = Fp.fromBytes(tail);
      if (!Fp.isValid(x))
        throw new Error("bad point: is not on curve, wrong x");
      const y2 = weierstrassEquation(x);
      let y3;
      try {
        y3 = Fp.sqrt(y2);
      } catch (sqrtError) {
        const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
        throw new Error("bad point: is not on curve, sqrt error" + err);
      }
      assertCompressionIsSupported();
      const isYOdd = Fp.isOdd(y3);
      const isHeadOdd = (head & 1) === 1;
      if (isHeadOdd !== isYOdd)
        y3 = Fp.neg(y3);
      return { x, y: y3 };
    } else if (length === uncomp && head === 4) {
      const L = Fp.BYTES;
      const x = Fp.fromBytes(tail.subarray(0, L));
      const y2 = Fp.fromBytes(tail.subarray(L, L * 2));
      if (!isValidXY(x, y2))
        throw new Error("bad point: is not on curve");
      return { x, y: y2 };
    } else {
      throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
    }
  }
  const encodePoint = extraOpts.toBytes || pointToBytes2;
  const decodePoint = extraOpts.fromBytes || pointFromBytes;
  function weierstrassEquation(x) {
    const x2 = Fp.sqr(x);
    const x3 = Fp.mul(x2, x);
    return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
  }
  function isValidXY(x, y2) {
    const left = Fp.sqr(y2);
    const right = weierstrassEquation(x);
    return Fp.eql(left, right);
  }
  if (!isValidXY(CURVE.Gx, CURVE.Gy))
    throw new Error("bad curve params: generator point");
  const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
  const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
  if (Fp.is0(Fp.add(_4a3, _27b2)))
    throw new Error("bad curve params: a or b");
  function acoord(title, n3, banZero = false) {
    if (!Fp.isValid(n3) || banZero && Fp.is0(n3))
      throw new Error(`bad point coordinate ${title}`);
    return n3;
  }
  function aprjpoint(other) {
    if (!(other instanceof Point))
      throw new Error("ProjectivePoint expected");
  }
  function splitEndoScalarN(k) {
    if (!endo || !endo.basises)
      throw new Error("no endo");
    return _splitEndoScalar(k, endo.basises, Fn.ORDER);
  }
  const toAffineMemo = memoized((p2, iz) => {
    const { X, Y, Z } = p2;
    if (Fp.eql(Z, Fp.ONE))
      return { x: X, y: Y };
    const is0 = p2.is0();
    if (iz == null)
      iz = is0 ? Fp.ONE : Fp.inv(Z);
    const x = Fp.mul(X, iz);
    const y2 = Fp.mul(Y, iz);
    const zz = Fp.mul(Z, iz);
    if (is0)
      return { x: Fp.ZERO, y: Fp.ZERO };
    if (!Fp.eql(zz, Fp.ONE))
      throw new Error("invZ was invalid");
    return { x, y: y2 };
  });
  const assertValidMemo = memoized((p2) => {
    if (p2.is0()) {
      if (extraOpts.allowInfinityPoint && !Fp.is0(p2.Y))
        return;
      throw new Error("bad point: ZERO");
    }
    const { x, y: y2 } = p2.toAffine();
    if (!Fp.isValid(x) || !Fp.isValid(y2))
      throw new Error("bad point: x or y not field elements");
    if (!isValidXY(x, y2))
      throw new Error("bad point: equation left != right");
    if (!p2.isTorsionFree())
      throw new Error("bad point: not in prime-order subgroup");
    return true;
  });
  function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
    k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
    k1p = negateCt(k1neg, k1p);
    k2p = negateCt(k2neg, k2p);
    return k1p.add(k2p);
  }
  class Point {
    /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
    constructor(X, Y, Z) {
      this.X = acoord("x", X);
      this.Y = acoord("y", Y, true);
      this.Z = acoord("z", Z);
      Object.freeze(this);
    }
    static CURVE() {
      return CURVE;
    }
    /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
    static fromAffine(p2) {
      const { x, y: y2 } = p2 || {};
      if (!p2 || !Fp.isValid(x) || !Fp.isValid(y2))
        throw new Error("invalid affine point");
      if (p2 instanceof Point)
        throw new Error("projective point not allowed");
      if (Fp.is0(x) && Fp.is0(y2))
        return Point.ZERO;
      return new Point(x, y2, Fp.ONE);
    }
    static fromBytes(bytes) {
      const P = Point.fromAffine(decodePoint(_abytes2(bytes, void 0, "point")));
      P.assertValidity();
      return P;
    }
    static fromHex(hex) {
      return Point.fromBytes(ensureBytes("pointHex", hex));
    }
    get x() {
      return this.toAffine().x;
    }
    get y() {
      return this.toAffine().y;
    }
    /**
     *
     * @param windowSize
     * @param isLazy true will defer table computation until the first multiplication
     * @returns
     */
    precompute(windowSize = 8, isLazy = true) {
      wnaf.createCache(this, windowSize);
      if (!isLazy)
        this.multiply(_3n2);
      return this;
    }
    // TODO: return `this`
    /** A point on curve is valid if it conforms to equation. */
    assertValidity() {
      assertValidMemo(this);
    }
    hasEvenY() {
      const { y: y2 } = this.toAffine();
      if (!Fp.isOdd)
        throw new Error("Field doesn't support isOdd");
      return !Fp.isOdd(y2);
    }
    /** Compare one point to another. */
    equals(other) {
      aprjpoint(other);
      const { X: X1, Y: Y1, Z: Z1 } = this;
      const { X: X2, Y: Y2, Z: Z2 } = other;
      const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
      const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
      return U1 && U2;
    }
    /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
    negate() {
      return new Point(this.X, Fp.neg(this.Y), this.Z);
    }
    // Renes-Costello-Batina exception-free doubling formula.
    // There is 30% faster Jacobian formula, but it is not complete.
    // https://eprint.iacr.org/2015/1060, algorithm 3
    // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
    double() {
      const { a, b: b2 } = CURVE;
      const b3 = Fp.mul(b2, _3n2);
      const { X: X1, Y: Y1, Z: Z1 } = this;
      let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
      let t0 = Fp.mul(X1, X1);
      let t1 = Fp.mul(Y1, Y1);
      let t2 = Fp.mul(Z1, Z1);
      let t3 = Fp.mul(X1, Y1);
      t3 = Fp.add(t3, t3);
      Z3 = Fp.mul(X1, Z1);
      Z3 = Fp.add(Z3, Z3);
      X3 = Fp.mul(a, Z3);
      Y3 = Fp.mul(b3, t2);
      Y3 = Fp.add(X3, Y3);
      X3 = Fp.sub(t1, Y3);
      Y3 = Fp.add(t1, Y3);
      Y3 = Fp.mul(X3, Y3);
      X3 = Fp.mul(t3, X3);
      Z3 = Fp.mul(b3, Z3);
      t2 = Fp.mul(a, t2);
      t3 = Fp.sub(t0, t2);
      t3 = Fp.mul(a, t3);
      t3 = Fp.add(t3, Z3);
      Z3 = Fp.add(t0, t0);
      t0 = Fp.add(Z3, t0);
      t0 = Fp.add(t0, t2);
      t0 = Fp.mul(t0, t3);
      Y3 = Fp.add(Y3, t0);
      t2 = Fp.mul(Y1, Z1);
      t2 = Fp.add(t2, t2);
      t0 = Fp.mul(t2, t3);
      X3 = Fp.sub(X3, t0);
      Z3 = Fp.mul(t2, t1);
      Z3 = Fp.add(Z3, Z3);
      Z3 = Fp.add(Z3, Z3);
      return new Point(X3, Y3, Z3);
    }
    // Renes-Costello-Batina exception-free addition formula.
    // There is 30% faster Jacobian formula, but it is not complete.
    // https://eprint.iacr.org/2015/1060, algorithm 1
    // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
    add(other) {
      aprjpoint(other);
      const { X: X1, Y: Y1, Z: Z1 } = this;
      const { X: X2, Y: Y2, Z: Z2 } = other;
      let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
      const a = CURVE.a;
      const b3 = Fp.mul(CURVE.b, _3n2);
      let t0 = Fp.mul(X1, X2);
      let t1 = Fp.mul(Y1, Y2);
      let t2 = Fp.mul(Z1, Z2);
      let t3 = Fp.add(X1, Y1);
      let t4 = Fp.add(X2, Y2);
      t3 = Fp.mul(t3, t4);
      t4 = Fp.add(t0, t1);
      t3 = Fp.sub(t3, t4);
      t4 = Fp.add(X1, Z1);
      let t5 = Fp.add(X2, Z2);
      t4 = Fp.mul(t4, t5);
      t5 = Fp.add(t0, t2);
      t4 = Fp.sub(t4, t5);
      t5 = Fp.add(Y1, Z1);
      X3 = Fp.add(Y2, Z2);
      t5 = Fp.mul(t5, X3);
      X3 = Fp.add(t1, t2);
      t5 = Fp.sub(t5, X3);
      Z3 = Fp.mul(a, t4);
      X3 = Fp.mul(b3, t2);
      Z3 = Fp.add(X3, Z3);
      X3 = Fp.sub(t1, Z3);
      Z3 = Fp.add(t1, Z3);
      Y3 = Fp.mul(X3, Z3);
      t1 = Fp.add(t0, t0);
      t1 = Fp.add(t1, t0);
      t2 = Fp.mul(a, t2);
      t4 = Fp.mul(b3, t4);
      t1 = Fp.add(t1, t2);
      t2 = Fp.sub(t0, t2);
      t2 = Fp.mul(a, t2);
      t4 = Fp.add(t4, t2);
      t0 = Fp.mul(t1, t4);
      Y3 = Fp.add(Y3, t0);
      t0 = Fp.mul(t5, t4);
      X3 = Fp.mul(t3, X3);
      X3 = Fp.sub(X3, t0);
      t0 = Fp.mul(t3, t1);
      Z3 = Fp.mul(t5, Z3);
      Z3 = Fp.add(Z3, t0);
      return new Point(X3, Y3, Z3);
    }
    subtract(other) {
      return this.add(other.negate());
    }
    is0() {
      return this.equals(Point.ZERO);
    }
    /**
     * Constant time multiplication.
     * Uses wNAF method. Windowed method may be 10% faster,
     * but takes 2x longer to generate and consumes 2x memory.
     * Uses precomputes when available.
     * Uses endomorphism for Koblitz curves.
     * @param scalar by which the point would be multiplied
     * @returns New point
     */
    multiply(scalar) {
      const { endo: endo2 } = extraOpts;
      if (!Fn.isValidNot0(scalar))
        throw new Error("invalid scalar: out of range");
      let point, fake;
      const mul = (n3) => wnaf.cached(this, n3, (p2) => normalizeZ(Point, p2));
      if (endo2) {
        const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
        const { p: k1p, f: k1f } = mul(k1);
        const { p: k2p, f: k2f } = mul(k2);
        fake = k1f.add(k2f);
        point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
      } else {
        const { p: p2, f } = mul(scalar);
        point = p2;
        fake = f;
      }
      return normalizeZ(Point, [point, fake])[0];
    }
    /**
     * Non-constant-time multiplication. Uses double-and-add algorithm.
     * It's faster, but should only be used when you don't care about
     * an exposed secret key e.g. sig verification, which works over *public* keys.
     */
    multiplyUnsafe(sc) {
      const { endo: endo2 } = extraOpts;
      const p2 = this;
      if (!Fn.isValid(sc))
        throw new Error("invalid scalar: out of range");
      if (sc === _0n4 || p2.is0())
        return Point.ZERO;
      if (sc === _1n4)
        return p2;
      if (wnaf.hasCache(this))
        return this.multiply(sc);
      if (endo2) {
        const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
        const { p1, p2: p22 } = mulEndoUnsafe(Point, p2, k1, k2);
        return finishEndo(endo2.beta, p1, p22, k1neg, k2neg);
      } else {
        return wnaf.unsafe(p2, sc);
      }
    }
    multiplyAndAddUnsafe(Q, a, b2) {
      const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b2));
      return sum.is0() ? void 0 : sum;
    }
    /**
     * Converts Projective point to affine (x, y) coordinates.
     * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
     */
    toAffine(invertedZ) {
      return toAffineMemo(this, invertedZ);
    }
    /**
     * Checks whether Point is free of torsion elements (is in prime subgroup).
     * Always torsion-free for cofactor=1 curves.
     */
    isTorsionFree() {
      const { isTorsionFree } = extraOpts;
      if (cofactor === _1n4)
        return true;
      if (isTorsionFree)
        return isTorsionFree(Point, this);
      return wnaf.unsafe(this, CURVE_ORDER).is0();
    }
    clearCofactor() {
      const { clearCofactor } = extraOpts;
      if (cofactor === _1n4)
        return this;
      if (clearCofactor)
        return clearCofactor(Point, this);
      return this.multiplyUnsafe(cofactor);
    }
    isSmallOrder() {
      return this.multiplyUnsafe(cofactor).is0();
    }
    toBytes(isCompressed = true) {
      _abool2(isCompressed, "isCompressed");
      this.assertValidity();
      return encodePoint(Point, this, isCompressed);
    }
    toHex(isCompressed = true) {
      return bytesToHex(this.toBytes(isCompressed));
    }
    toString() {
      return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
    }
    // TODO: remove
    get px() {
      return this.X;
    }
    get py() {
      return this.X;
    }
    get pz() {
      return this.Z;
    }
    toRawBytes(isCompressed = true) {
      return this.toBytes(isCompressed);
    }
    _setWindowSize(windowSize) {
      this.precompute(windowSize);
    }
    static normalizeZ(points) {
      return normalizeZ(Point, points);
    }
    static msm(points, scalars) {
      return pippenger(Point, Fn, points, scalars);
    }
    static fromPrivateKey(privateKey) {
      return Point.BASE.multiply(_normFnElement(Fn, privateKey));
    }
  }
  Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
  Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
  Point.Fp = Fp;
  Point.Fn = Fn;
  const bits = Fn.BITS;
  const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
  Point.BASE.precompute(8);
  return Point;
}
function pprefix(hasEvenY) {
  return Uint8Array.of(hasEvenY ? 2 : 3);
}
function SWUFpSqrtRatio(Fp, Z) {
  const q = Fp.ORDER;
  let l2 = _0n4;
  for (let o3 = q - _1n4; o3 % _2n2 === _0n4; o3 /= _2n2)
    l2 += _1n4;
  const c1 = l2;
  const _2n_pow_c1_1 = _2n2 << c1 - _1n4 - _1n4;
  const _2n_pow_c1 = _2n_pow_c1_1 * _2n2;
  const c2 = (q - _1n4) / _2n_pow_c1;
  const c3 = (c2 - _1n4) / _2n2;
  const c4 = _2n_pow_c1 - _1n4;
  const c5 = _2n_pow_c1_1;
  const c6 = Fp.pow(Z, c2);
  const c7 = Fp.pow(Z, (c2 + _1n4) / _2n2);
  let sqrtRatio = (u2, v) => {
    let tv1 = c6;
    let tv2 = Fp.pow(v, c4);
    let tv3 = Fp.sqr(tv2);
    tv3 = Fp.mul(tv3, v);
    let tv5 = Fp.mul(u2, tv3);
    tv5 = Fp.pow(tv5, c3);
    tv5 = Fp.mul(tv5, tv2);
    tv2 = Fp.mul(tv5, v);
    tv3 = Fp.mul(tv5, u2);
    let tv4 = Fp.mul(tv3, tv2);
    tv5 = Fp.pow(tv4, c5);
    let isQR = Fp.eql(tv5, Fp.ONE);
    tv2 = Fp.mul(tv3, c7);
    tv5 = Fp.mul(tv4, tv1);
    tv3 = Fp.cmov(tv2, tv3, isQR);
    tv4 = Fp.cmov(tv5, tv4, isQR);
    for (let i3 = c1; i3 > _1n4; i3--) {
      let tv52 = i3 - _2n2;
      tv52 = _2n2 << tv52 - _1n4;
      let tvv5 = Fp.pow(tv4, tv52);
      const e1 = Fp.eql(tvv5, Fp.ONE);
      tv2 = Fp.mul(tv3, tv1);
      tv1 = Fp.mul(tv1, tv1);
      tvv5 = Fp.mul(tv4, tv1);
      tv3 = Fp.cmov(tv2, tv3, e1);
      tv4 = Fp.cmov(tvv5, tv4, e1);
    }
    return { isValid: isQR, value: tv3 };
  };
  if (Fp.ORDER % _4n2 === _3n2) {
    const c12 = (Fp.ORDER - _3n2) / _4n2;
    const c22 = Fp.sqrt(Fp.neg(Z));
    sqrtRatio = (u2, v) => {
      let tv1 = Fp.sqr(v);
      const tv2 = Fp.mul(u2, v);
      tv1 = Fp.mul(tv1, tv2);
      let y1 = Fp.pow(tv1, c12);
      y1 = Fp.mul(y1, tv2);
      const y2 = Fp.mul(y1, c22);
      const tv3 = Fp.mul(Fp.sqr(y1), v);
      const isQR = Fp.eql(tv3, u2);
      let y3 = Fp.cmov(y2, y1, isQR);
      return { isValid: isQR, value: y3 };
    };
  }
  return sqrtRatio;
}
function mapToCurveSimpleSWU(Fp, opts) {
  validateField(Fp);
  const { A, B: B2, Z } = opts;
  if (!Fp.isValid(A) || !Fp.isValid(B2) || !Fp.isValid(Z))
    throw new Error("mapToCurveSimpleSWU: invalid opts");
  const sqrtRatio = SWUFpSqrtRatio(Fp, Z);
  if (!Fp.isOdd)
    throw new Error("Field does not have .isOdd()");
  return (u2) => {
    let tv1, tv2, tv3, tv4, tv5, tv6, x, y2;
    tv1 = Fp.sqr(u2);
    tv1 = Fp.mul(tv1, Z);
    tv2 = Fp.sqr(tv1);
    tv2 = Fp.add(tv2, tv1);
    tv3 = Fp.add(tv2, Fp.ONE);
    tv3 = Fp.mul(tv3, B2);
    tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO));
    tv4 = Fp.mul(tv4, A);
    tv2 = Fp.sqr(tv3);
    tv6 = Fp.sqr(tv4);
    tv5 = Fp.mul(tv6, A);
    tv2 = Fp.add(tv2, tv5);
    tv2 = Fp.mul(tv2, tv3);
    tv6 = Fp.mul(tv6, tv4);
    tv5 = Fp.mul(tv6, B2);
    tv2 = Fp.add(tv2, tv5);
    x = Fp.mul(tv1, tv3);
    const { isValid, value } = sqrtRatio(tv2, tv6);
    y2 = Fp.mul(tv1, u2);
    y2 = Fp.mul(y2, value);
    x = Fp.cmov(x, tv3, isValid);
    y2 = Fp.cmov(y2, value, isValid);
    const e1 = Fp.isOdd(u2) === Fp.isOdd(y2);
    y2 = Fp.cmov(Fp.neg(y2), y2, e1);
    const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];
    x = Fp.mul(x, tv4_inv);
    return { x, y: y2 };
  };
}
function getWLengths(Fp, Fn) {
  return {
    secretKey: Fn.BYTES,
    publicKey: 1 + Fp.BYTES,
    publicKeyUncompressed: 1 + 2 * Fp.BYTES,
    publicKeyHasPrefix: true,
    signature: 2 * Fn.BYTES
  };
}
function ecdh(Point, ecdhOpts = {}) {
  const { Fn } = Point;
  const randomBytes_ = ecdhOpts.randomBytes || randomBytes;
  const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
  function isValidSecretKey(secretKey) {
    try {
      return !!_normFnElement(Fn, secretKey);
    } catch (error) {
      return false;
    }
  }
  function isValidPublicKey(publicKey, isCompressed) {
    const { publicKey: comp, publicKeyUncompressed } = lengths;
    try {
      const l2 = publicKey.length;
      if (isCompressed === true && l2 !== comp)
        return false;
      if (isCompressed === false && l2 !== publicKeyUncompressed)
        return false;
      return !!Point.fromBytes(publicKey);
    } catch (error) {
      return false;
    }
  }
  function randomSecretKey(seed = randomBytes_(lengths.seed)) {
    return mapHashToField(_abytes2(seed, lengths.seed, "seed"), Fn.ORDER);
  }
  function getPublicKey(secretKey, isCompressed = true) {
    return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
  }
  function keygen(seed) {
    const secretKey = randomSecretKey(seed);
    return { secretKey, publicKey: getPublicKey(secretKey) };
  }
  function isProbPub(item) {
    if (typeof item === "bigint")
      return false;
    if (item instanceof Point)
      return true;
    const { secretKey, publicKey, publicKeyUncompressed } = lengths;
    if (Fn.allowedLengths || secretKey === publicKey)
      return void 0;
    const l2 = ensureBytes("key", item).length;
    return l2 === publicKey || l2 === publicKeyUncompressed;
  }
  function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
    if (isProbPub(secretKeyA) === true)
      throw new Error("first arg must be private key");
    if (isProbPub(publicKeyB) === false)
      throw new Error("second arg must be public key");
    const s3 = _normFnElement(Fn, secretKeyA);
    const b2 = Point.fromHex(publicKeyB);
    return b2.multiply(s3).toBytes(isCompressed);
  }
  const utils = {
    isValidSecretKey,
    isValidPublicKey,
    randomSecretKey,
    // TODO: remove
    isValidPrivateKey: isValidSecretKey,
    randomPrivateKey: randomSecretKey,
    normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
    precompute(windowSize = 8, point = Point.BASE) {
      return point.precompute(windowSize, false);
    }
  };
  return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
}
function ecdsa(Point, hash, ecdsaOpts = {}) {
  ahash(hash);
  _validateObject(ecdsaOpts, {}, {
    hmac: "function",
    lowS: "boolean",
    randomBytes: "function",
    bits2int: "function",
    bits2int_modN: "function"
  });
  const randomBytes3 = ecdsaOpts.randomBytes || randomBytes;
  const hmac2 = ecdsaOpts.hmac || ((key, ...msgs) => hmac(hash, key, concatBytes(...msgs)));
  const { Fp, Fn } = Point;
  const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
  const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
  const defaultSigOpts = {
    prehash: false,
    lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : false,
    format: void 0,
    //'compact' as ECDSASigFormat,
    extraEntropy: false
  };
  const defaultSigOpts_format = "compact";
  function isBiggerThanHalfOrder(number) {
    const HALF = CURVE_ORDER >> _1n4;
    return number > HALF;
  }
  function validateRS(title, num2) {
    if (!Fn.isValidNot0(num2))
      throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
    return num2;
  }
  function validateSigLength(bytes, format) {
    validateSigFormat(format);
    const size = lengths.signature;
    const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
    return _abytes2(bytes, sizer, `${format} signature`);
  }
  class Signature {
    constructor(r3, s3, recovery) {
      this.r = validateRS("r", r3);
      this.s = validateRS("s", s3);
      if (recovery != null)
        this.recovery = recovery;
      Object.freeze(this);
    }
    static fromBytes(bytes, format = defaultSigOpts_format) {
      validateSigLength(bytes, format);
      let recid;
      if (format === "der") {
        const { r: r4, s: s4 } = DER.toSig(_abytes2(bytes));
        return new Signature(r4, s4);
      }
      if (format === "recovered") {
        recid = bytes[0];
        format = "compact";
        bytes = bytes.subarray(1);
      }
      const L = Fn.BYTES;
      const r3 = bytes.subarray(0, L);
      const s3 = bytes.subarray(L, L * 2);
      return new Signature(Fn.fromBytes(r3), Fn.fromBytes(s3), recid);
    }
    static fromHex(hex, format) {
      return this.fromBytes(hexToBytes(hex), format);
    }
    addRecoveryBit(recovery) {
      return new Signature(this.r, this.s, recovery);
    }
    recoverPublicKey(messageHash) {
      const FIELD_ORDER = Fp.ORDER;
      const { r: r3, s: s3, recovery: rec } = this;
      if (rec == null || ![0, 1, 2, 3].includes(rec))
        throw new Error("recovery id invalid");
      const hasCofactor = CURVE_ORDER * _2n2 < FIELD_ORDER;
      if (hasCofactor && rec > 1)
        throw new Error("recovery id is ambiguous for h>1 curve");
      const radj = rec === 2 || rec === 3 ? r3 + CURVE_ORDER : r3;
      if (!Fp.isValid(radj))
        throw new Error("recovery id 2 or 3 invalid");
      const x = Fp.toBytes(radj);
      const R2 = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
      const ir = Fn.inv(radj);
      const h2 = bits2int_modN(ensureBytes("msgHash", messageHash));
      const u1 = Fn.create(-h2 * ir);
      const u2 = Fn.create(s3 * ir);
      const Q = Point.BASE.multiplyUnsafe(u1).add(R2.multiplyUnsafe(u2));
      if (Q.is0())
        throw new Error("point at infinify");
      Q.assertValidity();
      return Q;
    }
    // Signatures should be low-s, to prevent malleability.
    hasHighS() {
      return isBiggerThanHalfOrder(this.s);
    }
    toBytes(format = defaultSigOpts_format) {
      validateSigFormat(format);
      if (format === "der")
        return hexToBytes(DER.hexFromSig(this));
      const r3 = Fn.toBytes(this.r);
      const s3 = Fn.toBytes(this.s);
      if (format === "recovered") {
        if (this.recovery == null)
          throw new Error("recovery bit must be present");
        return concatBytes(Uint8Array.of(this.recovery), r3, s3);
      }
      return concatBytes(r3, s3);
    }
    toHex(format) {
      return bytesToHex(this.toBytes(format));
    }
    // TODO: remove
    assertValidity() {
    }
    static fromCompact(hex) {
      return Signature.fromBytes(ensureBytes("sig", hex), "compact");
    }
    static fromDER(hex) {
      return Signature.fromBytes(ensureBytes("sig", hex), "der");
    }
    normalizeS() {
      return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
    }
    toDERRawBytes() {
      return this.toBytes("der");
    }
    toDERHex() {
      return bytesToHex(this.toBytes("der"));
    }
    toCompactRawBytes() {
      return this.toBytes("compact");
    }
    toCompactHex() {
      return bytesToHex(this.toBytes("compact"));
    }
  }
  const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
    if (bytes.length > 8192)
      throw new Error("input is too large");
    const num2 = bytesToNumberBE(bytes);
    const delta = bytes.length * 8 - fnBits;
    return delta > 0 ? num2 >> BigInt(delta) : num2;
  };
  const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
    return Fn.create(bits2int(bytes));
  };
  const ORDER_MASK = bitMask(fnBits);
  function int2octets(num2) {
    aInRange("num < 2^" + fnBits, num2, _0n4, ORDER_MASK);
    return Fn.toBytes(num2);
  }
  function validateMsgAndHash(message, prehash) {
    _abytes2(message, void 0, "message");
    return prehash ? _abytes2(hash(message), void 0, "prehashed message") : message;
  }
  function prepSig(message, privateKey, opts) {
    if (["recovered", "canonical"].some((k) => k in opts))
      throw new Error("sign() legacy options not supported");
    const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
    message = validateMsgAndHash(message, prehash);
    const h1int = bits2int_modN(message);
    const d2 = _normFnElement(Fn, privateKey);
    const seedArgs = [int2octets(d2), int2octets(h1int)];
    if (extraEntropy != null && extraEntropy !== false) {
      const e3 = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
      seedArgs.push(ensureBytes("extraEntropy", e3));
    }
    const seed = concatBytes(...seedArgs);
    const m2 = h1int;
    function k2sig(kBytes) {
      const k = bits2int(kBytes);
      if (!Fn.isValidNot0(k))
        return;
      const ik = Fn.inv(k);
      const q = Point.BASE.multiply(k).toAffine();
      const r3 = Fn.create(q.x);
      if (r3 === _0n4)
        return;
      const s3 = Fn.create(ik * Fn.create(m2 + r3 * d2));
      if (s3 === _0n4)
        return;
      let recovery = (q.x === r3 ? 0 : 2) | Number(q.y & _1n4);
      let normS = s3;
      if (lowS && isBiggerThanHalfOrder(s3)) {
        normS = Fn.neg(s3);
        recovery ^= 1;
      }
      return new Signature(r3, normS, recovery);
    }
    return { seed, k2sig };
  }
  function sign(message, secretKey, opts = {}) {
    message = ensureBytes("message", message);
    const { seed, k2sig } = prepSig(message, secretKey, opts);
    const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
    const sig = drbg(seed, k2sig);
    return sig;
  }
  function tryParsingSig(sg) {
    let sig = void 0;
    const isHex = typeof sg === "string" || isBytes(sg);
    const isObj = !isHex && sg !== null && typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint";
    if (!isHex && !isObj)
      throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
    if (isObj) {
      sig = new Signature(sg.r, sg.s);
    } else if (isHex) {
      try {
        sig = Signature.fromBytes(ensureBytes("sig", sg), "der");
      } catch (derError) {
        if (!(derError instanceof DER.Err))
          throw derError;
      }
      if (!sig) {
        try {
          sig = Signature.fromBytes(ensureBytes("sig", sg), "compact");
        } catch (error) {
          return false;
        }
      }
    }
    if (!sig)
      return false;
    return sig;
  }
  function verify(signature, message, publicKey, opts = {}) {
    const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
    publicKey = ensureBytes("publicKey", publicKey);
    message = validateMsgAndHash(ensureBytes("message", message), prehash);
    if ("strict" in opts)
      throw new Error("options.strict was renamed to lowS");
    const sig = format === void 0 ? tryParsingSig(signature) : Signature.fromBytes(ensureBytes("sig", signature), format);
    if (sig === false)
      return false;
    try {
      const P = Point.fromBytes(publicKey);
      if (lowS && sig.hasHighS())
        return false;
      const { r: r3, s: s3 } = sig;
      const h2 = bits2int_modN(message);
      const is = Fn.inv(s3);
      const u1 = Fn.create(h2 * is);
      const u2 = Fn.create(r3 * is);
      const R2 = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
      if (R2.is0())
        return false;
      const v = Fn.create(R2.x);
      return v === r3;
    } catch (e3) {
      return false;
    }
  }
  function recoverPublicKey(signature, message, opts = {}) {
    const { prehash } = validateSigOpts(opts, defaultSigOpts);
    message = validateMsgAndHash(message, prehash);
    return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
  }
  return Object.freeze({
    keygen,
    getPublicKey,
    getSharedSecret,
    utils,
    lengths,
    Point,
    sign,
    verify,
    recoverPublicKey,
    Signature,
    hash
  });
}
function _weierstrass_legacy_opts_to_new(c) {
  const CURVE = {
    a: c.a,
    b: c.b,
    p: c.Fp.ORDER,
    n: c.n,
    h: c.h,
    Gx: c.Gx,
    Gy: c.Gy
  };
  const Fp = c.Fp;
  let allowedLengths = c.allowedPrivateKeyLengths ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l2) => Math.ceil(l2 / 2)))) : void 0;
  const Fn = Field(CURVE.n, {
    BITS: c.nBitLength,
    allowedLengths,
    modFromBytes: c.wrapPrivateKey
  });
  const curveOpts = {
    Fp,
    Fn,
    allowInfinityPoint: c.allowInfinityPoint,
    endo: c.endo,
    isTorsionFree: c.isTorsionFree,
    clearCofactor: c.clearCofactor,
    fromBytes: c.fromBytes,
    toBytes: c.toBytes
  };
  return { CURVE, curveOpts };
}
function _ecdsa_legacy_opts_to_new(c) {
  const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
  const ecdsaOpts = {
    hmac: c.hmac,
    randomBytes: c.randomBytes,
    lowS: c.lowS,
    bits2int: c.bits2int,
    bits2int_modN: c.bits2int_modN
  };
  return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
}
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
  const Point = _ecdsa.Point;
  return Object.assign({}, _ecdsa, {
    ProjectivePoint: Point,
    CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS))
  });
}
function weierstrass(c) {
  const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
  const Point = weierstrassN(CURVE, curveOpts);
  const signs = ecdsa(Point, hash, ecdsaOpts);
  return _ecdsa_new_output_to_legacy(c, signs);
}
var divNearest, DERErr, DER, _0n4, _1n4, _2n2, _3n2, _4n2;
var init_weierstrass = __esm({
  "node_modules/@noble/curves/esm/abstract/weierstrass.js"() {
    init_hmac();
    init_utils();
    init_utils2();
    init_curve();
    init_modular();
    divNearest = (num2, den) => (num2 + (num2 >= 0 ? den : -den) / _2n2) / den;
    DERErr = class extends Error {
      constructor(m2 = "") {
        super(m2);
      }
    };
    DER = {
      // asn.1 DER encoding utils
      Err: DERErr,
      // Basic building block is TLV (Tag-Length-Value)
      _tlv: {
        encode: (tag, data) => {
          const { Err: E } = DER;
          if (tag < 0 || tag > 256)
            throw new E("tlv.encode: wrong tag");
          if (data.length & 1)
            throw new E("tlv.encode: unpadded data");
          const dataLen = data.length / 2;
          const len = numberToHexUnpadded(dataLen);
          if (len.length / 2 & 128)
            throw new E("tlv.encode: long form length too big");
          const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
          const t2 = numberToHexUnpadded(tag);
          return t2 + lenLen + len + data;
        },
        // v - value, l - left bytes (unparsed)
        decode(tag, data) {
          const { Err: E } = DER;
          let pos = 0;
          if (tag < 0 || tag > 256)
            throw new E("tlv.encode: wrong tag");
          if (data.length < 2 || data[pos++] !== tag)
            throw new E("tlv.decode: wrong tlv");
          const first = data[pos++];
          const isLong = !!(first & 128);
          let length = 0;
          if (!isLong)
            length = first;
          else {
            const lenLen = first & 127;
            if (!lenLen)
              throw new E("tlv.decode(long): indefinite length not supported");
            if (lenLen > 4)
              throw new E("tlv.decode(long): byte length is too big");
            const lengthBytes = data.subarray(pos, pos + lenLen);
            if (lengthBytes.length !== lenLen)
              throw new E("tlv.decode: length bytes not complete");
            if (lengthBytes[0] === 0)
              throw new E("tlv.decode(long): zero leftmost byte");
            for (const b2 of lengthBytes)
              length = length << 8 | b2;
            pos += lenLen;
            if (length < 128)
              throw new E("tlv.decode(long): not minimal encoding");
          }
          const v = data.subarray(pos, pos + length);
          if (v.length !== length)
            throw new E("tlv.decode: wrong value length");
          return { v, l: data.subarray(pos + length) };
        }
      },
      // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
      // since we always use positive integers here. It must always be empty:
      // - add zero byte if exists
      // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
      _int: {
        encode(num2) {
          const { Err: E } = DER;
          if (num2 < _0n4)
            throw new E("integer: negative integers are not allowed");
          let hex = numberToHexUnpadded(num2);
          if (Number.parseInt(hex[0], 16) & 8)
            hex = "00" + hex;
          if (hex.length & 1)
            throw new E("unexpected DER parsing assertion: unpadded hex");
          return hex;
        },
        decode(data) {
          const { Err: E } = DER;
          if (data[0] & 128)
            throw new E("invalid signature integer: negative");
          if (data[0] === 0 && !(data[1] & 128))
            throw new E("invalid signature integer: unnecessary leading zero");
          return bytesToNumberBE(data);
        }
      },
      toSig(hex) {
        const { Err: E, _int: int, _tlv: tlv } = DER;
        const data = ensureBytes("signature", hex);
        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
        if (seqLeftBytes.length)
          throw new E("invalid signature: left bytes after parsing");
        const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
        const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
        if (sLeftBytes.length)
          throw new E("invalid signature: left bytes after parsing");
        return { r: int.decode(rBytes), s: int.decode(sBytes) };
      },
      hexFromSig(sig) {
        const { _tlv: tlv, _int: int } = DER;
        const rs = tlv.encode(2, int.encode(sig.r));
        const ss = tlv.encode(2, int.encode(sig.s));
        const seq = rs + ss;
        return tlv.encode(48, seq);
      }
    };
    _0n4 = BigInt(0);
    _1n4 = BigInt(1);
    _2n2 = BigInt(2);
    _3n2 = BigInt(3);
    _4n2 = BigInt(4);
  }
});

// node_modules/@noble/curves/esm/_shortw_utils.js
function createCurve(curveDef, defHash) {
  const create = (hash) => weierstrass({ ...curveDef, hash });
  return { ...create(defHash), create };
}
var init_shortw_utils = __esm({
  "node_modules/@noble/curves/esm/_shortw_utils.js"() {
    init_weierstrass();
  }
});

// node_modules/@noble/curves/esm/abstract/hash-to-curve.js
function i2osp(value, length) {
  anum(value);
  anum(length);
  if (value < 0 || value >= 1 << 8 * length)
    throw new Error("invalid I2OSP input: " + value);
  const res = Array.from({ length }).fill(0);
  for (let i3 = length - 1; i3 >= 0; i3--) {
    res[i3] = value & 255;
    value >>>= 8;
  }
  return new Uint8Array(res);
}
function strxor(a, b2) {
  const arr = new Uint8Array(a.length);
  for (let i3 = 0; i3 < a.length; i3++) {
    arr[i3] = a[i3] ^ b2[i3];
  }
  return arr;
}
function anum(item) {
  if (!Number.isSafeInteger(item))
    throw new Error("number expected");
}
function normDST(DST) {
  if (!isBytes(DST) && typeof DST !== "string")
    throw new Error("DST must be Uint8Array or string");
  return typeof DST === "string" ? utf8ToBytes(DST) : DST;
}
function expand_message_xmd(msg, DST, lenInBytes, H) {
  abytes(msg);
  anum(lenInBytes);
  DST = normDST(DST);
  if (DST.length > 255)
    DST = H(concatBytes(utf8ToBytes("H2C-OVERSIZE-DST-"), DST));
  const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
  const ell = Math.ceil(lenInBytes / b_in_bytes);
  if (lenInBytes > 65535 || ell > 255)
    throw new Error("expand_message_xmd: invalid lenInBytes");
  const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
  const Z_pad = i2osp(0, r_in_bytes);
  const l_i_b_str = i2osp(lenInBytes, 2);
  const b2 = new Array(ell);
  const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
  b2[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
  for (let i3 = 1; i3 <= ell; i3++) {
    const args = [strxor(b_0, b2[i3 - 1]), i2osp(i3 + 1, 1), DST_prime];
    b2[i3] = H(concatBytes(...args));
  }
  const pseudo_random_bytes = concatBytes(...b2);
  return pseudo_random_bytes.slice(0, lenInBytes);
}
function expand_message_xof(msg, DST, lenInBytes, k, H) {
  abytes(msg);
  anum(lenInBytes);
  DST = normDST(DST);
  if (DST.length > 255) {
    const dkLen = Math.ceil(2 * k / 8);
    DST = H.create({ dkLen }).update(utf8ToBytes("H2C-OVERSIZE-DST-")).update(DST).digest();
  }
  if (lenInBytes > 65535 || DST.length > 255)
    throw new Error("expand_message_xof: invalid lenInBytes");
  return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest();
}
function hash_to_field(msg, count, options) {
  _validateObject(options, {
    p: "bigint",
    m: "number",
    k: "number",
    hash: "function"
  });
  const { p: p2, k, m: m2, hash, expand, DST } = options;
  if (!isHash(options.hash))
    throw new Error("expected valid hash");
  abytes(msg);
  anum(count);
  const log2p = p2.toString(2).length;
  const L = Math.ceil((log2p + k) / 8);
  const len_in_bytes = count * m2 * L;
  let prb;
  if (expand === "xmd") {
    prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
  } else if (expand === "xof") {
    prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
  } else if (expand === "_internal_pass") {
    prb = msg;
  } else {
    throw new Error('expand must be "xmd" or "xof"');
  }
  const u2 = new Array(count);
  for (let i3 = 0; i3 < count; i3++) {
    const e3 = new Array(m2);
    for (let j = 0; j < m2; j++) {
      const elm_offset = L * (j + i3 * m2);
      const tv = prb.subarray(elm_offset, elm_offset + L);
      e3[j] = mod(os2ip(tv), p2);
    }
    u2[i3] = e3;
  }
  return u2;
}
function isogenyMap(field, map) {
  const coeff = map.map((i3) => Array.from(i3).reverse());
  return (x, y2) => {
    const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i3) => field.add(field.mul(acc, x), i3)));
    const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
    x = field.mul(xn, xd_inv);
    y2 = field.mul(y2, field.mul(yn, yd_inv));
    return { x, y: y2 };
  };
}
function createHasher2(Point, mapToCurve, defaults) {
  if (typeof mapToCurve !== "function")
    throw new Error("mapToCurve() must be defined");
  function map(num2) {
    return Point.fromAffine(mapToCurve(num2));
  }
  function clear(initial) {
    const P = initial.clearCofactor();
    if (P.equals(Point.ZERO))
      return Point.ZERO;
    P.assertValidity();
    return P;
  }
  return {
    defaults,
    hashToCurve(msg, options) {
      const opts = Object.assign({}, defaults, options);
      const u2 = hash_to_field(msg, 2, opts);
      const u0 = map(u2[0]);
      const u1 = map(u2[1]);
      return clear(u0.add(u1));
    },
    encodeToCurve(msg, options) {
      const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
      const opts = Object.assign({}, defaults, optsDst, options);
      const u2 = hash_to_field(msg, 1, opts);
      const u0 = map(u2[0]);
      return clear(u0);
    },
    /** See {@link H2CHasher} */
    mapToCurve(scalars) {
      if (!Array.isArray(scalars))
        throw new Error("expected array of bigints");
      for (const i3 of scalars)
        if (typeof i3 !== "bigint")
          throw new Error("expected array of bigints");
      return clear(map(scalars));
    },
    // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
    // RFC 9380, draft-irtf-cfrg-bbs-signatures-08
    hashToScalar(msg, options) {
      const N2 = Point.Fn.ORDER;
      const opts = Object.assign({}, defaults, { p: N2, m: 1, DST: _DST_scalar }, options);
      return hash_to_field(msg, 1, opts)[0][0];
    }
  };
}
var os2ip, _DST_scalar;
var init_hash_to_curve = __esm({
  "node_modules/@noble/curves/esm/abstract/hash-to-curve.js"() {
    init_utils2();
    init_modular();
    os2ip = bytesToNumberBE;
    _DST_scalar = utf8ToBytes("HashToScalar-");
  }
});

// node_modules/@noble/curves/esm/secp256k1.js
var secp256k1_exports = {};
__export(secp256k1_exports, {
  encodeToCurve: () => encodeToCurve,
  hashToCurve: () => hashToCurve,
  schnorr: () => schnorr,
  secp256k1: () => secp256k1,
  secp256k1_hasher: () => secp256k1_hasher
});
function sqrtMod(y2) {
  const P = secp256k1_CURVE.p;
  const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
  const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
  const b2 = y2 * y2 * y2 % P;
  const b3 = b2 * b2 * y2 % P;
  const b6 = pow2(b3, _3n3, P) * b3 % P;
  const b9 = pow2(b6, _3n3, P) * b3 % P;
  const b11 = pow2(b9, _2n3, P) * b2 % P;
  const b22 = pow2(b11, _11n, P) * b11 % P;
  const b44 = pow2(b22, _22n, P) * b22 % P;
  const b88 = pow2(b44, _44n, P) * b44 % P;
  const b176 = pow2(b88, _88n, P) * b88 % P;
  const b220 = pow2(b176, _44n, P) * b44 % P;
  const b223 = pow2(b220, _3n3, P) * b3 % P;
  const t1 = pow2(b223, _23n, P) * b22 % P;
  const t2 = pow2(t1, _6n, P) * b2 % P;
  const root2 = pow2(t2, _2n3, P);
  if (!Fpk1.eql(Fpk1.sqr(root2), y2))
    throw new Error("Cannot find square root");
  return root2;
}
function taggedHash(tag, ...messages) {
  let tagP = TAGGED_HASH_PREFIXES[tag];
  if (tagP === void 0) {
    const tagH = sha256(utf8ToBytes(tag));
    tagP = concatBytes(tagH, tagH);
    TAGGED_HASH_PREFIXES[tag] = tagP;
  }
  return sha256(concatBytes(tagP, ...messages));
}
function schnorrGetExtPubKey(priv) {
  const { Fn, BASE } = Pointk1;
  const d_ = _normFnElement(Fn, priv);
  const p2 = BASE.multiply(d_);
  const scalar = hasEven(p2.y) ? d_ : Fn.neg(d_);
  return { scalar, bytes: pointToBytes(p2) };
}
function lift_x(x) {
  const Fp = Fpk1;
  if (!Fp.isValidNot0(x))
    throw new Error("invalid x: Fail if x \u2265 p");
  const xx = Fp.create(x * x);
  const c = Fp.create(xx * x + BigInt(7));
  let y2 = Fp.sqrt(c);
  if (!hasEven(y2))
    y2 = Fp.neg(y2);
  const p2 = Pointk1.fromAffine({ x, y: y2 });
  p2.assertValidity();
  return p2;
}
function challenge(...args) {
  return Pointk1.Fn.create(num(taggedHash("BIP0340/challenge", ...args)));
}
function schnorrGetPublicKey(secretKey) {
  return schnorrGetExtPubKey(secretKey).bytes;
}
function schnorrSign(message, secretKey, auxRand = randomBytes(32)) {
  const { Fn } = Pointk1;
  const m2 = ensureBytes("message", message);
  const { bytes: px, scalar: d2 } = schnorrGetExtPubKey(secretKey);
  const a = ensureBytes("auxRand", auxRand, 32);
  const t2 = Fn.toBytes(d2 ^ num(taggedHash("BIP0340/aux", a)));
  const rand = taggedHash("BIP0340/nonce", t2, px, m2);
  const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
  const e3 = challenge(rx, px, m2);
  const sig = new Uint8Array(64);
  sig.set(rx, 0);
  sig.set(Fn.toBytes(Fn.create(k + e3 * d2)), 32);
  if (!schnorrVerify(sig, m2, px))
    throw new Error("sign: Invalid signature produced");
  return sig;
}
function schnorrVerify(signature, message, publicKey) {
  const { Fn, BASE } = Pointk1;
  const sig = ensureBytes("signature", signature, 64);
  const m2 = ensureBytes("message", message);
  const pub = ensureBytes("publicKey", publicKey, 32);
  try {
    const P = lift_x(num(pub));
    const r3 = num(sig.subarray(0, 32));
    if (!inRange(r3, _1n5, secp256k1_CURVE.p))
      return false;
    const s3 = num(sig.subarray(32, 64));
    if (!inRange(s3, _1n5, secp256k1_CURVE.n))
      return false;
    const e3 = challenge(Fn.toBytes(r3), pointToBytes(P), m2);
    const R2 = BASE.multiplyUnsafe(s3).add(P.multiplyUnsafe(Fn.neg(e3)));
    const { x, y: y2 } = R2.toAffine();
    if (R2.is0() || !hasEven(y2) || x !== r3)
      return false;
    return true;
  } catch (error) {
    return false;
  }
}
var secp256k1_CURVE, secp256k1_ENDO, _0n5, _1n5, _2n3, Fpk1, secp256k1, TAGGED_HASH_PREFIXES, pointToBytes, Pointk1, hasEven, num, schnorr, isoMap, mapSWU, secp256k1_hasher, hashToCurve, encodeToCurve;
var init_secp256k1 = __esm({
  "node_modules/@noble/curves/esm/secp256k1.js"() {
    init_sha2();
    init_utils();
    init_shortw_utils();
    init_hash_to_curve();
    init_modular();
    init_weierstrass();
    init_utils2();
    secp256k1_CURVE = {
      p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
      n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
      h: BigInt(1),
      a: BigInt(0),
      b: BigInt(7),
      Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
      Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
    };
    secp256k1_ENDO = {
      beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
      basises: [
        [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
        [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
      ]
    };
    _0n5 = /* @__PURE__ */ BigInt(0);
    _1n5 = /* @__PURE__ */ BigInt(1);
    _2n3 = /* @__PURE__ */ BigInt(2);
    Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
    secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
    TAGGED_HASH_PREFIXES = {};
    pointToBytes = (point) => point.toBytes(true).slice(1);
    Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();
    hasEven = (y2) => y2 % _2n3 === _0n5;
    num = bytesToNumberBE;
    schnorr = /* @__PURE__ */ (() => {
      const size = 32;
      const seedLength = 48;
      const randomSecretKey = (seed = randomBytes(seedLength)) => {
        return mapHashToField(seed, secp256k1_CURVE.n);
      };
      secp256k1.utils.randomSecretKey;
      function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };
      }
      return {
        keygen,
        getPublicKey: schnorrGetPublicKey,
        sign: schnorrSign,
        verify: schnorrVerify,
        Point: Pointk1,
        utils: {
          randomSecretKey,
          randomPrivateKey: randomSecretKey,
          taggedHash,
          // TODO: remove
          lift_x,
          pointToBytes,
          numberToBytesBE,
          bytesToNumberBE,
          mod
        },
        lengths: {
          secretKey: size,
          publicKey: size,
          publicKeyHasPrefix: false,
          signature: size * 2,
          seed: seedLength
        }
      };
    })();
    isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [
      // xNum
      [
        "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7",
        "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581",
        "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262",
        "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"
      ],
      // xDen
      [
        "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b",
        "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14",
        "0x0000000000000000000000000000000000000000000000000000000000000001"
        // LAST 1
      ],
      // yNum
      [
        "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c",
        "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3",
        "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931",
        "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"
      ],
      // yDen
      [
        "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b",
        "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573",
        "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f",
        "0x0000000000000000000000000000000000000000000000000000000000000001"
        // LAST 1
      ]
    ].map((i3) => i3.map((j) => BigInt(j)))))();
    mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {
      A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),
      B: BigInt("1771"),
      Z: Fpk1.create(BigInt("-11"))
    }))();
    secp256k1_hasher = /* @__PURE__ */ (() => createHasher2(secp256k1.Point, (scalars) => {
      const { x, y: y2 } = mapSWU(Fpk1.create(scalars[0]));
      return isoMap(x, y2);
    }, {
      DST: "secp256k1_XMD:SHA-256_SSWU_RO_",
      encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_",
      p: Fpk1.ORDER,
      m: 1,
      k: 128,
      expand: "xmd",
      hash: sha256
    }))();
    hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();
    encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();
  }
});

// node_modules/@noble/hashes/esm/sha256.js
var sha2562;
var init_sha256 = __esm({
  "node_modules/@noble/hashes/esm/sha256.js"() {
    init_sha2();
    sha2562 = sha256;
  }
});

// src/lib/nodeIdentity.js
async function storageGet(k) {
  try {
    if (globalThis.chrome?.storage?.local) {
      const o3 = await chrome.storage.local.get(k);
      return o3?.[k];
    }
  } catch {
  }
  try {
    return localStorage.getItem(k);
  } catch {
    return null;
  }
}
async function storageSet(k, v) {
  try {
    if (globalThis.chrome?.storage?.local) {
      await chrome.storage.local.set({ [k]: v });
      return;
    }
  } catch {
  }
  try {
    localStorage.setItem(k, typeof v === "string" ? v : JSON.stringify(v));
  } catch {
  }
}
function fromHex(h2) {
  const s3 = String(h2 || "").replace(/^0x/i, "");
  if (s3.length % 2) throw new Error("odd-length hex");
  const out = new Uint8Array(s3.length / 2);
  for (let i3 = 0; i3 < out.length; i3++) out[i3] = parseInt(s3.slice(i3 * 2, i3 * 2 + 2), 16);
  return out;
}
async function getNodeIdentity() {
  let rec = await storageGet(ID_KEY);
  if (typeof rec === "string") {
    try {
      rec = JSON.parse(rec);
    } catch {
      rec = null;
    }
  }
  if (rec?.privHex && rec?.pubHex) return rec;
  const priv = secp256k1.utils.randomPrivateKey();
  const identity = {
    v: 1,
    privHex: toHex(priv),
    pubHex: toHex(secp256k1.getPublicKey(priv, true)),
    at: Date.now()
  };
  await storageSet(ID_KEY, identity);
  return identity;
}
async function deriveKey(sharedX, ephPubHex, recipientPubHex) {
  const base = await crypto.subtle.importKey("raw", sharedX, "HKDF", false, ["deriveKey"]);
  return crypto.subtle.deriveKey(
    {
      name: "HKDF",
      hash: "SHA-256",
      salt: sha2562(utf8(`${SEAL_VERSION}|${ephPubHex}|${recipientPubHex}`)),
      // Binding the transcript into `info` means a sealed piece cannot be
      // replayed under a different version or recipient.
      info: utf8(SEAL_VERSION)
    },
    base,
    { name: "AES-GCM", length: 256 },
    false,
    ["encrypt", "decrypt"]
  );
}
async function sealTo(recipientPubHex, plaintext, aad = "") {
  const bytes = typeof plaintext === "string" ? utf8(plaintext) : plaintext;
  const eph = secp256k1.utils.randomPrivateKey();
  const ephPubHex = toHex(secp256k1.getPublicKey(eph, true));
  const shared = secp256k1.getSharedSecret(eph, fromHex(recipientPubHex), true);
  const key = await deriveKey(shared.slice(1), ephPubHex, String(recipientPubHex));
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const ct = await crypto.subtle.encrypt(
    { name: "AES-GCM", iv, additionalData: utf8(aad) },
    key,
    bytes
  );
  return {
    v: SEAL_VERSION,
    epk: ephPubHex,
    iv: toHex(iv),
    ct: toHex(new Uint8Array(ct)),
    aad: String(aad)
  };
}
async function unseal(sealed, privHex) {
  if (!sealed?.epk || !sealed?.iv || !sealed?.ct) throw new Error("malformed sealed blob");
  if (sealed.v && sealed.v !== SEAL_VERSION) throw new Error(`unknown seal version ${sealed.v}`);
  const priv = privHex || (await getNodeIdentity()).privHex;
  const pubHex = toHex(secp256k1.getPublicKey(fromHex(priv), true));
  const shared = secp256k1.getSharedSecret(fromHex(priv), fromHex(sealed.epk), true);
  const key = await deriveKey(shared.slice(1), sealed.epk, pubHex);
  const pt = await crypto.subtle.decrypt(
    { name: "AES-GCM", iv: fromHex(sealed.iv), additionalData: utf8(sealed.aad || "") },
    key,
    fromHex(sealed.ct)
  );
  return new Uint8Array(pt);
}
async function sealJson(recipientPubHex, value, aad = "") {
  return sealTo(recipientPubHex, utf8(JSON.stringify(value)), aad);
}
async function unsealJson(sealed, privHex) {
  return JSON.parse(new TextDecoder().decode(await unseal(sealed, privHex)));
}
function attestationDigest(claim) {
  const ordered = Object.keys(claim || {}).sort().map((k) => `${k}=${claim[k]}`).join("&");
  return sha2562(utf8(`wart-node-attest-v1|${ordered}`));
}
async function attest(claim) {
  const { privHex, pubHex } = await getNodeIdentity();
  const sig = secp256k1.sign(attestationDigest(claim), fromHex(privHex));
  return { pubHex, sigHex: toHex(sig.toCompactRawBytes()), claim };
}
var ID_KEY, SEAL_VERSION, toHex, utf8;
var init_nodeIdentity = __esm({
  "src/lib/nodeIdentity.js"() {
    "use strict";
    init_secp256k1();
    init_sha256();
    ID_KEY = "node.identity.v1";
    SEAL_VERSION = "seal-v1";
    toHex = (b2) => [...b2].map((x) => x.toString(16).padStart(2, "0")).join("");
    utf8 = (s3) => new TextEncoder().encode(String(s3));
  }
});

// src/lib/sealedPreshare.js
function xOf(id) {
  const x = modN(BigInt("0x" + toHex(sha2562(utf82(String(id))))));
  return x === 0n ? 1n : x;
}
function invN(a) {
  let [old_r, r3] = [modN(a), N];
  let [old_s, s3] = [1n, 0n];
  while (r3 !== 0n) {
    const q = old_r / r3;
    [old_r, r3] = [r3, old_r - q * r3];
    [old_s, s3] = [s3, old_s - q * s3];
  }
  return modN(old_s);
}
function shamirSplit(secretHex, ids, t2) {
  const coeffs = [BigInt("0x" + String(secretHex).replace(/^0x/i, ""))];
  for (let i3 = 1; i3 < t2; i3++) {
    const b2 = new Uint8Array(32);
    crypto.getRandomValues(b2);
    coeffs.push(modN(BigInt("0x" + toHex(b2))));
  }
  return ids.map((id) => {
    const x = xOf(id);
    let y2 = 0n;
    let p2 = 1n;
    for (const a of coeffs) {
      y2 = modN(y2 + a * p2);
      p2 = modN(p2 * x);
    }
    return { id, x: x.toString(), y: y2.toString(16).padStart(64, "0") };
  });
}
function shamirCombine(shares) {
  const pts = (shares || []).filter((s3) => s3?.x && s3?.y).map((s3) => ({ x: modN(BigInt(s3.x)), y: modN(BigInt("0x" + s3.y)) }));
  if (pts.length < 2) return null;
  let acc = 0n;
  for (let i3 = 0; i3 < pts.length; i3++) {
    let num2 = 1n;
    let den = 1n;
    for (let j = 0; j < pts.length; j++) {
      if (i3 === j) continue;
      num2 = modN(num2 * modN(-pts[j].x));
      den = modN(den * modN(pts[i3].x - pts[j].x));
    }
    acc = modN(acc + pts[i3].y * num2 * invN(den));
  }
  return acc.toString(16).padStart(64, "0");
}
async function packKeyCipher(packKeyHex, aad) {
  const base = await crypto.subtle.importKey("raw", fromHex(packKeyHex), "HKDF", false, [
    "deriveKey"
  ]);
  return crypto.subtle.deriveKey(
    { name: "HKDF", hash: "SHA-256", salt: sha2562(utf82(`${PACK_VERSION}|${aad}`)), info: utf82(PACK_VERSION) },
    base,
    { name: "AES-GCM", length: 256 },
    false,
    ["encrypt", "decrypt"]
  );
}
async function buildPack({ record, targets, t: t2 = 2, aad = "" }) {
  const usable = (targets || []).filter((x) => x?.id && x?.pubHex);
  if (usable.length < t2) {
    throw new Error(`need ${t2} sealable targets, have ${usable.length}`);
  }
  const packKey = new Uint8Array(32);
  crypto.getRandomValues(packKey);
  const packKeyHex = modN(BigInt("0x" + toHex(packKey))).toString(16).padStart(64, "0");
  const pieces = shamirSplit(packKeyHex, usable.map((x) => x.id), t2);
  const sealed = [];
  for (const piece of pieces) {
    const to = usable.find((x) => x.id === piece.id);
    sealed.push({
      id: piece.id,
      x: piece.x,
      toPub: to.pubHex,
      sealed: await sealJson(to.pubHex, { x: piece.x, y: piece.y }, aad)
    });
  }
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const key = await packKeyCipher(packKeyHex, aad);
  const ct = await crypto.subtle.encrypt(
    { name: "AES-GCM", iv, additionalData: utf82(aad) },
    key,
    utf82(JSON.stringify(record))
  );
  return {
    v: PACK_VERSION,
    t: t2,
    n: sealed.length,
    aad,
    pieces: sealed,
    encRecord: { iv: toHex(iv), ct: toHex(new Uint8Array(ct)) }
  };
}
async function resealPiece({ piece, toPubHex, aad, privHex }) {
  const opened = await unsealJson(piece.sealed, privHex);
  return {
    id: piece.id,
    x: opened.x,
    toPub: toPubHex,
    sealed: await sealJson(toPubHex, opened, aad)
  };
}
async function openPack({ pack, resealed, privHex }) {
  const shares = [];
  for (const p2 of resealed || []) {
    try {
      shares.push(await unsealJson(p2.sealed, privHex));
    } catch {
    }
  }
  if (shares.length < Number(pack?.t || 2)) return null;
  const packKeyHex = shamirCombine(shares);
  if (!packKeyHex) return null;
  try {
    const key = await packKeyCipher(packKeyHex, pack.aad || "");
    const pt = await crypto.subtle.decrypt(
      { name: "AES-GCM", iv: fromHex(pack.encRecord.iv), additionalData: utf82(pack.aad || "") },
      key,
      fromHex(pack.encRecord.ct)
    );
    return JSON.parse(new TextDecoder().decode(pt));
  } catch {
    return null;
  }
}
function chooseTargets({ orbit, selfId, otherHolderId, pubKeys = {}, exclude = [], max = 4 }) {
  const banned = new Set([selfId, otherHolderId, ...exclude].filter(Boolean));
  return (orbit || []).filter((id) => id && !banned.has(id) && !/(^|-)(vps|coordinator)(-|$)/i.test(id)).map((id) => ({ id, pubHex: pubKeys[id] || null })).filter((x) => x.pubHex).slice(0, max);
}
function packAad({ pool, role, P }) {
  return `${pool}|role=${Number(role)}|P=${String(P || "").toLowerCase()}`;
}
var N, PACK_VERSION, utf82, modN;
var init_sealedPreshare = __esm({
  "src/lib/sealedPreshare.js"() {
    "use strict";
    init_sha256();
    init_nodeIdentity();
    N = BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");
    PACK_VERSION = "preshare-sealed-v1";
    utf82 = (s3) => new TextEncoder().encode(String(s3));
    modN = (x) => (x % N + N) % N;
  }
});

// src/lib/preshareClient.js
var preshareClient_exports = {};
__export(preshareClient_exports, {
  identityFields: () => identityFields,
  packSeat: () => packSeat,
  recoverSeat: () => recoverSeat,
  serveResealRequests: () => serveResealRequests
});
function sigOf(role, targets) {
  return `${role}:${targets.map((t2) => t2.id).sort().join(",")}`;
}
async function identityFields({ pool, role, seatEpoch, signerId }) {
  const { pubHex } = await getNodeIdentity();
  const att = await attest({
    pool,
    role: Number(role) || 0,
    seatEpoch: Number(seatEpoch) || 0,
    signerId: String(signerId || "")
  });
  return { nodePubHex: pubHex, attestation: { sigHex: att.sigHex, claim: att.claim } };
}
async function packSeat({
  post,
  prefix,
  pool,
  signerId,
  role,
  P,
  record,
  orbit,
  orbitKeys,
  otherHolderId,
  t: t2 = 2,
  max = 4
}) {
  if (!record || !P || !(Number(role) === 1 || Number(role) === 2)) return null;
  const targets = chooseTargets({
    orbit,
    selfId: signerId,
    otherHolderId,
    pubKeys: orbitKeys || {},
    max
  });
  if (targets.length < t2) return null;
  const sig = sigOf(role, targets);
  if (packSig.get(`${pool}:${role}`) === sig) return null;
  try {
    const pack = await buildPack({ record, targets, t: t2, aad: packAad({ pool, role, P }) });
    const r3 = await post(`${prefix}_preshare_put`, { signerId, role: Number(role), pack });
    if (r3?.ok === false) return null;
    packSig.set(`${pool}:${role}`, sig);
    return targets.map((x) => x.id);
  } catch {
    return null;
  }
}
async function serveResealRequests({ post, prefix, signerId, requests }) {
  if (!Array.isArray(requests) || !requests.length) return 0;
  const { privHex } = await getNodeIdentity();
  let served = 0;
  for (const req of requests) {
    if (!req?.piece || !req?.requesterPub || !req?.requesterId) continue;
    try {
      const resealed = await resealPiece({
        piece: req.piece,
        toPubHex: req.requesterPub,
        aad: req.aad || "",
        privHex
      });
      await post(`${prefix}_preshare_reseal_put`, {
        signerId,
        role: Number(req.role) || 0,
        requesterId: req.requesterId,
        resealed
      });
      served++;
    } catch {
    }
  }
  return served;
}
async function recoverSeat({ post, prefix, signerId, role, P, pool }) {
  const { pubHex, privHex } = await getNodeIdentity();
  const aad = packAad({ pool, role, P });
  try {
    await post(`${prefix}_preshare_reseal_request`, {
      signerId,
      role: Number(role),
      pubHex,
      aad
    });
  } catch {
    return null;
  }
  let r3;
  try {
    r3 = await post(`${prefix}_preshare_collect`, { signerId, role: Number(role) });
  } catch {
    return null;
  }
  if (!r3?.pack || !Array.isArray(r3.resealed) || !r3.resealed.length) return null;
  if (r3.stale) return null;
  const record = await openPack({ pack: r3.pack, resealed: r3.resealed, privHex });
  if (!record?.userShareHex) return null;
  return record;
}
var packSig;
var init_preshareClient = __esm({
  "src/lib/preshareClient.js"() {
    "use strict";
    init_sealedPreshare();
    init_nodeIdentity();
    packSig = /* @__PURE__ */ new Map();
  }
});

// node_modules/bigint-crypto-utils/dist/index.browser.esm.js
function n(n3) {
  return n3 >= 0 ? n3 : -n3;
}
function t(n3) {
  if ("number" == typeof n3 && (n3 = BigInt(n3)), 1n === n3) return 1;
  let t2 = 1;
  do {
    t2++;
  } while ((n3 >>= 1n) > 1n);
  return t2;
}
function e(n3, t2) {
  if ("number" == typeof n3 && (n3 = BigInt(n3)), "number" == typeof t2 && (t2 = BigInt(t2)), n3 <= 0n || t2 <= 0n) throw new RangeError("a and b MUST be > 0");
  let e3 = 0n, r3 = 1n, o3 = 1n, i3 = 0n;
  for (; 0n !== n3; ) {
    const s3 = t2 / n3, u2 = t2 % n3, a = e3 - o3 * s3, c = r3 - i3 * s3;
    t2 = n3, n3 = u2, e3 = o3, r3 = i3, o3 = a, i3 = c;
  }
  return { g: t2, x: e3, y: r3 };
}
function r(n3, t2) {
  if ("number" == typeof n3 && (n3 = BigInt(n3)), "number" == typeof t2 && (t2 = BigInt(t2)), t2 <= 0n) throw new RangeError("n must be > 0");
  const e3 = n3 % t2;
  return e3 < 0n ? e3 + t2 : e3;
}
function o(n3, t2) {
  const o3 = e(r(n3, t2), t2);
  if (1n !== o3.g) throw new RangeError(`${n3.toString()} does not have inverse modulo ${t2.toString()}`);
  return r(o3.x, t2);
}
function i(n3, t2, e3) {
  if (n3.length !== t2.length) throw new RangeError("The remainders and modulos arrays should have the same length");
  const i3 = e3 ?? t2.reduce(((n4, t3) => n4 * t3), 1n);
  return t2.reduce(((t3, e4, s3) => {
    const u2 = i3 / e4;
    return r(t3 + u2 * o(u2, e4) % i3 * n3[s3] % i3, i3);
  }), 0n);
}
function s(t2, e3) {
  let r3 = "number" == typeof t2 ? BigInt(n(t2)) : n(t2), o3 = "number" == typeof e3 ? BigInt(n(e3)) : n(e3);
  if (0n === r3) return o3;
  if (0n === o3) return r3;
  let i3 = 0n;
  for (; 0n === (1n & (r3 | o3)); ) r3 >>= 1n, o3 >>= 1n, i3++;
  for (; 0n === (1n & r3); ) r3 >>= 1n;
  do {
    for (; 0n === (1n & o3); ) o3 >>= 1n;
    if (r3 > o3) {
      const n3 = r3;
      r3 = o3, o3 = n3;
    }
    o3 -= r3;
  } while (0n !== o3);
  return r3 << i3;
}
function u(t2, e3) {
  return "number" == typeof t2 && (t2 = BigInt(t2)), "number" == typeof e3 && (e3 = BigInt(e3)), 0n === t2 && 0n === e3 ? BigInt(0) : n(t2 / s(t2, e3) * e3);
}
function m(n3) {
  return n3.map(((n4) => n4[0] ** (n4[1] - 1n) * (n4[0] - 1n))).reduce(((n4, t2) => t2 * n4), 1n);
}
function d(t2, e3, s3, u2) {
  if ("number" == typeof t2 && (t2 = BigInt(t2)), "number" == typeof e3 && (e3 = BigInt(e3)), "number" == typeof s3 && (s3 = BigInt(s3)), s3 <= 0n) throw new RangeError("n must be > 0");
  if (1n === s3) return 0n;
  if (t2 = r(t2, s3), e3 < 0n) return o(d(t2, n(e3), s3, u2), s3);
  if (void 0 !== u2) return (function(n3, t3, e4, r3) {
    const o3 = r3.map(((n4) => n4[0] ** n4[1])), s4 = r3.map(((n4) => m([n4]))), u3 = s4.map(((e5, r4) => d(n3, t3 % e5, o3[r4])));
    return i(u3, o3, e4);
  })(t2, e3, s3, (function(n3) {
    const t3 = {};
    return n3.forEach(((n4) => {
      if ("bigint" == typeof n4 || "number" == typeof n4) {
        const e4 = String(n4);
        void 0 === t3[e4] ? t3[e4] = { p: BigInt(n4), k: 1n } : t3[e4].k += 1n;
      } else {
        const e4 = String(n4[0]);
        void 0 === t3[e4] ? t3[e4] = { p: BigInt(n4[0]), k: BigInt(n4[1]) } : t3[e4].k += BigInt(n4[1]);
      }
    })), Object.values(t3).map(((n4) => [n4.p, n4.k]));
  })(u2));
  let a = 1n;
  for (; e3 > 0; ) e3 % 2n === 1n && (a = a * t2 % s3), e3 /= 2n, t2 = t2 ** 2n % s3;
  return a;
}
function l(n3) {
  let t2 = 0n;
  for (const e3 of n3.values()) {
    t2 = (t2 << 8n) + BigInt(e3);
  }
  return t2;
}
function b(n3, t2 = false) {
  if (n3 < 1) throw new RangeError("byteLength MUST be > 0");
  return new Promise((function(e3, r3) {
    {
      const r4 = new Uint8Array(n3);
      if (n3 <= 65536) self.crypto.getRandomValues(r4);
      else for (let t3 = 0; t3 < Math.ceil(n3 / 65536); t3++) {
        const e4 = 65536 * t3, o3 = e4 + 65535 < n3 ? e4 + 65535 : n3 - 1;
        self.crypto.getRandomValues(r4.subarray(e4, o3));
      }
      t2 && (r4[0] = 128 | r4[0]), e3(r4);
    }
  }));
}
function h(n3, t2 = false) {
  if (n3 < 1) throw new RangeError("byteLength MUST be > 0");
  {
    const e3 = new Uint8Array(n3);
    if (n3 <= 65536) self.crypto.getRandomValues(e3);
    else for (let t3 = 0; t3 < Math.ceil(n3 / 65536); t3++) {
      const r3 = 65536 * t3, o3 = r3 + 65535 < n3 ? r3 + 65535 : n3 - 1;
      self.crypto.getRandomValues(e3.subarray(r3, o3));
    }
    return t2 && (e3[0] = 128 | e3[0]), e3;
  }
}
function w(n3, t2 = false) {
  if (n3 < 1) throw new RangeError("bitLength MUST be > 0");
  const e3 = Math.ceil(n3 / 8), r3 = n3 % 8;
  return new Promise(((n4, o3) => {
    b(e3, false).then((function(e4) {
      if (0 !== r3 && (e4[0] = e4[0] & 2 ** r3 - 1), t2) {
        const n5 = 0 !== r3 ? 2 ** (r3 - 1) : 128;
        e4[0] = e4[0] | n5;
      }
      n4(e4);
    }));
  }));
}
function p(n3, t2 = false) {
  if (n3 < 1) throw new RangeError("bitLength MUST be > 0");
  const e3 = h(Math.ceil(n3 / 8), false), r3 = n3 % 8;
  if (0 !== r3 && (e3[0] = e3[0] & 2 ** r3 - 1), t2) {
    const n4 = 0 !== r3 ? 2 ** (r3 - 1) : 128;
    e3[0] = e3[0] | n4;
  }
  return e3;
}
function y(n3, e3 = 1n) {
  if (n3 <= e3) throw new RangeError("Arguments MUST be: max > min");
  const r3 = n3 - e3, o3 = t(r3);
  let i3;
  do {
    i3 = l(p(o3));
  } while (i3 > r3);
  return i3 + e3;
}
function I(n3, t2 = 16, e3 = false) {
  if ("number" == typeof n3 && (n3 = BigInt(n3)), n3 < 0n) throw RangeError("w MUST be >= 0");
  return new Promise(((e4, r3) => {
    const o3 = new Worker($());
    o3.onmessage = (n4) => {
      void 0 !== n4?.data?._bcu?.isPrime && (o3.terminate(), e4(n4.data._bcu.isPrime));
    }, o3.onmessageerror = (n4) => {
      r3(n4);
    };
    const i3 = { _bcu: { rnd: n3, iterations: t2, id: 0 } };
    o3.postMessage(i3);
  }));
}
function S(n3, t2) {
  if (2n === n3) return true;
  if (0n === (1n & n3) || 1n === n3) return false;
  const e3 = [3n, 5n, 7n, 11n, 13n, 17n, 19n, 23n, 29n, 31n, 37n, 41n, 43n, 47n, 53n, 59n, 61n, 67n, 71n, 73n, 79n, 83n, 89n, 97n, 101n, 103n, 107n, 109n, 113n, 127n, 131n, 137n, 139n, 149n, 151n, 157n, 163n, 167n, 173n, 179n, 181n, 191n, 193n, 197n, 199n, 211n, 223n, 227n, 229n, 233n, 239n, 241n, 251n, 257n, 263n, 269n, 271n, 277n, 281n, 283n, 293n, 307n, 311n, 313n, 317n, 331n, 337n, 347n, 349n, 353n, 359n, 367n, 373n, 379n, 383n, 389n, 397n, 401n, 409n, 419n, 421n, 431n, 433n, 439n, 443n, 449n, 457n, 461n, 463n, 467n, 479n, 487n, 491n, 499n, 503n, 509n, 521n, 523n, 541n, 547n, 557n, 563n, 569n, 571n, 577n, 587n, 593n, 599n, 601n, 607n, 613n, 617n, 619n, 631n, 641n, 643n, 647n, 653n, 659n, 661n, 673n, 677n, 683n, 691n, 701n, 709n, 719n, 727n, 733n, 739n, 743n, 751n, 757n, 761n, 769n, 773n, 787n, 797n, 809n, 811n, 821n, 823n, 827n, 829n, 839n, 853n, 857n, 859n, 863n, 877n, 881n, 883n, 887n, 907n, 911n, 919n, 929n, 937n, 941n, 947n, 953n, 967n, 971n, 977n, 983n, 991n, 997n, 1009n, 1013n, 1019n, 1021n, 1031n, 1033n, 1039n, 1049n, 1051n, 1061n, 1063n, 1069n, 1087n, 1091n, 1093n, 1097n, 1103n, 1109n, 1117n, 1123n, 1129n, 1151n, 1153n, 1163n, 1171n, 1181n, 1187n, 1193n, 1201n, 1213n, 1217n, 1223n, 1229n, 1231n, 1237n, 1249n, 1259n, 1277n, 1279n, 1283n, 1289n, 1291n, 1297n, 1301n, 1303n, 1307n, 1319n, 1321n, 1327n, 1361n, 1367n, 1373n, 1381n, 1399n, 1409n, 1423n, 1427n, 1429n, 1433n, 1439n, 1447n, 1451n, 1453n, 1459n, 1471n, 1481n, 1483n, 1487n, 1489n, 1493n, 1499n, 1511n, 1523n, 1531n, 1543n, 1549n, 1553n, 1559n, 1567n, 1571n, 1579n, 1583n, 1597n];
  for (let t3 = 0; t3 < e3.length && e3[t3] <= n3; t3++) {
    const r4 = e3[t3];
    if (n3 === r4) return true;
    if (n3 % r4 === 0n) return false;
  }
  let r3 = 0n;
  const o3 = n3 - 1n;
  let i3 = o3;
  for (; i3 % 2n === 0n; ) i3 /= 2n, ++r3;
  const s3 = o3 / 2n ** r3;
  do {
    let t3 = d(y(o3, 2n), s3, n3);
    if (1n === t3 || t3 === o3) continue;
    let e4 = 1;
    for (; e4 < r3 && (t3 = d(t3, 2n, n3), t3 !== o3); ) {
      if (1n === t3) return false;
      e4++;
    }
    if (t3 !== o3) return false;
  } while (0 != --t2);
  return true;
}
function $() {
  let n3 = `
  'use strict';
  const ${e.name} = ${e.toString()};
  const ${o.name} = ${o.toString()};
  const ${d.name} = ${d.toString()};
  const ${r.name} = ${r.toString()};
  const ${p.name} = ${p.toString()};
  const ${h.name} = ${h.toString()};
  const ${y.name} = ${y.toString()};
  const ${I.name} = ${S.toString()};
  ${t.toString()};
  ${l.toString()};`;
  return n3 += `
  onmessage = async function(msg) {
    if (msg !== undefined && msg.data !== undefined && msg.data._bcu !== undefined && msg.data._bcu.id !== undefined && msg.data._bcu.iterations !== undefined && msg.data._bcu.rnd !== undefined) {
      const msgToParent = {
        _bcu: {
          isPrime: await ${I.name}(msg.data._bcu.rnd, msg.data._bcu.iterations),
          value: msg.data._bcu.rnd,
          id: msg.data._bcu.id
        }
      };
      postMessage(msgToParent);
    }
  }`, (function(n4) {
    n4 = `(() => {${n4}})()`;
    const t2 = new Blob([n4], { type: "text/javascript" });
    return window.URL.createObjectURL(t2);
  })(n3);
}
function R(n3, t2 = 16) {
  if (n3 < 1) throw new RangeError("bitLength MUST be > 0");
  if (!B) {
    let e3 = 0n;
    do {
      e3 = l(p(n3, true));
    } while (!S(e3, t2));
    return new Promise(((n4) => {
      n4(e3);
    }));
  }
  return new Promise(((e3, r3) => {
    const o3 = [], i3 = (r4, i4) => {
      if (r4._bcu.isPrime) {
        for (let n4 = 0; n4 < o3.length; n4++) o3[n4].terminate();
        for (; o3.length > 0; ) o3.pop();
        e3(r4._bcu.value);
      } else {
        const e4 = l(p(n3, true));
        try {
          const n4 = { _bcu: { rnd: e4, iterations: t2, id: r4._bcu.id } };
          i4.postMessage(n4);
        } catch (n4) {
        }
      }
    };
    {
      const n4 = $();
      for (let t3 = 0; t3 < self.navigator.hardwareConcurrency - 1; t3++) {
        const t4 = new Worker(n4);
        t4.onmessage = (n5) => i3(n5.data, t4), o3.push(t4);
      }
    }
    for (let e4 = 0; e4 < o3.length; e4++) w(n3, true).then((function(n4) {
      const r4 = l(n4);
      o3[e4].postMessage({ _bcu: { rnd: r4, iterations: t2, id: e4 } });
    })).catch(r3);
  }));
}
function M(n3, t2 = 16) {
  if (n3 < 1) throw new RangeError("bitLength MUST be > 0");
  let e3 = 0n;
  do {
    e3 = l(p(n3, true));
  } while (!S(e3, t2));
  return e3;
}
var B;
var init_index_browser_esm = __esm({
  "node_modules/bigint-crypto-utils/dist/index.browser.esm.js"() {
    B = false;
    void 0 !== self.Worker && (B = true);
  }
});

// node_modules/paillier-bigint/dist/index.browser.esm.js
var index_browser_esm_exports = {};
__export(index_browser_esm_exports, {
  PrivateKey: () => i2,
  PublicKey: () => n2,
  generateRandomKeys: () => o2,
  generateRandomKeysSync: () => s2
});
function e2(t2, n3) {
  return (t2 - 1n) / n3;
}
async function o2(o3 = 3072, s3 = false) {
  let h2, c, u2, d2, a, l2;
  do {
    h2 = await R(Math.floor(o3 / 2) + 1), c = await R(Math.floor(o3 / 2)), u2 = h2 * c;
  } while (c === h2 || t(u2) !== o3);
  if (s3) d2 = u2 + 1n, a = (h2 - 1n) * (c - 1n), l2 = o(a, u2);
  else {
    const n3 = u2 ** 2n;
    d2 = r2(u2, n3), a = u(h2 - 1n, c - 1n), l2 = o(e2(d(d2, a, n3), u2), u2);
  }
  const p2 = new n2(u2, d2);
  return { publicKey: p2, privateKey: new i2(a, l2, p2, h2, c) };
}
function s2(o3 = 3072, s3 = false) {
  let h2, c, u2, d2, a, l2;
  do {
    h2 = M(Math.floor(o3 / 2) + 1), c = M(Math.floor(o3 / 2)), u2 = h2 * c;
  } while (c === h2 || t(u2) !== o3);
  if (s3) d2 = u2 + 1n, a = (h2 - 1n) * (c - 1n), l2 = o(a, u2);
  else {
    const n3 = u2 ** 2n;
    d2 = r2(u2, n3), a = u(h2 - 1n, c - 1n), l2 = o(e2(d(d2, a, n3), u2), u2);
  }
  const p2 = new n2(u2, d2);
  return { publicKey: p2, privateKey: new i2(a, l2, p2, h2, c) };
}
function r2(n3, i3) {
  const e3 = y(n3), o3 = y(n3);
  return (e3 * n3 + 1n) * d(o3, n3, i3) % i3;
}
var n2, i2;
var init_index_browser_esm2 = __esm({
  "node_modules/paillier-bigint/dist/index.browser.esm.js"() {
    init_index_browser_esm();
    n2 = class {
      constructor(t2, n3) {
        this.n = t2, this._n2 = this.n ** 2n, this.g = n3;
      }
      get bitLength() {
        return t(this.n);
      }
      encrypt(n3, i3) {
        if (void 0 === i3) do {
          i3 = y(this.n);
        } while (1n !== s(i3, this.n));
        return d(this.g, n3, this._n2) * d(i3, this.n, this._n2) % this._n2;
      }
      addition(...t2) {
        return t2.reduce(((t3, n3) => t3 * n3 % this._n2), 1n);
      }
      plaintextAddition(n3, ...i3) {
        return i3.reduce(((n4, i4) => n4 * d(this.g, i4, this._n2) % this._n2), n3);
      }
      multiply(n3, i3) {
        return d(n3, i3, this._n2);
      }
    };
    i2 = class {
      constructor(t2, n3, i3, e3, o3) {
        this.lambda = t2, this.mu = n3, this._p = e3, this._q = o3, this.publicKey = i3;
      }
      get bitLength() {
        return t(this.publicKey.n);
      }
      get n() {
        return this.publicKey.n;
      }
      decrypt(n3) {
        return void 0 !== this._p && void 0 !== this._q ? e2(d(n3, this.lambda, this.publicKey._n2, [[this._p, 2], [this._q, 2]]), this.publicKey.n) * this.mu % this.publicKey.n : e2(d(n3, this.lambda, this.publicKey._n2), this.publicKey.n) * this.mu % this.publicKey.n;
      }
      getRandomFactor(n3) {
        if (this.publicKey.g !== this.n + 1n) throw RangeError("Cannot recover the random factor if publicKey.g != publicKey.n + 1. You should generate yout keys using the simple variant, e.g. generateRandomKeys(3072, true)");
        if (void 0 === this._p || void 0 === this._q) throw Error("Cannot get random factor without knowing p and q");
        const i3 = this.decrypt(n3), e3 = (this._p - 1n) * (this._q - 1n), o3 = o(this.n, e3), s3 = n3 * (1n - i3 * this.n) % this.publicKey._n2;
        return d(s3, o3, this.n, [[this._p, 1], [this._q, 1]]);
      }
    };
  }
});

// src/lib/lindellZk.js
var lindellZk_exports = {};
__export(lindellZk_exports, {
  LINDELL_Q_THIRD: () => LINDELL_Q_THIRD,
  LINDELL_RANGE_T: () => LINDELL_RANGE_T,
  PEDERSEN_G: () => PEDERSEN_G,
  PEDERSEN_H: () => PEDERSEN_H,
  PEDERSEN_N: () => PEDERSEN_N,
  SEC_P_COM: () => SEC_P_COM,
  SEC_P_STAT: () => SEC_P_STAT,
  encryptWithR: () => encryptWithR,
  invModQ: () => invModQ,
  pdlChallengePublic: () => pdlChallengePublic,
  pdlProverCommit: () => pdlProverCommit,
  pdlProverFinish: () => pdlProverFinish,
  pdlVerifierAccept: () => pdlVerifierAccept,
  pdlVerifierChallenge: () => pdlVerifierChallenge,
  pdlVerifierOpen: () => pdlVerifierOpen,
  proveEncEqualsDlog: () => proveEncEqualsDlog,
  proveRangeLindell: () => proveRangeLindell,
  proveSignC: () => proveSignC,
  randomCoprimeTo: () => randomCoprimeTo,
  randomShareLindellRange: () => randomShareLindellRange,
  runLindellPdl: () => runLindellPdl,
  sampleSignRho: () => sampleSignRho,
  scalarToHex: () => scalarToHex,
  verifyEncEqualsDlog: () => verifyEncEqualsDlog,
  verifyRangeLindell: () => verifyRangeLindell,
  verifySignC: () => verifySignC
});
function sha256Hex(s3) {
  return bytesToHex2(sha2562(new TextEncoder().encode(s3)));
}
function gcd(a, b2) {
  let x = a < 0n ? -a : a;
  let y2 = b2 < 0n ? -b2 : b2;
  while (y2 !== 0n) {
    const t2 = y2;
    y2 = x % y2;
    x = t2;
  }
  return x;
}
function modPow(base, exp, mod2) {
  let b2 = (base % mod2 + mod2) % mod2;
  let e3 = exp;
  let r3 = 1n;
  while (e3 > 0n) {
    if (e3 & 1n) r3 = r3 * b2 % mod2;
    b2 = b2 * b2 % mod2;
    e3 >>= 1n;
  }
  return r3;
}
function modInv(a, m2) {
  let t2 = 0n;
  let newt = 1n;
  let r3 = m2;
  let newr = (a % m2 + m2) % m2;
  while (newr !== 0n) {
    const q = r3 / newr;
    [t2, newt] = [newt, t2 - q * newt];
    [r3, newr] = [newr, r3 - q * newr];
  }
  if (r3 > 1n) throw new Error("not invertible");
  if (t2 < 0n) t2 += m2;
  return t2;
}
function homomorphicSubConst(pub, c, k) {
  const n22 = pub._n2;
  const gk = modPow(pub.g, k, n22);
  return BigInt(c) * modInv(gk, n22) % n22;
}
function randomBytes2(n3) {
  return crypto.getRandomValues(new Uint8Array(n3));
}
function bytesToBig(u8) {
  let x = 0n;
  for (const b2 of u8) x = x << 8n | BigInt(b2);
  return x;
}
function randomBelow(n3) {
  if (n3 <= 1n) throw new Error("randomBelow: n \u2264 1");
  const bits = n3.toString(2).length;
  const len = bits + 7 >> 3;
  for (let i3 = 0; i3 < 64; i3++) {
    const x = bytesToBig(randomBytes2(len + 4)) % n3;
    if (x > 0n) return x;
  }
  throw new Error("randomBelow failed");
}
function randomInclusive(lo, hi) {
  const span = hi - lo + 1n;
  if (span <= 0n) throw new Error("empty range");
  return lo + bytesToBig(randomBytes2(48)) % span;
}
function bytesToHex2(u8) {
  return Array.from(u8, (b2) => b2.toString(16).padStart(2, "0")).join("");
}
function randomCoprimeTo(n3) {
  for (let i3 = 0; i3 < 64; i3++) {
    const r3 = randomBelow(n3);
    if (r3 > 1n && gcd(r3, n3) === 1n) return r3;
  }
  throw new Error("coprime sample failed");
}
function randomShareLindellRange() {
  const x = randomInclusive(LINDELL_Q_THIRD, 2n * LINDELL_Q_THIRD);
  if (x === 0n) throw new Error("Lindell-range scalar was 0");
  return x;
}
function scalarToHex(s3) {
  const x = (s3 % CURVE_N + CURVE_N) % CURVE_N;
  return x.toString(16).padStart(64, "0");
}
function pointHex(P) {
  return bytesToHex2(P.toRawBytes(true));
}
function pointFromHex(hex) {
  return secp256k1.ProjectivePoint.fromHex(String(hex).replace(/^0x/i, ""));
}
function bigToDec(x) {
  return x.toString(10);
}
function encryptWithR(pub, m2) {
  const r3 = randomCoprimeTo(pub.n);
  const c = pub.encrypt(m2, r3);
  return { c, r: r3 };
}
function proveEncEqualsDlog({
  x,
  rEnc,
  c,
  paillierN,
  paillierG,
  Qhex,
  context = ""
}) {
  const pub = new n2(BigInt(paillierN), BigInt(paillierG));
  const N2 = pub.n;
  const xx = BigInt(x);
  const Qn = String(Qhex || "").replace(/^0x/i, "").toLowerCase();
  const want = pointHex(ecMul(G, xx));
  if (want !== Qn) {
    throw new Error("ENC_DLOG: x\xB7G \u2260 Q");
  }
  const xPrime = randomBelow(CURVE_N << 128n);
  const rPrime = randomCoprimeTo(N2);
  const Tenc = pub.encrypt(xPrime, rPrime);
  const Tpt = pointHex(ecMul(G, xPrime));
  const e3 = BigInt(
    "0x" + sha256Hex(
      [
        "wart-enc-dlog-v1",
        String(context || ""),
        String(N2),
        String(c),
        Qn,
        String(Tenc),
        Tpt
      ].join("|")
    ).slice(0, 32)
  );
  const zr = rPrime * modPow(BigInt(rEnc), e3, N2) % N2;
  return {
    Tenc: Tenc.toString(10),
    Tpt,
    e: e3.toString(10),
    zx: (xPrime + e3 * xx).toString(10),
    zr: zr.toString(10),
    context: String(context || "")
  };
}
function verifyEncEqualsDlog({
  c,
  paillierN,
  paillierG,
  Qhex,
  proof,
  context = ""
}) {
  if (!proof?.Tenc || proof.e == null || proof.zx == null || proof.zr == null) {
    throw new Error("ENC_DLOG_MISSING: need Enc(x)=x\xB7G proof");
  }
  const pub = new n2(BigInt(paillierN), BigInt(paillierG));
  const N2 = pub.n;
  const Qn = String(Qhex || "").replace(/^0x/i, "").toLowerCase();
  const Tenc = BigInt(proof.Tenc);
  const Tpt = String(proof.Tpt || "").replace(/^0x/i, "").toLowerCase();
  const e3 = BigInt(proof.e);
  const zx = BigInt(proof.zx);
  const zr = BigInt(proof.zr);
  const eWant = BigInt(
    "0x" + sha256Hex(
      [
        "wart-enc-dlog-v1",
        String(context || proof.context || ""),
        String(N2),
        String(c),
        Qn,
        String(Tenc),
        Tpt
      ].join("|")
    ).slice(0, 32)
  );
  if (e3 !== eWant) throw new Error("ENC_DLOG: Fiat-Shamir e mismatch");
  if (zr <= 0n || zr >= N2) throw new Error("ENC_DLOG: r response not in Z_N");
  const leftEnc = pub.encrypt(zx, zr);
  const rightEnc = pub.addition(Tenc, pub.multiply(BigInt(c), e3));
  if (leftEnc !== rightEnc) throw new Error("ENC_DLOG: Paillier relation fails");
  const Q = pointFromHex(Qn);
  const T = pointFromHex(Tpt);
  if (pointHex(ecMul(G, zx)) !== pointHex(ecMul(Q, e3).add(T))) {
    throw new Error("ENC_DLOG: zx\xB7G \u2260 T + e\xB7Q");
  }
  return { ok: true };
}
function commitHex(parts) {
  const nonce = bytesToHex2(randomBytes2(32));
  const msg = ["wart-lindell-com-v1", ...parts.map(String), nonce].join("|");
  return { com: sha256Hex(msg), nonce };
}
function openCommit(com, parts, nonce) {
  const msg = ["wart-lindell-com-v1", ...parts.map(String), String(nonce || "")].join("|");
  if (sha256Hex(msg) !== String(com || "").toLowerCase()) {
    throw new Error("LINDELL_PDL: commitment open failed");
  }
  return true;
}
function challengeBits(t2, parts) {
  const h2 = sha256Hex(["wart-lindell-range-fs-v1", ...parts.map(String)].join("|"));
  const x = BigInt("0x" + h2);
  const bits = [];
  for (let i3 = 0; i3 < t2; i3++) bits.push(Number(x >> BigInt(i3) & 1n));
  return bits;
}
function proveRangeLindell({
  x,
  rEnc,
  c,
  paillierN,
  paillierG,
  Q1,
  context = "",
  t: t2 = LINDELL_RANGE_T
}) {
  const pub = new n2(BigInt(paillierN), BigInt(paillierG));
  const q = CURVE_N;
  const ell = q / 3n;
  if (x < ell || x > 2n * ell) {
    throw new Error("LINDELL_RANGE: x1 not in [q/3, 2q/3] \u2014 resample the share");
  }
  const xp = x - ell;
  const cp = homomorphicSubConst(pub, c, ell);
  const pairs = [];
  const ws = [];
  for (let i3 = 0; i3 < t2; i3++) {
    let w1 = randomInclusive(ell, 2n * ell);
    let w2 = w1 - ell;
    if (randomInclusive(0n, 1n) === 1n) {
      const tmp = w1;
      w1 = w2;
      w2 = tmp;
    }
    const r1 = randomCoprimeTo(pub.n);
    const r22 = randomCoprimeTo(pub.n);
    const c1 = pub.encrypt(w1, r1);
    const c2 = pub.encrypt(w2, r22);
    pairs.push({ c1: bigToDec(c1), c2: bigToDec(c2) });
    ws.push({ w1, w2, r1, r2: r22 });
  }
  const e3 = challengeBits(t2, [
    context,
    String(c),
    Q1 || "",
    paillierN,
    bigToDec(cp),
    ...pairs.flatMap((p2) => [p2.c1, p2.c2])
  ]);
  const z = [];
  const rC = BigInt(rEnc);
  for (let i3 = 0; i3 < t2; i3++) {
    if (e3[i3] === 0) {
      z.push({
        e: 0,
        w1: bigToDec(ws[i3].w1),
        r1: bigToDec(ws[i3].r1),
        w2: bigToDec(ws[i3].w2),
        r2: bigToDec(ws[i3].r2)
      });
    } else {
      let j = 1;
      let w2 = xp + ws[i3].w1;
      let rj = ws[i3].r1;
      if (w2 < ell || w2 > 2n * ell) {
        j = 2;
        w2 = xp + ws[i3].w2;
        rj = ws[i3].r2;
      }
      if (w2 < ell || w2 > 2n * ell) {
        throw new Error("LINDELL_RANGE: no j with x+w_j in [\u2113,2\u2113]");
      }
      z.push({
        e: 1,
        j,
        w: bigToDec(w2),
        r: bigToDec(rC * rj % pub.n)
      });
    }
  }
  return { t: t2, pairs, z, context: String(context || "") };
}
function verifyRangeLindell({
  c,
  paillierN,
  paillierG,
  Q1,
  proof,
  context = ""
}) {
  if (!proof?.pairs || !proof?.z) {
    throw new Error("LINDELL_RANGE_MISSING: need Appendix A range proof on Enc(d1)");
  }
  const t2 = Number(proof.t || 0);
  if (t2 < LINDELL_RANGE_T) {
    throw new Error(`LINDELL_RANGE: t=${t2} < ${LINDELL_RANGE_T}`);
  }
  if (proof.pairs.length !== t2 || proof.z.length !== t2) {
    throw new Error("LINDELL_RANGE: pair/z length mismatch");
  }
  const pub = new n2(BigInt(paillierN), BigInt(paillierG));
  const q = CURVE_N;
  const ell = q / 3n;
  const cp = homomorphicSubConst(pub, c, ell);
  const e3 = challengeBits(t2, [
    context || proof.context || "",
    String(c),
    Q1 || "",
    String(paillierN),
    bigToDec(cp),
    ...proof.pairs.flatMap((p2) => [p2.c1, p2.c2])
  ]);
  for (let i3 = 0; i3 < t2; i3++) {
    const zi = proof.z[i3];
    const c1 = BigInt(proof.pairs[i3].c1);
    const c2 = BigInt(proof.pairs[i3].c2);
    if (e3[i3] === 0) {
      if (Number(zi.e) !== 0) throw new Error("LINDELL_RANGE: e_i=0 but z is open-sum");
      const w1 = BigInt(zi.w1);
      const w2 = BigInt(zi.w2);
      if (pub.encrypt(w1, BigInt(zi.r1)) !== c1 || pub.encrypt(w2, BigInt(zi.r2)) !== c2) {
        throw new Error("LINDELL_RANGE: Enc(w) \u2260 c_i (e=0)");
      }
      const inHi = (w3) => w3 >= ell && w3 <= 2n * ell;
      const inLo = (w3) => w3 >= 0n && w3 <= ell;
      const ok = inHi(w1) && inLo(w2) || inLo(w1) && inHi(w2);
      if (!ok) throw new Error("LINDELL_RANGE: w1/w2 not a complementary pair");
    } else {
      if (Number(zi.e) !== 1) throw new Error("LINDELL_RANGE: e_i=1 but z is open-both");
      const w2 = BigInt(zi.w);
      if (w2 < ell || w2 > 2n * ell) throw new Error("LINDELL_RANGE: opened w not in [\u2113,2\u2113]");
      const cj = Number(zi.j) === 2 ? c2 : c1;
      const got = pub.addition(cp, cj);
      if (pub.encrypt(w2, BigInt(zi.r)) !== got) {
        throw new Error("LINDELL_RANGE: Enc(x+w) \u2260 c \u2295 c_j");
      }
    }
  }
  return { ok: true, t: t2 };
}
function pdlVerifierChallenge({ ckey, paillierN, paillierG, Q1 }) {
  const pub = new n2(BigInt(paillierN), BigInt(paillierG));
  if (pub.n <= 2n * CURVE_N * CURVE_N + CURVE_N) {
    throw new Error("LINDELL_PDL: N too small (need N > 2q\xB2+q)");
  }
  const a = randomBelow(CURVE_N);
  const b2 = randomBelow(CURVE_N * CURVE_N);
  const r3 = randomCoprimeTo(pub.n);
  const cPrime = pub.addition(pub.multiply(BigInt(ckey), a), pub.encrypt(b2, r3));
  const com = commitHex([scalarToHex(a), b2.toString(10), Q1 || ""]);
  const bMod = b2 % CURVE_N;
  const aQ = pointFromHex(Q1).multiply(a);
  const Qexpect = bMod === 0n ? aQ : aQ.add(G.multiply(bMod));
  return {
    a: a.toString(10),
    b: b2.toString(10),
    r: r3.toString(10),
    cPrime: bigToDec(cPrime),
    comAB: com.com,
    nonceAB: com.nonce,
    Qexpect: pointHex(Qexpect),
    Q1,
    ckey: String(ckey),
    paillierN: String(paillierN),
    paillierG: String(paillierG)
  };
}
function pdlChallengePublic(ch) {
  return {
    cPrime: ch.cPrime,
    comAB: ch.comAB,
    Q1: ch.Q1,
    ckey: ch.ckey,
    paillierN: ch.paillierN,
    paillierG: ch.paillierG
  };
}
function pdlProverCommit({ cPrime, paillierN, paillierG, paillierLambda, paillierMu }) {
  const pub = new n2(BigInt(paillierN), BigInt(paillierG));
  const sk = new i2(BigInt(paillierLambda), BigInt(paillierMu), pub);
  const alpha = sk.decrypt(BigInt(cPrime));
  const aMod = alpha % CURVE_N;
  const Qhat = aMod === 0n ? secp256k1.ProjectivePoint.ZERO : G.multiply(aMod);
  const com = commitHex([pointHex(Qhat)]);
  return {
    alpha: alpha.toString(10),
    Qhat: pointHex(Qhat),
    comQ: com.com,
    nonceQ: com.nonce
  };
}
function pdlVerifierOpen(ch) {
  return {
    a: ch.a,
    b: ch.b,
    nonceAB: ch.nonceAB,
    comAB: ch.comAB,
    Q1: ch.Q1
  };
}
function pdlProverFinish({ alpha, x1, a, b: b2, Qhat, comQ, nonceQ, comAB, nonceAB, Q1 }) {
  const A = BigInt(a);
  const B2 = BigInt(b2);
  const al = BigInt(alpha);
  const x = BigInt(x1);
  if (al !== A * x + B2) {
    throw new Error("LINDELL_PDL: Dec(c\u2032) \u2260 a\xB7x1+b \u2014 refusing to open Q\u0302 (MAC mismatch)");
  }
  openCommit(comAB, [scalarToHex(A % CURVE_N), B2.toString(10), Q1 || ""], nonceAB);
  openCommit(comQ, [Qhat], nonceQ);
  return { Qhat, nonceQ, comQ };
}
function pdlVerifierAccept({ ch, Qhat, nonceQ, comQ }) {
  openCommit(ch.comAB, [scalarToHex(BigInt(ch.a) % CURVE_N), ch.b, ch.Q1 || ""], ch.nonceAB);
  openCommit(comQ, [Qhat], nonceQ);
  const a = BigInt(ch.a);
  const b2 = BigInt(ch.b);
  const bMod = b2 % CURVE_N;
  const aQ = pointFromHex(ch.Q1).multiply(a);
  const expect = bMod === 0n ? aQ : aQ.add(G.multiply(bMod));
  if (pointHex(expect) !== String(Qhat).replace(/^0x/i, "").toLowerCase()) {
    throw new Error("LINDELL_PDL: Q\u0302 \u2260 a\xB7Q1 + b\xB7G \u2014 Enc(d1) is not dlog(P1)");
  }
  return { ok: true };
}
function runLindellPdl({
  x1,
  rEnc,
  ckey,
  Q1,
  paillierN,
  paillierG,
  paillierLambda,
  paillierMu,
  context = "selftest"
}) {
  const range = proveRangeLindell({
    x: x1,
    rEnc,
    c: ckey,
    paillierN,
    paillierG,
    Q1,
    context
  });
  verifyRangeLindell({
    c: ckey,
    paillierN,
    paillierG,
    Q1,
    proof: range,
    context
  });
  const ch = pdlVerifierChallenge({ ckey, paillierN, paillierG, Q1 });
  const pr = pdlProverCommit({
    cPrime: ch.cPrime,
    paillierN,
    paillierG,
    paillierLambda,
    paillierMu
  });
  const open = pdlVerifierOpen(ch);
  pdlProverFinish({
    alpha: pr.alpha,
    x1,
    a: open.a,
    b: open.b,
    Qhat: pr.Qhat,
    comQ: pr.comQ,
    nonceQ: pr.nonceQ,
    comAB: open.comAB,
    nonceAB: open.nonceAB,
    Q1
  });
  pdlVerifierAccept({ ch, Qhat: pr.Qhat, nonceQ: pr.nonceQ, comQ: pr.comQ });
  return { ok: true, rangeT: range.t, pdlOk: true };
}
function randomLt(n3) {
  if (n3 <= 1n) return 0n;
  const bits = n3.toString(2).length;
  const len = bits + 7 >> 3;
  return bytesToBig(randomBytes2(len + 8)) % n3;
}
function ecMul(P, k) {
  let s3 = k % CURVE_N;
  if (s3 < 0n) s3 += CURVE_N;
  if (s3 === 0n) return secp256k1.ProjectivePoint.ZERO;
  return P.multiply(s3);
}
function pedersen(w2, r3) {
  return modPow(PEDERSEN_G, w2, PEDERSEN_N) * modPow(PEDERSEN_H, r3, PEDERSEN_N) % PEDERSEN_N;
}
function signCChallenge(parts) {
  const h2 = sha256Hex(["wart-lindell-c-zk-v1", ...parts.map(String)].join("|"));
  return BigInt("0x" + h2.slice(0, SEC_P_COM / 4));
}
function invModQ(a) {
  return modPow((a % CURVE_N + CURVE_N) % CURVE_N, CURVE_N - 2n, CURVE_N);
}
function inRange2(x, lo, hi) {
  return x >= lo && x < hi;
}
function proveSignC({
  paillierN,
  paillierG,
  ckey,
  c,
  Q2Hex,
  R2Hex,
  m: m2,
  r: r3,
  k2,
  x2,
  rho,
  rc,
  sid = "0",
  aux = 0
}) {
  const pub = new n2(BigInt(paillierN), BigInt(paillierG));
  const N2 = pub.n;
  const q = CURVE_N;
  const Q2n = String(Q2Hex).replace(/^0x/i, "").toLowerCase();
  const R2n = String(R2Hex).replace(/^0x/i, "").toLowerCase();
  const R2 = pointFromHex(R2n);
  const Q2 = pointFromHex(Q2n);
  const cKey = BigInt(ckey);
  const c3 = BigInt(c);
  const mm = BigInt(m2);
  const rr = BigInt(r3);
  const w1 = invModQ(k2);
  const w2 = w1 * (x2 % q) % q;
  const w3 = BigInt(rho);
  const w4 = BigInt(rc);
  const cKeyR = pub.multiply(cKey, rr);
  const r1w = randomLt(PEDERSEN_N << BigInt(SEC_P_STAT));
  const r2w = randomLt(PEDERSEN_N << BigInt(SEC_P_STAT));
  const r3w = randomLt(PEDERSEN_N << BigInt(SEC_P_STAT));
  const W1 = pedersen(w1, r1w);
  const W2 = pedersen(w2, r2w);
  const W3 = pedersen(w3, r3w);
  const w1t = randomLt(q << BigInt(SEC_P_STAT + SEC_P_COM));
  const w2t = randomLt(q << BigInt(SEC_P_STAT + SEC_P_COM));
  const w3t = randomLt(q * q << BigInt(3 * SEC_P_STAT + SEC_P_COM));
  const r1t = randomLt(PEDERSEN_N << BigInt(2 * SEC_P_STAT + SEC_P_COM));
  const r2t = randomLt(PEDERSEN_N << BigInt(2 * SEC_P_STAT + SEC_P_COM));
  const r3t = randomLt(PEDERSEN_N << BigInt(2 * SEC_P_STAT + SEC_P_COM));
  const W1t = pedersen(w1t, r1t);
  const W2t = pedersen(w2t, r2t);
  const W3t = pedersen(w3t, r3t);
  const Gtag = pointHex(ecMul(R2, w1t));
  const Q2tag = pointHex(ecMul(R2, w2t));
  const rEnc = randomCoprimeTo(N2);
  const temp = w1t * mm + w2t * rr + w3t * q;
  const Cenc = pub.addition(pub.encrypt(temp, rEnc), pub.multiply(cKeyR, w1t));
  const e3 = signCChallenge([
    N2,
    cKey,
    c3,
    Q2n,
    R2n,
    mm,
    rr,
    W1,
    W2,
    W3,
    W1t,
    W2t,
    W3t,
    Gtag,
    Q2tag,
    Cenc,
    sid,
    aux
  ]);
  return {
    W1: W1.toString(10),
    W2: W2.toString(10),
    W3: W3.toString(10),
    W1t: W1t.toString(10),
    W2t: W2t.toString(10),
    W3t: W3t.toString(10),
    Gtag,
    Q2tag,
    Cenc: Cenc.toString(10),
    e: e3.toString(10),
    w1tt: (w1t + e3 * w1).toString(10),
    w2tt: (w2t + e3 * w2).toString(10),
    w3tt: (w3t + e3 * w3).toString(10),
    r1tt: (r1t + e3 * r1w).toString(10),
    r2tt: (r2t + e3 * r2w).toString(10),
    r3tt: (r3t + e3 * r3w).toString(10),
    rEncTt: (rEnc * modPow(w4, e3, N2) % N2).toString(10)
  };
}
function verifySignC({
  paillierN,
  paillierG,
  ckey,
  c,
  Q2Hex,
  R2Hex,
  m: m2,
  r: r3,
  pokC,
  sid = "0",
  aux = 0
}) {
  if (!pokC?.e || !pokC?.Cenc) {
    throw new Error("LINDELL_C_ZK_MISSING: need Coinbase integer-commit proof of c");
  }
  const pub = new n2(BigInt(paillierN), BigInt(paillierG));
  const N2 = pub.n;
  const NN = pub._n2;
  const q = CURVE_N;
  const Q2 = pointFromHex(Q2Hex);
  const R2 = pointFromHex(R2Hex);
  const Gtag = pointFromHex(pokC.Gtag);
  const Q2tag = pointFromHex(pokC.Q2tag);
  const mm = BigInt(m2);
  const rr = BigInt(r3);
  const cKey = BigInt(ckey);
  const c3 = BigInt(c);
  const W1 = BigInt(pokC.W1);
  const W2 = BigInt(pokC.W2);
  const W3 = BigInt(pokC.W3);
  const W1t = BigInt(pokC.W1t);
  const W2t = BigInt(pokC.W2t);
  const W3t = BigInt(pokC.W3t);
  const Cenc = BigInt(pokC.Cenc);
  const e3 = BigInt(pokC.e);
  const w1tt = BigInt(pokC.w1tt);
  const w2tt = BigInt(pokC.w2tt);
  const w3tt = BigInt(pokC.w3tt);
  const r1tt = BigInt(pokC.r1tt);
  const r2tt = BigInt(pokC.r2tt);
  const r3tt = BigInt(pokC.r3tt);
  const rEncTt = BigInt(pokC.rEncTt);
  const eWant = signCChallenge([
    N2,
    cKey,
    c3,
    String(Q2Hex).replace(/^0x/i, "").toLowerCase(),
    String(R2Hex).replace(/^0x/i, "").toLowerCase(),
    mm,
    rr,
    W1,
    W2,
    W3,
    W1t,
    W2t,
    W3t,
    String(pokC.Gtag).replace(/^0x/i, "").toLowerCase(),
    String(pokC.Q2tag).replace(/^0x/i, "").toLowerCase(),
    Cenc,
    sid,
    aux
  ]);
  if (e3 !== eWant) throw new Error("LINDELL_C_ZK: Fiat-Shamir e mismatch");
  const pedHi = PEDERSEN_N << BigInt(2 * SEC_P_STAT + SEC_P_COM + 1);
  if (!inRange2(r1tt, 0n, pedHi) || !inRange2(r2tt, 0n, pedHi) || !inRange2(r3tt, 0n, pedHi)) {
    throw new Error("LINDELL_C_ZK: Pedersen randomness out of range");
  }
  if (mm >= q || rr >= q) throw new Error("LINDELL_C_ZK: m or r not in Z_q");
  const w1hi = q << BigInt(SEC_P_STAT + SEC_P_COM + 1);
  const w3hi = q * q << BigInt(3 * SEC_P_STAT + SEC_P_COM + 1);
  if (!inRange2(w1tt, 0n, w1hi) || !inRange2(w2tt, 0n, w1hi) || !inRange2(w3tt, 0n, w3hi)) {
    throw new Error("LINDELL_C_ZK: response out of range");
  }
  if (!inRange2(rEncTt, 0n, N2)) throw new Error("LINDELL_C_ZK: r_enc response not in Z_N");
  const Gcurve = G;
  if (pointHex(ecMul(R2, w1tt)) !== pointHex(ecMul(Gcurve, e3).add(Gtag))) {
    throw new Error("LINDELL_C_ZK: w1\xB7R2 \u2260 eG + G_tag \u2014 k2 inverse not bound");
  }
  if (pointHex(ecMul(R2, w2tt)) !== pointHex(ecMul(Q2, e3).add(Q2tag))) {
    throw new Error("LINDELL_C_ZK: w2\xB7R2 \u2260 e Q2 + Q2_tag \u2014 x2 not bound");
  }
  if (pedersen(w1tt, r1tt) !== W1t * modPow(W1, e3, PEDERSEN_N) % PEDERSEN_N) {
    throw new Error("LINDELL_C_ZK: Pedersen W1");
  }
  if (pedersen(w2tt, r2tt) !== W2t * modPow(W2, e3, PEDERSEN_N) % PEDERSEN_N) {
    throw new Error("LINDELL_C_ZK: Pedersen W2");
  }
  if (pedersen(w3tt, r3tt) !== W3t * modPow(W3, e3, PEDERSEN_N) % PEDERSEN_N) {
    throw new Error("LINDELL_C_ZK: Pedersen W3");
  }
  const cKeyR = pub.multiply(cKey, rr);
  const temp = w1tt * mm + w2tt * rr + w3tt * q;
  const left = pub.addition(pub.encrypt(temp, rEncTt), pub.multiply(cKeyR, w1tt));
  const right = pub.addition(Cenc, pub.multiply(c3, e3));
  if (left !== right) throw new Error("LINDELL_C_ZK: Paillier relation fails \u2014 c is not the Lindell tuple");
  return { ok: true };
}
function sampleSignRho() {
  return randomLt(CURVE_N * CURVE_N << BigInt(SEC_P_STAT * 2));
}
var CURVE_N, G, LINDELL_RANGE_T, LINDELL_Q_THIRD, SEC_P_STAT, SEC_P_COM, PEDERSEN_N, PEDERSEN_G, PEDERSEN_H;
var init_lindellZk = __esm({
  "src/lib/lindellZk.js"() {
    "use strict";
    init_secp256k1();
    init_sha256();
    init_index_browser_esm2();
    CURVE_N = secp256k1.CURVE.n;
    G = secp256k1.ProjectivePoint.BASE;
    LINDELL_RANGE_T = 40;
    LINDELL_Q_THIRD = CURVE_N / 3n;
    SEC_P_STAT = 80;
    SEC_P_COM = 128;
    PEDERSEN_N = BigInt(
      "23021179409182938570359750938980338144228252278091272301373977814239751374837999838492546432888767127769655940068264100853353551499366755577355531007018750768200171255441698821574892336993202780622143746877429267180956985375718503710984554436993994314439687609895321760284136988355617570080829893220388340848662424870689770253814604041743989571505561981559749559655239486273235991420864634594679913369883938003881718526701794556221696559508817046918913994546361857215207106703848946440502419613199522137735334940177512343371386118880901797914415961377788512776238741479649148106573475707451684652229544231196914573289"
    );
    PEDERSEN_G = BigInt(
      "18692609727959642347495417395722097525189086531367077703372461312274023157993906686576615309234701031882307230283129349048160114209918340065147702452404381410406703543047035263825585677685288105331451962046612323375135943439625150989289125977704731027044468880699601265142162637878950397691930657280005244438693270908351393909855450315038730976563321234196068882925686057387933231622612372734407696300564311472069289215359164131367652584423723804201294306251241012679464813370234988048205813130011019436870655061686956966570610789218397436279311675374020440160625193097157363946641954583407515109646139183272575875147"
    );
    PEDERSEN_H = BigInt(
      "1048665143557212763219747740365925372973495762670564399175662900857975294535671104954036501552639642493753905307453170704505994561004317929987661874942164325790769136087625173204744153810498026365780398250521692204997255045340560453829554404127652590720296677920879093396879580879248242026646264911671785581014516272702688970899804455365256101399624385933528202110196550761839775309049444508960694778077273805944573689614247122411049825824247506775813394277339807872884192982983105098004844709850011190976172521026823264137921322799866525778649032062366285804392400257876447684994961367594957563285783650449234172753"
    );
  }
});

// src/lib/pool3pClient.js
var pool3pClient_exports = {};
__export(pool3pClient_exports, {
  PAILLIER_BITS: () => PAILLIER_BITS,
  clientSignFinish: () => clientSignFinish,
  clientSignRound1: () => clientSignRound1,
  makeClientSeat: () => makeClientSeat,
  schnorrProveDlog: () => schnorrProveDlog,
  sealBindHex: () => sealBindHex,
  seatPokContext: () => seatPokContext,
  verifyShareSeal: () => verifyShareSeal
});
function modN2(a) {
  let x = a % CURVE_N2;
  if (x < 0n) x += CURVE_N2;
  return x;
}
function modPow2(base, exp, mod2) {
  let b2 = (base % mod2 + mod2) % mod2;
  let e3 = exp;
  let r3 = 1n;
  while (e3 > 0n) {
    if (e3 & 1n) r3 = r3 * b2 % mod2;
    b2 = b2 * b2 % mod2;
    e3 >>= 1n;
  }
  return r3;
}
function invScalar(a) {
  return modPow2(modN2(a), CURVE_N2 - 2n, CURVE_N2);
}
function hexToScalar(hex) {
  const h2 = String(hex ?? "").replace(/^0x/i, "").toLowerCase();
  if (!/^[0-9a-f]+$/.test(h2)) {
    throw new Error(`bad hex scalar (${String(hex).slice(0, 18) || "empty"})`);
  }
  return modN2(BigInt("0x" + h2));
}
function scalarToHex2(s3) {
  return modN2(s3).toString(16).padStart(64, "0");
}
function randomScalar() {
  for (let i3 = 0; i3 < 32; i3++) {
    const bytes = crypto.getRandomValues(new Uint8Array(48));
    let x = 0n;
    for (const b2 of bytes) x = x << 8n | BigInt(b2);
    x = modN2(x);
    if (x > 0n) return x;
  }
  throw new Error("scalar sample failed");
}
function pointToCompressedHex(P) {
  const bytes = P.toRawBytes(true);
  return [...bytes].map((b2) => b2.toString(16).padStart(2, "0")).join("");
}
function bytesToHex3(bytes) {
  return [...bytes].map((b2) => b2.toString(16).padStart(2, "0")).join("");
}
function sealBindHex(seal) {
  const msg = [
    "wart-3p-seal-v1",
    String(seal.address || ""),
    String(seal.publicKey || ""),
    String(seal.P1 || ""),
    String(seal.P2 || ""),
    String(seal.Pdapp || ""),
    String(Number(seal.seatEpoch || 0))
  ].join("|");
  return bytesToHex3(sha2562(new TextEncoder().encode(msg)));
}
function verifyShareSeal({ shareHex, role, seal }) {
  if (!seal || seal.scheme !== "wart-3p-seal-v1" || !seal.bind) {
    throw new Error("SEAL_MISSING: share has no 3P seal \u2014 refuse lease");
  }
  if (sealBindHex(seal) !== seal.bind) {
    throw new Error("SEAL_BROKEN: bind hash mismatch");
  }
  const P1 = secp256k1.ProjectivePoint.fromHex(String(seal.P1).replace(/^0x/i, ""));
  const P2 = secp256k1.ProjectivePoint.fromHex(String(seal.P2).replace(/^0x/i, ""));
  const Pd = secp256k1.ProjectivePoint.fromHex(String(seal.Pdapp).replace(/^0x/i, ""));
  const Q = secp256k1.ProjectivePoint.fromHex(String(seal.publicKey).replace(/^0x/i, ""));
  const sum = P1.add(P2).add(Pd);
  if (pointToCompressedHex(sum) !== pointToCompressedHex(Q)) {
    throw new Error("SEAL_BROKEN: P1+P2+Pdapp \u2260 Q \u2014 dealer combined/swapped seats");
  }
  const d2 = hexToScalar(shareHex);
  const Pgot = pointToCompressedHex(G2.multiply(d2)).toLowerCase();
  const Pwant = String(Number(role) === 1 ? seal.P1 : seal.P2).toLowerCase();
  if (Pgot !== Pwant) {
    throw new Error(`SEAL_BROKEN: d${role}\xB7G \u2260 P${role} \u2014 share was opened or replaced`);
  }
  return {
    ok: true,
    address: seal.address,
    seatEpoch: seal.seatEpoch,
    dealerSawPlaintext: !!seal.dealerSawPlaintext
  };
}
function makeClientSeat(role) {
  const d2 = randomScalar();
  return {
    role: Number(role),
    userShareHex: scalarToHex2(d2),
    P: pointToCompressedHex(G2.multiply(d2))
  };
}
function schnorrChallenge(Phex, Rhex, context) {
  const msg = [
    "wart-3p-schnorr-v1",
    String(context || ""),
    String(Phex || "").replace(/^0x/i, "").toLowerCase(),
    String(Rhex || "").replace(/^0x/i, "").toLowerCase()
  ].join("|");
  return hexToScalar(bytesToHex3(sha2562(new TextEncoder().encode(msg))));
}
function seatPokContext(kind, role, Phex) {
  return [
    "wart-3p-seat",
    String(kind || ""),
    String(Number(role || 0)),
    String(Phex || "").replace(/^0x/i, "").toLowerCase()
  ].join("|");
}
function schnorrProveDlog(shareHex, context) {
  const d2 = hexToScalar(shareHex);
  const Phex = pointToCompressedHex(G2.multiply(d2));
  let k;
  let Rhex;
  let e3;
  for (let i3 = 0; i3 < 8; i3++) {
    k = randomScalar();
    Rhex = pointToCompressedHex(G2.multiply(k));
    e3 = schnorrChallenge(Phex, Rhex, context);
    if (e3 !== 0n) break;
  }
  if (!e3) throw new Error("schnorr challenge was 0");
  return {
    P: Phex,
    R: Rhex,
    s: scalarToHex2(modN2(k + e3 * d2)),
    context: String(context || "")
  };
}
function clientSignRound1() {
  const k1 = randomScalar();
  return {
    k1Hex: scalarToHex2(k1),
    R1Hex: pointToCompressedHex(G2.multiply(k1))
  };
}
function normPubHex(hex) {
  return String(hex || "").replace(/^0x/i, "").toLowerCase();
}
function schnorrChallengeOnBase(statementHex, commitHex2, baseHex, context) {
  const msg = [
    "wart-3p-schnorr-base-v1",
    String(context || ""),
    normPubHex(baseHex),
    normPubHex(statementHex),
    normPubHex(commitHex2)
  ].join("|");
  return hexToScalar(bytesToHex3(sha2562(new TextEncoder().encode(msg))));
}
function lindellRPokContext({ R1Hex, RHex, rHex, hashHex, ciphertext }) {
  const cHash = bytesToHex3(sha2562(new TextEncoder().encode(String(ciphertext || ""))));
  return [
    "wart-3p-r-eq-k2r1-v1",
    normPubHex(R1Hex),
    normPubHex(RHex),
    String(rHex || "").replace(/^0x/i, "").toLowerCase(),
    String(hashHex || "").replace(/^0x/i, "").toLowerCase(),
    cHash
  ].join("|");
}
function verifyLindellR({ pok, k1Hex, R1Hex, RHex, rHex, hashHex, ciphertext }) {
  if (!pok?.R || !pok?.s) {
    throw new Error("LINDELL_R_POK_MISSING: need Schnorr that R = k2\xB7R1");
  }
  if (!RHex) throw new Error("LINDELL_R_POK_MISSING: need RHex");
  const k1 = hexToScalar(k1Hex);
  const R1got = pointToCompressedHex(G2.multiply(k1));
  const R1n = normPubHex(R1Hex || R1got);
  if (normPubHex(R1got) !== R1n) {
    throw new Error("LINDELL_R_POK: R1 \u2260 k1\xB7G");
  }
  const R2 = secp256k1.ProjectivePoint.fromHex(normPubHex(RHex));
  if (modN2(R2.toAffine().x) !== hexToScalar(rHex)) {
    throw new Error("LINDELL_R_POK: r \u2260 Rx(R) mod n");
  }
  const ctx = lindellRPokContext({
    R1Hex: R1n,
    RHex,
    rHex,
    hashHex,
    ciphertext
  });
  const statementHex = normPubHex(RHex);
  const Base = secp256k1.ProjectivePoint.fromHex(R1n);
  const Statement = secp256k1.ProjectivePoint.fromHex(statementHex);
  const T = secp256k1.ProjectivePoint.fromHex(normPubHex(pok.R));
  const s3 = hexToScalar(pok.s);
  const e3 = schnorrChallengeOnBase(statementHex, normPubHex(pok.R), R1n, ctx);
  const left = pointToCompressedHex(Base.multiply(s3));
  const right = pointToCompressedHex(T.add(Statement.multiply(e3)));
  if (left !== right) {
    throw new Error("LINDELL_R_POK: s\xB7R1 \u2260 T + e\xB7R \u2014 coordinator does not know k2");
  }
  return true;
}
function clientSignFinish({
  k1Hex,
  rHex,
  ciphertext,
  hashHex,
  clientSecret,
  publicKey,
  RHex,
  R1Hex,
  pokR,
  pokC,
  R2Hex,
  Q2Hex,
  ckeyAdj,
  sid,
  paillierN,
  paillierG
}) {
  if (!clientSecret?.paillierN || !clientSecret?.paillierLambda) {
    throw new Error("d1 seat missing Paillier key \u2014 re-enroll this tab as d1");
  }
  verifyLindellR({
    pok: pokR,
    k1Hex,
    R1Hex,
    RHex,
    rHex,
    hashHex,
    ciphertext
  });
  if (!sid) {
    throw new Error("LINDELL_C_ZK: missing ticket sid (do not hash the tx hash as the proof domain)");
  }
  if (!Q2Hex || !R2Hex || ckeyAdj == null) {
    throw new Error("LINDELL_C_ZK_MISSING: need Q2Hex, R2Hex, and ckeyAdj");
  }
  const pubN = paillierN || clientSecret.paillierN;
  const pubG = paillierG || clientSecret.paillierG;
  if (clientSecret.paillierN && pubN && BigInt(String(pubN)) !== BigInt(String(clientSecret.paillierN))) {
    throw new Error(
      "d1 Paillier N \u2260 Enc(d1) on coordinator \u2014 this tab is not the dealer that birthed d1"
    );
  }
  verifySignC({
    paillierN: pubN,
    paillierG: pubG,
    ckey: String(ckeyAdj),
    c: ciphertext,
    Q2Hex,
    R2Hex,
    m: hexToScalar(hashHex),
    r: hexToScalar(rHex),
    pokC,
    sid,
    aux: 0
  });
  const k1 = hexToScalar(k1Hex);
  const r3 = hexToScalar(rHex);
  const pub = new n2(BigInt(clientSecret.paillierN), BigInt(clientSecret.paillierG));
  const sk = new i2(
    BigInt(clientSecret.paillierLambda),
    BigInt(clientSecret.paillierMu),
    pub
  );
  const pt = sk.decrypt(BigInt(String(ciphertext).replace(/^0x/i, "")));
  let s3 = modN2(invScalar(k1) * modN2(pt));
  if (s3 > CURVE_N2 / 2n) s3 = CURVE_N2 - s3;
  const rPad = scalarToHex2(r3);
  const sPad = scalarToHex2(s3);
  const msgHex = String(hashHex || "").replace(/^0x/i, "");
  if (!/^[0-9a-f]{64}$/i.test(msgHex)) {
    throw new Error("d1 finish missing hashHex \u2014 wait for prepare");
  }
  const msg = new Uint8Array(32);
  for (let i3 = 0; i3 < 32; i3++) {
    msg[i3] = parseInt(msgHex.slice(i3 * 2, i3 * 2 + 2), 16);
  }
  const expectPub = String(
    publicKey || clientSecret.publicKey || clientSecret.seal?.publicKey || ""
  ).replace(/^0x/i, "").toLowerCase();
  if (!expectPub) {
    throw new Error("d1 finish missing pool pubkey \u2014 cannot pick recovery id");
  }
  let recid = null;
  for (let rec = 0; rec < 4; rec++) {
    try {
      const sig = new secp256k1.Signature(r3, s3).addRecoveryBit(rec);
      const recPub = [...sig.recoverPublicKey(msg).toRawBytes(true)].map((b2) => b2.toString(16).padStart(2, "0")).join("");
      if (recPub === expectPub) {
        recid = rec;
        break;
      }
    } catch {
    }
  }
  if (recid == null) {
    throw new Error(
      "3P recovery failed \u2014 signature does not match pool pubkey (do not submit v=0)"
    );
  }
  return {
    signature65: rPad + sPad + recid.toString(16).padStart(2, "0")
  };
}
var CURVE_N2, G2, PAILLIER_BITS;
var init_pool3pClient = __esm({
  "src/lib/pool3pClient.js"() {
    "use strict";
    init_secp256k1();
    init_sha256();
    init_index_browser_esm2();
    init_lindellZk();
    CURVE_N2 = secp256k1.CURVE.n;
    G2 = secp256k1.ProjectivePoint.BASE;
    PAILLIER_BITS = 2048;
  }
});

// node_modules/@noble/hashes/esm/sha3.js
function keccakP(s3, rounds = 24) {
  const B2 = new Uint32Array(5 * 2);
  for (let round = 24 - rounds; round < 24; round++) {
    for (let x = 0; x < 10; x++)
      B2[x] = s3[x] ^ s3[x + 10] ^ s3[x + 20] ^ s3[x + 30] ^ s3[x + 40];
    for (let x = 0; x < 10; x += 2) {
      const idx1 = (x + 8) % 10;
      const idx0 = (x + 2) % 10;
      const B0 = B2[idx0];
      const B1 = B2[idx0 + 1];
      const Th = rotlH(B0, B1, 1) ^ B2[idx1];
      const Tl = rotlL(B0, B1, 1) ^ B2[idx1 + 1];
      for (let y2 = 0; y2 < 50; y2 += 10) {
        s3[x + y2] ^= Th;
        s3[x + y2 + 1] ^= Tl;
      }
    }
    let curH = s3[2];
    let curL = s3[3];
    for (let t2 = 0; t2 < 24; t2++) {
      const shift = SHA3_ROTL[t2];
      const Th = rotlH(curH, curL, shift);
      const Tl = rotlL(curH, curL, shift);
      const PI = SHA3_PI[t2];
      curH = s3[PI];
      curL = s3[PI + 1];
      s3[PI] = Th;
      s3[PI + 1] = Tl;
    }
    for (let y2 = 0; y2 < 50; y2 += 10) {
      for (let x = 0; x < 10; x++)
        B2[x] = s3[y2 + x];
      for (let x = 0; x < 10; x++)
        s3[y2 + x] ^= ~B2[(x + 2) % 10] & B2[(x + 4) % 10];
    }
    s3[0] ^= SHA3_IOTA_H[round];
    s3[1] ^= SHA3_IOTA_L[round];
  }
  clean(B2);
}
var _0n6, _1n6, _2n4, _7n2, _256n, _0x71n, SHA3_PI, SHA3_ROTL, _SHA3_IOTA, IOTAS, SHA3_IOTA_H, SHA3_IOTA_L, rotlH, rotlL, Keccak, gen, keccak_256;
var init_sha3 = __esm({
  "node_modules/@noble/hashes/esm/sha3.js"() {
    init_u64();
    init_utils();
    _0n6 = BigInt(0);
    _1n6 = BigInt(1);
    _2n4 = BigInt(2);
    _7n2 = BigInt(7);
    _256n = BigInt(256);
    _0x71n = BigInt(113);
    SHA3_PI = [];
    SHA3_ROTL = [];
    _SHA3_IOTA = [];
    for (let round = 0, R2 = _1n6, x = 1, y2 = 0; round < 24; round++) {
      [x, y2] = [y2, (2 * x + 3 * y2) % 5];
      SHA3_PI.push(2 * (5 * y2 + x));
      SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
      let t2 = _0n6;
      for (let j = 0; j < 7; j++) {
        R2 = (R2 << _1n6 ^ (R2 >> _7n2) * _0x71n) % _256n;
        if (R2 & _2n4)
          t2 ^= _1n6 << (_1n6 << /* @__PURE__ */ BigInt(j)) - _1n6;
      }
      _SHA3_IOTA.push(t2);
    }
    IOTAS = split(_SHA3_IOTA, true);
    SHA3_IOTA_H = IOTAS[0];
    SHA3_IOTA_L = IOTAS[1];
    rotlH = (h2, l2, s3) => s3 > 32 ? rotlBH(h2, l2, s3) : rotlSH(h2, l2, s3);
    rotlL = (h2, l2, s3) => s3 > 32 ? rotlBL(h2, l2, s3) : rotlSL(h2, l2, s3);
    Keccak = class _Keccak extends Hash {
      // NOTE: we accept arguments in bytes instead of bits here.
      constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
        super();
        this.pos = 0;
        this.posOut = 0;
        this.finished = false;
        this.destroyed = false;
        this.enableXOF = false;
        this.blockLen = blockLen;
        this.suffix = suffix;
        this.outputLen = outputLen;
        this.enableXOF = enableXOF;
        this.rounds = rounds;
        anumber(outputLen);
        if (!(0 < blockLen && blockLen < 200))
          throw new Error("only keccak-f1600 function is supported");
        this.state = new Uint8Array(200);
        this.state32 = u32(this.state);
      }
      clone() {
        return this._cloneInto();
      }
      keccak() {
        swap32IfBE(this.state32);
        keccakP(this.state32, this.rounds);
        swap32IfBE(this.state32);
        this.posOut = 0;
        this.pos = 0;
      }
      update(data) {
        aexists(this);
        data = toBytes(data);
        abytes(data);
        const { blockLen, state } = this;
        const len = data.length;
        for (let pos = 0; pos < len; ) {
          const take = Math.min(blockLen - this.pos, len - pos);
          for (let i3 = 0; i3 < take; i3++)
            state[this.pos++] ^= data[pos++];
          if (this.pos === blockLen)
            this.keccak();
        }
        return this;
      }
      finish() {
        if (this.finished)
          return;
        this.finished = true;
        const { state, suffix, pos, blockLen } = this;
        state[pos] ^= suffix;
        if ((suffix & 128) !== 0 && pos === blockLen - 1)
          this.keccak();
        state[blockLen - 1] ^= 128;
        this.keccak();
      }
      writeInto(out) {
        aexists(this, false);
        abytes(out);
        this.finish();
        const bufferOut = this.state;
        const { blockLen } = this;
        for (let pos = 0, len = out.length; pos < len; ) {
          if (this.posOut >= blockLen)
            this.keccak();
          const take = Math.min(blockLen - this.posOut, len - pos);
          out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
          this.posOut += take;
          pos += take;
        }
        return out;
      }
      xofInto(out) {
        if (!this.enableXOF)
          throw new Error("XOF is not possible for this instance");
        return this.writeInto(out);
      }
      xof(bytes) {
        anumber(bytes);
        return this.xofInto(new Uint8Array(bytes));
      }
      digestInto(out) {
        aoutput(out, this);
        if (this.finished)
          throw new Error("digest() was already called");
        this.writeInto(out);
        this.destroy();
        return out;
      }
      digest() {
        return this.digestInto(new Uint8Array(this.outputLen));
      }
      destroy() {
        this.destroyed = true;
        clean(this.state);
      }
      _cloneInto(to) {
        const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
        to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
        to.state32.set(this.state32);
        to.pos = this.pos;
        to.posOut = this.posOut;
        to.finished = this.finished;
        to.rounds = rounds;
        to.suffix = suffix;
        to.outputLen = outputLen;
        to.enableXOF = enableXOF;
        to.destroyed = this.destroyed;
        return to;
      }
    };
    gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
    keccak_256 = /* @__PURE__ */ (() => gen(1, 136, 256 / 8))();
  }
});

// src/lib/cartesiNoticeProof.js
function keccakHex(bytes) {
  const out = keccak_256(bytes);
  return [...out].map((b2) => b2.toString(16).padStart(2, "0")).join("");
}
function validateNoticeSelector() {
  return "0x" + keccakHex(new TextEncoder().encode(VALIDATE_NOTICE_ABI)).slice(0, 8);
}
function pad32(hex) {
  return String(hex || "").replace(/^0x/i, "").padStart(64, "0");
}
function word(n3) {
  return BigInt(n3).toString(16).padStart(64, "0");
}
function encodeBytes(hex) {
  const h2 = String(hex || "").replace(/^0x/i, "");
  const even = h2.length % 2 ? "0" + h2 : h2;
  const len = even.length / 2;
  const pad = (64 - even.length % 64) % 64;
  return word(len) + even + "0".repeat(pad);
}
function encodeBytes32Array(arr) {
  const list = arr || [];
  let out = word(list.length);
  for (const x of list) out += pad32(x);
  return out;
}
function encodeValidity(v) {
  const headStatic = [
    word(v.inputIndexWithinEpoch),
    word(v.outputIndexWithinInput),
    pad32(v.outputHashesRootHash),
    pad32(v.vouchersEpochRootHash),
    pad32(v.noticesEpochRootHash),
    pad32(v.machineStateHash)
  ].join("");
  const headDynOff = 8 * 32;
  const arr1 = encodeBytes32Array(v.outputHashInOutputHashesSiblings);
  const arr2 = encodeBytes32Array(v.outputHashesInEpochSiblings);
  const off1 = headDynOff;
  const off2 = headDynOff + arr1.length / 2;
  return headStatic + word(off1) + word(off2) + arr1 + arr2;
}
function encodeProof(proof) {
  const v = proof.validity;
  const validityEnc = encodeValidity(v);
  const ctx = proof.context?.startsWith?.("0x") ? proof.context : `0x${proof.context || ""}`;
  const contextEnc = encodeBytes(ctx);
  const offValidity = 64;
  const offContext = 64 + validityEnc.length / 2;
  return word(offValidity) + word(offContext) + validityEnc + contextEnc;
}
function encodeValidateNoticeCall(payloadHex, proof) {
  const noticeEnc = encodeBytes(payloadHex);
  const proofEnc = encodeProof(proof);
  const offNotice = 64;
  const offProof = 64 + noticeEnc.length / 2;
  return validateNoticeSelector() + word(offNotice) + word(offProof) + noticeEnc + proofEnc;
}
function noticeHasProof(proof) {
  const v = proof?.validity;
  if (!v?.outputHashesRootHash || !v?.noticesEpochRootHash || !v?.machineStateHash) {
    return false;
  }
  return Array.isArray(v.outputHashInOutputHashesSiblings) && v.outputHashInOutputHashesSiblings.length > 0 && Array.isArray(v.outputHashesInEpochSiblings) && v.outputHashesInEpochSiblings.length > 0;
}
async function validateNoticeOnL1({
  payloadHex,
  proof,
  rpcUrl = CARTESI_L1_RPC,
  dapp = CARTESI_DAPP
} = {}) {
  if (!noticeHasProof(proof)) {
    return { ok: false, waiting: true, error: "waiting for Cartesi notice proof (epoch not claimed)" };
  }
  const data = encodeValidateNoticeCall(payloadHex, proof);
  const res = await fetch(rpcUrl, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({
      jsonrpc: "2.0",
      id: 1,
      method: "eth_call",
      params: [{ to: dapp, data }, "latest"]
    })
  });
  const body = await res.json().catch(() => ({}));
  if (body.error) {
    return { ok: false, waiting: false, error: body.error.message || "validateNotice rpc error" };
  }
  const raw = String(body.result || "");
  const ok = /^0x0*1$/.test(raw);
  if (!ok) {
    return { ok: false, waiting: false, error: "validateNotice returned false" };
  }
  return { ok: true, dapp, rpcUrl };
}
function ticketNeedsNoticeProof(ticketId, { labDemo } = {}) {
  const id = String(ticketId || "");
  if (!id) return false;
  if (labDemo || /^lab-demo-/.test(id)) return false;
  if (/^wart-pool-rotate-/.test(id)) return false;
  return true;
}
var CARTESI_L1_RPC, CARTESI_DAPP, VALIDATE_NOTICE_ABI, NOTICE_PROOF_GQL;
var init_cartesiNoticeProof = __esm({
  "src/lib/cartesiNoticeProof.js"() {
    "use strict";
    init_sha3();
    CARTESI_L1_RPC = "https://cartesi-bridge.duckdns.org/rpc";
    CARTESI_DAPP = "0xab7528bb862fB57E8A2BCd567a2e929a0Be56a5e";
    VALIDATE_NOTICE_ABI = "validateNotice(bytes,((uint64,uint64,bytes32,bytes32,bytes32,bytes32,bytes32[],bytes32[]),bytes))";
    NOTICE_PROOF_GQL = `
  index
  payload
  input { index }
  proof {
    context
    validity {
      inputIndexWithinEpoch
      outputIndexWithinInput
      outputHashesRootHash
      vouchersEpochRootHash
      noticesEpochRootHash
      machineStateHash
      outputHashInOutputHashesSiblings
      outputHashesInEpochSiblings
    }
  }
`;
  }
});

// src/lib/poolVerify.js
var poolVerify_exports = {};
__export(poolVerify_exports, {
  MAX_SPV_LAG: () => MAX_SPV_LAG,
  MIN_SPV_LAG: () => MIN_SPV_LAG,
  ROLLUP_GRAPHQL: () => ROLLUP_GRAPHQL,
  ROLLUP_INSPECT: () => ROLLUP_INSPECT,
  VERIFY_SNAPSHOT: () => VERIFY_SNAPSHOT,
  WART_HEAD: () => WART_HEAD,
  addrsMatch: () => addrsMatch,
  decodeInspectBody: () => decodeInspectBody,
  e8Match: () => e8Match,
  evaluateVerification: () => evaluateVerification,
  extractWartHead: () => extractWartHead,
  fetchIndependentHead: () => fetchIndependentHead,
  fetchInspectPool: () => fetchInspectPool,
  fetchReleaseNotice: () => fetchReleaseNotice,
  findInspectTicket: () => findInspectTicket,
  formatVerifyLine: () => formatVerifyLine,
  normAddr: () => normAddr,
  probeMachineHealth: () => probeMachineHealth,
  verifyOpenRequest: () => verifyOpenRequest
});
function hexToUtf8(raw) {
  const s3 = String(raw || "");
  if (!s3.startsWith("0x")) return s3;
  const hex = s3.slice(2);
  if (hex.length % 2 !== 0) return "";
  let out = "";
  for (let i3 = 0; i3 < hex.length; i3 += 2) {
    out += String.fromCharCode(parseInt(hex.slice(i3, i3 + 2), 16));
  }
  return out;
}
function normAddr(a) {
  return String(a || "").replace(/^0x/i, "").toLowerCase();
}
function addrsMatch(a, b2) {
  const na = normAddr(a);
  const nb = normAddr(b2);
  if (!na || !nb) return false;
  if (na === nb) return true;
  const a40 = na.length >= 40 ? na.slice(-40) : na;
  const b40 = nb.length >= 40 ? nb.slice(-40) : nb;
  return a40 === b40;
}
function e8Match(a, b2) {
  try {
    return BigInt(String(a || "0")) === BigInt(String(b2 || "0"));
  } catch {
    return false;
  }
}
function decodeInspectBody(body) {
  if (!body || typeof body !== "object") return null;
  for (const r3 of body.reports || []) {
    const txt = hexToUtf8(r3?.payload);
    try {
      const obj = JSON.parse(txt);
      if (obj && typeof obj === "object") {
        return {
          ...obj,
          processedInputCount: Number(body.processed_input_count ?? obj.processedInputCount ?? 0)
        };
      }
    } catch {
    }
  }
  return null;
}
function parseNoticePayload(raw) {
  const txt = hexToUtf8(raw);
  try {
    return JSON.parse(txt);
  } catch {
    return null;
  }
}
function extractWartHead(j) {
  const head = j?.data?.chainHead || j?.chainHead || j?.data || j;
  if (!head || typeof head !== "object") return null;
  const height = Number(head.height ?? head.blockHeight);
  if (!Number.isFinite(height) || height <= 0) return null;
  return {
    height,
    hash: String(head.hash || head.blockHash || "").replace(/^0x/i, "").toLowerCase()
  };
}
async function fetchJson(url, init) {
  const res = await fetch(url, { cache: "no-store", ...init });
  const body = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(body.error || `${url} HTTP ${res.status}`);
  return body;
}
async function fetchInspectPool() {
  if (inspectCache.value && Date.now() - inspectCache.at < INSPECT_TTL_MS) {
    return inspectCache.value;
  }
  try {
    const snap = await fetchJson(`${VERIFY_SNAPSHOT}1`);
    if (snap?.inspect?.pool?.ok) {
      const value2 = {
        source: "pool-snapshot",
        raw: snap.inspect.raw || snap.inspect,
        pool: snap.inspect.pool
      };
      inspectCache = { at: Date.now(), value: value2 };
      return value2;
    }
  } catch {
  }
  const raw = await fetchJson(ROLLUP_INSPECT);
  const pool = decodeInspectBody(raw);
  if (!pool?.ok) throw new Error("inspect/pool not ok");
  const value = { source: "rollup-inspect", raw, pool };
  inspectCache = { at: Date.now(), value };
  return value;
}
async function graphqlNoticesPage(cursor) {
  const after = cursor ? `, before: "${cursor}"` : "";
  const query = `{ notices(last: 100${after}) { pageInfo { hasPreviousPage startCursor } edges { node { ${NOTICE_PROOF_GQL} } } } vouchers(last: 20) { edges { node { index destination payload } } } }`;
  return fetchJson(ROLLUP_GRAPHQL, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ query })
  });
}
async function fetchReleaseNotice(ticketId) {
  const id = String(ticketId || "").trim();
  try {
    let cursor = null;
    let best = null;
    let voucherCount = 0;
    for (let page = 0; page < 20; page++) {
      const json = await graphqlNoticesPage(cursor);
      voucherCount = Math.max(
        voucherCount,
        (json?.data?.vouchers?.edges || []).length
      );
      const conn = json?.data?.notices || {};
      for (const e3 of conn.edges || []) {
        const obj = parseNoticePayload(e3?.node?.payload);
        if (!obj || obj.type !== "pool_release_ticket") continue;
        if (String(obj.ticketId || "") !== id) continue;
        const idx = Number(e3?.node?.index ?? 0);
        const proof = e3?.node?.proof || null;
        const row = {
          ...obj,
          _index: idx,
          _inputIndex: e3?.node?.input?.index ?? null,
          _payloadHex: e3?.node?.payload || null,
          _proof: proof,
          _hasProof: noticeHasProof(proof)
        };
        if (!best || idx >= best._index) best = row;
      }
      if (best) break;
      if (!conn.pageInfo?.hasPreviousPage || !conn.pageInfo?.startCursor) break;
      cursor = conn.pageInfo.startCursor;
    }
    return { source: "rollup-graphql", notice: best, voucherCount };
  } catch {
    const snap = await fetchJson(`${VERIFY_SNAPSHOT}${encodeURIComponent(id)}`);
    return {
      source: "pool-snapshot",
      notice: snap.notice || null,
      voucherCount: Number(snap.voucherCount || 0)
    };
  }
}
async function fetchIndependentHead() {
  try {
    const j = await fetchJson(WART_HEAD);
    const head = extractWartHead(j);
    if (head) return { source: "defi-head", ...head };
  } catch {
  }
  try {
    const snap = await fetchJson(`${VERIFY_SNAPSHOT}1`);
    const head = snap.wartHead;
    if (head?.height) return { source: "pool-snapshot", ...head };
  } catch {
  }
  throw new Error("independent Warthog head unavailable");
}
function findInspectTicket(pool, ticketId) {
  const id = String(ticketId || "").trim();
  const list = pool?.recentTickets || [];
  return list.find((t2) => String(t2.ticketId || "") === id) || null;
}
function evaluateVerification({
  req,
  inspectPool,
  notice,
  wartHead,
  requireNotice = true
}) {
  const checks = {
    inspect: false,
    notice: false,
    noticeProof: false,
    inspectTicket: false,
    spv: false
  };
  const reasons = [];
  const lab = Boolean(req?.labDemo) || /^lab-demo-/.test(String(req?.ticketId || ""));
  if (!inspectPool?.ok) {
    reasons.push("Cartesi inspect/pool is not ok");
  } else {
    checks.inspect = true;
  }
  if (req?.poolAddress && inspectPool?.poolAddress) {
    const known = [
      inspectPool.poolAddress,
      inspectPool.previousAddress,
      inspectPool.pendingNext?.address || inspectPool.pendingNext
    ].filter(Boolean);
    const liveOrRotate = known.some((a) => addrsMatch(req.poolAddress, a));
    if (!liveOrRotate) {
      const known3p = "ee6cfa285ab4c83c08622dfb1c64d75759d86ec13b18ec03";
      const knownOld = "966d1012941b1fb41d4fff2cadefca7115237dc1818a7cd7";
      const ticket3p = addrsMatch(req.poolAddress, known3p);
      const inspectLegacy = addrsMatch(inspectPool.poolAddress, knownOld);
      if (!(ticket3p && inspectLegacy)) {
        checks.inspect = false;
        reasons.push("inspect poolAddress \u2260 ticket pool");
      }
    }
  }
  const inspectTicket = inspectPool ? findInspectTicket(inspectPool, req.ticketId) : null;
  if (inspectTicket) {
    const amtOk = e8Match(inspectTicket.amountE8, req.amountE8);
    const toOk = !req.toAddress || addrsMatch(inspectTicket.toAddress, req.toAddress);
    if (amtOk && toOk) checks.inspectTicket = true;
    else reasons.push("inspect ticket amount/to mismatch");
  }
  if (notice && String(notice.ticketId || "") === String(req.ticketId || "")) {
    const amtOk = e8Match(notice.amountE8, req.amountE8);
    const toOk = !req.toAddress || !notice.toAddress || addrsMatch(notice.toAddress, req.toAddress);
    if (amtOk && toOk) checks.notice = true;
    else reasons.push("release notice amount/to mismatch \u2014 not this burn");
  } else if (requireNotice) {
    reasons.push("no pool_release_ticket notice \u2014 that notice is the burn attestation");
  }
  const needProof = requireNotice && ticketNeedsNoticeProof(req?.ticketId, { labDemo: lab });
  if (needProof && checks.notice) {
    if (notice?._noticeProofOk) checks.noticeProof = true;
    else if (inspectTicket?.status === "authorized" && checks.inspectTicket) {
      checks.noticeProof = true;
    } else if (!notice?._hasProof) {
      reasons.push("waiting for Cartesi notice proof (epoch not claimed)");
    } else {
      reasons.push("Cartesi notice proof present but validateNotice has not passed");
    }
  } else if (!needProof) {
    checks.noticeProof = true;
  }
  const spv = inspectPool?.spv || {};
  const machineH = Number(spv.bestHeight || 0);
  const machineHash = String(spv.bestHash || "").replace(/^0x/i, "").toLowerCase();
  const netH = Number(wartHead?.height || 0);
  const netHash = String(wartHead?.hash || "").replace(/^0x/i, "").toLowerCase();
  const lag = netH && machineH ? netH - machineH : null;
  if (!spv.bootstrapped) reasons.push("in-machine SPV light client is not bootstrapped");
  else if (!machineH) reasons.push("in-machine SPV has no tip");
  else if (!netH) reasons.push("independent Warthog head missing");
  else if (lag != null && (lag > MAX_SPV_LAG || lag < MIN_SPV_LAG)) {
    reasons.push(`SPV tip lag ${lag} outside ${MIN_SPV_LAG}\u2026${MAX_SPV_LAG}`);
  } else if (lag === 0 && machineHash && netHash && machineHash !== netHash) {
    reasons.push("SPV hash \u2260 independent head at same height");
  } else {
    checks.spv = true;
  }
  const authorizedTicket = checks.inspect && checks.inspectTicket && checks.notice && (String(inspectTicket?.status || notice?.status || "") === "authorized" || String(inspectTicket?.status || notice?.status || "") === "");
  const ok = checks.inspect && (!requireNotice || checks.notice) && (!needProof || checks.noticeProof) && (checks.spv || authorizedTicket);
  return {
    ok,
    lab,
    checks,
    reasons,
    inspectTicket: inspectTicket ? {
      ticketId: inspectTicket.ticketId,
      amountE8: inspectTicket.amountE8,
      toAddress: inspectTicket.toAddress,
      status: inspectTicket.status || null,
      reason: inspectTicket.reason || null
    } : null,
    notice: notice ? {
      ticketId: notice.ticketId,
      index: notice._index ?? notice.index ?? null,
      inputIndex: notice._inputIndex ?? null,
      amountE8: notice.amountE8,
      toAddress: notice.toAddress,
      reason: notice.reason || null,
      hasProof: !!notice._hasProof
    } : null,
    machine: {
      processedInputCount: Number(inspectPool?.processedInputCount || 0),
      poolAddress: inspectPool?.poolAddress || null,
      bestHeight: machineH || null,
      bestHash: machineHash || null,
      checkpointHeight: spv.checkpointHeight ?? null,
      checkpointHash: spv.checkpointHash || null
    },
    wartHead: wartHead ? { height: netH, hash: netHash, source: wartHead.source || null, lag } : null
  };
}
async function verifyOpenRequest(req) {
  const inspect = await fetchInspectPool();
  const gql = await fetchReleaseNotice(req.ticketId);
  const wartHead = await fetchIndependentHead();
  const notice = gql.notice;
  if (notice && ticketNeedsNoticeProof(req.ticketId, { labDemo: req.labDemo }) && notice._hasProof && notice._payloadHex) {
    const l1 = await validateNoticeOnL1({
      payloadHex: notice._payloadHex,
      proof: notice._proof
    });
    notice._noticeProofOk = !!l1.ok;
    notice._noticeProofError = l1.error || null;
    if (!l1.ok && l1.error && !l1.waiting) {
    }
  }
  const ev = evaluateVerification({
    req,
    inspectPool: inspect.pool,
    notice,
    wartHead
  });
  if (notice && notice._hasProof && !notice._noticeProofOk && ev.checks.notice) {
    const extra = notice._noticeProofError || "validateNotice failed";
    if (!ev.reasons.some((r3) => /validateNotice|notice proof/i.test(r3))) {
      ev.reasons.push(extra);
    }
    ev.ok = false;
    ev.checks.noticeProof = false;
  }
  return {
    ...ev,
    sources: {
      inspect: inspect.source,
      notice: gql.source,
      head: wartHead.source
    },
    voucherCount: gql.voucherCount || 0,
    attestation: {
      ticketId: req.ticketId,
      noticeOk: ev.checks.notice,
      noticeProofOk: ev.checks.noticeProof,
      inspectOk: ev.checks.inspect,
      inspectTicketOk: ev.checks.inspectTicket,
      spvOk: ev.checks.spv,
      noticeIndex: ev.notice?.index ?? null,
      machineInputs: ev.machine.processedInputCount,
      machineBestHeight: ev.machine.bestHeight,
      machineBestHash: ev.machine.bestHash,
      independentHeight: ev.wartHead?.height ?? null,
      independentHash: ev.wartHead?.hash ?? null,
      lag: ev.wartHead?.lag ?? null,
      sources: {
        inspect: inspect.source,
        notice: gql.source,
        head: wartHead.source
      },
      checkedAt: (/* @__PURE__ */ new Date()).toISOString()
    }
  };
}
async function probeMachineHealth() {
  const inspect = await fetchInspectPool();
  const wartHead = await fetchIndependentHead();
  const ev = evaluateVerification({
    req: { ticketId: "probe" },
    inspectPool: inspect.pool,
    notice: null,
    wartHead,
    requireNotice: false
  });
  return ev;
}
function formatVerifyLine(v) {
  if (!v) return "verify \u2014";
  const noticeBit = v.checks?.noticeProof ? "\u2713 notice-proof" : v.checks?.notice ? "\u2026 notice-proof" : v.ok ? "\u2014 notice" : "\u2717 notice";
  const bit = (ok, label) => `${ok ? "\u2713" : "\u2717"} ${label}`;
  const lag = v.wartHead?.lag == null ? "" : ` \xB7 lag ${v.wartHead.lag}`;
  const h2 = v.machine?.bestHeight ? ` \xB7 SPV #${v.machine.bestHeight}/${v.wartHead?.height || "?"}${lag}` : "";
  return `${noticeBit} \xB7 ${bit(v.checks?.inspect, "machine")} \xB7 ${bit(v.checks?.spv, "SPV")}${h2}`;
}
var ROLLUP_INSPECT, ROLLUP_GRAPHQL, WART_HEAD, VERIFY_SNAPSHOT, MAX_SPV_LAG, MIN_SPV_LAG, inspectCache, INSPECT_TTL_MS;
var init_poolVerify = __esm({
  "src/lib/poolVerify.js"() {
    "use strict";
    init_cartesiNoticeProof();
    ROLLUP_INSPECT = "https://cartesi-bridge.duckdns.org/rollup/inspect/pool";
    ROLLUP_GRAPHQL = "https://cartesi-bridge.duckdns.org/rollup/graphql";
    WART_HEAD = "https://warthog-defitestnet.duckdns.org/chain/head";
    VERIFY_SNAPSHOT = "https://cartesi-bridge.duckdns.org/api/pool?verifyTicket=";
    MAX_SPV_LAG = 256;
    MIN_SPV_LAG = -8;
    inspectCache = { at: 0, value: null };
    INSPECT_TTL_MS = 15e3;
  }
});

// node_modules/react/cjs/react-jsx-runtime.production.min.js
var require_react_jsx_runtime_production_min = __commonJS({
  "node_modules/react/cjs/react-jsx-runtime.production.min.js"(exports) {
    "use strict";
    var f = require_react();
    var k = Symbol.for("react.element");
    var l2 = Symbol.for("react.fragment");
    var m2 = Object.prototype.hasOwnProperty;
    var n3 = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner;
    var p2 = { key: true, ref: true, __self: true, __source: true };
    function q(c, a, g) {
      var b2, d2 = {}, e3 = null, h2 = null;
      void 0 !== g && (e3 = "" + g);
      void 0 !== a.key && (e3 = "" + a.key);
      void 0 !== a.ref && (h2 = a.ref);
      for (b2 in a) m2.call(a, b2) && !p2.hasOwnProperty(b2) && (d2[b2] = a[b2]);
      if (c && c.defaultProps) for (b2 in a = c.defaultProps, a) void 0 === d2[b2] && (d2[b2] = a[b2]);
      return { $$typeof: k, type: c, key: e3, ref: h2, props: d2, _owner: n3.current };
    }
    exports.Fragment = l2;
    exports.jsx = q;
    exports.jsxs = q;
  }
});

// node_modules/react/jsx-runtime.js
var require_jsx_runtime = __commonJS({
  "node_modules/react/jsx-runtime.js"(exports, module) {
    "use strict";
    if (true) {
      module.exports = require_react_jsx_runtime_production_min();
    } else {
      module.exports = null;
    }
  }
});

// scripts/extension-entry.jsx
var import_client = __toESM(require_client(), 1);

// src/components/WasmBrowserNode.jsx
var import_react3 = __toESM(require_react(), 1);

// src/lib/bridge.js
var OFFICIAL1 = {
  id: "official1",
  name: "Official1",
  host: "warthognode.duckdns.org",
  /** HTTPS base for JSON RPC */
  httpBase: "https://warthognode.duckdns.org",
  /**
   * P2P / browser-node WebSocket bridge path.
   * WASM nodes set ENV.WS_PEERS to this URL (semicolon-separated if multiple).
   */
  wsBridge: "wss://warthognode.duckdns.org/ws",
  /** Client RPC subscription stream (dashboards) — not the P2P bridge. */
  wsStream: "wss://warthognode.duckdns.org/stream",
  /**
   * Public checkpointed chain.db3 for browser OPFS fast-start (static nginx).
   * Not the live node DB — see docs/OFFICIAL1-SNAPSHOT.md.
   */
  snapshotChainDb: "https://warthognode.duckdns.org/snapshot/chain.db3",
  webrtc: true,
  flags: [
    "--rpc=127.0.0.1:3000",
    "--ws-port=10001",
    "--ws-bind-localhost",
    "--ws-x-forwarded-for",
    "--enable-webrtc",
    "--stratum=0.0.0.0:3456"
  ]
};
var DEFI_TESTNET = {
  id: "defi",
  name: "DeFi testnet",
  host: "warthog-defitestnet.duckdns.org",
  httpBase: "https://warthog-defitestnet.duckdns.org",
  wsBridge: "wss://warthog-defitestnet.duckdns.org/ws",
  wsStream: "wss://warthog-defitestnet.duckdns.org/stream",
  webrtc: false
};
var DEFAULT_WS_PEERS = OFFICIAL1.wsBridge;
var LOCAL_WS_BRIDGE_PATH = "/ws-bridge";
function isLocalDevHost(hostname = typeof window !== "undefined" ? window.location.hostname : "") {
  return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
}
function isExtensionPage(loc = typeof window !== "undefined" ? window.location : null) {
  if (!loc || !loc.protocol) return false;
  return /^(chrome|moz|safari)-extension:$/.test(loc.protocol);
}
function isExtensionPopup(loc = typeof window !== "undefined" ? window.location : null) {
  return isExtensionPage(loc) && /popup\.html$/i.test(loc.pathname || "");
}
function isExtensionSidePanel(loc = typeof window !== "undefined" ? window.location : null) {
  return isExtensionPage(loc) && /sidepanel\.html$/i.test(loc.pathname || "");
}
function openExtensionFullTab() {
  if (typeof chrome === "undefined" || !chrome.runtime?.getURL) {
    return false;
  }
  const url = chrome.runtime.getURL("node.html");
  if (chrome.runtime.sendMessage) {
    chrome.runtime.sendMessage({ type: "wart-open-full-tab" }).catch?.(() => {
      chrome.tabs?.create?.({ url });
    });
  } else {
    chrome.tabs?.create?.({ url });
  }
  try {
    if (isExtensionPopup()) window.close();
  } catch {
  }
  return true;
}
async function openExtensionSidePanel() {
  if (typeof chrome === "undefined" || !chrome.runtime?.sendMessage) {
    return false;
  }
  try {
    await chrome.runtime.sendMessage({ type: "wart-open-side-panel" });
    if (isExtensionPopup()) {
      try {
        window.close();
      } catch {
      }
    }
    return true;
  } catch {
    return false;
  }
}
function localDevWsBridgeUrl(loc = typeof window !== "undefined" ? window.location : null) {
  if (!loc) return `ws://127.0.0.1:4321${LOCAL_WS_BRIDGE_PATH}`;
  const scheme = loc.protocol === "https:" ? "wss" : "ws";
  return `${scheme}://${loc.host}${LOCAL_WS_BRIDGE_PATH}`;
}
function resolveDefaultWsPeers(loc = typeof window !== "undefined" ? window.location : null) {
  if (loc && isExtensionPage(loc)) {
    return DEFAULT_WS_PEERS;
  }
  if (loc && isLocalDevHost(loc.hostname)) {
    return localDevWsBridgeUrl(loc);
  }
  return DEFAULT_WS_PEERS;
}
function parsePeerList(raw) {
  return String(raw || "").split(/[;\n]+/).map((s3) => s3.trim()).filter(Boolean).filter((url, i3, arr) => arr.indexOf(url) === i3);
}
function formatPeerList(peers) {
  return parsePeerList(Array.isArray(peers) ? peers.join(";") : peers).join(";");
}
var MAINNET_WS_BRIDGES = [OFFICIAL1.wsBridge];
function mainnetPeerPreset() {
  return formatPeerList(MAINNET_WS_BRIDGES);
}
var PROXY_URL = "/api/proxy";
async function probeBridgeHttp(httpBase = OFFICIAL1.httpBase, { timeoutMs = 12e3 } = {}) {
  const base = String(httpBase || "").replace(/\/$/, "");
  const controller = new AbortController();
  const t2 = setTimeout(() => controller.abort(), timeoutMs);
  try {
    let res;
    if (isExtensionPage()) {
      res = await fetch(`${base}/chain/head`, {
        signal: controller.signal,
        headers: { Accept: "application/json" }
      });
    } else {
      try {
        res = await fetch(PROXY_URL, {
          method: "POST",
          signal: controller.signal,
          headers: { "Content-Type": "application/json", Accept: "application/json" },
          body: JSON.stringify({
            nodeBase: base,
            nodePath: "chain/head",
            method: "GET"
          })
        });
      } catch {
        res = await fetch(`${base}/chain/head`, {
          signal: controller.signal,
          headers: { Accept: "application/json" }
        });
      }
    }
    const text = await res.text();
    let json = null;
    try {
      json = JSON.parse(text);
    } catch {
      return {
        ok: false,
        error: `Non-JSON from chain/head (HTTP ${res.status}). Under COEP, use /api/proxy.`
      };
    }
    if (!res.ok || json?.code !== 0) {
      return { ok: false, error: json?.error || `HTTP ${res.status}`, data: json?.data };
    }
    return {
      ok: true,
      data: json.data,
      height: json.data?.height,
      synced: json.data?.synced
    };
  } catch (err) {
    return {
      ok: false,
      error: err.name === "AbortError" ? "timeout" : err.message || String(err)
    };
  } finally {
    clearTimeout(t2);
  }
}
function probeBridgeWs(wsUrl = OFFICIAL1.wsBridge, { timeoutMs = 14e3, protocol = "binary" } = {}) {
  return new Promise((resolve) => {
    let settled = false;
    let opened = false;
    let ws;
    const start = Date.now();
    const done = (result) => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      try {
        if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) {
          ws.close();
        }
      } catch {
      }
      resolve(result);
    };
    const timer = setTimeout(
      () => done({
        ok: false,
        detail: opened ? "timeout after open (unexpected)" : "timeout waiting for open \u2014 nginx /ws missing or node not on :10001",
        layer: "nginx-or-node"
      }),
      timeoutMs
    );
    try {
      ws = protocol ? new WebSocket(wsUrl, protocol) : new WebSocket(wsUrl);
    } catch (err) {
      done({ ok: false, detail: err.message || String(err), layer: "client" });
      return;
    }
    ws.onopen = () => {
      opened = true;
      const openedMs = Date.now() - start;
      done({ ok: true, detail: "open", openedMs, protocol: ws.protocol || protocol || "" });
    };
    ws.onerror = () => {
      if (!opened) {
        done({
          ok: false,
          detail: "WebSocket error before open (502 / refused / blocked)",
          layer: "nginx-or-node",
          hint: "502 usually means nginx location /ws \u2192 127.0.0.1:10001 is wrong, or wart-node is missing --ws-port=10001 (and --ws-x-forwarded-for so XFF is required)."
        });
      }
    };
    ws.onclose = (ev) => {
      if (!settled && !opened) {
        done({
          ok: false,
          detail: `closed before open code=${ev.code}${ev.reason ? ` ${ev.reason}` : ""}`,
          layer: "nginx-or-node"
        });
      }
    };
  });
}

// src/lib/wasmNode.js
var DEFAULT_WS_PEERS2 = DEFAULT_WS_PEERS;
var NODE_GLUE_URL = "/node/wart-node.js";
function isCrossOriginIsolated() {
  return typeof crossOriginIsolated !== "undefined" && crossOriginIsolated === true;
}
function hasSharedArrayBuffer() {
  return typeof SharedArrayBuffer !== "undefined";
}
function hasOpfs() {
  return typeof navigator !== "undefined" && navigator.storage && typeof navigator.storage.getDirectory === "function";
}
async function listOpfsEntries() {
  if (!hasOpfs()) return [];
  try {
    const root2 = await navigator.storage.getDirectory();
    const names = [];
    for await (const [name] of root2.entries()) {
      names.push(name);
    }
    return names;
  } catch {
    return [];
  }
}
var OPFS_NEEDS_RESET_KEY = "wartOpfsNeedsReset";
function markOpfsNeedsReset() {
  try {
    sessionStorage.setItem(OPFS_NEEDS_RESET_KEY, "1");
  } catch {
  }
}
function clearOpfsNeedsResetFlag() {
  try {
    sessionStorage.removeItem(OPFS_NEEDS_RESET_KEY);
  } catch {
  }
}
function opfsNeedsReset() {
  try {
    return sessionStorage.getItem(OPFS_NEEDS_RESET_KEY) === "1";
  } catch {
    return false;
  }
}
function terminateWasmWorkers(log) {
  const mods = [];
  if (typeof window !== "undefined") {
    if (window.wartNode) mods.push(window.wartNode);
    if (window.Module && window.Module !== window.wartNode) mods.push(window.Module);
  }
  let terminated = 0;
  for (const mod2 of mods) {
    try {
      const pt = mod2?.PThread;
      if (pt && typeof pt.terminateAllThreads === "function") {
        const n3 = (pt.runningWorkers?.length || 0) + (pt.unusedWorkers?.length || 0);
        pt.terminateAllThreads();
        terminated += n3 || 1;
        log?.(`[opfs] terminated Emscripten pthread pool (${n3 || "?"} workers)`);
      }
    } catch (e3) {
      log?.(`[opfs] PThread.terminateAllThreads failed: ${e3?.message || e3}`);
    }
    try {
      for (const w2 of mod2?.PThread?.runningWorkers || []) {
        try {
          w2.terminate?.();
        } catch {
        }
      }
      for (const w2 of mod2?.PThread?.unusedWorkers || []) {
        try {
          w2.terminate?.();
        } catch {
        }
      }
    } catch {
    }
  }
  if (typeof window !== "undefined") {
    try {
      window.wartNode = void 0;
    } catch {
    }
    try {
      window.Module = void 0;
    } catch {
    }
  }
  return { terminated };
}
async function clearOpfsStorage({
  retries = 6,
  retryDelayMs = 400,
  terminateWorkers = true,
  log
} = {}) {
  if (!hasOpfs()) {
    return { ok: false, error: "OPFS not available (need Chromium + secure context)" };
  }
  if (terminateWorkers) {
    terminateWasmWorkers(log);
    await new Promise((r3) => setTimeout(r3, 500));
  }
  let lastRemoved = [];
  let lastFailed = [];
  for (let attempt = 0; attempt < retries; attempt++) {
    try {
      const root2 = await navigator.storage.getDirectory();
      const removed = [];
      const failed = [];
      const names = [];
      for await (const [name] of root2.entries()) {
        names.push(name);
      }
      for (const name of names) {
        try {
          await root2.removeEntry(name, { recursive: true });
          removed.push(name);
        } catch (e3) {
          failed.push(`${name}: ${e3?.message || e3}`);
        }
      }
      lastRemoved = removed;
      lastFailed = failed;
      if (!failed.length) {
        const left = await listOpfsEntries();
        if (left.length === 0) {
          clearOpfsNeedsResetFlag();
          return { ok: true, removed, attempts: attempt + 1 };
        }
        lastFailed = left.map((n3) => `${n3}: still present after remove`);
      }
    } catch (e3) {
      lastFailed = [e3?.message || String(e3)];
    }
    if (terminateWorkers && attempt < retries - 1) {
      terminateWasmWorkers(log);
    }
    if (attempt < retries - 1) {
      await new Promise((r3) => setTimeout(r3, retryDelayMs * (attempt + 1)));
    }
  }
  return {
    ok: false,
    removed: lastRemoved,
    error: `Could not remove: ${lastFailed.join("; ")}. Another tab on this same host:port is almost certainly holding the OPFS lock. Close ALL tabs for this origin (check other windows too), then Recover again. Nuclear: DevTools \u2192 Application \u2192 Storage \u2192 "Clear site data".`
  };
}
async function recoverOpfsStorage({ reload = true, log } = {}) {
  markOpfsNeedsReset();
  log?.("[opfs] recover: terminating workers\u2026");
  terminateWasmWorkers(log);
  await new Promise((r3) => setTimeout(r3, 600));
  log?.("[opfs] recover: clearing OPFS\u2026");
  const result = await clearOpfsStorage({
    retries: 8,
    retryDelayMs: 350,
    terminateWorkers: true,
    log
  });
  if (result.ok) {
    log?.(`[opfs] recover: cleared ${result.removed?.join(", ") || "(empty)"}`);
  } else {
    log?.(`[opfs] recover: clear incomplete \u2014 ${result.error}`);
  }
  if (reload && typeof window !== "undefined") {
    const url = new URL(window.location.href);
    url.searchParams.set("resetDb", "1");
    log?.("[opfs] recover: reloading with ?resetDb=1 \u2026");
    window.location.replace(url.toString());
    return { ...result, reloading: true };
  }
  return { ...result, reloading: false };
}
async function prepareOpfsForStart({ forceClear = false } = {}) {
  if (!hasOpfs()) {
    return {
      ok: false,
      error: "OPFS is not available. Use Chrome/Edge on http://127.0.0.1 or https."
    };
  }
  const entries = await listOpfsEntries();
  const shouldClear = forceClear || opfsNeedsReset();
  if (!shouldClear) {
    return { ok: true, cleared: false, entries };
  }
  const result = await clearOpfsStorage();
  if (!result.ok) {
    return {
      ok: false,
      cleared: false,
      entries,
      error: result.error
    };
  }
  return {
    ok: true,
    cleared: true,
    removed: result.removed,
    entries: await listOpfsEntries()
  };
}
function isOpfsReadonlyError(err) {
  const msg = String(err?.message || err || "");
  return /readonly database|NoModificationAllowed|InvalidStateError|SQLITE_READONLY|write a readonly/i.test(msg);
}
function isWasmOomError(err) {
  const msg = String(err?.message || err || "");
  return /Cannot enlarge memory/i.test(msg) || /Aborted\([^)]*Cannot enlarge/i.test(msg) || /out of memory/i.test(msg) || /memory access out of bounds/i.test(msg) || /limit is\s+\d+\s+bytes!/i.test(msg);
}
function resolveWsPeers(search = typeof window !== "undefined" ? window.location.search : "") {
  try {
    const params = new URLSearchParams(search);
    const fromQuery = params.get("peers") || params.get("WS_PEERS");
    if (fromQuery && fromQuery.trim()) return fromQuery.trim();
  } catch {
  }
  try {
    const stored = localStorage.getItem("wsPeers");
    if (stored && stored.trim()) {
      const pageDefault = resolveDefaultWsPeers();
      if (typeof window !== "undefined" && pageDefault.includes("/ws-bridge") && /warthognode\.duckdns\.org\/ws/.test(stored) && !paramsHasForcePublic(search)) {
        return pageDefault;
      }
      return stored.trim();
    }
  } catch {
  }
  return resolveDefaultWsPeers();
}
function paramsHasForcePublic(search) {
  try {
    return new URLSearchParams(search).get("publicWs") === "1";
  } catch {
    return false;
  }
}
function applyWsPeersEnv(mod2, peers) {
  const value = String(peers || DEFAULT_WS_PEERS2);
  if (!mod2 || typeof mod2 !== "object") {
    throw new Error("applyWsPeersEnv: missing runtime Module");
  }
  if (!mod2.ENV) mod2.ENV = {};
  mod2.ENV.WS_PEERS = value;
  if (mod2.getEnvStrings && mod2.getEnvStrings.strings) {
    mod2.getEnvStrings.strings = void 0;
  }
  return value;
}
function createModuleConfig({
  wsPeers,
  print,
  setStatus,
  onChain,
  onConnect,
  onDisconnect,
  onMempoolAdd,
  onMempoolErase,
  onProgress
} = {}) {
  const peers = wsPeers || DEFAULT_WS_PEERS2;
  const statusState = { time: Date.now(), text: "" };
  let depTotal = 0;
  const peerCount = String(peers).split(/[;]+/).map((s3) => s3.trim()).filter(Boolean).length;
  const config = {
    /** Used by startWasmNode installLocalBridgeWsRewrite. */
    __wsPeers: peers,
    /**
     * Passed to C main as argv. Browser core also enables WebRTC by default;
     * this keeps the flag explicit if config.cpp path changes.
     */
    arguments: ["--enable-webrtc"],
    locateFile(path) {
      if (path.endsWith(".wasm") || path.endsWith(".worker.js") || path.endsWith(".worker.mjs") || path.endsWith(".js")) {
        return `/node/${path.split("/").pop().replace(/\.mjs$/, ".js")}`;
      }
      return `/node/${path}`;
    },
    /**
     * preRun receives the *real* Module. Set ENV here before C main/getenv.
     */
    preRun: [
      (mod2) => {
        try {
          const value = applyWsPeersEnv(mod2, peers);
          print?.(`[preRun] ENV.WS_PEERS=${value} (${peerCount} peer URL${peerCount === 1 ? "" : "s"})`);
          print?.("[preRun] argv --enable-webrtc (parallel peers via Official1 signaling when available)");
        } catch (e3) {
          print?.(`[preRun] ENV set failed: ${e3?.message || e3}`);
        }
      }
    ],
    onRuntimeInitialized() {
      print?.("[runtime] onRuntimeInitialized \u2014 C/C++ main will run");
      print?.(`[runtime] WS_PEERS=${peers}`);
      print?.("[runtime] sync build: window=32 \xB7 maxRequests=32 \xB7 heap 2048MB \xB7 WebRTC on");
      setStatus?.("Runtime initialized \u2014 full node starting");
    },
    onChain: (event) => onChain?.(event),
    onConnect: (event) => onConnect?.(event),
    onDisconnect: (event) => onDisconnect?.(event),
    onMempoolAdd: (event) => onMempoolAdd?.(event),
    onMempoolErase: (event) => onMempoolErase?.(event),
    print: (...args) => {
      const text = args.map(String).join(" ");
      console.log(text);
      print?.(text);
    },
    printErr: (...args) => {
      const text = args.map(String).join(" ");
      console.error(text);
      print?.(text);
    },
    setStatus: (text) => {
      if (text === statusState.text) return;
      const m2 = String(text || "").match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/);
      const now = Date.now();
      if (m2 && now - statusState.time < 30) return;
      statusState.time = now;
      statusState.text = text;
      if (m2) {
        onProgress?.({
          label: m2[1],
          value: parseInt(m2[2], 10) * 100,
          max: parseInt(m2[4], 10) * 100
        });
        setStatus?.(m2[1].trim());
      } else {
        onProgress?.(null);
        setStatus?.(text || "");
      }
    },
    totalDependencies: 0,
    monitorRunDependencies(left) {
      depTotal = Math.max(depTotal, left);
      this.totalDependencies = depTotal;
      config.setStatus(
        left ? `Preparing\u2026 (${depTotal - left}/${depTotal})` : "All downloads complete."
      );
    }
  };
  return config;
}
function isExtensionPage2() {
  return typeof location !== "undefined" && /^(chrome|moz|safari)-extension:$/.test(location.protocol);
}
async function loadEmscriptenFactory(glueUrl = NODE_GLUE_URL) {
  const absolute = new URL(glueUrl, window.location.href).href;
  if (isExtensionPage2() || absolute.startsWith("chrome-extension:")) {
    const mod2 = await import(
      /* @vite-ignore */
      absolute
    );
    const initModule = mod2.default;
    if (typeof initModule !== "function") {
      throw new Error("wart-node.js did not export a default factory function");
    }
    return initModule;
  }
  const res = await fetch(absolute, { credentials: "same-origin" });
  if (!res.ok) {
    throw new Error(`Failed to load ${glueUrl}: HTTP ${res.status} ${res.statusText}`);
  }
  const source = await res.text();
  const patched = `const __wartGlueMetaUrl = ${JSON.stringify(absolute)};
` + source.replace(/import\.meta\.url/g, "__wartGlueMetaUrl");
  const blob = new Blob([patched], { type: "text/javascript" });
  const blobUrl = URL.createObjectURL(blob);
  try {
    const mod2 = await import(
      /* @vite-ignore */
      blobUrl
    );
    const initModule = mod2.default;
    if (typeof initModule !== "function") {
      throw new Error("wart-node.js did not export a default factory function");
    }
    setTimeout(() => URL.revokeObjectURL(blobUrl), 12e4);
    return initModule;
  } catch (err) {
    URL.revokeObjectURL(blobUrl);
    throw err;
  }
}
function installLocalBridgeWsRewrite(targetWssUrl, log) {
  if (typeof window === "undefined") return;
  const target = String(targetWssUrl || DEFAULT_WS_PEERS2).split(";")[0].trim();
  if (!target) return;
  window.__wartWsRewriteTarget = target;
  if (!window.__wartNativeWebSocket) {
    window.__wartNativeWebSocket = window.WebSocket;
  }
  if (window.__wartWsRewriteInstalled && window.__wartWsRewriteVersion === 4) {
    log?.(`[ws-handshake] target updated \u2192 ${target}`);
    return;
  }
  const Orig = window.__wartNativeWebSocket || window.WebSocket;
  const localBridge = /^(ws:\/\/)(127\.0\.0\.1|localhost|\[::1\]):10001\/?$/i;
  const isP2pBridge = (u2) => typeof u2 === "string" && (/\/ws-bridge\/?(\?|$)/.test(u2) || /\/ws\/?(\?|$)/.test(u2) || localBridge.test(u2)) && !/\/stream\/?(\?|$)/.test(u2);
  function toU8(data) {
    if (data instanceof ArrayBuffer) return new Uint8Array(data);
    if (data instanceof Uint8Array) return data;
    if (ArrayBuffer.isView(data)) {
      return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
    }
    return null;
  }
  function normalizeProtocols(protocols, bridge) {
    let protos = protocols;
    if (bridge && (protos === void 0 || protos === null || protos === "")) {
      return "binary";
    }
    if (Array.isArray(protos) && protos.length === 1) return protos[0];
    return protos;
  }
  function installP2pWsGlue(ws, finalUrl) {
    let cppOnOpen = null;
    let cppOnMessage = null;
    let cppOnClose = null;
    let cppOnError = null;
    let openedAt = 0;
    let wasmNotified = false;
    let openTimer = null;
    const earlyMessages = [];
    ws.binaryType = "arraybuffer";
    Object.defineProperty(ws, "onopen", {
      configurable: true,
      enumerable: true,
      get: () => cppOnOpen,
      set: (fn) => {
        cppOnOpen = fn;
      }
    });
    Object.defineProperty(ws, "onmessage", {
      configurable: true,
      enumerable: true,
      get: () => cppOnMessage,
      set: (fn) => {
        cppOnMessage = fn;
      }
    });
    Object.defineProperty(ws, "onclose", {
      configurable: true,
      enumerable: true,
      get: () => cppOnClose,
      set: (fn) => {
        cppOnClose = fn;
      }
    });
    Object.defineProperty(ws, "onerror", {
      configurable: true,
      enumerable: true,
      get: () => cppOnError,
      set: (fn) => {
        cppOnError = fn;
      }
    });
    const hexPrefix = (u8, n3 = 24) => [...u8.subarray(0, Math.min(n3, u8.length))].map((b2) => b2.toString(16).padStart(2, "0")).join("");
    const deliverMessage = (ev) => {
      try {
        cppOnMessage?.(ev);
      } catch (e3) {
        log?.(`[ws-handshake] cpp onmessage error: ${e3?.message || e3}`);
      }
    };
    const notifyWasmOpen = () => {
      if (wasmNotified || ws.readyState !== Orig.OPEN) return;
      wasmNotified = true;
      log?.(
        `[ws-handshake] notifying WASM onopen after settle (${Date.now() - openedAt}ms) \u2014 C++ will send GRUNT? on wire`
      );
      try {
        cppOnOpen?.({ type: "open", target: ws });
      } catch (e3) {
        log?.(`[ws-handshake] cpp onopen error: ${e3?.message || e3}`);
        console.error("[ws-handshake] cpp onopen error", e3);
      }
      while (earlyMessages.length) {
        deliverMessage(earlyMessages.shift());
      }
    };
    ws.addEventListener("open", () => {
      openedAt = Date.now();
      log?.(
        `[ws-handshake] open (${finalUrl}) \u2014 settle 250ms then WASM onopen (C++ owns GRUNT; no JS dual-handshake)`
      );
      openTimer = setTimeout(notifyWasmOpen, 250);
    });
    ws.addEventListener("message", (ev) => {
      const u8 = toU8(ev.data) || new Uint8Array(0);
      const magic = new TextDecoder().decode(u8.subarray(0, Math.min(14, u8.length)));
      log?.(
        `[ws-handshake] rx ${u8.length}B magic=${JSON.stringify(magic)} hex=${hexPrefix(u8)} wasmOpen=${wasmNotified}`
      );
      if (!wasmNotified) {
        earlyMessages.push(ev);
        return;
      }
      deliverMessage(ev);
    });
    ws.addEventListener("close", (ev) => {
      if (openTimer) clearTimeout(openTimer);
      const ms = openedAt ? Date.now() - openedAt : -1;
      log?.(
        `[ws-handshake] close code=${ev.code} wasClean=${ev.wasClean} wasmOpen=${wasmNotified} openForMs=${ms} reason=${JSON.stringify(ev.reason || "")}`
      );
      cppOnClose?.(ev);
    });
    ws.addEventListener("error", () => {
      log?.(
        `[ws-handshake] socket error (readyState=${ws.readyState} url=${finalUrl})`
      );
      cppOnError?.({ type: "error", target: ws });
    });
    const protoSend = Orig.prototype.send;
    ws.send = function wartSend(data) {
      const u8 = toU8(data);
      if (u8) {
        const magic = new TextDecoder().decode(u8.subarray(0, Math.min(14, u8.length)));
        log?.(
          `[ws-handshake] tx ${u8.length}B magic=${JSON.stringify(magic)} hex=${hexPrefix(u8)}`
        );
      } else {
        log?.(`[ws-handshake] tx (non-binary) typeof=${typeof data}`);
      }
      return protoSend.call(this, data);
    };
  }
  const WartWebSocket = new Proxy(Orig, {
    construct(Target, args) {
      let url = args[0];
      let protocols = args[1];
      let finalUrl = url;
      if (typeof url === "string" && localBridge.test(url)) {
        finalUrl = window.__wartWsRewriteTarget || target;
        log?.(`[ws-rewrite] ${url} \u2192 ${finalUrl}`);
        console.info(`[ws-rewrite] ${url} \u2192 ${finalUrl}`);
      }
      const bridge = isP2pBridge(finalUrl);
      const protos = normalizeProtocols(protocols, bridge);
      const constructArgs = protos === void 0 || protos === null ? [finalUrl] : [finalUrl, protos];
      const ws = Reflect.construct(Target, constructArgs, Target);
      if (bridge) {
        log?.(`[ws-handshake] dial ${finalUrl} protocol=${JSON.stringify(protos ?? null)}`);
        installP2pWsGlue(ws, finalUrl);
      }
      return ws;
    }
  });
  window.WebSocket = WartWebSocket;
  window.__wartWsRewriteInstalled = true;
  window.__wartWsRewriteVersion = 4;
  log?.(
    "[ws-handshake] installed v4 (delay onopen; C++ wire GRUNT; no JS dual-handshake) \u2014 P2P /ws only"
  );
}
async function startWasmNode(moduleConfig) {
  if (!isCrossOriginIsolated()) {
    throw new Error(
      "Page is not cross-origin isolated. SharedArrayBuffer (pthreads) is unavailable. Serve with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp."
    );
  }
  if (!hasSharedArrayBuffer()) {
    throw new Error("SharedArrayBuffer is not available in this browser/context.");
  }
  const target = moduleConfig?.__wsPeers || DEFAULT_WS_PEERS2;
  installLocalBridgeWsRewrite(target, moduleConfig?.print);
  const initModule = await loadEmscriptenFactory(NODE_GLUE_URL);
  const instance = await initModule(moduleConfig);
  return instance;
}

// src/lib/opfsSnapshot.js
var CHAIN_DB_NAME = "chain.db3";
var PEERS_DB_NAME = "peers_v2.db3";
var RXTX_DB_NAME = "rxtx.db3";
var OPFS_MAX_SAFE_DB_BYTES = 16 * 1024 * 1024 * 1024;
var CHAIN_SIDE_NAMES = [
  "chain.db3-wal",
  "chain.db3-shm",
  "chain.db3-journal"
];
function formatBytes(n3) {
  const x = Number(n3) || 0;
  if (x < 1024) return `${x} B`;
  if (x < 1024 * 1024) return `${(x / 1024).toFixed(1)} KB`;
  if (x < 1024 * 1024 * 1024) return `${(x / (1024 * 1024)).toFixed(1)} MB`;
  return `${(x / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}
function isSqliteDiskIoError(err) {
  const msg = String(err?.message || err || "");
  return /disk I\/O error|SQLITE_IOERR|database disk image is malformed|file is not a database|SQLITE_CORRUPT|not a database/i.test(msg);
}
async function inspectSqliteHeader(source) {
  let head;
  try {
    if (source instanceof Uint8Array) {
      head = source.length >= 20 ? source.subarray(0, 20) : source;
    } else if (source instanceof ArrayBuffer) {
      head = new Uint8Array(source.byteLength >= 20 ? source.slice(0, 20) : source);
    } else if (source && typeof source.slice === "function") {
      head = new Uint8Array(await source.slice(0, 20).arrayBuffer());
    } else {
      return { ok: false, error: "Could not read SQLite header" };
    }
  } catch (e3) {
    return { ok: false, error: `Could not read file header: ${e3?.message || e3}` };
  }
  if (head.length < 16) {
    return { ok: false, error: "File too small for a SQLite header" };
  }
  const magic = "SQLite format 3\0";
  for (let i3 = 0; i3 < 16; i3++) {
    if (head[i3] !== magic.charCodeAt(i3)) {
      return {
        ok: false,
        error: "Selected file is not a SQLite database (missing \u201CSQLite format 3\u201D header). Pick the main chain.db3 only \u2014 not -wal/-shm, not a zip, not a partial copy."
      };
    }
  }
  if (head.length < 20) {
    return { ok: true, walMode: false };
  }
  const writeVer = head[18];
  const readVer = head[19];
  const walMode = writeVer === 2 || readVer === 2;
  return { ok: true, walMode, writeVer, readVer };
}
async function verifyOpfsChainDb() {
  if (!hasOpfs()) {
    return { ok: false, error: "OPFS not available" };
  }
  try {
    const root2 = await navigator.storage.getDirectory();
    const handle = await root2.getFileHandle(CHAIN_DB_NAME);
    const file = await handle.getFile();
    if (file.size < 100) {
      return { ok: false, error: `chain.db3 too small (${formatBytes(file.size)})`, bytes: file.size };
    }
    const inspected = await inspectSqliteHeader(file);
    if (!inspected.ok) {
      return { ok: false, error: inspected.error, bytes: file.size };
    }
    if (inspected.walMode) {
      return {
        ok: false,
        error: `OPFS ${CHAIN_DB_NAME} is still in SQLite WAL mode (header write/read version 2). On the native host stop the node, then: sqlite3 chain.db3 "PRAGMA wal_checkpoint(TRUNCATE); PRAGMA journal_mode=DELETE;" \u2014 import only that single file (no -wal/-shm).`,
        bytes: file.size
      };
    }
    return { ok: true, bytes: file.size };
  } catch (e3) {
    return { ok: false, error: e3?.message || String(e3) };
  }
}
async function removeOpfsNames(root2, names, log) {
  for (const name of names) {
    try {
      await root2.removeEntry(name, { recursive: true });
      log?.(`[snapshot] removed OPFS ${name}`);
    } catch {
    }
  }
}
async function importChainDbBlob(blob, {
  log,
  onProgress,
  clearPeerDbs = true
} = {}) {
  if (!hasOpfs()) {
    return { ok: false, error: "OPFS not available (need Chromium + secure context)" };
  }
  if (!blob || typeof blob.size !== "number") {
    return { ok: false, error: "No snapshot file provided" };
  }
  if (blob.size < 1024) {
    return { ok: false, error: `File too small (${formatBytes(blob.size)}) \u2014 not a chain.db3` };
  }
  if (blob.size >= OPFS_MAX_SAFE_DB_BYTES) {
    return {
      ok: false,
      error: `Refusing import: ${formatBytes(blob.size)} exceeds the ${formatBytes(OPFS_MAX_SAFE_DB_BYTES)} soft cap (browser storage / practicality). Split or use a smaller snapshot.`
    };
  }
  const inspected = await inspectSqliteHeader(blob);
  if (!inspected.ok) {
    return { ok: false, error: inspected.error };
  }
  if (inspected.walMode) {
    return {
      ok: false,
      error: 'Refusing import: chain.db3 is still in SQLite WAL mode. Stop the native node completely, then run: sqlite3 chain.db3 "PRAGMA wal_checkpoint(TRUNCATE); PRAGMA journal_mode=DELETE;" Confirm no chain.db3-wal / -shm remain, then re-import that single file.'
    };
  }
  if (blob.name && /(-wal|-shm|-journal)$/i.test(blob.name)) {
    return {
      ok: false,
      error: `Refusing ${blob.name}. Import only the main chain.db3 after WAL checkpoint (see snapshot prep steps).`
    };
  }
  log?.(`[snapshot] terminating workers before OPFS write\u2026`);
  terminateWasmWorkers(log);
  await new Promise((r3) => setTimeout(r3, 500));
  const root2 = await navigator.storage.getDirectory();
  const total = blob.size;
  log?.(`[snapshot] writing ${CHAIN_DB_NAME} (${formatBytes(total)})\u2026`);
  log?.(
    "[snapshot] tip: native DB must be stopped + wal_checkpoint(TRUNCATE) + journal_mode=DELETE or SQLite will throw disk I/O error in the browser"
  );
  await removeOpfsNames(root2, [CHAIN_DB_NAME, ...CHAIN_SIDE_NAMES], log);
  if (clearPeerDbs) {
    await removeOpfsNames(
      root2,
      [PEERS_DB_NAME, RXTX_DB_NAME, "testnet3_chain.db3", "testnet_peers.db3", "testnet_rxtx.db3"],
      log
    );
  }
  const handle = await root2.getFileHandle(CHAIN_DB_NAME, { create: true });
  const writable = await handle.createWritable({ keepExistingData: false });
  let written = 0;
  try {
    if (typeof blob.stream === "function" && typeof writable.write === "function") {
      const reader = blob.stream().getReader();
      let lastPct = -1;
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        await writable.write(value);
        written += value.byteLength || value.length || 0;
        const pct = total > 0 ? Math.floor(written / total * 100) : 0;
        if (pct !== lastPct && (pct % 5 === 0 || pct === 100)) {
          lastPct = pct;
          onProgress?.({ written, total, pct });
          log?.(`[snapshot] ${pct}% \xB7 ${formatBytes(written)} / ${formatBytes(total)}`);
        }
      }
    } else {
      await writable.write(blob);
      written = total;
      onProgress?.({ written: total, total, pct: 100 });
    }
    await writable.close();
  } catch (e3) {
    try {
      await writable.abort?.();
    } catch {
    }
    return { ok: false, error: e3?.message || String(e3) };
  }
  if (written !== total) {
    return {
      ok: false,
      error: `Write size mismatch: wrote ${formatBytes(written)} of ${formatBytes(total)}. Delete local data and re-import.`
    };
  }
  const verify = await verifyOpfsChainDb();
  if (!verify.ok) {
    return { ok: false, error: verify.error || "Post-write verify failed" };
  }
  if (verify.bytes !== total) {
    return {
      ok: false,
      error: `OPFS size ${formatBytes(verify.bytes)} \u2260 source ${formatBytes(total)}. Truncated write \u2014 free disk, clear site data, re-import.`
    };
  }
  const entries = await listOpfsEntries();
  log?.(
    `[snapshot] verified SQLite header \xB7 ${formatBytes(verify.bytes)} \xB7 journal header ${inspected.walMode ? "WAL (bad for browser)" : "DELETE (ok)"}`
  );
  log?.(`[snapshot] done \u2014 OPFS: ${entries.join(", ") || "(empty?)"}`);
  log?.(
    "[snapshot] note: header/size check \u2260 full WASM open. Close other tabs on this origin, then Start once."
  );
  return { ok: true, bytes: total, entries, verified: true, walMode: inspected.walMode };
}
async function importChainDbFromUrl(url, { log, onProgress, clearPeerDbs = true } = {}) {
  const u2 = String(url || "").trim();
  if (!u2) return { ok: false, error: "Empty snapshot URL" };
  log?.(`[snapshot] fetching ${u2}\u2026`);
  let res;
  try {
    res = await fetch(u2, { credentials: "omit", mode: "cors" });
  } catch (e3) {
    return {
      ok: false,
      error: `Fetch failed: ${e3?.message || e3}. Under COEP, the host must send Cross-Origin-Resource-Policy (or host the file same-origin).`
    };
  }
  if (!res.ok) {
    return { ok: false, error: `HTTP ${res.status} ${res.statusText}` };
  }
  const total = Number(res.headers.get("content-length")) || 0;
  if (total >= OPFS_MAX_SAFE_DB_BYTES) {
    return {
      ok: false,
      error: `Refusing URL import: Content-Length ${formatBytes(total)} exceeds the ${formatBytes(OPFS_MAX_SAFE_DB_BYTES)} soft cap.`
    };
  }
  if (!res.body) {
    const blob = await res.blob();
    return importChainDbBlob(blob, { log, onProgress, clearPeerDbs });
  }
  log?.(`[snapshot] streaming into OPFS${total ? ` (${formatBytes(total)})` : ""}\u2026`);
  terminateWasmWorkers(log);
  await new Promise((r3) => setTimeout(r3, 500));
  if (!hasOpfs()) {
    return { ok: false, error: "OPFS not available" };
  }
  const root2 = await navigator.storage.getDirectory();
  try {
    await root2.removeEntry(CHAIN_DB_NAME);
  } catch {
  }
  if (clearPeerDbs) {
    for (const name of [PEERS_DB_NAME, RXTX_DB_NAME]) {
      try {
        await root2.removeEntry(name);
      } catch {
      }
    }
  }
  await removeOpfsNames(root2, [CHAIN_DB_NAME, ...CHAIN_SIDE_NAMES], log);
  const handle = await root2.getFileHandle(CHAIN_DB_NAME, { create: true });
  const writable = await handle.createWritable({ keepExistingData: false });
  const reader = res.body.getReader();
  let written = 0;
  let lastPct = -1;
  let headerBuf = null;
  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      if (!headerBuf || headerBuf.length < 20) {
        const chunk = value instanceof Uint8Array ? value : new Uint8Array(value);
        if (!headerBuf) {
          headerBuf = chunk.length >= 20 ? chunk.subarray(0, 20) : chunk.slice();
        } else {
          const need = 20 - headerBuf.length;
          const next = new Uint8Array(headerBuf.length + Math.min(need, chunk.length));
          next.set(headerBuf);
          next.set(chunk.subarray(0, Math.min(need, chunk.length)), headerBuf.length);
          headerBuf = next;
        }
        if (headerBuf.length >= 20) {
          const inspected = await inspectSqliteHeader(headerBuf);
          if (!inspected.ok || inspected.walMode) {
            try {
              await writable.abort?.();
            } catch {
            }
            try {
              await reader.cancel();
            } catch {
            }
            await removeOpfsNames(root2, [CHAIN_DB_NAME, ...CHAIN_SIDE_NAMES], log);
            return {
              ok: false,
              error: inspected.ok ? "Refusing import: remote chain.db3 is still in SQLite WAL mode. Checkpoint + journal_mode=DELETE on the host before serving the file." : inspected.error
            };
          }
        }
      }
      await writable.write(value);
      written += value.byteLength;
      if (written >= OPFS_MAX_SAFE_DB_BYTES) {
        try {
          await writable.abort?.();
        } catch {
        }
        try {
          await reader.cancel();
        } catch {
        }
        await removeOpfsNames(root2, [CHAIN_DB_NAME, ...CHAIN_SIDE_NAMES], log);
        return {
          ok: false,
          error: `Download reached ${formatBytes(written)} (over soft cap ${formatBytes(OPFS_MAX_SAFE_DB_BYTES)}). Aborted.`
        };
      }
      if (total > 0) {
        const pct = Math.floor(written / total * 100);
        if (pct !== lastPct && (pct % 5 === 0 || pct === 100)) {
          lastPct = pct;
          onProgress?.({ written, total, pct });
          log?.(`[snapshot] ${pct}% \xB7 ${formatBytes(written)} / ${formatBytes(total)}`);
        }
      } else if (written % (32 * 1024 * 1024) < value.byteLength) {
        log?.(`[snapshot] ${formatBytes(written)} written\u2026`);
        onProgress?.({ written, total: 0, pct: 0 });
      }
    }
    await writable.close();
  } catch (e3) {
    try {
      await writable.abort?.();
    } catch {
    }
    return { ok: false, error: e3?.message || String(e3) };
  }
  if (total > 0 && written !== total) {
    return {
      ok: false,
      error: `Download size mismatch: got ${formatBytes(written)}, Content-Length ${formatBytes(total)}`
    };
  }
  const verify = await verifyOpfsChainDb();
  if (!verify.ok) {
    return { ok: false, error: verify.error || "Post-write verify failed" };
  }
  const entries = await listOpfsEntries();
  log?.(`[snapshot] verified \xB7 ${formatBytes(written)}`);
  return { ok: true, bytes: written, entries, verified: true };
}
async function getLocalChainDbInfo() {
  if (!hasOpfs()) return { present: false };
  try {
    const root2 = await navigator.storage.getDirectory();
    const handle = await root2.getFileHandle(CHAIN_DB_NAME);
    const file = await handle.getFile();
    return { present: true, bytes: file.size, name: CHAIN_DB_NAME };
  } catch {
    return { present: false };
  }
}

// src/lib/snapshotPublic.js
var DEFAULT_PUBLIC_SNAPSHOT_URL = "/snapshot/chain.db3";
var PUBLIC_SNAPSHOT_MANIFEST_URL = "/snapshot/manifest.json";
function resolvePublicSnapshotUrl(loc = typeof window !== "undefined" ? window.location : null) {
  try {
    if (loc?.search) {
      const q = new URLSearchParams(loc.search).get("snapshot")?.trim();
      if (q && (/^https?:\/\//i.test(q) || q.startsWith("/"))) {
        return q;
      }
    }
  } catch {
  }
  const envUrl = import.meta.env.PUBLIC_SNAPSHOT_URL;
  if (envUrl && String(envUrl).trim()) return String(envUrl).trim();
  return DEFAULT_PUBLIC_SNAPSHOT_URL;
}
async function fetchPublicSnapshotManifest(url = PUBLIC_SNAPSHOT_MANIFEST_URL) {
  try {
    const res = await fetch(url, { credentials: "same-origin", cache: "no-cache" });
    if (!res.ok) return null;
    const data = await res.json();
    if (!data || typeof data !== "object") return null;
    return data;
  } catch {
    return null;
  }
}
async function probePublicSnapshotUrl(url) {
  const u2 = String(url || "").trim();
  if (!u2) return { ok: false, error: "Empty snapshot URL" };
  const opts = { method: "HEAD", credentials: "omit", mode: "cors", cache: "no-cache" };
  try {
    let res = await fetch(u2, opts);
    if (res.status === 405 || res.status === 501) {
      res = await fetch(u2, {
        method: "GET",
        headers: { Range: "bytes=0-0" },
        credentials: "omit",
        mode: "cors",
        cache: "no-cache"
      });
    }
    if (!res.ok && res.status !== 206) {
      return { ok: false, status: res.status, error: `HTTP ${res.status}` };
    }
    const len = res.headers.get("content-length") || res.headers.get("content-range")?.split("/")?.[1];
    const bytes = len != null && len !== "" && !Number.isNaN(Number(len)) ? Number(len) : null;
    try {
      await res.body?.cancel?.();
    } catch {
    }
    return { ok: true, status: res.status, bytes };
  } catch (e3) {
    return {
      ok: false,
      error: e3?.message || String(e3) || "Fetch failed (COEP/CORP or network). Cross-origin hosts need CORP."
    };
  }
}
async function loadAvailablePublicSnapshot() {
  const man = await fetchPublicSnapshotManifest();
  const url = String(
    man?.url || resolvePublicSnapshotUrl() || DEFAULT_PUBLIC_SNAPSHOT_URL
  ).trim();
  if (!url) return null;
  const probe = await probePublicSnapshotUrl(url);
  if (!probe.ok) return null;
  return {
    ...man && typeof man === "object" ? man : {},
    url,
    bytes: probe.bytes ?? man?.bytes ?? void 0,
    available: true
  };
}
function publicSnapshotLabel(manifest) {
  const parts = ["public snapshot"];
  if (manifest?.height != null) parts.push(`height ${Number(manifest.height).toLocaleString()}`);
  if (manifest?.bytes != null) parts.push(formatBytes(manifest.bytes));
  return parts.join(" \xB7 ");
}
function snapshotMissingTip(url) {
  const u2 = String(url || "");
  const isSameOriginPath = u2.startsWith("/snapshot/");
  if (!isSameOriginPath) {
    return "[snapshot] tip: host unreachable or blocked by COEP. Serve with Cross-Origin-Resource-Policy: cross-origin (or same-origin), or use Choose file\u2026 for a local chain.db3.";
  }
  try {
    const host = typeof window !== "undefined" ? window.location.hostname : "";
    const isLocal = host === "localhost" || host === "127.0.0.1" || host === "[::1]";
    if (isLocal) {
      return "[snapshot] tip: same-origin file missing? Run `npm run snapshot:link` (links ~/Downloads/chain.db3 into public/snapshot/) and restart dev.";
    }
  } catch {
  }
  return "[snapshot] tip: production does not ship multi\u2011GB chain.db3 (gitignored). Host it on a CDN/VPS with CORP, set PUBLIC_SNAPSHOT_URL or manifest.url, or use Choose file\u2026 with a local checkpointed chain.db3.";
}

// src/lib/presets.js
var PRESETS = {
  public: {
    id: "public",
    label: "Official1 (warthognode)",
    httpBase: OFFICIAL1.httpBase,
    streamUrl: OFFICIAL1.wsStream,
    wsBridge: OFFICIAL1.wsBridge,
    note: "Official1 full node + browser bridge (wss://\u2026/ws)"
  },
  defi: {
    id: "defi",
    label: "DeFi testnet",
    httpBase: DEFI_TESTNET.httpBase,
    streamUrl: DEFI_TESTNET.wsStream,
    wsBridge: DEFI_TESTNET.wsBridge,
    note: "DeFi testnet"
  },
  local: {
    id: "local",
    label: "Local node",
    httpBase: "http://127.0.0.1:3000",
    streamUrl: "ws://127.0.0.1:10001/stream",
    wsBridge: "ws://127.0.0.1:10001",
    note: "Local full node: HTTP :3000, bridge WS :10001"
  }
};
function formatHashrate(N2) {
  let n3 = Number(N2) || 0;
  let i3 = 0;
  while (n3 >= 1e3 && i3 <= 10) {
    n3 /= 1e3;
    i3 += 1;
  }
  return `${n3.toFixed(2)} ${["h", "kh", "Mh", "Gh", "Th", "Ph", "Eh", "Zh", "Yh", "Rh", "Qh"][i3]}`;
}
function shortAddr(addr, n3 = 6) {
  if (!addr || typeof addr !== "string") return "\u2014";
  if (addr.length <= n3 * 2 + 1) return addr;
  return `${addr.slice(0, n3)}\u2026${addr.slice(-n3)}`;
}

// src/components/PoolThresholdSigner.jsx
var import_react = __toESM(require_react(), 1);

// src/lib/poolSigner.js
var DEFAULT_POOL_API = "https://cartesi-bridge.duckdns.org/api/pool";
var ENABLED_KEY = "wart.poolSigner.enabled";
var PANEL_KEY = "wart.poolSigner.panelOpen";
var STATS_KEY = "wart.poolSigner.stats";
var ID_KEY2 = "wart.poolSigner.signerId";
var SHARE_KEY = "wart.poolSigner.enrolledShare";
var liveShare = null;
var pendingIdentityFields = null;
async function preshare() {
  return Promise.resolve().then(() => (init_preshareClient(), preshareClient_exports));
}
function is3pShare(share) {
  if (!share || typeof share !== "object") return false;
  if (share.waitlist || share.clientBorn) return true;
  if (String(share.scheme || "").includes("3p-ecdsa")) return true;
  const role = Number(share.role);
  return role === 1 || role === 2;
}
function uuid() {
  if (globalThis.crypto?.randomUUID) return crypto.randomUUID();
  const b2 = new Uint8Array(16);
  crypto.getRandomValues(b2);
  b2[6] = b2[6] & 15 | 64;
  b2[8] = b2[8] & 63 | 128;
  const h2 = [...b2].map((x) => x.toString(16).padStart(2, "0")).join("");
  return `${h2.slice(0, 8)}-${h2.slice(8, 12)}-${h2.slice(12, 16)}-${h2.slice(16, 20)}-${h2.slice(20)}`;
}
function normalizeShare(j) {
  if (!j || typeof j !== "object") return null;
  const signerId = String(j.signerId || "").trim();
  const scheme = String(j.scheme || "");
  if (j.waitlist || Number(j.role) === 0) {
    return {
      scheme: scheme || "wart-3p-ecdsa-lindell-v1",
      role: 0,
      waitlist: true,
      signerId,
      poolAddress: j.poolAddress || null,
      message: j.message || "3P roster full",
      source: j.source || "enrolled"
    };
  }
  if (scheme.includes("3p-ecdsa") || Number(j.role) === 1 || Number(j.role) === 2) {
    const shareHex2 = String(j.userShareHex || j.shareHex || "").replace(/^0x/i, "").toLowerCase();
    const role = Number(j.role || j.shareIndex || 0);
    if (!/^[0-9a-f]{64}$/.test(shareHex2) || role !== 1 && role !== 2 || !signerId) {
      return null;
    }
    return {
      scheme: scheme || "wart-3p-ecdsa-lindell-v1",
      role,
      shareIndex: role,
      shareHex: shareHex2,
      userShareHex: shareHex2,
      signerId,
      poolAddress: j.poolAddress || null,
      publicKey: j.publicKey || null,
      paillierLambda: j.paillierLambda || null,
      paillierMu: j.paillierMu || null,
      paillierN: j.paillierN || null,
      paillierG: j.paillierG || null,
      source: j.source || "enrolled",
      waitlist: false,
      message: j.message || null,
      seatEpoch: j.seatEpoch == null ? null : Number(j.seatEpoch),
      leaseMs: Number(j.leaseMs || 12e4),
      orbit: j.orbit || null,
      seal: j.seal || null
    };
  }
  const shareHex = String(j.shareHex || "").replace(/^0x/i, "").toLowerCase();
  const shareIndex = Number(j.shareIndex);
  if (!/^[0-9a-f]{64}$/.test(shareHex) || !Number.isFinite(shareIndex) || !signerId) {
    return null;
  }
  return {
    scheme: j.scheme || "wart-pool-threshold-shamir-v0",
    poolAddress: j.poolAddress || null,
    threshold: Number(j.threshold || j.need || 3),
    n: Number(j.n || 8),
    shareIndex,
    shareHex,
    signerId,
    source: j.source || "enrolled",
    shamirT: Number(j.shamirT || 3),
    enrolled: j.enrolled,
    active: j.active,
    need: j.need || j.threshold,
    epoch: j.epoch == null ? null : Number(j.epoch),
    leaseMs: Number(j.leaseMs || 12e4)
  };
}
async function storageGet2(key) {
  try {
    if (typeof chrome !== "undefined" && chrome.storage?.local) {
      const got = await chrome.storage.local.get(key);
      return got[key];
    }
  } catch {
  }
  try {
    const raw = localStorage.getItem(key);
    return raw ? JSON.parse(raw) : void 0;
  } catch {
    return void 0;
  }
}
async function storageSet2(key, value) {
  try {
    if (typeof chrome !== "undefined" && chrome.storage?.local) {
      await chrome.storage.local.set({ [key]: value });
      return;
    }
  } catch {
  }
  try {
    localStorage.setItem(key, JSON.stringify(value));
  } catch {
  }
}
async function storageRemove(key) {
  try {
    if (typeof chrome !== "undefined" && chrome.storage?.local) {
      await chrome.storage.local.remove(key);
    }
  } catch {
  }
  try {
    localStorage.removeItem(key);
  } catch {
  }
}
function isEpochDead(err) {
  const msg = err?.message || String(err || "");
  return /EPOCH_ROTATED|share is dead|share material|does not match/i.test(msg);
}
async function getOrCreateSignerId() {
  let id = await storageGet2(ID_KEY2);
  if (typeof id === "string" && id.length >= 16) return id;
  id = `node-${uuid()}`;
  await storageSet2(ID_KEY2, id);
  return id;
}
async function poolGet(api, qs) {
  const url = `${api}${api.includes("?") ? "&" : "?"}${qs}`;
  const res = await fetch(url, { cache: "no-store" });
  const body = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(body.error || `GET ${res.status}`);
  return body;
}
async function poolPost(api, body) {
  const res = await fetch(api, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(body)
  });
  const j = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(j.error || `POST ${res.status}`);
  return j;
}
async function withRetry(fn, { tries = 3, delayMs = 400 } = {}) {
  let last;
  for (let i3 = 0; i3 < tries; i3++) {
    try {
      return await fn();
    } catch (e3) {
      last = e3;
      if (i3 < tries - 1) {
        await new Promise((r3) => setTimeout(r3, delayMs * (i3 + 1)));
      }
    }
  }
  throw last;
}
async function fetchThresholdStatus(api = DEFAULT_POOL_API) {
  return withRetry(() => poolGet(api, "threshold=1"));
}
async function fetchPool3pStatus(api = DEFAULT_POOL_API) {
  return withRetry(
    () => poolPost(api, { action: "pool3p_status" })
  );
}
function compactPointHex(hex) {
  return String(hex || "").replace(/^0x/i, "").toLowerCase();
}
function bytesToHex4(bytes) {
  return Array.from(bytes, (b2) => b2.toString(16).padStart(2, "0")).join("");
}
async function hexMatchesLivePoint(hex, expectedP) {
  const want = compactPointHex(expectedP);
  if (!hex || !want) return false;
  try {
    return compactPointHex(await pointOfShare(hex)) === want;
  } catch {
    return false;
  }
}
async function postD2Offer(share, req, api, p3, startHex) {
  const send = async (hex2) => {
    const fresh = await fetchPool3pStatus(api).catch(() => p3);
    const n3 = fresh?.paillierN || p3?.paillierN;
    const g = fresh?.paillierG || p3?.paillierG;
    const P2 = compactPointHex(fresh?.seal?.P2 || p3?.seal?.P2 || "");
    if (!fresh?.address || !n3 || !g || !P2) {
      return {
        ok: true,
        waiting: true,
        ticketId: req.ticketId,
        error: "waiting for sealed pool Enc(d1) (N,g) and P2"
      };
    }
    if (!hex2) throw new Error("d2 hex missing in this tab");
    const zk = await Promise.resolve().then(() => (init_lindellZk(), lindellZk_exports));
    const { PublicKey } = await Promise.resolve().then(() => (init_index_browser_esm2(), index_browser_esm_exports));
    const { seatPokContext: seatPokContext2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
    const x = BigInt("0x" + String(hex2).replace(/^0x/i, ""));
    const pub = new PublicKey(BigInt(n3), BigInt(g));
    const enc = zk.encryptWithR(pub, x);
    const ctx = `${seatPokContext2("offer-d2", 2, P2)}|${req.ticketId}`;
    const body = {
      action: "pool3p_d2",
      ticketId: req.ticketId,
      signerId: share.signerId,
      encD2: enc.c.toString(),
      encDlogProof: zk.proveEncEqualsDlog({
        x,
        rEnc: enc.r,
        c: enc.c,
        paillierN: n3,
        paillierG: g,
        Qhex: P2,
        context: ctx
      }),
      amountE8: req.amountE8,
      toAddress: req.toAddress
    };
    if (x >= zk.LINDELL_Q_THIRD && x <= 2n * zk.LINDELL_Q_THIRD) {
      body.rangeProof = zk.proveRangeLindell({
        x,
        rEnc: enc.r,
        c: enc.c,
        paillierN: n3,
        paillierG: g,
        Q1: P2,
        context: ctx
      });
    }
    return poolPost(api, body);
  };
  let hex = startHex;
  let d2;
  try {
    d2 = await send(hex);
  } catch (e3) {
    const msg = e3?.message || String(e3);
    if (/x·G ≠ Q|ENC_DLOG: zx/i.test(msg)) {
      d2 = { recover: 2, error: msg, expectedP: p3?.seal?.P2 };
    } else {
      throw e3;
    }
  }
  if (d2?.recover === 2 || /d2·G ≠ live P2|ENC_DLOG/i.test(d2?.error || "")) {
    const recovered = await tryRecoverFromPack(share.signerId, 2, api, {
      expectedP: d2.expectedP || p3?.seal?.P2,
      poolAddress: share.poolAddress || p3?.address,
      publicKey: p3?.seal?.publicKey || p3?.publicKey,
      seal: p3?.seal
    });
    if (recovered?.userShareHex) {
      writeBornCache(recovered);
      liveShare = recovered;
      hex = recovered.userShareHex;
      return send(hex);
    }
    return { ok: false, ticketId: req.ticketId, error: d2.error };
  }
  return d2.skipped ? { ok: true, orbitOnly: true, ticketId: req.ticketId, note: d2.error } : d2;
}
async function pointOfShare(hex) {
  const { secp256k1: secp256k12 } = await Promise.resolve().then(() => (init_secp256k1(), secp256k1_exports));
  const n3 = secp256k12.CURVE.n;
  const h2 = String(hex || "").replace(/^0x/i, "");
  const d2 = BigInt("0x" + h2) % n3;
  if (d2 <= 0n) return "";
  const pt = secp256k12.ProjectivePoint.BASE.multiply(d2);
  if (typeof pt.toHex === "function") return compactPointHex(pt.toHex(true));
  return bytesToHex4(pt.toRawBytes(true));
}
async function findBornCacheForRole(role, expectedP) {
  const want = String(expectedP || "").replace(/^0x/i, "").toLowerCase();
  const match = async (c) => {
    if (!c?.userShareHex) return false;
    if (!want) return true;
    const p2 = await pointOfShare(c.userShareHex);
    return p2.toLowerCase() === want;
  };
  const sid = await storageGet2(ID_KEY2);
  if (typeof sid === "string") {
    const next = await readNextBornCache(sid, role);
    if (await match(next)) return next;
    const c = await readBornCache(sid, role);
    if (await match(c)) return c;
  }
  try {
    for (let i3 = 0; i3 < localStorage.length; i3++) {
      const k = localStorage.key(i3);
      if (!k || !k.endsWith(`.${role}`)) continue;
      if (!k.startsWith("wart.poolSigner.born.") && !k.startsWith("wart.poolSigner.bornNext.")) {
        continue;
      }
      const c = JSON.parse(localStorage.getItem(k) || "null");
      if (await match(c)) return c;
    }
  } catch {
  }
  try {
    if (typeof chrome !== "undefined" && chrome.storage?.local) {
      const all = await chrome.storage.local.get(null);
      for (const [k, v] of Object.entries(all || {})) {
        if (!k.startsWith("wart.poolSigner.born.") && !k.startsWith("wart.poolSigner.bornNext.") || !v?.userShareHex) {
          continue;
        }
        if (Number(v.role) !== Number(role) && !k.endsWith(`.${role}`)) continue;
        if (await match(v)) return v;
      }
    }
  } catch {
  }
  return null;
}
function nextBornCacheKey(signerId, role) {
  return `wart.poolSigner.bornNext.${signerId}.${role}`;
}
function writeNextBornCache(share) {
  if (!share?.signerId || !share.userShareHex) return;
  const key = nextBornCacheKey(share.signerId, share.role);
  try {
    sessionStorage.setItem(key, JSON.stringify(share));
  } catch {
  }
  void storageSet2(key, share);
}
async function readNextBornCache(signerId, role) {
  const key = nextBornCacheKey(signerId, role);
  try {
    const raw = sessionStorage.getItem(key);
    if (raw) {
      const j = JSON.parse(raw);
      if (j?.userShareHex) return j;
    }
  } catch {
  }
  try {
    const stored = await storageGet2(key);
    if (stored?.userShareHex) return stored;
  } catch {
  }
  return null;
}
function normHex(v) {
  return String(v || "").replace(/^0x/i, "").toLowerCase();
}
async function stampNextBornAddress(share, st) {
  const nextAddr = normHex(st?.rotation?.next?.address);
  if (!nextAddr || !share?.signerId) return;
  const role = Number(share.role || 0);
  if (role !== 1 && role !== 2) return;
  const cached = await readNextBornCache(share.signerId, role);
  if (!cached?.userShareHex) return;
  if (normHex(cached.poolAddress) === nextAddr) return;
  writeNextBornCache({
    ...cached,
    poolAddress: nextAddr,
    publicKey: st.rotation?.next?.publicKey || cached.publicKey,
    message: cached.message || `next Q d${role} born \u2014 ${nextAddr}`
  });
}
async function maybePromoteNextQ(share, st) {
  const phase = String(st?.rotation?.phase || "");
  const need = st?.rotation?.next?.needBirth || st?.rotation?.needBirth;
  if (phase === "need_birth" || phase === "next_ready" || need && (need[1] || need["1"] || need[2] || need["2"])) {
    return null;
  }
  const liveAddr = normHex(st?.address);
  if (!liveAddr || !share?.signerId) return null;
  const role = Number(share.role || 0);
  if (role !== 1 && role !== 2) return null;
  const cached = await readNextBornCache(share.signerId, role);
  if (!cached?.userShareHex) return null;
  const cachedAddr = normHex(cached.poolAddress);
  const liveP = normHex(role === 1 ? st?.seal?.P1 : st?.seal?.P2);
  const cachedP = normHex(cached.P);
  const pMatch = !!(cachedP && liveP && cachedP === liveP);
  if (cachedAddr !== liveAddr && !pMatch) return null;
  const promoted = {
    ...cached,
    scheme: cached.scheme || "wart-3p-ecdsa-lindell-v1",
    role,
    shareIndex: role,
    clientBorn: true,
    nextQ: false,
    message: `live on rotated Q ${liveAddr}`
  };
  writeBornCache(promoted);
  liveShare = promoted;
  return promoted;
}
async function maybeBirthNextQ(share, api) {
  const st = await fetchPool3pStatus(api).catch(() => null);
  await stampNextBornAddress(share, st);
  const promoted = await maybePromoteNextQ(share, st);
  if (promoted) return promoted;
  const need = st?.rotation?.next?.needBirth || st?.rotation?.needBirth;
  const bornBy = st?.rotation?.next?.bornBy || {};
  if (!need) return null;
  const sid = share?.signerId;
  const liveRole = Number(share.role || 0);
  const need1 = !!(need[1] || need["1"]) && bornBy[1] !== sid;
  const need2 = !!(need[2] || need["2"]) && bornBy[2] !== sid;
  if (!need1 && !need2) return null;
  const role = need1 && liveRole === 1 ? 1 : need2 && liveRole === 2 ? 2 : need1 ? 1 : need2 ? 2 : null;
  if (!role) return null;
  const { makeClientSeat: makeClientSeat2, schnorrProveDlog: schnorrProveDlog2, seatPokContext: seatPokContext2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
  const seat = makeClientSeat2(role);
  const body = {
    action: "pool3p_birth_next",
    signerId: share.signerId,
    role,
    P: seat.P
  };
  if (role === 1) {
    const zk = await Promise.resolve().then(() => (init_lindellZk(), lindellZk_exports));
    const { generateRandomKeys } = await Promise.resolve().then(() => (init_index_browser_esm2(), index_browser_esm_exports));
    const { PAILLIER_BITS: PAILLIER_BITS2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
    const d1 = zk.randomShareLindellRange();
    seat.userShareHex = zk.scalarToHex(d1);
    seat.P = await pointOfShare(seat.userShareHex);
    body.P = seat.P;
    const { publicKey: pk, privateKey: sk } = await generateRandomKeys(PAILLIER_BITS2);
    const enc = zk.encryptWithR(pk, d1);
    body.encD1 = enc.c.toString();
    body.paillierN = pk.n.toString();
    body.paillierG = pk.g.toString();
    body.rangeProof = zk.proveRangeLindell({
      x: d1,
      rEnc: enc.r,
      c: enc.c,
      paillierN: pk.n.toString(),
      paillierG: pk.g.toString(),
      Q1: seat.P,
      context: seatPokContext2("birth-next", 1, seat.P)
    });
    seat.paillierLambda = sk.lambda.toString();
    seat.paillierMu = sk.mu.toString();
    seat.paillierN = pk.n.toString();
    seat.paillierG = pk.g.toString();
  }
  body.pok = schnorrProveDlog2(seat.userShareHex, seatPokContext2("birth-next", role, seat.P));
  let ack = await poolPost(api, body);
  if (role === 1 && ack?.needPdl) {
    const zk = await Promise.resolve().then(() => (init_lindellZk(), lindellZk_exports));
    const pr = zk.pdlProverCommit({
      cPrime: ack.pdl.cPrime,
      paillierN: seat.paillierN,
      paillierG: seat.paillierG,
      paillierLambda: seat.paillierLambda,
      paillierMu: seat.paillierMu
    });
    const opened = await poolPost(api, {
      action: "pool3p_pdl_commit",
      signerId: share.signerId,
      comQ: pr.comQ,
      kind: "birth-next"
    });
    zk.pdlProverFinish({
      alpha: pr.alpha,
      x1: BigInt("0x" + String(seat.userShareHex).replace(/^0x/i, "")),
      a: opened.a,
      b: opened.b,
      Qhat: pr.Qhat,
      comQ: pr.comQ,
      nonceQ: pr.nonceQ,
      comAB: opened.comAB,
      nonceAB: opened.nonceAB,
      Q1: seat.P
    });
    ack = await poolPost(api, {
      action: "pool3p_pdl_finish",
      signerId: share.signerId,
      Qhat: pr.Qhat,
      nonceQ: pr.nonceQ,
      comQ: pr.comQ,
      kind: "birth-next"
    });
  }
  const born = {
    ...seat,
    scheme: "wart-3p-ecdsa-lindell-v1",
    role,
    shareIndex: role,
    signerId: share.signerId,
    userShareHex: seat.userShareHex,
    clientBorn: true,
    nextQ: true,
    poolAddress: ack.address || null,
    publicKey: ack.publicKey || null,
    seal: ack.seal || null,
    message: ack.ready ? `next Q d${role} born \u2014 ${ack.address || "waiting other seat"}` : `next Q d${role} born`
  };
  writeNextBornCache(born);
  return born;
}
async function enrollSigner(signerId, api = DEFAULT_POOL_API) {
  const r3 = await withRetry(
    () => poolPost(api, {
      action: "threshold_enroll",
      signerId,
      role: typeof chrome !== "undefined" && chrome.runtime?.id ? "extension-node" : "browser-node"
    })
  );
  let recoverErr = null;
  if (r3.recoverVacant && (r3.expectedP || r3.vacantBorn)) {
    const role = Number(r3.recoverVacant || 1);
    const P = r3.expectedP || r3.vacantBorn?.[String(role)]?.expectedP;
    const cached = await findBornCacheForRole(role, P);
    if (cached?.userShareHex) {
      if (cached.signerId && cached.signerId !== signerId) {
        await storageSet2(ID_KEY2, cached.signerId);
      }
      try {
        const { schnorrProveDlog: schnorrProveDlog2, seatPokContext: seatPokContext2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
        await poolPost(api, {
          action: "pool3p_claim_born",
          signerId: cached.signerId || signerId,
          role,
          pok: schnorrProveDlog2(
            cached.userShareHex,
            seatPokContext2("claim", role, cached.P || P)
          )
        });
        liveShare = { ...cached, clientBorn: true, waitlist: false, role };
        return liveShare;
      } catch (e3) {
        recoverErr = e3;
      }
    }
    try {
      const sealedRec = await (await preshare()).recoverSeat({
        post: (action, body) => poolPost(api, { action, ...body }),
        prefix: "pool3p",
        pool: "wart",
        signerId,
        role,
        P
      });
      if (sealedRec?.userShareHex) {
        const pt = compactPointHex(await pointOfShare(sealedRec.userShareHex));
        if (!P || pt === compactPointHex(P)) {
          const claimed = { ...sealedRec, role, signerId, clientBorn: true, waitlist: false };
          writeBornCache(claimed);
          liveShare = claimed;
          return liveShare;
        }
      }
    } catch {
    }
    try {
      const recovered = await tryRecoverFromPack(signerId, role, api, {
        ...r3,
        expectedP: P
      });
      if (recovered?.userShareHex) {
        writeBornCache(recovered);
        liveShare = recovered;
        if (Number(role) === 1) {
          try {
            liveShare = await ensureD1Paillier(recovered, api);
          } catch {
          }
        }
        return liveShare;
      }
    } catch (e3) {
      recoverErr = e3;
    }
  }
  if (r3.needBirth && (r3.role === 1 || r3.role === 2)) {
    const cached = await readBornCache(signerId, r3.role);
    const sameDapp = cached?.userShareHex && r3.Pdapp && compactPointHex(cached.Pdapp || cached.seal?.Pdapp || "") === compactPointHex(r3.Pdapp);
    const sameAddr = !r3.poolAddress || !cached?.poolAddress || normHex(cached.poolAddress) === normHex(r3.poolAddress);
    if (sameDapp && sameAddr) {
      liveShare = cached;
      return cached;
    }
    const born = await birthAndUploadSeat(signerId, r3.role, api, r3);
    writeBornCache(born);
    liveShare = born;
    await storageSet2(ID_KEY2, born.signerId);
    await storageRemove(SHARE_KEY);
    return born;
  }
  if (r3.clientBorn && (r3.role === 1 || r3.role === 2) && !r3.needBirth) {
    const liveP = r3.expectedP || r3.seal?.[Number(r3.role) === 1 ? "P1" : "P2"];
    const cached = await findBornCacheForRole(r3.role, liveP) || await readNextBornCache(signerId, r3.role) || await readBornCache(signerId, r3.role);
    if (cached?.userShareHex) {
      const p2 = liveP ? await pointOfShare(cached.userShareHex) : "";
      if (!liveP || compactPointHex(p2) === compactPointHex(liveP)) {
        writeBornCache({ ...cached, role: Number(r3.role), nextQ: false });
        liveShare = {
          ...r3,
          ...cached,
          userShareHex: cached.userShareHex,
          shareHex: cached.userShareHex,
          clientBorn: true,
          waitlist: false,
          nextQ: false,
          role: Number(r3.role)
        };
        attachPaillier(liveShare, cached);
        return liveShare;
      }
    }
    try {
      const recovered = await tryRecoverFromPack(signerId, r3.role, api, {
        ...r3,
        expectedP: r3.expectedP || r3.seal?.[Number(r3.role) === 1 ? "P1" : "P2"]
      });
      if (recovered?.userShareHex) {
        writeBornCache(recovered);
        liveShare = recovered;
        if (Number(r3.role) === 1) {
          try {
            liveShare = await ensureD1Paillier(recovered, api);
          } catch {
          }
        }
        return liveShare;
      }
    } catch (e3) {
      recoverErr = e3;
    }
  }
  if (r3.clientBorn && (r3.role === 1 || r3.role === 2) && liveShare?.role === r3.role && liveShare.userShareHex) {
    liveShare = {
      ...liveShare,
      ...normalizeShare({
        ...r3,
        userShareHex: liveShare.userShareHex,
        shareHex: liveShare.userShareHex,
        paillierLambda: liveShare.paillierLambda,
        paillierMu: liveShare.paillierMu,
        paillierN: liveShare.paillierN || r3.paillierN,
        paillierG: liveShare.paillierG || r3.paillierG,
        source: "client-born"
      }),
      clientBorn: true
    };
    return liveShare;
  }
  const share = normalizeShare({
    ...r3,
    source: "enrolled",
    message: recoverErr ? `rebuild failed: ${recoverErr.message || recoverErr}` : r3.message
  });
  if (!share) throw new Error("enroll returned no share");
  if (!share.waitlist && r3.seal && (share.role === 1 || share.role === 2) && (share.userShareHex || share.shareHex)) {
    const { verifyShareSeal: verifyShareSeal2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
    verifyShareSeal2({
      shareHex: share.userShareHex || share.shareHex,
      role: share.role,
      seal: r3.seal
    });
    share.seal = r3.seal;
    share.sealOk = true;
  }
  liveShare = share;
  await storageSet2(ID_KEY2, share.signerId);
  await storageRemove(SHARE_KEY);
  return share;
}
async function birthAndUploadSeat(signerId, role, api, hint) {
  const { makeClientSeat: makeClientSeat2, schnorrProveDlog: schnorrProveDlog2, seatPokContext: seatPokContext2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
  const seat = makeClientSeat2(role);
  const body = {
    action: "pool3p_birth",
    signerId,
    role,
    P: seat.P
  };
  if (Number(role) === 1) {
    const zk = await Promise.resolve().then(() => (init_lindellZk(), lindellZk_exports));
    const { generateRandomKeys } = await Promise.resolve().then(() => (init_index_browser_esm2(), index_browser_esm_exports));
    const { PAILLIER_BITS: PAILLIER_BITS2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
    const d1 = zk.randomShareLindellRange();
    seat.userShareHex = zk.scalarToHex(d1);
    seat.P = await pointOfShare(seat.userShareHex);
    body.P = seat.P;
    const { publicKey: pk, privateKey: sk } = await generateRandomKeys(PAILLIER_BITS2);
    const enc = zk.encryptWithR(pk, d1);
    body.encD1 = enc.c.toString();
    body.paillierN = pk.n.toString();
    body.paillierG = pk.g.toString();
    body.rangeProof = zk.proveRangeLindell({
      x: d1,
      rEnc: enc.r,
      c: enc.c,
      paillierN: pk.n.toString(),
      paillierG: pk.g.toString(),
      Q1: seat.P,
      context: seatPokContext2("birth", 1, seat.P)
    });
    seat.paillierLambda = sk.lambda.toString();
    seat.paillierMu = sk.mu.toString();
    seat.paillierN = pk.n.toString();
    seat.paillierG = pk.g.toString();
  }
  body.pok = schnorrProveDlog2(seat.userShareHex, seatPokContext2("birth", role, seat.P));
  let ack = await poolPost(api, body);
  if (Number(role) === 1 && ack?.needPdl) {
    const zk = await Promise.resolve().then(() => (init_lindellZk(), lindellZk_exports));
    const pr = zk.pdlProverCommit({
      cPrime: ack.pdl.cPrime,
      paillierN: seat.paillierN,
      paillierG: seat.paillierG,
      paillierLambda: seat.paillierLambda,
      paillierMu: seat.paillierMu
    });
    const opened = await poolPost(api, {
      action: "pool3p_pdl_commit",
      signerId,
      comQ: pr.comQ,
      kind: "birth"
    });
    zk.pdlProverFinish({
      alpha: pr.alpha,
      x1: BigInt("0x" + String(seat.userShareHex).replace(/^0x/i, "")),
      a: opened.a,
      b: opened.b,
      Qhat: pr.Qhat,
      comQ: pr.comQ,
      nonceQ: pr.nonceQ,
      comAB: opened.comAB,
      nonceAB: opened.nonceAB,
      Q1: seat.P
    });
    ack = await poolPost(api, {
      action: "pool3p_pdl_finish",
      signerId,
      Qhat: pr.Qhat,
      nonceQ: pr.nonceQ,
      comQ: pr.comQ,
      kind: "birth"
    });
  }
  const share = {
    scheme: "wart-3p-ecdsa-lindell-v1",
    role: Number(role),
    shareIndex: Number(role),
    shareHex: seat.userShareHex,
    userShareHex: seat.userShareHex,
    signerId,
    poolAddress: ack.address || hint.poolAddress || null,
    publicKey: ack.publicKey || hint.publicKey || null,
    Pdapp: ack.Pdapp || hint.Pdapp || ack.seal?.Pdapp || hint.seal?.Pdapp || null,
    P: seat.P,
    source: "client-born",
    waitlist: false,
    clientBorn: true,
    seatEpoch: ack.seal?.seatEpoch ?? 0,
    seal: ack.seal || null,
    paillierLambda: seat.paillierLambda || null,
    paillierMu: seat.paillierMu || null,
    paillierN: seat.paillierN || null,
    paillierG: seat.paillierG || null,
    message: ack.ready ? `d${role} born \u2014 pool address ready` : `d${role} born \u2014 waiting for the other seat`
  };
  try {
    await packNextSeat(share, api);
  } catch (e3) {
    share.message = `${share.message} \xB7 pack later: ${e3.message || e3}`;
  }
  writeBornCache(share);
  return share;
}
function bornCacheKey(signerId, role) {
  return `wart.poolSigner.born.${signerId}.${role}`;
}
function readBornCacheSync(signerId, role) {
  try {
    const raw = sessionStorage.getItem(bornCacheKey(signerId, role));
    return raw ? JSON.parse(raw) : null;
  } catch {
    return null;
  }
}
async function readBornCache(signerId, role) {
  const ss = readBornCacheSync(signerId, role);
  if (ss?.userShareHex) return ss;
  try {
    const stored = await storageGet2(bornCacheKey(signerId, role));
    if (stored?.userShareHex) return stored;
  } catch {
  }
  return ss;
}
function writeBornCache(share) {
  if (!share?.signerId || !share.userShareHex) return;
  const key = bornCacheKey(share.signerId, share.role);
  try {
    sessionStorage.setItem(key, JSON.stringify(share));
  } catch {
  }
  void storageSet2(key, share);
}
function attachPaillier(target, src) {
  if (!target || !src) return target;
  if (src.paillierLambda && !target.paillierLambda) {
    target.paillierLambda = src.paillierLambda;
    target.paillierMu = src.paillierMu;
    target.paillierN = src.paillierN || target.paillierN;
    target.paillierG = src.paillierG || target.paillierG;
  }
  return target;
}
async function tryRecoverFromPack(signerId, role, api, hint) {
  const pack = await poolPost(api, {
    action: "pool3p_preshare_collect",
    signerId,
    role
  });
  const need = Number(pack?.t || 2);
  if (!pack?.shares || pack.shares.length < need) {
    throw new Error(
      `orbit pack incomplete (have ${pack?.shares?.length || 0}, need ${need})`
    );
  }
  if (pack?.stale) {
    throw new Error(pack.message || `orbit pack is previous Q (not live P${role})`);
  }
  const nextHex = shamirCombineLocal(pack.shares);
  if (!nextHex) throw new Error("orbit pack combine failed");
  const n3 = BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");
  const want = compactPointHex(hint?.expectedP || pack.P || "");
  const packedP = compactPointHex(pack.Pnext || "");
  if (want && packedP && packedP !== want) {
    throw new Error(`orbit pack is previous Q (not live P${role})`);
  }
  const cands = [nextHex];
  if (pack.delta) {
    const dlt = BigInt("0x" + String(pack.delta).replace(/^0x/i, ""));
    let cur = (BigInt("0x" + nextHex) - dlt) % n3;
    if (cur < 0n) cur += n3;
    cands.unshift(cur.toString(16).padStart(64, "0"));
  }
  let hex = null;
  for (const c of cands) {
    if (!want) {
      hex = c;
      break;
    }
    const p2 = compactPointHex(await pointOfShare(c));
    if (p2 === want) {
      hex = c;
      break;
    }
  }
  if (!hex) {
    throw new Error(`orbit pack reconstructed but did not match live P${role}`);
  }
  const { schnorrProveDlog: schnorrProveDlog2, seatPokContext: seatPokContext2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
  const ack = await poolPost(api, {
    action: "pool3p_claim_born",
    signerId,
    role,
    pok: schnorrProveDlog2(hex, seatPokContext2("claim", role, want || await pointOfShare(hex)))
  });
  return {
    scheme: "wart-3p-ecdsa-lindell-v1",
    role: Number(ack?.role || role),
    shareIndex: Number(ack?.role || role),
    shareHex: hex,
    userShareHex: hex,
    signerId,
    clientBorn: true,
    source: "orbit-reconstruct",
    waitlist: false,
    poolAddress: hint.poolAddress || ack?.poolAddress || pack.poolAddress || null,
    publicKey: hint.publicKey || ack?.publicKey || null,
    seatEpoch: ack?.seatEpoch ?? hint.seatEpoch ?? 0,
    seal: ack?.seal || hint.seal || null,
    message: `d${role} rebuilt from orbit pack (t=${pack.t || 2} + \u03B4)`
  };
}
function shamirCombineLocal(shares) {
  const n3 = BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");
  const pts = shares.map((s3) => ({ x: BigInt(String(s3.x)), y: BigInt("0x" + String(s3.y).replace(/^0x/i, "")) }));
  const invN2 = (a) => {
    let b2 = (a % n3 + n3) % n3;
    let e3 = n3 - 2n;
    let r3 = 1n;
    while (e3 > 0n) {
      if (e3 & 1n) r3 = r3 * b2 % n3;
      b2 = b2 * b2 % n3;
      e3 >>= 1n;
    }
    return r3;
  };
  let acc = 0n;
  for (let i3 = 0; i3 < pts.length; i3++) {
    let num2 = 1n;
    let den = 1n;
    for (let j = 0; j < pts.length; j++) {
      if (i3 === j) continue;
      num2 = num2 * ((n3 - pts[j].x % n3) % n3) % n3;
      den = den * (((pts[i3].x - pts[j].x) % n3 + n3) % n3) % n3;
    }
    acc = (acc + pts[i3].y * num2 * invN2(den)) % n3;
  }
  return acc.toString(16).padStart(64, "0");
}
async function packCachedSeat(share, api, role, hex) {
  if (!hex) return null;
  const st = await fetchPool3pStatus(api).catch(() => null);
  const P = await pointOfShare(hex);
  return (await preshare()).packSeat({
    post: (action, body) => poolPost(api, { action, ...body }),
    prefix: "pool3p",
    pool: "wart",
    signerId: share.signerId,
    role,
    P,
    record: { userShareHex: hex, role: Number(role), P, scheme: share.scheme },
    orbit: st?.orbit?.live || [],
    orbitKeys: st?.orbitKeys || {},
    otherHolderId: Number(role) === 1 ? st?.holder2 : st?.holder1
  }).catch(() => null);
}
async function packNextSeat(share, api) {
  return packCachedSeat(share, api, share.role, share.userShareHex);
}
async function loadActiveShare(api = DEFAULT_POOL_API) {
  await storageRemove(SHARE_KEY);
  const signerId = await getOrCreateSignerId();
  return enrollSigner(signerId, api);
}
function dropLiveShare() {
  liveShare = null;
}
async function applyIncomingShare(raw, prev) {
  if (!raw || raw.waitlist || Number(raw.role) !== 1 && Number(raw.role) !== 2) {
    return null;
  }
  if (raw.needBirth) {
    return null;
  }
  if (raw.clientBorn && !raw.userShareHex && !raw.shareHex && prev?.userShareHex) {
    const livePdapp = compactPointHex(raw.Pdapp || raw.seal?.Pdapp || "");
    const prevPdapp = compactPointHex(prev.Pdapp || prev.seal?.Pdapp || "");
    const liveAddr = normHex(raw.poolAddress || raw.address || raw.seal?.address);
    const prevAddr = normHex(prev.poolAddress || prev.seal?.address);
    const pdappOk = !livePdapp || !prevPdapp || livePdapp === prevPdapp;
    const addrOk = !liveAddr || !prevAddr || liveAddr === prevAddr;
    if (pdappOk && addrOk) {
      raw = {
        ...raw,
        userShareHex: prev.userShareHex,
        shareHex: prev.userShareHex,
        paillierLambda: prev.paillierLambda,
        paillierMu: prev.paillierMu,
        paillierN: prev.paillierN,
        paillierG: prev.paillierG,
        Pdapp: prev.Pdapp || raw.Pdapp,
        P: prev.P
      };
    }
  }
  const share = normalizeShare({ ...raw, source: raw.source || "heartbeat" });
  if (!share || share.waitlist) return null;
  if (raw.seal && (share.role === 1 || share.role === 2)) {
    try {
      const { verifyShareSeal: verifyShareSeal2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
      verifyShareSeal2({
        shareHex: share.userShareHex || share.shareHex,
        role: share.role,
        seal: raw.seal
      });
      share.seal = raw.seal;
      share.sealOk = true;
    } catch {
      share.seal = raw.seal;
      share.sealOk = false;
    }
  }
  liveShare = share;
  if (prev?.signerId) await storageSet2(ID_KEY2, prev.signerId);
  return share;
}
async function heartbeat(share, api = DEFAULT_POOL_API) {
  if (is3pShare(share)) {
    const r4 = await withRetry(
      () => poolPost(api, {
        action: "pool3p_heartbeat",
        signerId: share.signerId,
        seatEpoch: share.seatEpoch,
        // Public key so other seats can seal pieces to this node, plus a signed
        // presence claim. Ignored by a coordinator that has not deployed these.
        ...pendingIdentityFields || {}
      })
    );
    pendingIdentityFields = await (await preshare()).identityFields({
      pool: "wart",
      role: share?.role ?? 0,
      seatEpoch: share?.seatEpoch ?? 0,
      signerId: share.signerId
    }).catch(() => null);
    await (await preshare()).serveResealRequests({
      post: (action, body) => poolPost(api, { action, ...body }),
      prefix: "pool3p",
      signerId: share.signerId,
      requests: r4.resealRequests
    }).catch(() => 0);
    let next = share;
    const promoted = await maybePromoteNextQ(share, {
      ...r4,
      address: r4.address || r4.seal?.address
    }).catch(() => null);
    if (promoted?.userShareHex) next = promoted;
    const assigned = Number(r4.role || r4.share?.role || 0);
    const iAmHolder1 = r4.holder1 === share.signerId || r4.holders?.["1"]?.signerId === share.signerId;
    const iAmHolder2 = r4.holder2 === share.signerId || r4.holders?.["2"]?.signerId === share.signerId;
    const wantRole = iAmHolder1 ? 1 : iAmHolder2 ? 2 : assigned;
    const seal0 = r4.seal || next.seal;
    const livePdapp = compactPointHex(r4.Pdapp || r4.share?.Pdapp || r4.seal?.Pdapp);
    const minePdapp = compactPointHex(next.Pdapp || next.seal?.Pdapp);
    const needBirth = !!(r4.needBirth || r4.share?.needBirth);
    let hexMatchesLive = true;
    if (needBirth) hexMatchesLive = false;
    if (livePdapp && minePdapp && livePdapp !== minePdapp) hexMatchesLive = false;
    if ((wantRole === 1 || wantRole === 2) && next.userShareHex && seal0) {
      try {
        const { verifyShareSeal: verifyShareSeal2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
        verifyShareSeal2({
          shareHex: next.userShareHex,
          role: wantRole,
          seal: seal0
        });
        hexMatchesLive = true;
      } catch {
        hexMatchesLive = false;
      }
    }
    if ((wantRole === 1 || wantRole === 2) && (needBirth || next.waitlist || Number(next.role) !== wantRole || !next.userShareHex || !hexMatchesLive)) {
      next = await enrollSigner(share.signerId, api);
      if (next?.userShareHex) return { ...r4, share: next, shareUpdated: true };
    }
    const liveIds = r4.orbit?.live || [];
    const h1 = r4.holder1 || r4.holders?.["1"]?.signerId;
    const h2 = r4.holder2 || r4.holders?.["2"]?.signerId;
    const ghostOrVacant = !h1 || !h2 || h1 && !liveIds.includes(h1) || h2 && !liveIds.includes(h2) || Number(r4.recoverVacant || 0) > 0;
    if ((next.waitlist || Number(next.role) === 0) && ghostOrVacant) {
      try {
        const recovered = await enrollSigner(share.signerId, api);
        if (recovered && !recovered.waitlist && recovered.userShareHex) {
          next = recovered;
          return { ...r4, share: next, shareUpdated: true };
        }
        if (recovered?.message) {
          next = { ...next, message: recovered.message };
        }
      } catch (e3) {
        next = {
          ...next,
          message: `rebuild failed: ${e3?.message || e3}`
        };
      }
    }
    if (r4.share) {
      const applied = await applyIncomingShare(r4.share, next);
      if (applied) next = applied;
    }
    const seal = r4.seal || next.seal;
    if ((next.role === 1 || next.role === 2) && next.userShareHex && seal) {
      try {
        const { verifyShareSeal: verifyShareSeal2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
        verifyShareSeal2({
          shareHex: next.userShareHex,
          role: next.role,
          seal
        });
      } catch (e3) {
        if (/d[12]·G ≠ P|share was opened or replaced/i.test(e3?.message || "")) {
          const wantP = seal[next.role === 1 ? "P1" : "P2"];
          const fromCache = await findBornCacheForRole(next.role, wantP);
          if (fromCache?.userShareHex) {
            writeBornCache({ ...fromCache, role: next.role, nextQ: false });
            next = { ...fromCache, role: next.role, nextQ: false, seal };
            liveShare = next;
          } else {
            try {
              const recovered = await tryRecoverFromPack(share.signerId, next.role, api, {
                expectedP: wantP,
                poolAddress: next.poolAddress || r4.address,
                publicKey: seal.publicKey || next.publicKey,
                seal
              });
              if (recovered?.userShareHex) {
                writeBornCache(recovered);
                next = recovered;
                liveShare = recovered;
                if (Number(next.role) === 1) {
                  try {
                    next = await ensureD1Paillier(recovered, api);
                  } catch {
                  }
                }
              }
            } catch (e22) {
              next = {
                ...next,
                message: e22?.message || e3.message
              };
            }
          }
        }
      }
    }
    if ((next.role === 1 || next.role === 2) && Number(r4.role || 0) === 0) {
      next = {
        scheme: share.scheme || "wart-3p-ecdsa-lindell-v1",
        role: 0,
        waitlist: true,
        signerId: share.signerId,
        poolAddress: share.poolAddress || null,
        message: "Seat released \u2014 orbit voter until a seat is free",
        source: "demoted"
      };
      liveShare = next;
    }
    if ((next.role === 1 || next.role === 2) && next.userShareHex) {
      try {
        await packNextSeat(next, api);
      } catch {
      }
    }
    if (!h2 && (r4.seal?.P2 || next.seal?.P2)) {
      try {
        const cached2 = await findBornCacheForRole(2, r4.seal?.P2 || next.seal?.P2);
        if (cached2?.userShareHex) {
          await packCachedSeat(next, api, 2, cached2.userShareHex);
        }
      } catch {
      }
    }
    try {
      const born = await maybeBirthNextQ(next, api);
      if (born?.userShareHex && born.nextQ === false) {
        next = born;
        liveShare = born;
      } else if (born?.message) {
        next = { ...next, message: born.message };
      }
    } catch (e3) {
      next = {
        ...next,
        message: `next Q birth: ${e3?.message || e3}`
      };
    }
    return { ...r4, share: next };
  }
  const r3 = await withRetry(
    () => poolPost(api, {
      action: "threshold_heartbeat",
      signerId: share.signerId,
      shareIndex: share.shareIndex,
      epoch: share.epoch
    })
  );
  if (r3.rotated || r3.epoch != null && share.epoch != null && Number(r3.epoch) !== Number(share.epoch)) {
    liveShare = null;
    const err = new Error(
      "EPOCH_ROTATED: share is dead \u2014 re-enroll over HTTPS for a fresh lease"
    );
    err.code = "EPOCH_ROTATED";
    throw err;
  }
  return r3;
}
var k1ByTicket = /* @__PURE__ */ new Map();
var fatalTickets = /* @__PURE__ */ new Map();
var K1_STORE = "wart.poolSigner.k1.";
function persistK1(ticketId, k1) {
  if (!ticketId || !k1) return;
  k1ByTicket.set(ticketId, k1);
  try {
    sessionStorage.setItem(K1_STORE + ticketId, JSON.stringify(k1));
  } catch {
  }
}
function loadK1(ticketId) {
  if (k1ByTicket.has(ticketId)) return k1ByTicket.get(ticketId);
  try {
    const raw = sessionStorage.getItem(K1_STORE + ticketId);
    if (raw) {
      const k = JSON.parse(raw);
      if (k?.k1Hex) {
        k1ByTicket.set(ticketId, k);
        return k;
      }
    }
  } catch {
  }
  return null;
}
function dropK1(ticketId) {
  k1ByTicket.delete(ticketId);
  try {
    sessionStorage.removeItem(K1_STORE + ticketId);
  } catch {
  }
}
async function ensureD1Paillier(share, api) {
  if (share?.paillierN && share?.paillierLambda) return share;
  const cached = await readBornCache(share.signerId, 1);
  if (cached?.paillierLambda && cached.userShareHex === share.userShareHex) {
    attachPaillier(share, cached);
    if (share.paillierLambda) {
      writeBornCache(share);
      return share;
    }
  }
  if (!share?.userShareHex) {
    const err = new Error(
      "d1 hex missing in this tab \u2014 use the original Chrome/Brave tab that birthed d1"
    );
    err.code = "D1_NO_HEX";
    throw err;
  }
  const zk = await Promise.resolve().then(() => (init_lindellZk(), lindellZk_exports));
  const { generateRandomKeys } = await Promise.resolve().then(() => (init_index_browser_esm2(), index_browser_esm_exports));
  const { PAILLIER_BITS: PAILLIER_BITS2, schnorrProveDlog: schnorrProveDlog2, seatPokContext: seatPokContext2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
  const { publicKey: pk, privateKey: sk } = await generateRandomKeys(PAILLIER_BITS2);
  const x1 = BigInt("0x" + String(share.userShareHex).replace(/^0x/i, ""));
  const P = await pointOfShare(share.userShareHex);
  const enc = zk.encryptWithR(pk, x1);
  const ctx = seatPokContext2("rekey", 1, P);
  const body = {
    action: "pool3p_rekey_d1",
    signerId: share.signerId,
    encD1: enc.c.toString(),
    paillierN: pk.n.toString(),
    paillierG: pk.g.toString(),
    pok: schnorrProveDlog2(share.userShareHex, ctx)
  };
  if (x1 >= zk.LINDELL_Q_THIRD && x1 <= 2n * zk.LINDELL_Q_THIRD) {
    body.rangeProof = zk.proveRangeLindell({
      x: x1,
      rEnc: enc.r,
      c: enc.c,
      paillierN: pk.n.toString(),
      paillierG: pk.g.toString(),
      Q1: P,
      context: ctx
    });
  }
  let ack = await poolPost(api, body);
  if (ack?.needPdl) {
    const pr = zk.pdlProverCommit({
      cPrime: ack.pdl.cPrime,
      paillierN: pk.n.toString(),
      paillierG: pk.g.toString(),
      paillierLambda: sk.lambda.toString(),
      paillierMu: sk.mu.toString()
    });
    const opened = await poolPost(api, {
      action: "pool3p_pdl_commit",
      signerId: share.signerId,
      comQ: pr.comQ,
      kind: "rekey"
    });
    zk.pdlProverFinish({
      alpha: pr.alpha,
      x1,
      a: opened.a,
      b: opened.b,
      Qhat: pr.Qhat,
      comQ: pr.comQ,
      nonceQ: pr.nonceQ,
      comAB: opened.comAB,
      nonceAB: opened.nonceAB,
      Q1: P
    });
    ack = await poolPost(api, {
      action: "pool3p_pdl_finish",
      signerId: share.signerId,
      Qhat: pr.Qhat,
      nonceQ: pr.nonceQ,
      comQ: pr.comQ,
      kind: "rekey"
    });
  }
  if (!ack?.ok || ack?.needPdl) {
    const err = new Error(ack?.error || "d1 Paillier rekey failed");
    err.code = "D1_REKEY_FAILED";
    throw err;
  }
  share.paillierLambda = sk.lambda.toString();
  share.paillierMu = sk.mu.toString();
  share.paillierN = pk.n.toString();
  share.paillierG = pk.g.toString();
  writeBornCache(share);
  liveShare = share;
  return share;
}
async function sign3pAsRole1(share, req, api) {
  if (fatalTickets.has(req.ticketId)) {
    const prev = String(fatalTickets.get(req.ticketId) || "");
    if (!/rekey denied|d1·G ≠|wrong tab|missing Paillier/i.test(prev)) {
      return { ok: false, fatal: true, ticketId: req.ticketId, error: prev };
    }
    fatalTickets.delete(req.ticketId);
  }
  const { clientSignRound1: clientSignRound12, clientSignFinish: clientSignFinish2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
  let ready;
  try {
    ready = await ensureD1Paillier(share, api);
  } catch (e3) {
    const msg = e3?.message || String(e3);
    if (/rekey denied|d1·G ≠ live P1|wrong tab/i.test(msg)) {
      try {
        const recovered = await tryRecoverFromPack(share.signerId, 1, api, {
          expectedP: (await fetchPool3pStatus(api).catch(() => null))?.seal?.P1,
          poolAddress: share.poolAddress,
          publicKey: share.publicKey,
          seal: share.seal
        });
        if (recovered?.userShareHex) {
          writeBornCache(recovered);
          ready = await ensureD1Paillier(recovered, api);
        }
      } catch (e22) {
        return { ok: false, waiting: true, ticketId: req.ticketId, error: e22?.message || msg };
      }
    }
    if (!ready?.paillierLambda) {
      return { ok: false, waiting: true, ticketId: req.ticketId, error: msg };
    }
  }
  const live = await fetchPool3pStatus(api).catch(() => null);
  const poolPub = live?.seal?.publicKey || live?.publicKey || ready.publicKey || ready.seal?.publicKey;
  if (poolPub) ready.publicKey = poolPub;
  let k1 = loadK1(req.ticketId);
  let st = await poolPost(api, { action: "pool3p_ticket", ticketId: req.ticketId });
  const ticketHash = String(st.hashHex || "").replace(/^0x/i, "").toLowerCase();
  const k1Hash = String(k1?.hashHex || "").replace(/^0x/i, "").toLowerCase();
  if (k1 && ticketHash && k1Hash && k1Hash !== ticketHash) {
    dropK1(req.ticketId);
    k1 = null;
    if (st.haveR1 || st.hasPartial) {
      await poolPost(api, {
        action: "pool3p_reset_r1",
        ticketId: req.ticketId,
        signerId: ready.signerId
      }).catch(() => null);
      st = await poolPost(api, { action: "pool3p_ticket", ticketId: req.ticketId });
    }
  }
  if (k1 && st.R1Hex && k1.R1Hex && String(k1.R1Hex).toLowerCase() !== String(st.R1Hex).toLowerCase()) {
    dropK1(req.ticketId);
    k1 = null;
  }
  if (!k1 && (st.haveR1 || st.hasPartial)) {
    return {
      ok: true,
      waiting: true,
      ticketId: req.ticketId,
      error: "d1 R1 already posted in another tab \u2014 use the dealer that holds k1"
    };
  }
  if (!k1 || !st.haveR1) {
    const prep = await poolPost(api, {
      action: "pool3p_prepare",
      ticketId: req.ticketId,
      toAddress: req.toAddress || st.toAddress,
      amountE8: req.amountE8 || st.amountE8
    });
    const rnd = clientSignRound12();
    k1 = { ...rnd, hashHex: prep.hashHex };
    const r1 = await poolPost(api, {
      action: "pool3p_r1",
      ticketId: req.ticketId,
      signerId: ready.signerId,
      R1Hex: rnd.R1Hex,
      hashHex: prep.hashHex,
      amountE8: req.amountE8 || st.amountE8,
      toAddress: req.toAddress || st.toAddress
    });
    if (r1?.ok === false) {
      return { ok: false, ticketId: req.ticketId, error: r1.error || "R1 rejected", waiting: true };
    }
    persistK1(req.ticketId, k1);
    st = await poolPost(api, { action: "pool3p_ticket", ticketId: req.ticketId });
  }
  if (!st.hasPartial && st.haveR1 && st.haveD2) {
    st = await poolPost(api, { action: "pool3p_relindell", ticketId: req.ticketId }).catch(() => st);
  }
  if (!st.hasPartial) {
    return { ok: true, waiting: true, status: st.status, ticketId: req.ticketId };
  }
  const tryFinish = () => clientSignFinish2({
    k1Hex: k1.k1Hex,
    rHex: st.rHex,
    ciphertext: st.ciphertext,
    hashHex: st.hashHex || k1.hashHex,
    clientSecret: ready,
    publicKey: poolPub,
    RHex: st.RHex,
    pokR: st.pokR,
    pokC: st.pokC,
    R2Hex: st.R2Hex,
    Q2Hex: st.Q2Hex,
    ckeyAdj: st.ckeyAdj,
    sid: req.ticketId || st.ticketId,
    paillierN: st.paillierN,
    paillierG: st.paillierG
  });
  let fin;
  try {
    fin = tryFinish();
  } catch (e3) {
    const msg = e3?.message || String(e3);
    if (/LINDELL_C_ZK|Paillier N ≠|not the dealer that birthed/i.test(msg)) {
      return { ok: false, waiting: true, ticketId: req.ticketId, error: msg };
    }
    if (/recovery failed|does not match pool pubkey|missing pool pubkey/i.test(msg)) {
      st = await poolPost(api, { action: "pool3p_relindell", ticketId: req.ticketId }).catch(() => st);
      try {
        if (st?.hasPartial) fin = tryFinish();
      } catch (e22) {
        return { ok: false, waiting: true, ticketId: req.ticketId, error: e22?.message || msg };
      }
    } else {
      throw e3;
    }
  }
  if (!fin?.signature65) {
    return { ok: false, waiting: true, ticketId: req.ticketId, error: "d1 finish not ready" };
  }
  try {
    const paid = await poolPost(api, {
      action: "pool3p_submit",
      ticketId: req.ticketId,
      signature65: fin.signature65,
      hashHex: st.hashHex || k1.hashHex
    });
    dropK1(req.ticketId);
    fatalTickets.delete(req.ticketId);
    return paid;
  } catch (e3) {
    const msg = e3?.message || String(e3);
    return { ok: false, waiting: true, ticketId: req.ticketId, error: msg };
  }
}
async function contributeOpen(share, api = DEFAULT_POOL_API) {
  const st = await fetchThresholdStatus(api);
  const p3 = await fetchPool3pStatus(api).catch(() => null);
  const seen = /* @__PURE__ */ new Set();
  const open = [];
  for (const r3 of [...p3?.open || [], ...st.open || []]) {
    const id = String(r3?.ticketId || "");
    if (!id || seen.has(id)) continue;
    if (r3.status !== "open" && r3.status !== "failed" && r3.status !== "wait_r1" && r3.status !== "wait_d2" && r3.status !== "partial" && r3.status !== "ready") {
      continue;
    }
    seen.add(id);
    open.push({ ...r3, status: "open" });
  }
  const rawActionable = open.filter(
    (r3) => !r3.labDemo && !/^lab-demo-/.test(String(r3.ticketId || ""))
  );
  const rotateOpen = rawActionable.filter((r3) => /^wart-pool-rotate-/.test(String(r3.ticketId || "")));
  const keepRotate = p3?.rotation?.sweepTicketId && rotateOpen.some((r3) => r3.ticketId === p3.rotation.sweepTicketId) ? p3.rotation.sweepTicketId : rotateOpen[0]?.ticketId || null;
  const actionable = rawActionable.filter((r3) => {
    if (!/^wart-pool-rotate-/.test(String(r3.ticketId || ""))) return true;
    return keepRotate && r3.ticketId === keepRotate;
  });
  const results = [];
  let lastVerify = null;
  const { verifyOpenRequest: verifyOpenRequest2, probeMachineHealth: probeMachineHealth2 } = await Promise.resolve().then(() => (init_poolVerify(), poolVerify_exports));
  if (actionable.length === 0) {
    try {
      lastVerify = await probeMachineHealth2();
    } catch (e3) {
      lastVerify = { ok: false, checks: {}, reasons: [e3?.message || String(e3)] };
    }
    return {
      status: st,
      pool3p: p3,
      results,
      openCount: 0,
      ignoredOpen: open.length,
      lastVerify
    };
  }
  for (const req of actionable) {
    let verify;
    try {
      if (/^wart-pool-rotate-/.test(String(req.ticketId || ""))) {
        lastVerify = { ok: true, rotationSweep: true, checks: { inspect: true } };
        verify = lastVerify;
      } else {
        verify = await verifyOpenRequest2({
          ticketId: req.ticketId,
          toAddress: req.toAddress,
          amountE8: req.amountE8,
          poolAddress: share.poolAddress || p3?.address || st.signers?.poolAddress,
          labDemo: Boolean(req.labDemo)
        });
        lastVerify = verify;
      }
    } catch (e3) {
      lastVerify = { ok: false, checks: {}, reasons: [e3?.message || String(e3)] };
      verify = lastVerify;
    }
    if (!verify.ok) {
      const reasons = (verify.reasons || []).map((r3) => String(r3));
      const waitingProof = reasons.some(
        (r3) => /waiting for Cartesi notice proof/i.test(r3)
      );
      const authorized = String(verify.inspectTicket?.status || "") === "authorized" || !!(verify.checks?.inspectTicket && verify.checks?.notice);
      if (!authorized && !(waitingProof && is3pShare(share))) {
        results.push({
          ticketId: req.ticketId,
          skipped: true,
          waiting: waitingProof,
          waitingOn: waitingProof ? "notice-proof" : void 0,
          error: reasons.join("; ") || "verification failed",
          verify
        });
        continue;
      }
    }
    try {
      let r3;
      if (is3pShare(share)) {
        await poolPost(api, {
          action: "pool3p_orbit_attest",
          signerId: share.signerId,
          ticketId: req.ticketId
        }).catch(() => null);
      }
      const role = Number(share.role || 0);
      const hex = share.userShareHex || share.shareHex;
      let d2Hex = hex;
      let canOfferD2 = is3pShare(share) && !!hex && (role === 2 || await hexMatchesLivePoint(hex, p3?.seal?.P2));
      if (!canOfferD2 && is3pShare(share) && p3?.seal?.P2) {
        const cached2 = await findBornCacheForRole(2, p3.seal.P2);
        if (cached2?.userShareHex) {
          d2Hex = cached2.userShareHex;
          canOfferD2 = await hexMatchesLivePoint(d2Hex, p3.seal.P2);
        }
      }
      if (canOfferD2) {
        r3 = await postD2Offer(
          { ...share, role: 2, userShareHex: d2Hex },
          req,
          api,
          p3,
          d2Hex
        );
        if (role === 1 && r3 && !r3.fatal) {
          const fin = await sign3pAsRole1(share, req, api);
          if (fin?.fatal) {
            results.push({ ticketId: req.ticketId, ...fin, verify });
            continue;
          }
          if (fin?.signature65 || fin?.txHash || fin?.payout?.txHash) r3 = fin;
        }
      } else if (share.waitlist || role === 0) {
        r3 = { ok: true, orbitOnly: true, ticketId: req.ticketId };
      } else if (is3pShare(share) && role === 1) {
        r3 = await sign3pAsRole1(share, req, api);
        if (r3?.fatal) {
          results.push({ ticketId: req.ticketId, ...r3, verify });
          continue;
        }
      } else {
        r3 = await withRetry(
          () => poolPost(api, {
            action: "threshold_contribute",
            ticketId: req.ticketId,
            shareIndex: share.shareIndex,
            shareHex: share.shareHex,
            signerId: share.signerId,
            verification: verify.attestation
          })
        );
      }
      results.push({ ticketId: req.ticketId, ...r3, verify });
    } catch (e3) {
      const msg = e3?.message || String(e3);
      if (/must come from the current d[12] holder|no d[12] holder/i.test(msg)) {
        results.push({
          ticketId: req.ticketId,
          ok: true,
          orbitOnly: true,
          error: msg
        });
        continue;
      }
      if (/missing prepare|hash mismatch|recovery failed|do not submit v=0|R1 rejected/i.test(msg)) {
        results.push({
          ticketId: req.ticketId,
          ok: false,
          waiting: true,
          error: msg
        });
        continue;
      }
      if (/missing Paillier|d1 hex missing|rekey denied|D1_/.test(msg)) {
        fatalTickets.set(req.ticketId, msg);
        results.push({ ticketId: req.ticketId, ok: false, fatal: true, error: msg });
        continue;
      }
      if (isEpochDead(e3) || e3?.code === "SEAT_ROTATED") {
        liveShare = null;
      }
      throw e3;
    }
  }
  return { status: st, pool3p: p3, results, openCount: actionable.length, lastVerify };
}
async function hasStoredSignerId() {
  const id = await storageGet2(ID_KEY2);
  return typeof id === "string" && id.length >= 16;
}
async function readEnabled() {
  const v = await storageGet2(ENABLED_KEY);
  if (v === void 0 || v === null) {
    return hasStoredSignerId();
  }
  return Boolean(v);
}
async function writeEnabled(on) {
  await storageSet2(ENABLED_KEY, Boolean(on));
}
async function readPanelOpen() {
  const v = await storageGet2(PANEL_KEY);
  if (v === void 0 || v === null) {
    return readEnabled();
  }
  return Boolean(v);
}
async function writePanelOpen(open) {
  await storageSet2(PANEL_KEY, Boolean(open));
}
function stopSigningLocal() {
  dropLiveShare();
}
async function readStats() {
  const s3 = await storageGet2(STATS_KEY);
  return {
    signedCount: Number(s3?.signedCount || 0),
    lastTicket: s3?.lastTicket || null,
    lastPaid: Boolean(s3?.lastPaid),
    lastTx: s3?.lastTx || null,
    lastAt: s3?.lastAt || null,
    lastMsg: s3?.lastMsg || null,
    history: Array.isArray(s3?.history) ? s3.history : []
  };
}
async function writeStats(partial) {
  const prev = await readStats();
  const history = Array.isArray(prev.history) ? prev.history.slice() : [];
  const add = partial.appendPaid;
  if (add?.txHash || add?.ticketId) {
    const tx = add.txHash ? String(add.txHash) : "";
    const dup = history.some(
      (h2) => tx && h2.txHash === tx || !tx && h2.ticketId === add.ticketId && h2.at === add.at
    );
    if (!dup) {
      history.unshift({
        ticketId: add.ticketId || null,
        txHash: tx || null,
        amountE8: add.amountE8 || null,
        at: add.at || Date.now()
      });
    }
  }
  const next = { ...prev, ...partial, history: history.slice(0, 24) };
  delete next.appendPaid;
  await storageSet2(STATS_KEY, next);
  return next;
}

// src/components/PoolThresholdSigner.jsx
init_poolVerify();
var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
var POLL_IDLE_MS = 2e3;
var POLL_HOT_MS = 800;
var SIGNED_HOLD_MS = 12e3;
var TRANSIENT = /missing prepare|hash mismatch|recovery failed|do not submit v=0|R1 rejected|waiting|rebuild failed|not the current d[12]|orbit pack incomplete/i;
function shortId(id) {
  const s3 = String(id || "");
  if (s3.length <= 18) return s3;
  return `${s3.slice(0, 10)}\u2026${s3.slice(-4)}`;
}
function shortTicket(id) {
  const s3 = String(id || "");
  if (s3.length <= 22) return s3;
  return `${s3.slice(0, 14)}\u2026`;
}
function shortTx(id) {
  const s3 = String(id || "");
  if (s3.length <= 18) return s3;
  return `${s3.slice(0, 10)}\u2026${s3.slice(-8)}`;
}
function seatLabel(share) {
  if (!share) return "joining";
  if (share.waitlist) return "orbit voter";
  if (share.role === 1) return "d1 seat";
  if (share.role === 2) return "d2 seat";
  return `slot ${share.shareIndex ?? "?"}`;
}
function e8ToWart(e8) {
  const n3 = Number(e8);
  if (!Number.isFinite(n3)) return null;
  return (n3 / 1e8).toFixed(2).replace(/\.00$/, "");
}
function useRotateDue(rotation) {
  const [due, setDue] = (0, import_react.useState)(
    rotation?.dueInEpochs == null ? null : Number(rotation.dueInEpochs)
  );
  const snap = (0, import_react.useRef)({
    due: rotation?.dueInEpochs,
    at: Date.now()
  });
  (0, import_react.useEffect)(() => {
    snap.current = { due: rotation?.dueInEpochs, at: Date.now() };
    setDue(rotation?.dueInEpochs == null ? null : Number(rotation.dueInEpochs));
  }, [rotation?.dueInEpochs, rotation?.block, rotation?.phase]);
  (0, import_react.useEffect)(() => {
    const id = setInterval(() => {
      const s3 = snap.current;
      if (s3.due == null || !Number.isFinite(Number(s3.due))) return;
      const slipped = Math.floor((Date.now() - s3.at) / 3e3);
      setDue(Math.max(0, Number(s3.due) - slipped));
    }, 1e3);
    return () => clearInterval(id);
  }, []);
  return due;
}
function PoolThresholdSigner() {
  const [share, setShare] = (0, import_react.useState)(null);
  const [enabled, setEnabled] = (0, import_react.useState)(false);
  const [panelOpen, setPanelOpen] = (0, import_react.useState)(false);
  const [ready, setReady] = (0, import_react.useState)(false);
  const [status, setStatus] = (0, import_react.useState)(null);
  const [pool3p, setPool3p] = (0, import_react.useState)(null);
  const [phase, setPhase] = (0, import_react.useState)("idle");
  const [log, setLog] = (0, import_react.useState)("node ready \u2014 signing is opt-in");
  const [error, setError] = (0, import_react.useState)(null);
  const [stats, setStats] = (0, import_react.useState)({ signedCount: 0, history: [] });
  const [verify, setVerify] = (0, import_react.useState)(null);
  const tickLock = (0, import_react.useRef)(false);
  const lastLog = (0, import_react.useRef)("");
  const signedUntil = (0, import_react.useRef)(0);
  const hotRef = (0, import_react.useRef)(false);
  const putLog = (msg) => {
    if (!msg || msg === lastLog.current) return;
    lastLog.current = msg;
    setLog(msg);
  };
  const joinOrbit = (0, import_react.useCallback)(async () => {
    const s3 = await loadActiveShare();
    const p3 = await fetchPool3pStatus().catch(() => null);
    setShare(s3);
    setPool3p(p3);
    putLog(
      s3.waitlist ? "orbit voter \u2014 this tab attests tickets and can rebuild a vacant seat" : s3.role === 1 ? "holding d1 \u2014 this tab finishes 3P Lindell" : s3.role === 2 ? "holding d2 \u2014 this tab offers the additive share" : `joined as slot ${s3.shareIndex}`
    );
    setError(null);
    setPhase("online");
    return s3;
  }, []);
  (0, import_react.useEffect)(() => {
    let cancelled = false;
    (async () => {
      const on = await readEnabled();
      const open2 = await readPanelOpen();
      const st = await readStats();
      if (cancelled) return;
      setEnabled(on);
      setPanelOpen(open2);
      setStats(st);
      if (!on) {
        stopSigningLocal();
        setShare(null);
        setPhase("paused");
        putLog("signing off \u2014 this tab is a node only until you opt in");
        setReady(true);
        return;
      }
      try {
        await joinOrbit();
      } catch (e3) {
        if (!cancelled) {
          setPhase("error");
          setError(e3?.message || String(e3));
          putLog("could not join 3P orbit");
        }
      } finally {
        if (!cancelled) setReady(true);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [joinOrbit]);
  const tick = (0, import_react.useCallback)(async () => {
    if (!share || !enabled || tickLock.current) return;
    tickLock.current = true;
    try {
      const hb = await heartbeat(share);
      if (hb?.share && hb.share !== share) {
        setShare(hb.share);
      }
      if (hb?.orbit || hb?.holders || hb?.holder1 || hb?.seatEpoch != null || hb?.rotation) {
        setPool3p((prev) => ({
          ...prev || {},
          orbit: hb.orbit || prev?.orbit,
          seatEpoch: hb.seatEpoch ?? prev?.seatEpoch,
          holder1: hb.holder1 ?? prev?.holder1,
          holder2: hb.holder2 ?? prev?.holder2,
          holders: hb.holders || prev?.holders,
          rotation: hb.rotation || prev?.rotation,
          packs: hb.packs || prev?.packs
        }));
      }
      const active = hb?.share || share;
      const { status: st, pool3p: p3, results, openCount, lastVerify } = await contributeOpen(active);
      hotRef.current = Number(openCount || 0) > 0;
      if (lastVerify) setVerify(lastVerify);
      if (p3) {
        setPool3p((prev) => ({
          ...prev || {},
          ...p3,
          holders: p3.holders || hb?.holders || prev?.holders
        }));
      }
      setStatus(st);
      const liveN2 = p3?.orbit?.liveCount ?? hb?.orbit?.liveCount ?? 0;
      const last = results[results.length - 1] || {};
      const paidTx = last.payout?.txHash || last.txHash || null;
      const justPaid = Boolean(last.paid || last.alreadyPaid || paidTx);
      if (justPaid && paidTx) {
        signedUntil.current = Date.now() + SIGNED_HOLD_MS;
        setStats(
          await writeStats({
            signedCount: Number(stats.signedCount || 0) + 1,
            lastTicket: last.ticketId || null,
            lastPaid: true,
            lastTx: paidTx,
            lastAt: Date.now(),
            lastMsg: last.message || null,
            appendPaid: {
              ticketId: last.ticketId,
              txHash: paidTx,
              amountE8: last.amountE8 || last.payout?.amountE8,
              at: Date.now()
            }
          })
        );
        setPhase("signed");
        setError(null);
        putLog(`paid ${shortTicket(last.ticketId)} \xB7 ${shortTx(paidTx)}`);
        return;
      }
      if (last.fatal) {
        setPhase("error");
        setError(last.error || "this tab cannot finish the ticket");
        putLog(last.error || "cannot finish from this tab");
        return;
      }
      if (openCount === 0) {
        if (Date.now() < signedUntil.current) {
          setPhase("signed");
        } else {
          setPhase("online");
          setError(null);
          putLog(`${seatLabel(active)} \xB7 ${liveN2} live \xB7 idle`);
        }
        return;
      }
      const waiting = last.waiting || last.orbitOnly;
      if (waiting || TRANSIENT.test(String(last.error || ""))) {
        setPhase("signing");
        if (!TRANSIENT.test(String(last.error || ""))) setError(null);
        else setError(null);
        putLog(
          last.waiting ? `room ${shortTicket(last.ticketId)} \xB7 waiting on the other seat` : last.orbitOnly ? `orbit attested ${shortTicket(last.ticketId)}` : `${seatLabel(active)} \xB7 ${shortTicket(last.ticketId)}`
        );
        return;
      }
      setPhase("signing");
      setError(null);
      putLog(`signing ${shortTicket(last.ticketId)} \xB7 ${seatLabel(active)}`);
    } catch (e3) {
      const msg = e3?.message || String(e3);
      if (TRANSIENT.test(msg)) {
        setPhase("signing");
        setError(null);
        putLog(msg.replace(/^Error:\s*/i, ""));
      } else {
        setPhase("error");
        setError(msg);
        putLog(msg);
      }
      if (/EPOCH_ROTATED|SEAT_ROTATED|share is dead|does not own|share material|missing Paillier/i.test(
        msg
      )) {
        try {
          const s3 = await loadActiveShare();
          setShare(s3);
          putLog(`rejoined as ${seatLabel(s3)}`);
          setPhase("online");
          setError(null);
        } catch {
        }
      }
      try {
        setStatus(await fetchThresholdStatus(DEFAULT_POOL_API));
        setPool3p(await fetchPool3pStatus(DEFAULT_POOL_API));
      } catch {
      }
    } finally {
      tickLock.current = false;
    }
  }, [share, enabled, stats.signedCount]);
  (0, import_react.useEffect)(() => {
    if (!share || !enabled) return void 0;
    let stopped = false;
    let tid;
    const loop = async () => {
      try {
        await tick();
      } catch {
      }
      if (stopped) return;
      const hidden = typeof document !== "undefined" && document.visibilityState === "hidden";
      const wait2 = hidden ? POLL_IDLE_MS : hotRef.current ? POLL_HOT_MS : POLL_IDLE_MS;
      tid = setTimeout(loop, wait2);
    };
    const wake = () => {
      if (stopped || tickLock.current) return;
      clearTimeout(tid);
      loop();
    };
    document.addEventListener("visibilitychange", wake);
    window.addEventListener("focus", wake);
    loop();
    return () => {
      stopped = true;
      clearTimeout(tid);
      document.removeEventListener("visibilitychange", wake);
      window.removeEventListener("focus", wake);
    };
  }, [share, enabled, tick]);
  const toggle = async () => {
    const next = !enabled;
    setEnabled(next);
    await writeEnabled(next);
    if (!next) {
      stopSigningLocal();
      setShare(null);
      setPhase("paused");
      setError(null);
      putLog("signing off \u2014 left the 3P orbit (node still runs)");
      return;
    }
    setPhase("online");
    putLog("joining 3P orbit\u2026");
    try {
      await joinOrbit();
    } catch (e3) {
      setPhase("error");
      setError(e3?.message || String(e3));
      putLog("could not join 3P orbit");
    }
  };
  const togglePanel = async () => {
    const next = !panelOpen;
    setPanelOpen(next);
    await writePanelOpen(next);
  };
  const open = (0, import_react.useMemo)(() => {
    const seen = /* @__PURE__ */ new Set();
    const out = [];
    for (const r3 of [...pool3p?.open || [], ...status?.open || []]) {
      const id = String(r3?.ticketId || "");
      if (!id || seen.has(id)) continue;
      if (r3.labDemo || /^lab-demo-/.test(id)) continue;
      seen.add(id);
      out.push(r3);
    }
    return out;
  }, [pool3p?.open, status?.open]);
  const liveOrbit = pool3p?.orbit?.live || [];
  const liveN = pool3p?.orbit?.liveCount ?? liveOrbit.length;
  const paidList = (0, import_react.useMemo)(() => {
    const fromServer = (pool3p?.paid || []).map((p2) => ({
      ticketId: p2.ticketId,
      txHash: p2.txHash,
      amountE8: p2.amountE8,
      at: p2.at
    }));
    const fromLocal = stats.history || [];
    const seen = /* @__PURE__ */ new Set();
    const out = [];
    for (const row of [...fromServer, ...fromLocal]) {
      const key = row.ticketId || row.txHash;
      if (!key || seen.has(key)) continue;
      seen.add(key);
      out.push(row);
    }
    return out.slice(0, 16);
  }, [pool3p?.paid, stats.history]);
  const room = open[0] || null;
  const steps = {
    d1: !!(room?.steps?.d1 ?? room?.haveR1),
    d2: !!(room?.steps?.d2 ?? room?.haveD2),
    lindell: !!(room?.steps?.lindell ?? room?.hasPartial),
    paid: !!(room?.steps?.paid || phase === "signed")
  };
  const wait = room?.waitingOn || [];
  const lastErr = room?.lastError ? String(room.lastError).slice(0, 48) : "";
  const errStep = !lastErr ? null : wait.includes("d2") || wait.includes("d2-holder") || /d2/i.test(lastErr) ? "d2" : wait.includes("d1") || /r1|\bd1\b/i.test(lastErr) ? "d1" : wait.includes("lindell") || /lindell|partial|k1/i.test(lastErr) ? "lindell" : wait.includes("notice-proof") ? !steps.d1 ? "d1" : !steps.d2 ? "d2" : "lindell" : steps.lindell ? "paid" : null;
  const stepHint = (key, idle, done) => {
    if (done) return idle;
    if (!room) return "idle";
    if (errStep === key && lastErr) return `waiting \xB7 ${lastErr}`;
    return "waiting";
  };
  const isOrbit = !share || share.waitlist || Number(share.role) === 0;
  const rotateDue = useRotateDue(pool3p?.rotation);
  const d1Pack = pool3p?.packs?.["1"] || pool3p?.packs?.[1];
  const d2Pack = pool3p?.packs?.["2"] || pool3p?.packs?.[2];
  const phaseLabel = !enabled ? "Off" : !share && phase === "error" ? "Offline" : !share ? "Joining" : phase === "signed" ? "Paid" : phase === "error" ? "Retrying" : room ? isOrbit ? "Attesting" : "In the room" : "Listening";
  const controls = /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "pool-signer__controls", children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      "button",
      {
        type: "button",
        className: `btn btn--ghost${enabled ? " is-on" : ""}`,
        onClick: toggle,
        disabled: !ready,
        title: enabled ? "Leave the 3P orbit. The WASM node keeps running." : "Join the 3P orbit as a signer (attest tickets; may hold d1/d2).",
        children: enabled ? "Signing ON" : "Signing OFF"
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      "button",
      {
        type: "button",
        className: "btn btn--ghost",
        onClick: togglePanel,
        "aria-expanded": panelOpen,
        title: panelOpen ? "Hide the signer dashboard" : "Show the signer dashboard",
        children: panelOpen ? "Hide panel" : "Show panel"
      }
    )
  ] });
  if (!panelOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("section", { className: "panel pool-signer pool-signer--collapsed", "aria-label": "3P pool signer", children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "panel__head", children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h2", { children: "3P pool signer" }),
        controls
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
        "div",
        {
          className: `pool-signer__status is-${!enabled ? "idle" : phase === "signing" ? "signing" : phase === "error" ? "err" : phase === "signed" ? "ok" : "idle"}`,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "pool-signer__dot", "aria-hidden": true }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: phaseLabel }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "pool-signer__count", children: enabled ? `${seatLabel(share)} \xB7 ${liveN} live` : "node only \u2014 not in the orbit" })
          ]
        }
      ),
      error ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "dash__error", children: error }) : null
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("section", { className: "panel pool-signer", "aria-label": "3P pool signer", children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "panel__head", children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h2", { children: "3P pool signer" }),
      controls
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
      "div",
      {
        className: `pool-signer__status is-${phase === "signing" ? "signing" : phase === "error" ? "err" : phase === "signed" ? "ok" : "idle"}`,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "pool-signer__dot", "aria-hidden": true }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: phaseLabel }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "pool-signer__count", children: enabled ? `${seatLabel(share)} \xB7 ${liveN} live` : "node only \u2014 not in the orbit" })
        ]
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "pool-signer__lead", children: !enabled ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
      "This tab can run the WASM node without signing. Turn",
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: "Signing ON" }),
      " to join the 3P orbit (attest tickets; you may be offered d1 or d2)."
    ] }) : share ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
      "You are ",
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: shortId(share.signerId) }),
      share.role === 1 ? " \xB7 d1 finishes Lindell (Paillier stays in this tab)" : share.role === 2 ? " \xB7 d2 offers its share into the room" : " \xB7 orbit voter: no d1/d2 share (expected) \u2014 you only attest",
      pool3p?.clientBorn ? ". VPS has d_dapp only." : ""
    ] }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: "Joining the 3P orbit\u2026" }) }),
    enabled ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "pool-signer__seats", "aria-label": "d1 and d2 holders", children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
        "div",
        {
          className: `pool-signer__seat${share?.role === 1 ? " is-you" : ""}${pool3p?.holder1 ? " is-held" : ""}`,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "pool-signer__seat-k", children: "d1" }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: share?.role === 1 ? "YOU" : pool3p?.holder1 ? shortId(pool3p.holder1) : "vacant" }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: share?.role === 1 ? "Lindell finish" : pool3p?.holder1 ? pool3p.d1Live ? "live" : "assigned" : "will rebuild from orbit pack" })
          ]
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
        "div",
        {
          className: `pool-signer__seat${share?.role === 2 ? " is-you" : ""}${pool3p?.holder2 ? " is-held" : ""}`,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "pool-signer__seat-k", children: "d2" }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: share?.role === 2 ? "YOU" : pool3p?.holder2 ? shortId(pool3p.holder2) : "vacant" }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: share?.role === 2 ? "additive share" : pool3p?.holder2 ? pool3p.d2Live ? "live" : "assigned" : "will rebuild from orbit pack" })
          ]
        }
      )
    ] }) : null,
    enabled ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("ol", { className: "pool-signer__steps", "aria-label": "ceremony progress", children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { className: steps.d1 ? "is-done" : "is-wait", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "1" }),
          " d1 R1 ",
          stepHint("d1", "in", steps.d1)
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { className: steps.d2 ? "is-done" : "is-wait", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "2" }),
          " d2 share ",
          stepHint("d2", "in", steps.d2)
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { className: steps.lindell ? "is-done" : "is-wait", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "3" }),
          " Lindell ",
          stepHint("lindell", "combined", steps.lindell)
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { className: steps.paid ? "is-done" : "is-wait", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "4" }),
          " ",
          steps.paid ? "broadcast" : errStep === "paid" && lastErr ? `held \xB7 ${lastErr}` : room ? isOrbit ? "orbit attested" : "broadcast" : "idle"
        ] })
      ] }),
      d1Pack && !d1Pack.ready ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { className: "pool-signer__meta is-warn", children: [
        "d1 pack not on this orbit (",
        d1Pack.liveCovered || 0,
        "/",
        d1Pack.liveNeed || 0,
        " live) \u2014 the d1 tab must republish"
      ] }) : null,
      d2Pack && !d2Pack.ready ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { className: "pool-signer__meta is-warn", children: [
        "d2 pack not on this orbit (",
        d2Pack.liveCovered || 0,
        "/",
        d2Pack.liveNeed || 0,
        " live)"
      ] }) : null,
      verify && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: `pool-signer__meta${verify.ok === false ? " is-warn" : ""}`, children: formatVerifyLine(verify) }),
      open.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { className: "pool-signer__meta", children: [
        "Open room: ",
        open.map((r3) => shortTicket(r3.ticketId)).join(" \xB7 "),
        open.some((r3) => Number(r3.amountE8) > 0 && !r3.steps?.paid) ? " \u2014 stranded unlock: leave Signing ON to pay from the live Q" : ""
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)("ul", { className: "pool-signer__slots", "aria-label": "live orbit", children: liveOrbit.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { children: "No live orbit yet \u2014 this tab appears after the first heartbeat." }) : liveOrbit.map((id) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { className: id === share?.signerId ? "is-me" : void 0, children: [
        shortId(id),
        id === pool3p?.holder1 ? " \xB7 d1" : "",
        id === pool3p?.holder2 ? " \xB7 d2" : "",
        id === "pool-3p-orbit-vps" ? " \xB7 VPS" : "",
        id !== pool3p?.holder1 && id !== pool3p?.holder2 && id !== "pool-3p-orbit-vps" ? " \xB7 orbit" : "",
        id === share?.signerId ? " \xB7 you" : ""
      ] }, id)) })
    ] }) : null,
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "pool-signer__meta", children: log }),
    pool3p?.address ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { className: "pool-signer__meta", style: { wordBreak: "break-all" }, children: [
      "Pool ",
      pool3p.address,
      pool3p.clientBorn ? " \xB7 client-born 3P" : ""
    ] }) : null,
    pool3p?.rotation || rotateDue != null ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { className: "pool-signer__rotate", children: [
      "Q rotate ",
      pool3p?.rotation?.phase || "idle",
      rotateDue != null ? ` \xB7 ${rotateDue} epochs left` : "",
      pool3p?.rotation?.intervalEpochs ? ` / ${pool3p.rotation.intervalEpochs}` : "",
      (() => {
        const need = pool3p?.rotation?.next?.needBirth || {};
        const bornBy = pool3p?.rotation?.next?.bornBy || {};
        const sid = share?.signerId;
        const role = Number(share?.role || 0);
        const can = need[1] && bornBy[1] !== sid && (role === 1 || role === 0) || need[2] && bornBy[2] !== sid && (role === 2 || role === 0);
        return can ? " \xB7 this tab should birth the next Q" : "";
      })(),
      pool3p?.rotation?.next?.address ? ` \xB7 next ${String(pool3p.rotation.next.address).slice(0, 12)}\u2026` : ""
    ] }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "pool-signer__rotate", children: "Q rotate \xB7 waiting for coordinator clock" }),
    error ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "dash__error", children: error }) : null,
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("details", { className: "pool-signer__history", open: paidList.length > 0, children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("summary", { children: [
        "Signed",
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: paidList.length })
      ] }),
      paidList.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "pool-signer__meta", children: "No paid 3P withdraws in this tab yet." }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("ul", { className: "pool-signer__slots pool-signer__slots--history", children: paidList.map((row) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { children: [
        row.amountE8 ? `${e8ToWart(row.amountE8) || "?"} WART \xB7 ` : "",
        shortTicket(row.ticketId),
        row.txHash ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
          " \xB7 ",
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { className: "pool-signer__tx", title: row.txHash, children: shortTx(row.txHash) })
        ] }) : " \xB7 submitted"
      ] }, row.txHash || row.ticketId)) })
    ] })
  ] });
}

// src/components/EthPoolThresholdSigner.jsx
var import_react2 = __toESM(require_react(), 1);

// src/lib/ethPoolSigner.js
var DEFAULT_POOL_API2 = "https://cartesi-bridge.duckdns.org/api/pool";
var ENABLED_KEY2 = "eth.poolSigner.enabled";
var PANEL_KEY2 = "eth.poolSigner.panelOpen";
var ID_KEY3 = "eth.poolSigner.signerId";
var SHARE_KEY2 = "eth.poolSigner.enrolledShare";
var liveShare2 = null;
async function preshare2() {
  return Promise.resolve().then(() => (init_preshareClient(), preshareClient_exports));
}
function uuid2() {
  if (globalThis.crypto?.randomUUID) return crypto.randomUUID();
  const b2 = new Uint8Array(16);
  crypto.getRandomValues(b2);
  return [...b2].map((x) => x.toString(16).padStart(2, "0")).join("");
}
async function storageGet3(k) {
  try {
    if (globalThis.chrome?.storage?.local) {
      const o3 = await chrome.storage.local.get(k);
      return o3?.[k];
    }
  } catch {
  }
  try {
    return localStorage.getItem(k);
  } catch {
    return null;
  }
}
async function storageSet3(k, v) {
  try {
    if (globalThis.chrome?.storage?.local) {
      await chrome.storage.local.set({ [k]: v });
      return;
    }
  } catch {
  }
  try {
    localStorage.setItem(k, typeof v === "string" ? v : JSON.stringify(v));
  } catch {
  }
}
async function storageRemove2(k) {
  try {
    if (globalThis.chrome?.storage?.local) await chrome.storage.local.remove(k);
  } catch {
  }
  try {
    localStorage.removeItem(k);
  } catch {
  }
}
async function storageKeys() {
  try {
    if (globalThis.chrome?.storage?.local) {
      return Object.keys(await chrome.storage.local.get(null) || {});
    }
  } catch {
  }
  try {
    return Object.keys(localStorage);
  } catch {
    return [];
  }
}
async function poolPost2(api, body) {
  const ac = new AbortController();
  const timer = setTimeout(() => ac.abort(), 2e4);
  try {
    const res = await fetch(api || DEFAULT_POOL_API2, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(body),
      signal: ac.signal
    });
    const j = await res.json().catch(() => ({}));
    if (!res.ok || j.error) throw new Error(j.error || j.message || `eth3p ${res.status}`);
    return j;
  } finally {
    clearTimeout(timer);
  }
}
async function readEnabled2() {
  const v = await storageGet3(ENABLED_KEY2);
  return v === true || v === "1" || v === "true";
}
async function writeEnabled2(on) {
  await storageSet3(ENABLED_KEY2, on ? "1" : "0");
}
async function readPanelOpen2() {
  const v = await storageGet3(PANEL_KEY2);
  return v !== "0" && v !== false;
}
async function writePanelOpen2(open) {
  await storageSet3(PANEL_KEY2, open ? "1" : "0");
}
async function getOrCreateSignerId2() {
  let id = await storageGet3(ID_KEY3);
  if (id && String(id).startsWith("eth-node-")) return String(id);
  id = `eth-node-${uuid2()}`;
  await storageSet3(ID_KEY3, id);
  return id;
}
function bornKey(signerId, role) {
  return `eth.poolSigner.born.${signerId}.${role}`;
}
function nextBornKey(signerId, role) {
  return `eth.poolSigner.born.next.${signerId}.${role}`;
}
async function writeBornCache2(share) {
  if (!share?.userShareHex || !(share.role === 1 || share.role === 2)) return;
  await storageSet3(bornKey(share.signerId, share.role), share);
}
async function readBornCache2(signerId, role) {
  const raw = await storageGet3(bornKey(signerId, role));
  if (raw && typeof raw === "object") return raw;
  if (typeof raw === "string") {
    try {
      return JSON.parse(raw);
    } catch {
      return null;
    }
  }
  return null;
}
async function readNextBornCache2(signerId, role) {
  const raw = await storageGet3(nextBornKey(signerId, role));
  if (raw && typeof raw === "object") return raw;
  if (typeof raw === "string") {
    try {
      return JSON.parse(raw);
    } catch {
      return null;
    }
  }
  return null;
}
function compactPt(p2) {
  return String(p2 || "").replace(/^0x/i, "").toLowerCase();
}
async function loadHexForLiveSeat(signerId, role, st, api) {
  const live = await readBornCache2(signerId, role);
  if (await shareSignsLiveSeat(live, st, role)) return live;
  const nxt = await readNextBornCache2(signerId, role);
  if (await shareSignsLiveSeat(nxt, st, role)) {
    const promoted = {
      ...nxt,
      nextQ: false,
      role,
      poolAddress: st?.address || nxt.poolAddress,
      seal: st?.seal || nxt.seal
    };
    await writeBornCache2(promoted);
    return promoted;
  }
  const mine = /* @__PURE__ */ new Set([bornKey(signerId, role), nextBornKey(signerId, role)]);
  for (const key of await storageKeys()) {
    if (!key.startsWith("eth.poolSigner.born") || mine.has(key)) continue;
    let row = await storageGet3(key);
    if (typeof row === "string") {
      try {
        row = JSON.parse(row);
      } catch {
        continue;
      }
    }
    if (!row || typeof row !== "object") continue;
    if (!await shareSignsLiveSeat(row, st, role)) continue;
    const recovered = {
      ...row,
      nextQ: false,
      role,
      signerId,
      P: compactPt(role === 1 ? st?.seal?.P1 : st?.seal?.P2),
      poolAddress: st?.address || row.poolAddress,
      publicKey: st?.seal?.publicKey || st?.publicKey || row.publicKey,
      Pdapp: st?.Pdapp || st?.seal?.Pdapp || row.Pdapp,
      seal: st?.seal || row.seal
    };
    await writeBornCache2(recovered);
    console.warn(`[eth3p] recovered seat e${role} share from ${key}`);
    return recovered;
  }
  if (api) {
    try {
      const liveP = compactPt(role === 1 ? st?.seal?.P1 : st?.seal?.P2);
      const rec = await (await preshare2()).recoverSeat({
        post: (action, body) => poolPost2(api, { action, ...body }),
        prefix: "eth3p",
        pool: "eth",
        signerId,
        role,
        P: liveP
      });
      if (rec?.userShareHex && await pointOfShare2(rec.userShareHex) === liveP) {
        const recovered = {
          ...rec,
          nextQ: false,
          role,
          signerId,
          P: liveP,
          poolAddress: st?.address || rec.poolAddress,
          seal: st?.seal || rec.seal
        };
        await writeBornCache2(recovered);
        console.warn(`[eth3p] recovered seat e${role} from orbit preshare pack`);
        return recovered;
      }
    } catch {
    }
  }
  return null;
}
async function pointOfShare2(hex) {
  const { secp256k1: secp256k12 } = await Promise.resolve().then(() => (init_secp256k1(), secp256k1_exports));
  const h2 = String(hex).replace(/^0x/i, "");
  const d2 = BigInt("0x" + h2);
  const bytes = secp256k12.ProjectivePoint.BASE.multiply(d2).toRawBytes(true);
  return [...bytes].map((b2) => b2.toString(16).padStart(2, "0")).join("");
}
var pendingSeatFault = null;
function reportSeatFault(role, reason) {
  pendingSeatFault = {
    role: Number(role) || 0,
    reason: String(reason || "unknown").slice(0, 300),
    at: Date.now()
  };
}
function clearSeatFault() {
  pendingSeatFault = null;
}
async function shareSignsLiveSeat(row, st, role) {
  if (!row?.userShareHex) return false;
  const liveP = compactPt(role === 1 ? st?.seal?.P1 : st?.seal?.P2);
  if (!liveP) return false;
  try {
    return await pointOfShare2(row.userShareHex) === liveP;
  } catch {
    return false;
  }
}
async function birthAndUploadSeat2(signerId, role, api, hint) {
  const { makeClientSeat: makeClientSeat2, schnorrProveDlog: schnorrProveDlog2, seatPokContext: seatPokContext2, PAILLIER_BITS: PAILLIER_BITS2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
  const seat = makeClientSeat2(role);
  const body = {
    action: "eth3p_birth",
    signerId,
    role,
    P: seat.P
  };
  if (Number(role) === 1) {
    const zk = await Promise.resolve().then(() => (init_lindellZk(), lindellZk_exports));
    const { generateRandomKeys } = await Promise.resolve().then(() => (init_index_browser_esm2(), index_browser_esm_exports));
    const d1 = zk.randomShareLindellRange();
    seat.userShareHex = zk.scalarToHex(d1);
    seat.P = await pointOfShare2(seat.userShareHex);
    body.P = seat.P;
    const { publicKey: pk, privateKey: sk } = await generateRandomKeys(PAILLIER_BITS2);
    const enc = zk.encryptWithR(pk, d1);
    body.encD1 = enc.c.toString();
    body.paillierN = pk.n.toString();
    body.paillierG = pk.g.toString();
    body.rangeProof = zk.proveRangeLindell({
      x: d1,
      rEnc: enc.r,
      c: enc.c,
      paillierN: pk.n.toString(),
      paillierG: pk.g.toString(),
      Q1: seat.P,
      context: seatPokContext2("birth", 1, seat.P)
    });
    seat.paillierLambda = sk.lambda.toString();
    seat.paillierMu = sk.mu.toString();
    seat.paillierN = pk.n.toString();
    seat.paillierG = pk.g.toString();
  }
  body.pok = schnorrProveDlog2(seat.userShareHex, seatPokContext2("birth", role, seat.P));
  let ack = await poolPost2(api, body);
  if (Number(role) === 1 && ack?.needPdl) {
    const zk = await Promise.resolve().then(() => (init_lindellZk(), lindellZk_exports));
    const pr = zk.pdlProverCommit({
      cPrime: ack.pdl.cPrime,
      paillierN: seat.paillierN,
      paillierG: seat.paillierG,
      paillierLambda: seat.paillierLambda,
      paillierMu: seat.paillierMu
    });
    const opened = await poolPost2(api, {
      action: "eth3p_pdl_commit",
      signerId,
      comQ: pr.comQ
    });
    zk.pdlProverFinish({
      alpha: pr.alpha,
      x1: BigInt("0x" + String(seat.userShareHex).replace(/^0x/i, "")),
      a: opened.a,
      b: opened.b,
      Qhat: pr.Qhat,
      comQ: pr.comQ,
      nonceQ: pr.nonceQ,
      comAB: opened.comAB,
      nonceAB: opened.nonceAB,
      Q1: seat.P
    });
    ack = await poolPost2(api, {
      action: "eth3p_pdl_finish",
      signerId,
      Qhat: pr.Qhat,
      nonceQ: pr.nonceQ,
      comQ: pr.comQ
    });
  }
  const share = {
    scheme: "eth-3p-ecdsa-lindell-v1",
    role: Number(role),
    shareIndex: Number(role),
    shareHex: seat.userShareHex,
    userShareHex: seat.userShareHex,
    signerId,
    poolAddress: ack.address || hint.poolAddress || null,
    publicKey: ack.publicKey || hint.publicKey || null,
    Pdapp: ack.Pdapp || hint.Pdapp || null,
    P: seat.P,
    clientBorn: true,
    waitlist: false,
    seatEpoch: ack.seal?.seatEpoch ?? 0,
    seal: ack.seal || null,
    paillierLambda: seat.paillierLambda || null,
    paillierMu: seat.paillierMu || null,
    paillierN: seat.paillierN || null,
    paillierG: seat.paillierG || null,
    message: ack.ready ? `e${role} born \u2014 ETH pool address ready` : `e${role} born`
  };
  writeBornCache2(share);
  liveShare2 = share;
  return share;
}
async function enrollEthSigner(api = DEFAULT_POOL_API2) {
  const signerId = await getOrCreateSignerId2();
  const r3 = await poolPost2(api, { action: "eth3p_enroll", signerId });
  if (r3.needBirth && (r3.role === 1 || r3.role === 2)) {
    const cached = await readBornCache2(signerId, r3.role);
    const same = cached?.userShareHex && r3.Pdapp && String(cached.Pdapp || cached.seal?.Pdapp || "").toLowerCase() === String(r3.Pdapp).toLowerCase();
    if (same) {
      liveShare2 = cached;
      return cached;
    }
    return birthAndUploadSeat2(signerId, r3.role, api, r3);
  }
  if (r3.clientBorn && (r3.role === 1 || r3.role === 2) && !r3.needBirth) {
    const cached = await readBornCache2(signerId, r3.role);
    if (cached?.userShareHex) {
      liveShare2 = { ...r3, ...cached, userShareHex: cached.userShareHex };
      return liveShare2;
    }
  }
  liveShare2 = r3;
  await storageSet3(ID_KEY3, signerId);
  await storageRemove2(SHARE_KEY2);
  return r3;
}
var k1ByTicket2 = /* @__PURE__ */ new Map();
async function contributeEthOpen(share, open, api) {
  if (!Array.isArray(open) || !open.length) return;
  const role = Number(share?.role || 0);
  if (!share?.userShareHex) {
    if (role === 1 || role === 2) {
      reportSeatFault(role, "seat holder has no share that signs for the live Q");
    }
    return;
  }
  const needStatus = open.some((t2) => !t2.paillierN || !t2.paillierG);
  const st = needStatus ? await fetchEth3pStatus(api).catch(() => null) : null;
  for (const req of open) {
    const id = String(req.ticketId || "");
    if (!id || req.status === "paid") continue;
    try {
      if (role === 2) {
        const zk = await Promise.resolve().then(() => (init_lindellZk(), lindellZk_exports));
        const { PublicKey } = await Promise.resolve().then(() => (init_index_browser_esm2(), index_browser_esm_exports));
        const { seatPokContext: seatPokContext2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
        const n3 = st?.paillierN || req.paillierN;
        const g = st?.paillierG || req.paillierG;
        const P2 = String(st?.seal?.P2 || req.P2Hex || "").replace(/^0x/i, "").toLowerCase();
        if (!n3 || !g || !P2) continue;
        const x = BigInt("0x" + String(share.userShareHex).replace(/^0x/i, ""));
        const pub = new PublicKey(BigInt(n3), BigInt(g));
        const enc = zk.encryptWithR(pub, x);
        const ctx = `${seatPokContext2("offer-d2", 2, P2)}|${id}`;
        const body = {
          action: "eth3p_d2",
          ticketId: id,
          signerId: share.signerId,
          encD2: enc.c.toString(),
          encDlogProof: zk.proveEncEqualsDlog({
            x,
            rEnc: enc.r,
            c: enc.c,
            paillierN: n3,
            paillierG: g,
            Qhex: P2,
            context: ctx
          })
        };
        if (x >= zk.LINDELL_Q_THIRD && x <= 2n * zk.LINDELL_Q_THIRD) {
          body.rangeProof = zk.proveRangeLindell({
            x,
            rEnc: enc.r,
            c: enc.c,
            paillierN: n3,
            paillierG: g,
            Q1: P2,
            context: ctx
          });
        }
        await poolPost2(api, body);
      } else if (role === 1) {
        const { clientSignRound1: clientSignRound12, clientSignFinish: clientSignFinish2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
        let t2 = await poolPost2(api, { action: "eth3p_ticket", ticketId: id });
        let k1 = k1ByTicket2.get(id);
        const ticketHash = String(t2.hashHex || "").replace(/^0x/i, "").toLowerCase();
        const k1Hash = String(k1?.hashHex || "").replace(/^0x/i, "").toLowerCase();
        if (k1 && ticketHash && k1Hash && k1Hash !== ticketHash) {
          k1ByTicket2.delete(id);
          k1 = null;
        }
        if (!k1 || !t2.haveR1) {
          const rnd = clientSignRound12();
          k1 = { ...rnd, hashHex: t2.hashHex };
          await poolPost2(api, {
            action: "eth3p_r1",
            ticketId: id,
            signerId: share.signerId,
            R1Hex: rnd.R1Hex,
            hashHex: t2.hashHex
          });
          k1ByTicket2.set(id, k1);
          t2 = await poolPost2(api, { action: "eth3p_ticket", ticketId: id });
        }
        if (!t2.hasPartial) continue;
        const fin = clientSignFinish2({
          k1Hex: k1.k1Hex,
          rHex: t2.rHex,
          ciphertext: t2.ciphertext,
          hashHex: t2.hashHex || k1.hashHex,
          clientSecret: share,
          // `st` is only fetched when a ticket is missing its Paillier params,
          // so for a normal ticket it is null and this was undefined. Without a
          // pool pubkey clientSignFinish cannot pick the recovery id and throws.
          publicKey: st?.seal?.publicKey || st?.publicKey || req.publicKey || share.publicKey || share.seal?.publicKey,
          RHex: t2.RHex,
          pokR: t2.pokR,
          pokC: t2.pokC,
          R2Hex: t2.R2Hex,
          Q2Hex: t2.Q2Hex,
          ckeyAdj: t2.ckeyAdj,
          sid: id,
          paillierN: t2.paillierN,
          paillierG: t2.paillierG
        });
        if (fin?.signature65) {
          await poolPost2(api, {
            action: "eth3p_submit",
            ticketId: id,
            signature65: fin.signature65
          });
          k1ByTicket2.delete(id);
        }
      }
      clearSeatFault();
    } catch (e3) {
      const msg = e3?.message || String(e3);
      console.warn("[eth3p contribute]", id, msg);
      if (role === 1 || role === 2) reportSeatFault(role, `${id}: ${msg}`);
    }
  }
}
async function maybeBirthEthNext(share, api) {
  const st = await fetchEth3pStatus(api).catch(() => null);
  const need = st?.rotation?.next?.needBirth;
  const bornBy = st?.rotation?.next?.bornBy || {};
  if (!need) return null;
  const sid = share?.signerId;
  const liveRole = Number(share.role || 0);
  const need1 = !!(need[1] || need["1"]) && bornBy[1] !== sid;
  const need2 = !!(need[2] || need["2"]) && bornBy[2] !== sid;
  if (!need1 && !need2) return null;
  const role = need1 && liveRole === 1 ? 1 : need2 && liveRole === 2 ? 2 : need1 ? 1 : need2 ? 2 : null;
  if (!role) return null;
  const { makeClientSeat: makeClientSeat2, schnorrProveDlog: schnorrProveDlog2, seatPokContext: seatPokContext2, PAILLIER_BITS: PAILLIER_BITS2 } = await Promise.resolve().then(() => (init_pool3pClient(), pool3pClient_exports));
  const seat = makeClientSeat2(role);
  const body = {
    action: "eth3p_birth_next",
    signerId: share.signerId,
    role,
    P: seat.P
  };
  if (role === 1) {
    const zk = await Promise.resolve().then(() => (init_lindellZk(), lindellZk_exports));
    const { generateRandomKeys } = await Promise.resolve().then(() => (init_index_browser_esm2(), index_browser_esm_exports));
    const d1 = zk.randomShareLindellRange();
    seat.userShareHex = zk.scalarToHex(d1);
    seat.P = await pointOfShare2(seat.userShareHex);
    body.P = seat.P;
    const { publicKey: pk, privateKey: sk } = await generateRandomKeys(PAILLIER_BITS2);
    const enc = zk.encryptWithR(pk, d1);
    body.encD1 = enc.c.toString();
    body.paillierN = pk.n.toString();
    body.paillierG = pk.g.toString();
    body.rangeProof = zk.proveRangeLindell({
      x: d1,
      rEnc: enc.r,
      c: enc.c,
      paillierN: pk.n.toString(),
      paillierG: pk.g.toString(),
      Q1: seat.P,
      context: seatPokContext2("birth-next", 1, seat.P)
    });
    seat.paillierLambda = sk.lambda.toString();
    seat.paillierMu = sk.mu.toString();
    seat.paillierN = pk.n.toString();
    seat.paillierG = pk.g.toString();
  }
  body.pok = schnorrProveDlog2(seat.userShareHex, seatPokContext2("birth-next", role, seat.P));
  let ack = await poolPost2(api, body);
  if (role === 1 && ack?.needPdl) {
    const zk = await Promise.resolve().then(() => (init_lindellZk(), lindellZk_exports));
    const pr = zk.pdlProverCommit({
      cPrime: ack.pdl.cPrime,
      paillierN: seat.paillierN,
      paillierG: seat.paillierG,
      paillierLambda: seat.paillierLambda,
      paillierMu: seat.paillierMu
    });
    const opened = await poolPost2(api, {
      action: "eth3p_pdl_commit_next",
      signerId: share.signerId,
      comQ: pr.comQ
    });
    zk.pdlProverFinish({
      alpha: pr.alpha,
      x1: BigInt("0x" + String(seat.userShareHex).replace(/^0x/i, "")),
      a: opened.a,
      b: opened.b,
      Qhat: pr.Qhat,
      comQ: pr.comQ,
      nonceQ: pr.nonceQ,
      comAB: opened.comAB,
      nonceAB: opened.nonceAB,
      Q1: seat.P
    });
    ack = await poolPost2(api, {
      action: "eth3p_pdl_finish_next",
      signerId: share.signerId,
      Qhat: pr.Qhat,
      nonceQ: pr.nonceQ,
      comQ: pr.comQ
    });
  }
  const born = {
    scheme: "eth-3p-ecdsa-lindell-v1",
    role,
    shareHex: seat.userShareHex,
    userShareHex: seat.userShareHex,
    signerId: share.signerId,
    poolAddress: ack.address || null,
    publicKey: ack.publicKey || null,
    Pdapp: ack.Pdapp || ack.seal?.Pdapp || null,
    P: seat.P,
    nextQ: true,
    clientBorn: true,
    seal: ack.seal || null,
    paillierLambda: seat.paillierLambda || null,
    paillierMu: seat.paillierMu || null,
    paillierN: seat.paillierN || null,
    paillierG: seat.paillierG || null
  };
  await storageSet3(nextBornKey(share.signerId, role), born);
  return born;
}
async function heartbeatEth(share, api = DEFAULT_POOL_API2) {
  const signerId = share?.signerId || await getOrCreateSignerId2();
  const r3 = await poolPost2(api, {
    action: "eth3p_heartbeat",
    signerId,
    seatEpoch: share?.seatEpoch ?? 0,
    // Publishes this node's public key (so others can seal pieces to it) and a
    // signed presence claim. Best-effort: an old coordinator ignores both.
    ...await (await preshare2()).identityFields({
      pool: "eth",
      role: share?.role ?? 0,
      seatEpoch: share?.seatEpoch ?? 0,
      signerId
    }).catch(() => ({})),
    // Reported one beat late by construction: the fault is raised while handling
    // the previous response. That is soon enough — a stuck seat stays stuck.
    ...pendingSeatFault ? { seatFault: pendingSeatFault } : {}
  });
  const role = Number(r3.role || r3.share?.role || share?.role || 0);
  await (await preshare2()).serveResealRequests({
    post: (action, body) => poolPost2(api, { action, ...body }),
    prefix: "eth3p",
    signerId,
    requests: r3.resealRequests
  }).catch(() => 0);
  let hexShare = share?.userShareHex ? share : liveShare2;
  if (role === 1 || role === 2) {
    if (!await shareSignsLiveSeat(hexShare, r3, role)) {
      const cached = await loadHexForLiveSeat(signerId, role, r3, api);
      hexShare = cached?.userShareHex ? { ...r3.share, ...cached, role } : null;
    }
    if (hexShare?.userShareHex) clearSeatFault();
  }
  if (r3.needBirth && (role === 1 || role === 2) && !hexShare?.userShareHex) {
    hexShare = await enrollEthSigner(api);
  }
  const live = hexShare?.userShareHex ? hexShare : share;
  if (live?.userShareHex && (role === 1 || role === 2)) {
    await (await preshare2()).packSeat({
      post: (action, body) => poolPost2(api, { action, ...body }),
      prefix: "eth3p",
      pool: "eth",
      signerId,
      role,
      P: compactPt(role === 1 ? r3?.seal?.P1 : r3?.seal?.P2),
      // Role 2 cannot rebuild Enc(d2) from the scalar alone, and nobody can
      // finish a partial ticket without these, so the Paillier private key
      // travels with the share.
      record: {
        userShareHex: live.userShareHex,
        role,
        scheme: live.scheme || "eth-3p-ecdsa-lindell-v1",
        paillierN: live.paillierN,
        paillierG: live.paillierG,
        paillierLambda: live.paillierLambda,
        paillierMu: live.paillierMu,
        P: live.P,
        publicKey: live.publicKey || r3?.seal?.publicKey,
        Pdapp: live.Pdapp || r3?.Pdapp,
        seal: live.seal || r3?.seal
      },
      orbit: r3?.orbit?.live || [],
      orbitKeys: r3?.orbitKeys || {},
      otherHolderId: role === 1 ? r3?.holder2 : r3?.holder1
    }).catch(() => null);
  }
  if ((r3.open || []).length && (role === 1 || role === 2)) {
    await contributeEthOpen({ ...live || {}, role, signerId }, r3.open, api);
  }
  try {
    await maybeBirthEthNext({ ...live || {}, role, signerId }, api);
  } catch (e3) {
    const msg = e3?.message || String(e3);
    if (!/already born/i.test(msg)) {
      console.warn("[eth3p birth_next]", msg);
      r3.birthNextError = msg;
    }
  }
  const merged = live?.userShareHex ? { ...r3.share || {}, ...live, userShareHex: live.userShareHex, role } : r3.share || share;
  liveShare2 = merged;
  return { ...r3, share: merged };
}
async function loadActiveEthShare() {
  if (liveShare2) return liveShare2;
  return enrollEthSigner();
}
async function fetchEth3pStatus(api = DEFAULT_POOL_API2) {
  return poolPost2(api, { action: "eth3p_status" });
}
function stopEthSigningLocal() {
  liveShare2 = null;
}

// src/components/EthPoolThresholdSigner.jsx
var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
var TRANSIENT2 = /Failed to fetch|fetch failed|NetworkError|Load failed|aborted|AbortError|502|503|504|network|ECONNRESET/i;
function shortId2(id) {
  const s3 = String(id || "");
  if (s3.length <= 18) return s3;
  return `${s3.slice(0, 10)}\u2026${s3.slice(-4)}`;
}
function shortTicket2(id) {
  const s3 = String(id || "");
  if (s3.length <= 22) return s3;
  return `${s3.slice(0, 14)}\u2026`;
}
function shortTx2(id) {
  const s3 = String(id || "");
  if (s3.length <= 18) return s3;
  return `${s3.slice(0, 10)}\u2026${s3.slice(-8)}`;
}
function e8ToEth(e8) {
  const n3 = Number(e8);
  if (!Number.isFinite(n3)) return null;
  return (n3 / 1e8).toFixed(2).replace(/\.00$/, "");
}
function isRotateRow(row) {
  const kind = String(row?.kind || "");
  const id = String(row?.ticketId || "");
  return kind.startsWith("rotate") || id.startsWith("eth-rotate");
}
function seatLabel2(share) {
  if (!share) return "joining";
  if (share.waitlist) return "orbit voter";
  if (share.role === 1) return "e1 seat";
  if (share.role === 2) return "e2 seat";
  return "orbit";
}
function EthPoolThresholdSigner() {
  const [share, setShare] = (0, import_react2.useState)(null);
  const [enabled, setEnabled] = (0, import_react2.useState)(false);
  const [panelOpen, setPanelOpen] = (0, import_react2.useState)(false);
  const [ready, setReady] = (0, import_react2.useState)(false);
  const [eth3p, setEth3p] = (0, import_react2.useState)(null);
  const [log, setLog] = (0, import_react2.useState)("ETH 3P off");
  const [error, setError] = (0, import_react2.useState)(null);
  const signedUntil = (0, import_react2.useRef)(0);
  const lastPaidTx = (0, import_react2.useRef)("");
  const join = (0, import_react2.useCallback)(async () => {
    const s3 = await loadActiveEthShare();
    const st = await fetchEth3pStatus().catch(() => null);
    setShare(s3);
    setEth3p(st);
    setLog(
      s3.waitlist ? "ETH orbit voter" : s3.role === 1 ? "holding e1 \u2014 Enc(e1) stays in this tab" : s3.role === 2 ? "holding e2" : "joined ETH 3P"
    );
    setError(null);
    return s3;
  }, []);
  (0, import_react2.useEffect)(() => {
    let cancelled = false;
    (async () => {
      const on = await readEnabled2();
      const open = await readPanelOpen2();
      if (cancelled) return;
      setEnabled(on);
      setPanelOpen(open);
      if (!on) {
        stopEthSigningLocal();
        setReady(true);
        return;
      }
      try {
        await join();
      } catch (e3) {
        if (!cancelled) setError(e3?.message || String(e3));
      } finally {
        if (!cancelled) setReady(true);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [join]);
  const shareRef = (0, import_react2.useRef)(share);
  shareRef.current = share;
  (0, import_react2.useEffect)(() => {
    if (!enabled) return void 0;
    let stop = false;
    let inflight = false;
    const tick = async () => {
      if (stop || inflight) return;
      inflight = true;
      try {
        const cur = shareRef.current;
        if (!cur) return;
        const hb = await heartbeatEth(cur);
        if (stop) return;
        setError(null);
        if (hb?.share) setShare(hb.share);
        setEth3p((p2) => ({
          ...p2 || {},
          holder1: hb.holder1 ?? p2?.holder1,
          holder2: hb.holder2 ?? p2?.holder2,
          orbit: hb.orbit || p2?.orbit,
          address: hb.address || p2?.address,
          e1Live: hb.orbit?.live?.includes(hb.holder1),
          e2Live: hb.orbit?.live?.includes(hb.holder2),
          open: hb.open ?? p2?.open,
          lastPaid: hb.lastPaid ?? p2?.lastPaid,
          burnBin: p2?.burnBin,
          rotation: hb.rotation ?? p2?.rotation,
          signed: hb.signed ?? p2?.signed
        }));
        const paidTx = hb.lastPaid?.txHash || hb.lastPaid?.payout?.txHash || "";
        if (paidTx && paidTx !== lastPaidTx.current) {
          lastPaidTx.current = paidTx;
          signedUntil.current = Date.now() + 12e3;
        }
        const rot = hb.rotation || {};
        const nxt = rot.next;
        if ((hb.open || []).length) {
          setLog(`room ${hb.open[0].ticketId} \xB7 ${hb.open[0].status}`);
        } else if (rot.phase && rot.phase !== "idle") {
          const n1 = nxt?.seatsReady?.["1"] || nxt?.seatsReady?.[1];
          const n22 = nxt?.seatsReady?.["2"] || nxt?.seatsReady?.[2];
          setLog(
            `rotate ${rot.phase}` + (nxt ? ` \xB7 next e1 ${n1 ? "born" : "need birth"} \xB7 next e2 ${n22 ? "born" : "need birth"}` : "") + (rot.lastError ? ` \xB7 ${rot.lastError}` : "") + (hb.birthNextError ? ` \xB7 ${hb.birthNextError}` : "")
          );
        } else if (Date.now() < signedUntil.current && paidTx) {
          setLog(`paid ${paidTx.slice(0, 10)}\u2026`);
        } else {
          setLog(
            cur.role === 1 ? "holding e1 \u2014 Enc(e1) stays in this tab" : cur.role === 2 ? "holding e2" : "ETH orbit"
          );
        }
      } catch (e3) {
        const msg = e3?.message || String(e3);
        if (stop) return;
        if (TRANSIENT2.test(msg) || e3?.name === "AbortError") {
          setLog("ETH coordinator unreachable \u2014 retrying");
          return;
        }
        setError(msg);
      } finally {
        inflight = false;
      }
    };
    tick();
    const id = setInterval(tick, 2500);
    return () => {
      stop = true;
      clearInterval(id);
    };
  }, [enabled]);
  const toggle = async () => {
    const next = !enabled;
    await writeEnabled2(next);
    setEnabled(next);
    if (!next) {
      stopEthSigningLocal();
      setShare(null);
      setLog("ETH signing off");
      return;
    }
    try {
      await join();
    } catch (e3) {
      setError(e3?.message || String(e3));
    }
  };
  const togglePanel = async () => {
    const next = !panelOpen;
    await writePanelOpen2(next);
    setPanelOpen(next);
  };
  const liveN = eth3p?.orbit?.liveCount || 0;
  const openRoom = (eth3p?.open || []).find((t2) => t2.status !== "paid") || null;
  const showPaid = !openRoom && Date.now() < signedUntil.current && eth3p?.lastPaid;
  const room = openRoom || (showPaid ? eth3p.lastPaid : null);
  const paidNow = !!(room && (room.status === "paid" || room.txHash || room.payout?.txHash));
  const steps = {
    e1: paidNow || !!(room?.haveR1 || room?.R1Hex),
    e2: paidNow || !!room?.haveD2,
    lindell: paidNow || !!(room?.hasPartial || room?.ciphertext || room?.status === "partial"),
    paid: paidNow
  };
  const phase = !enabled ? "Off" : paidNow ? "Paid" : openRoom ? "In the room" : seatLabel2(share);
  const statusClass = paidNow ? "ok" : openRoom ? "signing" : "idle";
  const controls = /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "pool-signer__controls", children: [
    /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
      "button",
      {
        type: "button",
        className: `btn btn--ghost${enabled ? " is-on" : ""}`,
        onClick: toggle,
        disabled: !ready,
        children: enabled ? "ETH Signing ON" : "ETH Signing OFF"
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { type: "button", className: "btn btn--ghost", onClick: togglePanel, children: panelOpen ? "Hide ETH panel" : "Show ETH panel" })
  ] });
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("section", { className: `panel pool-signer${panelOpen ? "" : " pool-signer--collapsed"}`, "aria-label": "ETH 3P signer", children: [
    /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "panel__head", children: [
      /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("h2", { children: "ETH 3P signer (e1 / e2)" }),
      controls
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: `pool-signer__status is-${statusClass}`, children: [
      /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "pool-signer__dot", "aria-hidden": true }),
      /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("strong", { children: phase }),
      /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "pool-signer__count", children: enabled ? `${seatLabel2(share)} \xB7 ${liveN} live \xB7 ${eth3p?.address ? "Q sealed" : "unsealed"}` : "not in ETH orbit" })
    ] }),
    error ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { className: "dash__error", children: error }) : null,
    panelOpen ? /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("p", { className: "pool-signer__lead", children: [
        "Separate from WART d1/d2. Two tabs with ETH Signing ON birth the Ethereum 3P Q.",
        share?.signerId ? /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
          " ",
          "You are ",
          /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("code", { children: shortId2(share.signerId) })
        ] }) : null
      ] }),
      enabled ? /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "pool-signer__seats", "aria-label": "e1 and e2 holders", children: [
        /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: `pool-signer__seat${share?.role === 1 ? " is-you" : ""}${eth3p?.holder1 ? " is-held" : ""}`, children: [
          /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "pool-signer__seat-k", children: "e1" }),
          /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("strong", { children: share?.role === 1 ? "YOU" : eth3p?.holder1 ? shortId2(eth3p.holder1) : "vacant" }),
          /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: steps.paid ? "signed" : steps.e1 ? "R1 in" : share?.role === 1 ? "Lindell finish" : eth3p?.e1Live ? "live" : eth3p?.holder1 ? "assigned" : "vacant" })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: `pool-signer__seat${share?.role === 2 ? " is-you" : ""}${eth3p?.holder2 ? " is-held" : ""}`, children: [
          /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "pool-signer__seat-k", children: "e2" }),
          /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("strong", { children: share?.role === 2 ? "YOU" : eth3p?.holder2 ? shortId2(eth3p.holder2) : "vacant" }),
          /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: steps.paid ? "signed" : steps.e2 ? "share in" : share?.role === 2 ? "additive share" : eth3p?.e2Live ? "live" : eth3p?.holder2 ? "assigned" : "vacant" })
        ] })
      ] }) : null,
      eth3p?.rotation && eth3p.rotation.phase && eth3p.rotation.phase !== "idle" ? /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("ol", { className: "pool-signer__steps", "aria-label": "ETH next-Q birth", children: [
        /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
          "li",
          {
            className: eth3p.rotation.next?.seatsReady?.["1"] || eth3p.rotation.next?.seatsReady?.[1] ? "is-done" : "is-wait",
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: "n1" }),
              " next e1",
              " ",
              eth3p.rotation.next?.seatsReady?.["1"] || eth3p.rotation.next?.seatsReady?.[1] ? "born" : "need birth"
            ]
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
          "li",
          {
            className: eth3p.rotation.next?.seatsReady?.["2"] || eth3p.rotation.next?.seatsReady?.[2] ? "is-done" : "is-wait",
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: "n2" }),
              " next e2",
              " ",
              eth3p.rotation.next?.seatsReady?.["2"] || eth3p.rotation.next?.seatsReady?.[2] ? "born" : "need birth"
            ]
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("li", { className: eth3p.rotation.phase === "sweeping" || eth3p.rotation.phase === "cutover" ? "is-done" : "is-wait", children: [
          /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: "s" }),
          " sweep ",
          eth3p.rotation.phase === "sweeping" ? "in room" : eth3p.rotation.phase === "cutover" || eth3p.rotation.sweepTxHash ? "done" : "idle"
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
          "li",
          {
            className: eth3p.rotation.phase === "idle" && !eth3p.rotation.next ? "is-done" : "is-wait",
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: "c" }),
              " cutover",
              " ",
              eth3p.rotation.phase === "idle" && !eth3p.rotation.next ? "done" : eth3p.rotation.phase === "cutover" ? "in progress" : "waiting"
            ]
          }
        )
      ] }) : null,
      enabled ? /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("ol", { className: "pool-signer__steps", "aria-label": "ETH Lindell progress", children: [
        /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("li", { className: steps.e1 ? "is-done" : "is-wait", children: [
          /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: "1" }),
          " e1 R1 ",
          steps.e1 ? "in" : room ? "waiting" : "idle"
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("li", { className: steps.e2 ? "is-done" : "is-wait", children: [
          /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: "2" }),
          " e2 share ",
          steps.e2 ? "in" : room ? "waiting" : "idle"
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("li", { className: steps.lindell ? "is-done" : "is-wait", children: [
          /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: "3" }),
          " Lindell ",
          steps.lindell ? "combined" : room ? "waiting" : "idle"
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("li", { className: steps.paid ? "is-done" : "is-wait", children: [
          /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: "4" }),
          " ",
          steps.paid ? "broadcast" : room ? "broadcast" : "idle"
        ] })
      ] }) : null,
      room ? /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("p", { className: "pool-signer__meta", children: [
        steps.paid ? "paid" : "open",
        " ",
        shortTicket2(room.ticketId),
        room.txHash || room.payout?.txHash ? ` \xB7 ${shortTx2(room.txHash || room.payout.txHash)}` : ""
      ] }) : null,
      /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("p", { className: "pool-signer__meta", children: [
        eth3p?.address ? `ETH Q ${eth3p.address}` : "Waiting for e1 + e2 birth",
        eth3p?.burnBin ? ` \xB7 burn bin ${shortId2(eth3p.burnBin)}` : "",
        eth3p?.rotation ? ` \xB7 rotate ${eth3p.rotation.phase || "idle"} \xB7 ${eth3p.rotation.dueInEpochs ?? "\u2014"} epochs` + (eth3p.rotation.intervalEpochs ? ` / ${eth3p.rotation.intervalEpochs}` : "") + (eth3p.rotation.next?.needBirth?.[1] || eth3p.rotation.next?.needBirth?.["1"] ? " \xB7 need next e1" : "") + (eth3p.rotation.next?.needBirth?.[2] || eth3p.rotation.next?.needBirth?.["2"] ? " \xB7 need next e2" : "") + (eth3p.rotation.next?.address ? ` \xB7 next ${String(eth3p.rotation.next.address).slice(0, 10)}\u2026` : "") : ""
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { className: "pool-signer__meta", children: log }),
      /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("ul", { className: "pool-signer__slots", "aria-label": "live ETH orbit", children: (eth3p?.orbit?.live || []).length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("li", { children: "No live ETH orbit yet" }) : (eth3p.orbit.live || []).map((id) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("li", { className: id === share?.signerId ? "is-me" : void 0, children: [
        shortId2(id),
        id === eth3p?.holder1 ? " \xB7 e1" : "",
        id === eth3p?.holder2 ? " \xB7 e2" : "",
        id === share?.signerId ? " \xB7 you" : ""
      ] }, id)) }),
      /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("details", { className: "pool-signer__history", open: (eth3p?.signed || []).length > 0, children: [
        /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("summary", { children: [
          "Signed",
          /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: (eth3p?.signed || []).length })
        ] }),
        (eth3p?.signed || []).length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { className: "pool-signer__meta", children: "No paid ETH 3P txs in this session yet." }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("ul", { className: "pool-signer__slots pool-signer__slots--history", children: (eth3p.signed || []).map((row) => {
          const amt = e8ToEth(row.amountE8);
          const skip = row.kind === "rotate-skip" || isRotateRow(row) && !row.txHash;
          const fromTo = skip && row.fromAddress && row.toAddress ? `${shortTx2(row.fromAddress)}\u2192${shortTx2(row.toAddress)}` : null;
          return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("li", { children: [
            amt != null ? `${amt} ETH \xB7 ` : "",
            skip ? `rotate skip \xB7 ${fromTo || shortTicket2(row.ticketId)}` : shortTicket2(row.ticketId),
            row.txHash ? /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
              " \xB7 ",
              /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("code", { className: "pool-signer__tx", title: row.txHash, children: shortTx2(row.txHash) })
            ] }) : null
          ] }, row.txHash || row.ticketId);
        }) })
      ] })
    ] }) : null
  ] });
}

// src/components/WasmBrowserNode.jsx
var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1);
var MAX_LOG = 400;
var MAX_ROWS = 50;
var SYNC_SAMPLE_MS = 6e4;
function WasmBrowserNode() {
  const [isolated, setIsolated] = (0, import_react3.useState)(false);
  const [sab, setSab] = (0, import_react3.useState)(false);
  const [opfsOk, setOpfsOk] = (0, import_react3.useState)(false);
  const [wsPeers, setWsPeers] = (0, import_react3.useState)(DEFAULT_WS_PEERS2);
  const [peersInput, setPeersInput] = (0, import_react3.useState)(DEFAULT_WS_PEERS2);
  const [status, setStatus] = (0, import_react3.useState)("Ready \u2014 click Start full node");
  const [running, setRunning] = (0, import_react3.useState)(false);
  const [starting, setStarting] = (0, import_react3.useState)(false);
  const [stopping, setStopping] = (0, import_react3.useState)(false);
  const [storageFatal, setStorageFatal] = (0, import_react3.useState)(false);
  const [memoryFatal, setMemoryFatal] = (0, import_react3.useState)(false);
  const [clearingOpfs, setClearingOpfs] = (0, import_react3.useState)(false);
  const [error, setError] = (0, import_react3.useState)(null);
  const [progress, setProgress] = (0, import_react3.useState)(null);
  const [bridgeHttp, setBridgeHttp] = (0, import_react3.useState)({ state: "idle" });
  const [bridgeWs, setBridgeWs] = (0, import_react3.useState)({ state: "idle" });
  const [bridgeStream, setBridgeStream] = (0, import_react3.useState)({ state: "idle" });
  const [chain, setChain] = (0, import_react3.useState)(null);
  const [peerCount, setPeerCount] = (0, import_react3.useState)(0);
  const [peers, setPeers] = (0, import_react3.useState)([]);
  const [mempoolCount, setMempoolCount] = (0, import_react3.useState)(0);
  const [mempool, setMempool] = (0, import_react3.useState)([]);
  const [logLines, setLogLines] = (0, import_react3.useState)([]);
  const [syncStats, setSyncStats] = (0, import_react3.useState)(null);
  const [tabHidden, setTabHidden] = (0, import_react3.useState)(false);
  const [snapshotBusy, setSnapshotBusy] = (0, import_react3.useState)(false);
  const [snapshotUrl, setSnapshotUrl] = (0, import_react3.useState)("");
  const [localDbInfo, setLocalDbInfo] = (0, import_react3.useState)(null);
  const [publicSnapshot, setPublicSnapshot] = (0, import_react3.useState)(null);
  const snapshotFileRef = (0, import_react3.useRef)(null);
  const startedRef = (0, import_react3.useRef)(false);
  const storageFatalRef = (0, import_react3.useRef)(false);
  const memoryFatalRef = (0, import_react3.useRef)(false);
  const consoleRef = (0, import_react3.useRef)(null);
  const heightSamplesRef = (0, import_react3.useRef)([]);
  const netHeightRef = (0, import_react3.useRef)(null);
  const appendLog = (0, import_react3.useCallback)((text) => {
    setLogLines((prev) => {
      const next = [...prev, `${(/* @__PURE__ */ new Date()).toLocaleTimeString()}  ${text}`];
      return next.length > MAX_LOG ? next.slice(-MAX_LOG) : next;
    });
  }, []);
  const runBridgeProbes = (0, import_react3.useCallback)(async (wsUrl, { probeP2pWs = false, probeStream = false } = {}) => {
    setBridgeHttp({ state: "checking" });
    if (probeP2pWs) {
      setBridgeWs({ state: "checking" });
    } else {
      setBridgeWs({
        state: "skipped",
        detail: "not auto-probed (protects handshake slot)"
      });
    }
    if (probeStream) {
      setBridgeStream({ state: "checking" });
    } else {
      setBridgeStream({
        state: "skipped",
        detail: "optional RPC feed \u2014 not used by full WASM node"
      });
    }
    appendLog(`Probing Official1 HTTP ${OFFICIAL1.httpBase}/chain/head \u2026`);
    const http = await probeBridgeHttp(OFFICIAL1.httpBase);
    if (http.ok) {
      setBridgeHttp({
        state: "ok",
        height: http.height ?? http.data?.height,
        synced: http.synced ?? http.data?.synced
      });
      appendLog(
        `Official1 HTTP OK \u2014 height ${http.height ?? http.data?.height ?? "?"} synced=${http.synced ?? http.data?.synced ?? "?"}`
      );
    } else {
      setBridgeHttp({ state: "bad", error: http.error });
      appendLog(`Official1 HTTP FAIL \u2014 ${http.error}`);
    }
    if (probeP2pWs) {
      appendLog(
        `\u26A0 Probing P2P ${wsUrl} \u2014 this burns Official1\u2019s per-IP connect slot (~30s). Wait \u226530s before Start full WASM node.`
      );
      const ws = await probeBridgeWs(wsUrl, { protocol: "binary", timeoutMs: 1e4 });
      if (ws.ok) {
        setBridgeWs({ state: "ok", detail: ws.detail, openedMs: ws.openedMs });
        appendLog(`Official1 /ws OPEN (${ws.openedMs ?? "?"}ms) \u2014 wait 30s before Start`);
      } else {
        setBridgeWs({ state: "bad", detail: ws.detail });
        appendLog(`Official1 /ws FAIL \u2014 ${ws.detail}`);
      }
    } else {
      appendLog(
        `P2P /ws (${wsUrl}) not auto-probed \u2014 protects Official1 handshake slot. Start full WASM node does the real GRUNT handshake.`
      );
    }
    if (probeStream) {
      appendLog(`Probing RPC stream ${OFFICIAL1.wsStream} (optional) \u2026`);
      const stream = await probeBridgeWs(OFFICIAL1.wsStream, { protocol: null, timeoutMs: 1e4 });
      if (stream.ok) {
        setBridgeStream({ state: "ok", detail: stream.detail, openedMs: stream.openedMs });
        appendLog(`Official1 /stream OPEN (${stream.openedMs ?? "?"}ms)`);
      } else {
        setBridgeStream({ state: "bad", detail: stream.detail });
        appendLog(`Official1 /stream FAIL (optional) \u2014 ${stream.detail}`);
      }
    } else {
      appendLog(
        `/stream is optional (RPC dashboards only). Full WASM node uses /ws via Start \u2014 not needed on page load.`
      );
    }
    appendLog(
      "If Isolation OK + HTTP OK \u2192 click Start full WASM node (real GRUNT on /ws). VPS: journalctl -u warthog-api.service -f | grep -iE 'websocket|webrtc'"
    );
  }, [appendLog]);
  (0, import_react3.useEffect)(() => {
    let cancelled = false;
    (async () => {
      setIsolated(isCrossOriginIsolated());
      setSab(hasSharedArrayBuffer());
      setOpfsOk(hasOpfs());
      const peers2 = resolveWsPeers();
      setWsPeers(peers2);
      setPeersInput(peers2);
      try {
        const boot = await window.__wartOpfsBootstrap;
        if (cancelled) return;
        if (boot && boot.skipped !== true) {
          if (boot.ok) {
            storageFatalRef.current = false;
            setStorageFatal(false);
            appendLog(
              `OPFS bootstrap wipe OK \u2014 removed: ${boot.removed?.length ? boot.removed.join(", ") : "(empty)"}`
            );
            setStatus("OPFS reset OK \u2014 click Start full WASM node once");
          } else if (boot.failed?.length || boot.error) {
            storageFatalRef.current = true;
            setStorageFatal(true);
            appendLog(
              `OPFS bootstrap wipe FAILED \u2014 ${boot.failed?.join("; ") || boot.error}. Close EVERY other tab/window on this host:port (including duplicates), then Recover again. Or: DevTools \u2192 Application \u2192 Storage \u2192 Clear site data.`
            );
            setStatus("OPFS still locked by another tab \u2014 close all tabs for this origin");
          }
          try {
            const clean2 = new URL(window.location.href);
            if (clean2.searchParams.has("resetDb") || clean2.searchParams.has("resetdb")) {
              clean2.searchParams.delete("resetDb");
              clean2.searchParams.delete("resetdb");
              window.history.replaceState({}, "", clean2.toString());
            }
          } catch {
          }
        }
      } catch (e3) {
        appendLog(`OPFS bootstrap error: ${e3?.message || e3}`);
      }
      if (cancelled) return;
      if (opfsNeedsReset()) {
        appendLog("Session still marked dirty \u2014 second OPFS clear (workers already dead on fresh load)\u2026");
        const r3 = await clearOpfsStorage({
          terminateWorkers: false,
          retries: 5,
          log: appendLog
        });
        if (cancelled) return;
        if (r3.ok) {
          storageFatalRef.current = false;
          setStorageFatal(false);
          appendLog(`Second clear OK \u2014 ${r3.removed?.join(", ") || "(empty)"}`);
          setStatus("OPFS clear OK \u2014 Start full WASM node once");
        } else {
          storageFatalRef.current = true;
          setStorageFatal(true);
          appendLog(`Second clear FAILED: ${r3.error}`);
        }
      }
      if (!cancelled) {
        runBridgeProbes(peers2);
      }
      try {
        const man = await loadAvailablePublicSnapshot();
        if (!cancelled && man) {
          setPublicSnapshot(man);
          if (man.url && !snapshotUrl) {
            setSnapshotUrl(man.url);
          }
        } else if (!cancelled) {
          setPublicSnapshot(null);
        }
      } catch {
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [runBridgeProbes, appendLog]);
  (0, import_react3.useEffect)(() => {
    const el = consoleRef.current;
    if (!el) return;
    const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
    const stickThresholdPx = 64;
    if (distanceFromBottom <= stickThresholdPx) {
      requestAnimationFrame(() => {
        if (consoleRef.current) {
          consoleRef.current.scrollTop = consoleRef.current.scrollHeight;
        }
      });
    }
  }, [logLines]);
  (0, import_react3.useEffect)(() => {
    const onVis = () => {
      const hidden = document.visibilityState === "hidden";
      setTabHidden(hidden);
      if (hidden && startedRef.current) {
        appendLog("[sync] Tab hidden \u2014 browser may throttle the node. Keep this tab focused for faster IBD.");
      }
    };
    document.addEventListener("visibilitychange", onVis);
    return () => document.removeEventListener("visibilitychange", onVis);
  }, [appendLog]);
  const refreshLocalDbInfo = (0, import_react3.useCallback)(async () => {
    const info = await getLocalChainDbInfo();
    setLocalDbInfo(info);
    return info;
  }, []);
  (0, import_react3.useEffect)(() => {
    refreshLocalDbInfo();
  }, [refreshLocalDbInfo]);
  const nodeHealthy = running && !storageFatal && !memoryFatal;
  const configuredPeerCount = (0, import_react3.useMemo)(
    () => parsePeerList(wsPeers).length,
    [wsPeers]
  );
  const canStart = (0, import_react3.useMemo)(
    () => isolated && sab && !running && !starting && !stopping && !storageFatal && !clearingOpfs && !snapshotBusy,
    [isolated, sab, running, starting, stopping, storageFatal, clearingOpfs, snapshotBusy]
  );
  const canImportPublicSnapshot = (0, import_react3.useMemo)(
    () => opfsOk && !running && !starting && !stopping && !snapshotBusy && !clearingOpfs,
    [opfsOk, running, starting, stopping, snapshotBusy, clearingOpfs]
  );
  const canImportSiteSnapshot = (0, import_react3.useMemo)(
    () => canImportPublicSnapshot && !!publicSnapshot?.url,
    [canImportPublicSnapshot, publicSnapshot]
  );
  const canStop = (0, import_react3.useMemo)(
    () => running && !starting && !stopping && !clearingOpfs,
    [running, starting, stopping, clearingOpfs]
  );
  const canClearOpfs = (0, import_react3.useMemo)(
    () => opfsOk && !starting && !stopping && !clearingOpfs && (!running || storageFatal),
    [opfsOk, starting, stopping, clearingOpfs, running, storageFatal]
  );
  const handleOpfsReadonly = (0, import_react3.useCallback)((sourceText) => {
    markOpfsNeedsReset();
    storageFatalRef.current = true;
    setStorageFatal(true);
    setRunning(false);
    startedRef.current = false;
    try {
      terminateWasmWorkers(appendLog);
    } catch {
    }
    setError(
      "SQLite readonly / OPFS lock \u2014 close every other tab on this host:port, then click Recover (clear OPFS + reload). Do not spam Start."
    );
    setStatus("OPFS / SQLite write failed \u2014 use Recover");
    appendLog(
      `[storage] readonly/OPFS lock${sourceText ? `: ${String(sourceText).slice(0, 120)}` : ""}`
    );
  }, [appendLog]);
  const handleWasmOom = (0, import_react3.useCallback)((sourceText) => {
    if (memoryFatalRef.current) return;
    memoryFatalRef.current = true;
    setMemoryFatal(true);
    setRunning(false);
    startedRef.current = false;
    try {
      terminateWasmWorkers(appendLog);
    } catch {
    }
    const snippet = sourceText ? String(sourceText).slice(0, 200) : "";
    setError(
      "WASM heap exhausted (Cannot enlarge memory). The full-chain sync needs more browser RAM than this node build allows. OPFS data is usually still intact \u2014 Stop is not required; after a rebuild with a higher MAXIMUM_MEMORY you can Start again to resume. Restarting the same build will hit the same wall."
    );
    setStatus("WASM out of memory \u2014 heap limit reached");
    appendLog(`[memory] WASM OOM / Cannot enlarge memory${snippet ? `: ${snippet}` : ""}`);
    appendLog(
      "[memory] Fix: rebuild public/node triad with -sMAXIMUM_MEMORY=2048mb (or higher). Clear/Recover only if you want a full resync after upgrading."
    );
  }, [appendLog]);
  const handleSqliteDiskIo = (0, import_react3.useCallback)((sourceText) => {
    setRunning(false);
    startedRef.current = false;
    try {
      terminateWasmWorkers(appendLog);
    } catch {
    }
    const snippet = sourceText ? String(sourceText).slice(0, 180) : "";
    setError(
      "SQLite disk I/O error opening chain.db3. Common causes: WAL/hot copy import, another tab holding OPFS, or a bad multi\u2011GB write. Close every other tab on this origin \u2192 Clear local data \u2192 re-import a checkpointed DELETE-mode chain.db3 \u2192 Start once."
    );
    setStatus("OPFS SQLite open failed \u2014 see console");
    appendLog(`[storage] SQLite disk I/O / open failure${snippet ? `: ${snippet}` : ""}`);
    appendLog(
      "[storage] Prefer: close ALL tabs for this origin \u2192 Clear local data \u2192 re-import chain.db3 (journal_mode=DELETE, no -wal/-shm) \u2192 Start once."
    );
    appendLog(
      '[storage] If never checkpointed on native: stop node \u2192 sqlite3 chain.db3 "PRAGMA wal_checkpoint(TRUNCATE); PRAGMA journal_mode=DELETE;" \u2192 import only that file.'
    );
  }, [appendLog]);
  const applyPeers = () => {
    const v = formatPeerList(peersInput.trim() || DEFAULT_WS_PEERS2);
    setPeersInput(v);
    setWsPeers(v);
    try {
      localStorage.setItem("wsPeers", v);
    } catch {
    }
    const n3 = parsePeerList(v).length;
    appendLog(`Bridge peers set \u2192 ${n3} URL${n3 === 1 ? "" : "s"}: ${v}`);
    runBridgeProbes(v);
  };
  const useOfficial1 = () => {
    const v = mainnetPeerPreset();
    setPeersInput(v);
    setWsPeers(v);
    try {
      localStorage.setItem("wsPeers", v);
    } catch {
    }
    appendLog(`Reset to mainnet bridge preset \u2192 ${v}`);
    runBridgeProbes(v);
  };
  const useLocalProxy = () => {
    const url = localDevWsBridgeUrl();
    setPeersInput(url);
    setWsPeers(url);
    try {
      localStorage.setItem("wsPeers", url);
    } catch {
    }
    appendLog(
      `Using local dev WS proxy \u2192 ${url} (requires restarted \`npm run dev\` with /ws-bridge proxy). Do not Probe /ws on public URL before Start.`
    );
    runBridgeProbes(url, { probeP2pWs: false });
  };
  const testRawWs = async () => {
    const url = (peersInput.trim() || wsPeers || resolveDefaultWsPeers()).split(";")[0].trim();
    appendLog(`Raw WSS open test \u2192 ${url} (success = onopen; close after open is OK for bare client)`);
    const result = await probeBridgeWs(url, { protocol: "binary", timeoutMs: 12e3 });
    if (result.ok) {
      appendLog(`Raw open OK in ${result.openedMs ?? "?"}ms \u2014 bridge reachable from this browser`);
      setBridgeWs({ state: "ok", detail: result.detail, openedMs: result.openedMs });
    } else {
      appendLog(`Raw open FAIL \u2014 ${result.detail}`);
      setBridgeWs({ state: "bad", detail: result.detail });
    }
  };
  (0, import_react3.useEffect)(() => {
    if (bridgeHttp?.height != null) {
      netHeightRef.current = Number(bridgeHttp.height);
    }
  }, [bridgeHttp?.height]);
  const onChain = (0, import_react3.useCallback)((event) => {
    if (!event) return;
    const height = Number(event.length ?? event.height ?? 0) || 0;
    setChain({
      height,
      difficulty: event.difficulty,
      worksum: event.worksum
    });
    const now = Date.now();
    const samples = heightSamplesRef.current;
    samples.push({ t: now, h: height });
    while (samples.length > 2 && now - samples[0].t > SYNC_SAMPLE_MS) {
      samples.shift();
    }
    if (samples.length >= 2) {
      const first = samples[0];
      const last = samples[samples.length - 1];
      const dt = (last.t - first.t) / 1e3;
      const dh = last.h - first.h;
      if (dt > 0.5 && dh >= 0) {
        const blocksPerSec = dh / dt;
        const netH = netHeightRef.current;
        const lag = netH != null && Number.isFinite(netH) ? Math.max(0, netH - height) : null;
        const etaSec = lag != null && blocksPerSec > 0.01 ? lag / blocksPerSec : null;
        setSyncStats({
          blocksPerSec,
          lag,
          etaSec,
          netHeight: netH ?? null,
          localHeight: height
        });
      }
    }
  }, []);
  const onConnect = (0, import_react3.useCallback)((event) => {
    if (!event) return;
    setPeerCount(event.total ?? 0);
    setPeers((prev) => {
      const row = {
        id: event.id,
        inbound: event.inbound,
        type: event.type,
        address: event.address,
        since: event.since
      };
      const next = [row, ...prev.filter((p2) => p2.id !== event.id)];
      return next.slice(0, MAX_ROWS);
    });
  }, []);
  const onDisconnect = (0, import_react3.useCallback)((event) => {
    if (!event) return;
    setPeerCount(event.total ?? 0);
    setPeers((prev) => prev.filter((p2) => p2.id !== event.id));
  }, []);
  const onMempoolAdd = (0, import_react3.useCallback)((event) => {
    if (!event) return;
    setMempoolCount(event.total ?? 0);
    setMempool((prev) => {
      const row = {
        id: event.id,
        fromAddress: event.fromAddress,
        toAddress: event.toAddress,
        amount: event.amount,
        fee: event.fee,
        txHash: event.txHash
      };
      const next = [row, ...prev.filter((p2) => p2.id !== event.id)];
      return next.slice(0, MAX_ROWS);
    });
  }, []);
  const onMempoolErase = (0, import_react3.useCallback)((event) => {
    if (!event) return;
    setMempoolCount(event.total ?? 0);
    setMempool((prev) => prev.filter((p2) => p2.id !== event.id));
  }, []);
  const clearOpfs = async () => {
    if (!canClearOpfs) return;
    setClearingOpfs(true);
    setError(null);
    appendLog("Terminating WASM workers, then clearing OPFS\u2026");
    try {
      terminateWasmWorkers(appendLog);
      const before = await listOpfsEntries();
      appendLog(`OPFS before: ${before.length ? before.join(", ") : "(empty)"}`);
      const result = await clearOpfsStorage({ terminateWorkers: true, log: appendLog });
      if (result.ok) {
        storageFatalRef.current = false;
        setStorageFatal(false);
        startedRef.current = false;
        setRunning(false);
        appendLog(`OPFS cleared \u2014 removed: ${result.removed?.join(", ") || "(already empty)"}`);
        setStatus("OPFS cleared \u2014 click Start full WASM node (one tab only)");
      } else {
        setError(result.error || "OPFS clear failed");
        appendLog(`OPFS clear FAILED: ${result.error}`);
        setStatus("OPFS clear failed \u2014 use Recover, or close all tabs for this origin");
      }
    } catch (err) {
      setError(err.message || String(err));
      appendLog(`OPFS clear ERROR: ${err.message || err}`);
    } finally {
      setClearingOpfs(false);
    }
  };
  const recoverOpfs = async () => {
    if (starting || stopping || clearingOpfs) return;
    setClearingOpfs(true);
    setError(null);
    startedRef.current = false;
    setRunning(false);
    markOpfsNeedsReset();
    appendLog("Recover: kill workers \u2192 clear OPFS \u2192 reload (?resetDb=1)\u2026");
    try {
      await recoverOpfsStorage({ reload: true, log: appendLog });
    } catch (err) {
      appendLog(`Recover error: ${err.message || err}`);
      try {
        const url = new URL(window.location.href);
        url.searchParams.set("resetDb", "1");
        window.location.replace(url.toString());
      } catch {
        window.location.reload();
      }
    }
  };
  const stop = async () => {
    if (!running || starting || stopping || clearingOpfs) return;
    setStopping(true);
    setError(null);
    setStatus("Stopping\u2026");
    appendLog("Stopping node \u2014 terminating workers (local chain data kept)\u2026");
    try {
      terminateWasmWorkers(appendLog);
    } catch (err) {
      appendLog(`Stop warning: ${err?.message || err}`);
    }
    startedRef.current = false;
    setRunning(false);
    memoryFatalRef.current = false;
    setMemoryFatal(false);
    setProgress(null);
    setChain(null);
    setSyncStats(null);
    heightSamplesRef.current = [];
    setPeerCount(0);
    setPeers([]);
    setMempoolCount(0);
    setMempool([]);
    await new Promise((r3) => setTimeout(r3, 600));
    setStatus("Stopped \u2014 click Start to run again");
    appendLog("Node stopped. OPFS unchanged. You can Start again (wait a few seconds if reconnect fails).");
    setStopping(false);
    refreshLocalDbInfo();
  };
  const importSnapshotFile = async (file) => {
    if (!file || running || starting || stopping || snapshotBusy) return;
    setSnapshotBusy(true);
    setError(null);
    appendLog(`[snapshot] importing file \u201C${file.name}\u201D (${formatBytes(file.size)})\u2026`);
    try {
      const result = await importChainDbBlob(file, { log: appendLog });
      if (!result.ok) {
        setError(result.error || "Snapshot import failed");
        appendLog(`[snapshot] FAIL \u2014 ${result.error}`);
      } else {
        appendLog(
          `[snapshot] OK \u2014 ${formatBytes(result.bytes)}. Press Start to catch up remaining tip blocks.`
        );
        await refreshLocalDbInfo();
      }
    } catch (err) {
      setError(err?.message || String(err));
      appendLog(`[snapshot] ERROR \u2014 ${err?.message || err}`);
    } finally {
      setSnapshotBusy(false);
      if (snapshotFileRef.current) snapshotFileRef.current.value = "";
    }
  };
  const importSnapshotUrl = async (urlOverride) => {
    if (running || starting || stopping || snapshotBusy) return;
    const url = String(urlOverride || snapshotUrl || resolvePublicSnapshotUrl()).trim();
    if (!url) {
      setError("Enter a snapshot URL (must be fetchable under COEP / same-origin).");
      return;
    }
    setSnapshotBusy(true);
    setError(null);
    appendLog(`[snapshot] downloading ${url}\u2026`);
    try {
      const result = await importChainDbFromUrl(url, { log: appendLog });
      if (!result.ok) {
        setError(result.error || "Snapshot URL import failed");
        appendLog(`[snapshot] FAIL \u2014 ${result.error}`);
        if (/404|403|HTTP/.test(String(result.error || "")) || url.startsWith("/snapshot/")) {
          appendLog(snapshotMissingTip(url));
        }
      } else {
        appendLog(
          `[snapshot] OK \u2014 ${formatBytes(result.bytes)}. Press Start to catch up remaining tip blocks.`
        );
        await refreshLocalDbInfo();
      }
    } catch (err) {
      setError(err?.message || String(err));
      appendLog(`[snapshot] ERROR \u2014 ${err?.message || err}`);
    } finally {
      setSnapshotBusy(false);
    }
  };
  const importPublicSnapshot = async () => {
    const url = publicSnapshot?.url || resolvePublicSnapshotUrl();
    setSnapshotUrl(url);
    appendLog(`[snapshot] importing ${publicSnapshotLabel(publicSnapshot)}\u2026`);
    await importSnapshotUrl(url);
  };
  const start = async () => {
    if (startedRef.current || starting || stopping || storageFatal || storageFatalRef.current) return;
    setStarting(true);
    setError(null);
    storageFatalRef.current = false;
    setStorageFatal(false);
    memoryFatalRef.current = false;
    setMemoryFatal(false);
    setSyncStats(null);
    heightSamplesRef.current = [];
    setStatus("Loading WASM full node\u2026");
    appendLog("Starting Warthog WASM full node\u2026");
    appendLog(
      `crossOriginIsolated=${isCrossOriginIsolated()} SharedArrayBuffer=${hasSharedArrayBuffer()} OPFS=${hasOpfs()}`
    );
    appendLog(
      `Sync profile: ${configuredPeerCount} WS peer URL(s) \xB7 WebRTC on \xB7 keep this tab focused`
    );
    if (localDbInfo?.present) {
      appendLog(
        `Local ${localDbInfo.name || "chain.db3"} present (${formatBytes(localDbInfo.bytes)}) \u2014 will resume / catch up`
      );
    }
    if (opfsNeedsReset()) {
      appendLog("Prior OPFS failure flagged \u2014 clearing storage before boot\u2026");
    }
    try {
      if (!hasOpfs()) {
        throw new Error(
          "OPFS is not available. Use Chrome/Edge (or Chromium) on http://127.0.0.1 or https. The full node stores chain.db3 under /opfs via createSyncAccessHandle."
        );
      }
      const prep = await prepareOpfsForStart({ forceClear: opfsNeedsReset() });
      if (!prep.ok) {
        throw new Error(prep.error || "OPFS prepare failed");
      }
      if (prep.cleared) {
        appendLog(`OPFS pre-cleared: ${prep.removed?.join(", ") || "(empty)"}`);
      }
      appendLog(
        `OPFS entries: ${prep.entries?.length ? prep.entries.join(", ") : "(empty \u2014 will create DBs)"}`
      );
      appendLog(`Using WS_PEERS=${wsPeers}`);
      appendLog(`Official1 bridge flags expected: ${OFFICIAL1.flags?.join(" ")}`);
      appendLog("Booting public/node WASM (expect log: Warthog Node v0.9.6 / Adding websocket peer \u2026)");
      appendLog(
        "Handshake v4: settle ~250ms after open, then C++ sends WARTHOG GRUNT? on the wire (same as CLI tester). Official1: 1 connect/IP (~30s) \u2014 do not probe /ws first."
      );
      appendLog(
        "Storage: chain/peers use OPFS (/opfs/*.db3). Only one tab per origin. If readonly database \u2192 Recover (clear + reload), then Start once."
      );
      await new Promise((r3) => setTimeout(r3, 400));
      const moduleConfig = createModuleConfig({
        wsPeers,
        print: (text) => {
          appendLog(text);
          if (isOpfsReadonlyError(text)) {
            handleOpfsReadonly(text);
          } else if (isWasmOomError(text)) {
            handleWasmOom(text);
          } else if (isSqliteDiskIoError(text)) {
            handleSqliteDiskIo(text);
          }
        },
        setStatus,
        onChain,
        onConnect,
        onDisconnect,
        onMempoolAdd,
        onMempoolErase,
        onProgress: setProgress
      });
      const instance = await startWasmNode(moduleConfig);
      window.wartNode = instance;
      window.Module = instance;
      if (storageFatalRef.current) {
        appendLog("Runtime returned but storage is fatal \u2014 use Recover, do not trust peer state");
        setStatus("OPFS / SQLite write failed \u2014 use Recover");
        setRunning(false);
        startedRef.current = false;
      } else if (memoryFatalRef.current) {
        appendLog("Runtime returned but WASM heap is exhausted \u2014 do not trust peer/chain state");
        setStatus("WASM out of memory \u2014 heap limit reached");
        setRunning(false);
        startedRef.current = false;
      } else {
        startedRef.current = true;
        setRunning(true);
        setStatus("Full node runtime started \u2014 watch peers / chain / console for GRUNT");
        appendLog("Emscripten runtime ready \u2014 full node is running in this tab");
        appendLog("Expect: [ws-handshake] \u2026 GRUNT complete \xB7 Adding websocket peer \u2026");
        appendLog("VPS: journalctl -u warthog-api.service -f | grep -iE 'websocket|webrtc'");
      }
    } catch (err) {
      console.error(err);
      const msg = err.message || String(err);
      if (isOpfsReadonlyError(err)) {
        handleOpfsReadonly(msg);
      } else if (isWasmOomError(err)) {
        handleWasmOom(msg);
      } else if (isSqliteDiskIoError(err)) {
        handleSqliteDiskIo(msg);
      } else {
        setError(msg);
        setStatus("Failed to start");
      }
      appendLog(`ERROR: ${msg}`);
      startedRef.current = false;
      setRunning(false);
    } finally {
      setStarting(false);
    }
  };
  const browserReady = isolated && sab && opfsOk;
  const badgeClass = storageFatal || memoryFatal ? "is-bad" : nodeHealthy ? "is-ok" : browserReady ? "is-ok" : "is-warn";
  const badgeLabel = storageFatal ? "Needs fix" : memoryFatal ? "Out of memory" : nodeHealthy ? "Running" : browserReady ? "Ready" : "Setup needed";
  const friendlyStatus = (() => {
    if (storageFatal) {
      return "Storage is locked. Close other tabs on this site, then use Recover below.";
    }
    if (memoryFatal) {
      return "WASM ran out of memory during sync (heap limit). Local chain data is usually kept \u2014 Start again after upgrading the node build, or try Start once more if you already have the 2048\u202FMB build.";
    }
    if (stopping) return "Stopping your node\u2026";
    if (nodeHealthy) {
      if (chain?.height != null) {
        return `Your node is live on the network \xB7 block #${chain.height}`;
      }
      return "Your node is running \u2014 connecting to the network\u2026";
    }
    if (starting) return "Starting your node \u2014 this can take a moment\u2026";
    if (!isolated || !sab) {
      return "This page needs a special browser mode. Use Chrome/Edge via the normal site link, not a bare IP.";
    }
    if (!opfsOk) {
      return "This browser cannot store the chain. Please use Chrome or Edge on HTTPS (or localhost).";
    }
    if (status?.startsWith("Stopped")) {
      return "Node stopped. Local data is kept \u2014 press Start when you want to run again.";
    }
    if (bridgeHttp.state === "ok") {
      return `Network is reachable${bridgeHttp.height != null ? ` (height #${bridgeHttp.height})` : ""}. Press Start to run a full node in this tab.`;
    }
    if (bridgeHttp.state === "checking") return "Checking network\u2026";
    if (bridgeHttp.state === "bad") {
      return "Could not reach the public network probe \u2014 you can still try Start.";
    }
    return status || "Ready when you are.";
  })();
  const displayPeerCount = peerCount || peers.length;
  const displayMempoolCount = mempoolCount || mempool.length;
  const formatEta = (sec) => {
    if (sec == null || !Number.isFinite(sec) || sec < 0) return "\u2014";
    if (sec < 90) return `~${Math.round(sec)}s`;
    if (sec < 3600) return `~${Math.round(sec / 60)}m`;
    const h2 = Math.floor(sec / 3600);
    const m2 = Math.round(sec % 3600 / 60);
    return `~${h2}h ${m2}m`;
  };
  const syncRateLabel = syncStats?.blocksPerSec != null ? `${syncStats.blocksPerSec < 10 ? syncStats.blocksPerSec.toFixed(1) : Math.round(syncStats.blocksPerSec)} blk/s` : null;
  const inExtPopup = isExtensionPopup();
  const inExtSide = isExtensionSidePanel();
  const inExtDocked = inExtPopup || inExtSide;
  const inExtPage = isExtensionPage();
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: `dash${inExtDocked ? " dash--popup" : ""}${inExtSide ? " dash--sidepanel" : ""}`, children: [
    /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("header", { className: "dash__header", children: [
      /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "dash__brand", children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("img", { src: "/img/main_logo.png", alt: "", className: "dash__logo" }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { children: [
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("h1", { children: inExtDocked ? "Warthog Node" : "Warthog in your browser" }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "dash__subtitle", children: inExtSide ? "Side panel \u2014 stays open while you browse" : inExtPopup ? "Toolbar popup \u2014 dock to side panel to stay open" : inExtPage ? "Full node in this tab \u2014 keep focused while syncing" : "Run a full node in this tab \u2014 no install required" })
        ] })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: `dash__badge ${badgeClass}`, children: badgeLabel })
    ] }),
    inExtPopup && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "ext-popup-banner", children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: "This popup closes when you click away" }),
        " ",
        "\u2014 that stops the node. Prefer ",
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: "Open side panel" }),
        " ",
        "(stays open like Leo) for sync, or ",
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: "Expand to tab" }),
        "."
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "ext-popup-toolbar", children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
          "button",
          {
            type: "button",
            className: "btn btn--start",
            onClick: () => openExtensionSidePanel(),
            title: "Dock in the browser side panel \u2014 stays open while you browse",
            children: "Open side panel"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
          "button",
          {
            type: "button",
            className: "btn btn--ghost",
            onClick: () => openExtensionFullTab(),
            title: "Open full dashboard tab (do not run popup + tab at once)",
            children: "Expand to tab"
          }
        )
      ] })
    ] }),
    inExtSide && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "ext-popup-banner", children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: "Stays open while you browse" }),
        " ",
        "other tabs. Closing this side panel stops the node. One surface only (don\u2019t also Start in a tab)."
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "ext-popup-toolbar", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
        "button",
        {
          type: "button",
          className: "btn btn--ghost",
          onClick: () => openExtensionFullTab(),
          title: "Open full dashboard tab for a larger view",
          children: "Expand to tab"
        }
      ) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(PoolThresholdSigner, {}),
    /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(EthPoolThresholdSigner, {}),
    /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("section", { className: "panel hero", children: [
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "hero__status", children: friendlyStatus }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "hero__actions", children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
          "button",
          {
            type: "button",
            className: `btn btn--start${nodeHealthy ? " is-running" : ""}`,
            onClick: start,
            disabled: !canStart,
            children: starting ? "Starting\u2026" : stopping ? "Please wait\u2026" : storageFatal ? "Fix storage first" : memoryFatal ? "Memory limit hit \u2014 Start to retry" : nodeHealthy ? "Node is running" : "Start node"
          }
        ),
        (running || stopping) && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
          "button",
          {
            type: "button",
            className: "btn btn--stop",
            onClick: stop,
            disabled: !canStop,
            title: "Stop the node in this tab (keeps local chain data)",
            children: stopping ? "Stopping\u2026" : "Stop node"
          }
        ),
        !nodeHealthy && !localDbInfo?.present && publicSnapshot && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
          "button",
          {
            type: "button",
            className: "btn btn--ghost",
            onClick: importPublicSnapshot,
            disabled: !canImportSiteSnapshot,
            title: `Import site chain.db3 (${formatBytes(publicSnapshot.bytes || 0)}` + (publicSnapshot.height != null ? `, height ${Number(publicSnapshot.height).toLocaleString()}` : "") + ")",
            children: snapshotBusy ? "Importing snapshot\u2026" : "Import snapshot"
          }
        )
      ] }),
      progress && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
        "progress",
        {
          className: "hero__progress",
          value: progress.value,
          max: progress.max
        }
      ),
      !nodeHealthy && !storageFatal && !memoryFatal && !stopping && browserReady && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "hero__hint", children: inExtSide ? "Side panel can stay open while you use other tabs. Close the panel \u2192 node stops." : inExtPopup ? "Use Open side panel to keep the node up while browsing." : "Keep this tab focused for faster sync. Only one tab per site can run the node." }),
      tabHidden && nodeHealthy && !inExtSide && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "dash__error", style: { marginTop: "0.85rem", textAlign: "left" }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: "Tab in background" }),
        " \u2014 Chrome may throttle the WASM node. Switch back to this tab to keep IBD moving."
      ] }),
      error && !memoryFatal && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "dash__error", style: { marginTop: "0.85rem", textAlign: "left" }, children: error }),
      memoryFatal && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "dash__error", style: { marginTop: "0.85rem", textAlign: "left" }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: "Out of memory" }),
        " \u2014 the WASM node hit its heap limit (",
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { children: "Cannot enlarge memory" }),
        "). Full-chain sync around mid/late IBD needs more than older 768\u202FMB builds allowed.",
        /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("ol", { className: "dash__checklist", children: [
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("li", { children: [
            "This build should use ",
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: "2048\u202FMB" }),
            " max heap \u2014 hard-refresh after deploy."
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("li", { children: [
            "Local OPFS chain data is usually kept; you do ",
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: "not" }),
            " need Recover just for OOM."
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("li", { children: [
            "Press ",
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: "Start" }),
            " again to resume (if height still stalls at the same point, the triad was not upgraded)."
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("li", { children: "Use a 64-bit desktop Chrome/Edge with enough free RAM; close heavy tabs if needed." })
        ] })
      ] }),
      storageFatal && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "dash__error", style: { marginTop: "0.85rem", textAlign: "left" }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: "Storage locked" }),
        " \u2014 another tab may still be using this site's data.",
        /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("ol", { className: "dash__checklist", children: [
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("li", { children: "Close every other tab or window on this same site." }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("li", { children: [
            "Open ",
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: "Advanced" }),
            " below and click ",
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: "Recover" }),
            " once."
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("li", { children: "If that fails: clear site data in the browser, refresh, then Start once." })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "controls__actions", style: { marginTop: "0.65rem" }, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
          "button",
          {
            type: "button",
            className: "btn btn--danger-ghost",
            onClick: recoverOpfs,
            disabled: starting || clearingOpfs || !opfsOk,
            children: clearingOpfs ? "Recovering\u2026" : "Recover & reload"
          }
        ) })
      ] })
    ] }),
    !inExtPage && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("section", { className: "panel ext-download", "aria-label": "Chromium extension download", children: [
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "panel__head", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("h2", { children: "Chromium extension" }) }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "ext-download__lead", children: "Same full WASM node as this page, as a Chrome / Brave / Edge extension. Side panel stays open while you browse (more reliable isolation on Brave)." }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "ext-download__actions", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
        "a",
        {
          className: "btn btn--ghost",
          href: "/downloads/warthog_node_extension.zip",
          download: "warthog_node_extension.zip",
          children: "Download extension (.zip)"
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("ol", { className: "ext-download__steps", children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("li", { children: [
          "Unzip the archive (one folder: ",
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { children: "warthog_node_extension" }),
          ")."
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("li", { children: [
          "Open ",
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { children: "chrome://extensions" }),
          " (or ",
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { children: "brave://extensions" }),
          ")."
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("li", { children: [
          "Enable ",
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: "Developer mode" }),
          " \u2192 ",
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: "Load unpacked" }),
          "."
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("li", { children: [
          "Select the unzipped folder that contains ",
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { children: "manifest.json" }),
          "."
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("li", { children: [
          "Click the toolbar icon \u2192 side panel \u2192 ",
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: "Start node" }),
          "."
        ] })
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "snapshot", "aria-label": "Network snapshot", children: [
      /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "snapshot__card", children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "snapshot__label", children: "Block height" }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "snapshot__value", children: chain?.height != null ? `#${chain.height}` : "\u2014" }),
        bridgeHttp?.height != null && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { className: "snapshot__sub", children: [
          "network #",
          bridgeHttp.height,
          syncStats?.lag != null ? ` \xB7 lag ${syncStats.lag.toLocaleString()}` : ""
        ] }),
        chain?.difficulty != null && !bridgeHttp?.height && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "snapshot__sub", children: formatHashrate(chain.difficulty) })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "snapshot__card", children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "snapshot__label", children: "Sync rate" }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "snapshot__value", children: nodeHealthy && syncRateLabel ? syncRateLabel : "\u2014" }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "snapshot__sub", children: nodeHealthy && syncStats?.etaSec != null ? `ETA ${formatEta(syncStats.etaSec)}` : nodeHealthy ? "measuring\u2026" : "after start" })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "snapshot__card", children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "snapshot__label", children: "Connections" }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "snapshot__value", children: nodeHealthy || peers.length ? displayPeerCount : "\u2014" }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "snapshot__sub", children: nodeHealthy ? `${displayPeerCount === 1 ? "peer" : "peers"} \xB7 ${configuredPeerCount} WS URL${configuredPeerCount === 1 ? "" : "s"}` : "after start" })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "snapshot__card", children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "snapshot__label", children: "Pending txs" }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "snapshot__value", children: nodeHealthy || mempool.length ? displayMempoolCount : "\u2014" }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "snapshot__sub", children: "mempool" })
      ] })
    ] }),
    (!isolated || !sab) && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "dash__error", children: [
      "This site must load with secure isolation headers so the node can run in-browser. Open it via the normal HTTPS link (or ",
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { children: "npm run dev" }),
      " locally on localhost), not a raw IP address."
    ] }),
    isolated && sab && !opfsOk && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "dash__error", children: [
      "Storage is unavailable. Use Chrome or Edge on HTTPS (or ",
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { children: "http://127.0.0.1" }),
      ")."
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "lists-row", children: [
      /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("section", { className: "panel", children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "panel__head", children: [
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("h2", { children: "Connections" }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "panel__count", children: displayPeerCount })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "list", children: peers.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "list__empty", children: nodeHealthy ? "Waiting for peers\u2026" : "Start the node to connect" }) : peers.map((p2) => {
          const inbound = p2.inbound === true || p2.inbound === "true" || p2.inbound === 1 || p2.inbound === "1";
          const addr = String(p2.address ?? "\u2014");
          return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "list-item", children: [
            /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "list-item__row", children: [
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "list-item__main", children: String(p2.type || "peer") }),
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: `tag ${inbound ? "tag--in" : "tag--out"}`, children: inbound ? "in" : "out" })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "list-item__addr", title: addr, children: shortAddr(addr, 10) }),
            p2.since != null && p2.since !== "" && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "list-item__amounts", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { className: "muted", children: [
              "since ",
              String(p2.since)
            ] }) })
          ] }, String(p2.id));
        }) })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("section", { className: "panel", children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "panel__head", children: [
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("h2", { children: "Pending transactions" }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "panel__count", children: displayMempoolCount })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "list", children: mempool.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "list__empty", children: nodeHealthy ? "No pending transactions" : "Empty until the node is running" }) : mempool.map((tx) => /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "list-item", children: [
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "list-item__row", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { className: "list-item__main", title: String(tx.fromAddress || ""), children: [
            shortAddr(tx.fromAddress, 5),
            " \u2192 ",
            shortAddr(tx.toAddress, 5)
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "list-item__amounts", children: [
            /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { children: [
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "muted", children: "amount " }),
              tx.amount ?? "\u2014"
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { children: [
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "muted", children: "fee " }),
              tx.fee ?? "\u2014"
            ] })
          ] })
        ] }, String(tx.id ?? tx.txHash))) })
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("details", { className: "advanced", children: [
      /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("summary", { children: [
        "Advanced",
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "advanced__hint", children: "Network settings, diagnostics & logs" })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "advanced__body", children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "advanced__section", children: [
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("h3", { children: "Browser readiness" }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "checks-grid", children: [
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Stat, { label: "Isolation", value: isolated ? "OK" : "Missing" }),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Stat, { label: "Shared memory", value: sab ? "OK" : "Missing" }),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Stat, { label: "Storage", value: opfsOk ? "OK" : "Missing" }),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Stat, { label: "Mode", value: "Full node" })
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "advanced__section", children: [
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("h3", { children: "Public network" }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("p", { className: "muted small", style: { margin: "0 0 0.5rem" }, children: [
            "Connected via ",
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: OFFICIAL1.name }),
            bridgeHttp.state === "ok" && bridgeHttp.height != null ? ` \xB7 network height #${bridgeHttp.height}` : ""
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "status-row", children: [
            /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "status-card", children: [
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "label", children: "Network HTTP" }),
              /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { children: [
                bridgeHttp.state === "ok" && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
                  "OK",
                  bridgeHttp.height != null ? ` \xB7 #${bridgeHttp.height}` : ""
                ] }),
                bridgeHttp.state === "bad" && `Down \xB7 ${bridgeHttp.error}`,
                bridgeHttp.state === "checking" && "Checking\u2026",
                bridgeHttp.state === "idle" && "\u2014"
              ] })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "status-card", children: [
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "label", children: "P2P bridge" }),
              /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { children: [
                bridgeWs.state === "ok" && `Open \xB7 ${bridgeWs.openedMs ?? "?"}ms`,
                bridgeWs.state === "bad" && `Not ready \xB7 ${bridgeWs.detail}`,
                bridgeWs.state === "skipped" && "Not probed (safer)",
                bridgeWs.state === "checking" && "Checking\u2026",
                bridgeWs.state === "idle" && "\u2014"
              ] })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
              "div",
              {
                className: "status-card",
                title: "Official1 dashboard WebSocket only \u2014 not used by this full node. See docs/TRANSACTIONS.md",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "label", children: "RPC stream" }),
                  /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { children: [
                    bridgeStream.state === "ok" && `Open \xB7 ${bridgeStream.openedMs ?? "?"}ms`,
                    bridgeStream.state === "bad" && `Fail \xB7 ${bridgeStream.detail}`,
                    bridgeStream.state === "skipped" && "Optional \xB7 not used",
                    bridgeStream.state === "checking" && "Checking\u2026",
                    bridgeStream.state === "idle" && "\u2014"
                  ] })
                ]
              }
            )
          ] }),
          bridgeHttp.state === "bad" && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "dash__error", style: { marginTop: "0.5rem" }, children: [
            "Network probe failed (",
            bridgeHttp.error,
            "). Starting the node may still work."
          ] }),
          bridgeWs.state === "bad" && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "dash__error", style: { marginTop: "0.5rem" }, children: [
            "Bridge probe failed for ",
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { className: "mono", children: wsPeers || OFFICIAL1.wsBridge }),
            bridgeWs.detail ? ` (${bridgeWs.detail})` : "",
            ". You can still try Start if the browser is Ready."
          ] })
        ] }),
        chain && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "advanced__section", children: [
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("h3", { children: "Chain detail" }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "chain-grid", children: [
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Stat, { label: "Height", value: String(chain.height) }),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Stat, { label: "Difficulty", value: formatHashrate(chain.difficulty) }),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Stat, { label: "Worksum", value: formatHashrate(chain.worksum) })
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "advanced__section", children: [
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("h3", { children: "Peer endpoints (multi-peer)" }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("p", { className: "muted small", style: { margin: "0 0 0.5rem" }, children: [
            "Semicolon-separated ",
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { children: "wss://\u2026/ws" }),
            " URLs. More bridges = more parallel block batches. WebRTC is enabled so Official1 can also introduce extra peers after connect."
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "controls__custom", children: [
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
              "input",
              {
                type: "text",
                value: peersInput,
                onChange: (e3) => setPeersInput(e3.target.value),
                disabled: running || starting,
                placeholder: `${OFFICIAL1.wsBridge};wss://other-bridge/ws`,
                "aria-label": "WebSocket peer URLs"
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "controls__actions", children: [
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { type: "button", className: "btn", onClick: applyPeers, disabled: running || starting, children: "Save" }),
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { type: "button", className: "btn btn--ghost", onClick: useOfficial1, disabled: running || starting, children: "Official1" }),
              isLocalDevHost() && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { type: "button", className: "btn btn--ghost", onClick: useLocalProxy, disabled: running || starting, children: "Local proxy" })
            ] })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "controls__meta", style: { marginTop: "0.5rem" }, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { className: "mono muted small", title: wsPeers, children: [
            "WS_PEERS (",
            configuredPeerCount,
            ")=",
            wsPeers
          ] }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "advanced__section", children: [
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("h3", { children: "Chain snapshot" }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("p", { className: "muted small", style: { margin: "0 0 0.65rem" }, children: [
            "Skip most of genesis\u2192tip, then Start to catch up. Local:",
            " ",
            localDbInfo?.present ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: formatBytes(localDbInfo.bytes) }) : /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("em", { children: "none" }),
            publicSnapshot?.height != null ? /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
              " \xB7 ",
              "Site offer:",
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("strong", { children: [
                "h",
                Number(publicSnapshot.height).toLocaleString()
              ] }),
              " ",
              "(",
              formatBytes(publicSnapshot.bytes || 0),
              ")"
            ] }) : /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
              " \xB7 ",
              "Site offer: ",
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("em", { children: "none on this host" }),
              " ",
              "(use Choose file or a CDN URL)"
            ] })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "controls__actions", style: { flexWrap: "wrap", gap: "0.5rem" }, children: [
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
              "button",
              {
                type: "button",
                className: "btn",
                onClick: importPublicSnapshot,
                disabled: !canImportSiteSnapshot,
                title: publicSnapshot ? void 0 : "No reachable site snapshot (Netlify does not ship multi\u2011GB chain.db3)",
                children: snapshotBusy ? "Importing\u2026" : "Import site snapshot"
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("label", { className: "btn btn--ghost", style: { cursor: canImportPublicSnapshot ? "pointer" : "not-allowed" }, children: [
              "Choose file\u2026",
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
                "input",
                {
                  ref: snapshotFileRef,
                  type: "file",
                  accept: ".db3,application/octet-stream",
                  disabled: !canImportPublicSnapshot,
                  style: { display: "none" },
                  onChange: (e3) => {
                    const f = e3.target.files?.[0];
                    if (f) importSnapshotFile(f);
                  },
                  "aria-label": "Import chain.db3 file"
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "controls__custom", style: { marginTop: "0.65rem" }, children: [
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
              "input",
              {
                type: "url",
                value: snapshotUrl,
                onChange: (e3) => setSnapshotUrl(e3.target.value),
                disabled: running || starting || stopping || snapshotBusy,
                placeholder: "Or paste URL\u2026",
                "aria-label": "Snapshot URL"
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "controls__actions", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
              "button",
              {
                type: "button",
                className: "btn btn--ghost",
                onClick: () => importSnapshotUrl(),
                disabled: !canImportPublicSnapshot || !snapshotUrl.trim(),
                children: "Import URL"
              }
            ) })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("p", { className: "muted small", style: { margin: "0.5rem 0 0" }, children: [
            "Own file must be checkpointed DELETE-mode ",
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { children: "chain.db3" }),
            " only (no ",
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { children: "-wal" }),
            "). Local dev: ",
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { children: "npm run snapshot:link" }),
            ". Production: host the .db3 on a CDN/VPS with",
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { children: "Cross-Origin-Resource-Policy" }),
            " and set ",
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { children: "PUBLIC_SNAPSHOT_URL" }),
            " ",
            "or ",
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { children: "manifest.url" }),
            " \u2014 do not force-deploy multi\u2011GB to Netlify."
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "advanced__section", children: [
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("h3", { children: "Tools" }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "controls__actions", children: [
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
              "button",
              {
                type: "button",
                className: "btn btn--ghost",
                onClick: () => runBridgeProbes(wsPeers, { probeP2pWs: false, probeStream: false }),
                disabled: running || starting,
                children: "Re-check network"
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
              "button",
              {
                type: "button",
                className: "btn btn--ghost",
                onClick: testRawWs,
                disabled: running || starting,
                title: "Open WebSocket only \u2014 burns public /ws slot if pointed at Official1",
                children: "Test connection"
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
              "button",
              {
                type: "button",
                className: "btn btn--ghost",
                onClick: () => runBridgeProbes(wsPeers, { probeP2pWs: true }),
                disabled: running || starting,
                title: "Opens P2P /ws \u2014 burns Official1 per-IP slot for ~30s",
                children: "Probe P2P (caution)"
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
              "button",
              {
                type: "button",
                className: "btn btn--ghost",
                onClick: clearOpfs,
                disabled: !canClearOpfs,
                title: "Delete local chain databases for this site",
                children: clearingOpfs ? "Clearing\u2026" : "Clear local data"
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
              "button",
              {
                type: "button",
                className: "btn btn--danger-ghost",
                onClick: recoverOpfs,
                disabled: starting || clearingOpfs || !opfsOk,
                title: "Clear storage and reload the page",
                children: "Recover & reload"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("details", { className: "dash__help", children: [
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("summary", { children: "For operators (VPS / nginx)" }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("ol", { className: "dash__checklist", children: [
            /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("li", { children: [
              "Browser needs isolation headers (COOP/COEP), WASM under",
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { className: "mono", children: "/node/" }),
              ", and",
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { className: "mono", children: "WS_PEERS=wss://\u2026/ws" }),
              "."
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("li", { children: [
              "Node flags:",
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { className: "mono", children: OFFICIAL1.flags?.join(" ") || "\u2014" })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("li", { children: [
              "Nginx: proxy ",
              /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { className: "mono", children: "/ws" }),
              " to localhost with Upgrade + X-Forwarded-For."
            ] })
          ] })
        ] })
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("section", { className: "panel", children: [
      /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "panel__head", children: [
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("h2", { children: "Activity log" }),
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "panel__count muted small", title: status, children: status })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
        "textarea",
        {
          ref: consoleRef,
          className: "console",
          readOnly: true,
          value: logLines.join("\n"),
          spellCheck: false,
          "aria-label": "Node console log"
        }
      )
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("footer", { className: "dash__footer", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { children: "A full Warthog node runs inside this browser tab via WebAssembly. Leave the tab open while it syncs and stays connected." }) })
  ] });
}
function Stat({ label, value }) {
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "stat", children: [
    /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "stat__label", children: label }),
    /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "stat__value", children: value })
  ] });
}

// scripts/extension-entry.jsx
var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1);
var isPopup = /popup\.html$/i.test(location.pathname);
var isSide = /sidepanel\.html$/i.test(location.pathname);
document.documentElement.classList.add("extension-shell");
if (isPopup) {
  document.documentElement.classList.add("extension-popup");
  document.body.classList.add("extension-popup");
} else if (isSide) {
  document.documentElement.classList.add("extension-sidepanel");
  document.body.classList.add("extension-sidepanel");
} else {
  document.documentElement.classList.add("extension-tab");
  document.body.classList.add("extension-tab");
}
var root = document.getElementById("root");
if (!root) {
  throw new Error("#root missing \u2014 popup/node.html is incomplete");
}
(0, import_client.createRoot)(root).render(/* @__PURE__ */ (0, import_jsx_runtime4.jsx)(WasmBrowserNode, {}));
/*! Bundled license information:

react/cjs/react.production.min.js:
  (**
   * @license React
   * react.production.min.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

scheduler/cjs/scheduler.production.min.js:
  (**
   * @license React
   * scheduler.production.min.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

react-dom/cjs/react-dom.production.min.js:
  (**
   * @license React
   * react-dom.production.min.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

@noble/hashes/esm/utils.js:
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)

@noble/curves/esm/utils.js:
@noble/curves/esm/abstract/modular.js:
@noble/curves/esm/abstract/curve.js:
@noble/curves/esm/abstract/weierstrass.js:
@noble/curves/esm/_shortw_utils.js:
@noble/curves/esm/secp256k1.js:
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)

react/cjs/react-jsx-runtime.production.min.js:
  (**
   * @license React
   * react-jsx-runtime.production.min.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)
*/
