"use strict";
(() => {
  var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, {
    get: (a, b2) => (typeof require !== "undefined" ? require : a)[b2]
  }) : x2)(function(x2) {
    if (typeof require !== "undefined") return require.apply(this, arguments);
    throw Error('Dynamic require of "' + x2 + '" is not supported');
  });

  // ../../node_modules/.pnpm/@r-wasm+webr@0.2.0_@xterm+xterm@6.0.0_classnames@2.5.1_prop-types@15.8.1/node_modules/@r-wasm/webr/dist/webr.mjs
  var In = Object.create;
  var Ir = Object.defineProperty;
  var Un = Object.getOwnPropertyDescriptor;
  var Cn = Object.getOwnPropertyNames;
  var jn = Object.getPrototypeOf;
  var Nn = Object.prototype.hasOwnProperty;
  var H = ((r) => typeof __require < "u" ? __require : typeof Proxy < "u" ? new Proxy(r, { get: (e, t) => (typeof __require < "u" ? __require : e)[t] }) : r)(function(r) {
    if (typeof __require < "u") return __require.apply(this, arguments);
    throw new Error('Dynamic require of "' + r + '" is not supported');
  });
  var P = (r, e) => () => (e || r((e = { exports: {} }).exports, e), e.exports);
  var Bn = (r, e, t, n) => {
    if (e && typeof e == "object" || typeof e == "function") for (let s of Cn(e)) !Nn.call(r, s) && s !== t && Ir(r, s, { get: () => e[s], enumerable: !(n = Un(e, s)) || n.enumerable });
    return r;
  };
  var Y = (r, e, t) => (t = r != null ? In(jn(r)) : {}, Bn(e || !r || !r.__esModule ? Ir(t, "default", { value: r, enumerable: true }) : t, r));
  var Qt = (r, e, t) => {
    if (!e.has(r)) throw TypeError("Cannot " + t);
  };
  var i = (r, e, t) => (Qt(r, e, "read from private field"), t ? t.call(r) : e.get(r));
  var u = (r, e, t) => {
    if (e.has(r)) throw TypeError("Cannot add the same private member more than once");
    e instanceof WeakSet ? e.add(r) : e.set(r, t);
  };
  var h = (r, e, t, n) => (Qt(r, e, "write to private field"), n ? n.call(r, t) : e.set(r, t), t);
  var v = (r, e, t) => (Qt(r, e, "access private method"), t);
  var _e = P((O) => {
    "use strict";
    Object.defineProperty(O, "__esModule", { value: true });
    O.getUint64 = O.getInt64 = O.setInt64 = O.setUint64 = O.UINT32_MAX = void 0;
    O.UINT32_MAX = 4294967295;
    function qn(r, e, t) {
      let n = t / 4294967296, s = t;
      r.setUint32(e, n), r.setUint32(e + 4, s);
    }
    O.setUint64 = qn;
    function Vn(r, e, t) {
      let n = Math.floor(t / 4294967296), s = t;
      r.setUint32(e, n), r.setUint32(e + 4, s);
    }
    O.setInt64 = Vn;
    function Jn(r, e) {
      let t = r.getInt32(e), n = r.getUint32(e + 4);
      return t * 4294967296 + n;
    }
    O.getInt64 = Jn;
    function Hn(r, e) {
      let t = r.getUint32(e), n = r.getUint32(e + 4);
      return t * 4294967296 + n;
    }
    O.getUint64 = Hn;
  });
  var at = P((_) => {
    "use strict";
    var Yt, er, tr;
    Object.defineProperty(_, "__esModule", { value: true });
    _.utf8DecodeTD = _.TEXT_DECODER_THRESHOLD = _.utf8DecodeJs = _.utf8EncodeTE = _.TEXT_ENCODER_THRESHOLD = _.utf8EncodeJs = _.utf8Count = void 0;
    var jr = _e(), it = (typeof process > "u" || ((Yt = process == null ? void 0 : process.env) === null || Yt === void 0 ? void 0 : Yt.TEXT_ENCODING) !== "never") && typeof TextEncoder < "u" && typeof TextDecoder < "u";
    function zn(r) {
      let e = r.length, t = 0, n = 0;
      for (; n < e; ) {
        let s = r.charCodeAt(n++);
        if (s & 4294967168) if (!(s & 4294965248)) t += 2;
        else {
          if (s >= 55296 && s <= 56319 && n < e) {
            let o = r.charCodeAt(n);
            (o & 64512) === 56320 && (++n, s = ((s & 1023) << 10) + (o & 1023) + 65536);
          }
          s & 4294901760 ? t += 4 : t += 3;
        }
        else {
          t++;
          continue;
        }
      }
      return t;
    }
    _.utf8Count = zn;
    function Xn(r, e, t) {
      let n = r.length, s = t, o = 0;
      for (; o < n; ) {
        let a = r.charCodeAt(o++);
        if (a & 4294967168) if (!(a & 4294965248)) e[s++] = a >> 6 & 31 | 192;
        else {
          if (a >= 55296 && a <= 56319 && o < n) {
            let c = r.charCodeAt(o);
            (c & 64512) === 56320 && (++o, a = ((a & 1023) << 10) + (c & 1023) + 65536);
          }
          a & 4294901760 ? (e[s++] = a >> 18 & 7 | 240, e[s++] = a >> 12 & 63 | 128, e[s++] = a >> 6 & 63 | 128) : (e[s++] = a >> 12 & 15 | 224, e[s++] = a >> 6 & 63 | 128);
        }
        else {
          e[s++] = a;
          continue;
        }
        e[s++] = a & 63 | 128;
      }
    }
    _.utf8EncodeJs = Xn;
    var Se = it ? new TextEncoder() : void 0;
    _.TEXT_ENCODER_THRESHOLD = it ? typeof process < "u" && ((er = process == null ? void 0 : process.env) === null || er === void 0 ? void 0 : er.TEXT_ENCODING) !== "force" ? 200 : 0 : jr.UINT32_MAX;
    function Gn(r, e, t) {
      e.set(Se.encode(r), t);
    }
    function $n(r, e, t) {
      Se.encodeInto(r, e.subarray(t));
    }
    _.utf8EncodeTE = Se != null && Se.encodeInto ? $n : Gn;
    var Kn = 4096;
    function Qn(r, e, t) {
      let n = e, s = n + t, o = [], a = "";
      for (; n < s; ) {
        let c = r[n++];
        if (!(c & 128)) o.push(c);
        else if ((c & 224) === 192) {
          let p = r[n++] & 63;
          o.push((c & 31) << 6 | p);
        } else if ((c & 240) === 224) {
          let p = r[n++] & 63, w = r[n++] & 63;
          o.push((c & 31) << 12 | p << 6 | w);
        } else if ((c & 248) === 240) {
          let p = r[n++] & 63, w = r[n++] & 63, Z = r[n++] & 63, J = (c & 7) << 18 | p << 12 | w << 6 | Z;
          J > 65535 && (J -= 65536, o.push(J >>> 10 & 1023 | 55296), J = 56320 | J & 1023), o.push(J);
        } else o.push(c);
        o.length >= Kn && (a += String.fromCharCode(...o), o.length = 0);
      }
      return o.length > 0 && (a += String.fromCharCode(...o)), a;
    }
    _.utf8DecodeJs = Qn;
    var Zn = it ? new TextDecoder() : null;
    _.TEXT_DECODER_THRESHOLD = it ? typeof process < "u" && ((tr = process == null ? void 0 : process.env) === null || tr === void 0 ? void 0 : tr.TEXT_DECODER) !== "force" ? 200 : 0 : jr.UINT32_MAX;
    function Yn(r, e, t) {
      let n = r.subarray(e, e + t);
      return Zn.decode(n);
    }
    _.utf8DecodeTD = Yn;
  });
  var nr = P((lt) => {
    "use strict";
    Object.defineProperty(lt, "__esModule", { value: true });
    lt.ExtData = void 0;
    var rr = class {
      constructor(e, t) {
        this.type = e, this.data = t;
      }
    };
    lt.ExtData = rr;
  });
  var ut = P((ct) => {
    "use strict";
    Object.defineProperty(ct, "__esModule", { value: true });
    ct.DecodeError = void 0;
    var ue = class extends Error {
      constructor(e) {
        super(e);
        let t = Object.create(ue.prototype);
        Object.setPrototypeOf(this, t), Object.defineProperty(this, "name", { configurable: true, enumerable: false, value: ue.name });
      }
    };
    ct.DecodeError = ue;
  });
  var sr = P((T) => {
    "use strict";
    Object.defineProperty(T, "__esModule", { value: true });
    T.timestampExtension = T.decodeTimestampExtension = T.decodeTimestampToTimeSpec = T.encodeTimestampExtension = T.encodeDateToTimeSpec = T.encodeTimeSpecToTimestamp = T.EXT_TIMESTAMP = void 0;
    var es = ut(), Nr = _e();
    T.EXT_TIMESTAMP = -1;
    var ts = 4294967296 - 1, rs = 17179869184 - 1;
    function Br({ sec: r, nsec: e }) {
      if (r >= 0 && e >= 0 && r <= rs) if (e === 0 && r <= ts) {
        let t = new Uint8Array(4);
        return new DataView(t.buffer).setUint32(0, r), t;
      } else {
        let t = r / 4294967296, n = r & 4294967295, s = new Uint8Array(8), o = new DataView(s.buffer);
        return o.setUint32(0, e << 2 | t & 3), o.setUint32(4, n), s;
      }
      else {
        let t = new Uint8Array(12), n = new DataView(t.buffer);
        return n.setUint32(0, e), (0, Nr.setInt64)(n, 4, r), t;
      }
    }
    T.encodeTimeSpecToTimestamp = Br;
    function Lr(r) {
      let e = r.getTime(), t = Math.floor(e / 1e3), n = (e - t * 1e3) * 1e6, s = Math.floor(n / 1e9);
      return { sec: t + s, nsec: n - s * 1e9 };
    }
    T.encodeDateToTimeSpec = Lr;
    function Fr(r) {
      if (r instanceof Date) {
        let e = Lr(r);
        return Br(e);
      } else return null;
    }
    T.encodeTimestampExtension = Fr;
    function qr(r) {
      let e = new DataView(r.buffer, r.byteOffset, r.byteLength);
      switch (r.byteLength) {
        case 4:
          return { sec: e.getUint32(0), nsec: 0 };
        case 8: {
          let t = e.getUint32(0), n = e.getUint32(4), s = (t & 3) * 4294967296 + n, o = t >>> 2;
          return { sec: s, nsec: o };
        }
        case 12: {
          let t = (0, Nr.getInt64)(e, 4), n = e.getUint32(0);
          return { sec: t, nsec: n };
        }
        default:
          throw new es.DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${r.length}`);
      }
    }
    T.decodeTimestampToTimeSpec = qr;
    function Vr(r) {
      let e = qr(r);
      return new Date(e.sec * 1e3 + e.nsec / 1e6);
    }
    T.decodeTimestampExtension = Vr;
    T.timestampExtension = { type: T.EXT_TIMESTAMP, encode: Fr, decode: Vr };
  });
  var ht = P((dt) => {
    "use strict";
    Object.defineProperty(dt, "__esModule", { value: true });
    dt.ExtensionCodec = void 0;
    var pt = nr(), ns = sr(), ke = class {
      constructor() {
        this.builtInEncoders = [], this.builtInDecoders = [], this.encoders = [], this.decoders = [], this.register(ns.timestampExtension);
      }
      register({ type: e, encode: t, decode: n }) {
        if (e >= 0) this.encoders[e] = t, this.decoders[e] = n;
        else {
          let s = 1 + e;
          this.builtInEncoders[s] = t, this.builtInDecoders[s] = n;
        }
      }
      tryToEncode(e, t) {
        for (let n = 0; n < this.builtInEncoders.length; n++) {
          let s = this.builtInEncoders[n];
          if (s != null) {
            let o = s(e, t);
            if (o != null) {
              let a = -1 - n;
              return new pt.ExtData(a, o);
            }
          }
        }
        for (let n = 0; n < this.encoders.length; n++) {
          let s = this.encoders[n];
          if (s != null) {
            let o = s(e, t);
            if (o != null) {
              let a = n;
              return new pt.ExtData(a, o);
            }
          }
        }
        return e instanceof pt.ExtData ? e : null;
      }
      decode(e, t, n) {
        let s = t < 0 ? this.builtInDecoders[-1 - t] : this.decoders[t];
        return s ? s(e, t, n) : new pt.ExtData(t, e);
      }
    };
    dt.ExtensionCodec = ke;
    ke.defaultCodec = new ke();
  });
  var or = P((pe) => {
    "use strict";
    Object.defineProperty(pe, "__esModule", { value: true });
    pe.createDataView = pe.ensureUint8Array = void 0;
    function Jr(r) {
      return r instanceof Uint8Array ? r : ArrayBuffer.isView(r) ? new Uint8Array(r.buffer, r.byteOffset, r.byteLength) : r instanceof ArrayBuffer ? new Uint8Array(r) : Uint8Array.from(r);
    }
    pe.ensureUint8Array = Jr;
    function ss(r) {
      if (r instanceof ArrayBuffer) return new DataView(r);
      let e = Jr(r);
      return new DataView(e.buffer, e.byteOffset, e.byteLength);
    }
    pe.createDataView = ss;
  });
  var ar = P((U) => {
    "use strict";
    Object.defineProperty(U, "__esModule", { value: true });
    U.Encoder = U.DEFAULT_INITIAL_BUFFER_SIZE = U.DEFAULT_MAX_DEPTH = void 0;
    var De = at(), os = ht(), Hr = _e(), is = or();
    U.DEFAULT_MAX_DEPTH = 100;
    U.DEFAULT_INITIAL_BUFFER_SIZE = 2048;
    var ir = class {
      constructor(e = os.ExtensionCodec.defaultCodec, t = void 0, n = U.DEFAULT_MAX_DEPTH, s = U.DEFAULT_INITIAL_BUFFER_SIZE, o = false, a = false, c = false, p = false) {
        this.extensionCodec = e, this.context = t, this.maxDepth = n, this.initialBufferSize = s, this.sortKeys = o, this.forceFloat32 = a, this.ignoreUndefined = c, this.forceIntegerToFloat = p, this.pos = 0, this.view = new DataView(new ArrayBuffer(this.initialBufferSize)), this.bytes = new Uint8Array(this.view.buffer);
      }
      reinitializeState() {
        this.pos = 0;
      }
      encodeSharedRef(e) {
        return this.reinitializeState(), this.doEncode(e, 1), this.bytes.subarray(0, this.pos);
      }
      encode(e) {
        return this.reinitializeState(), this.doEncode(e, 1), this.bytes.slice(0, this.pos);
      }
      doEncode(e, t) {
        if (t > this.maxDepth) throw new Error(`Too deep objects in depth ${t}`);
        e == null ? this.encodeNil() : typeof e == "boolean" ? this.encodeBoolean(e) : typeof e == "number" ? this.encodeNumber(e) : typeof e == "string" ? this.encodeString(e) : this.encodeObject(e, t);
      }
      ensureBufferSizeToWrite(e) {
        let t = this.pos + e;
        this.view.byteLength < t && this.resizeBuffer(t * 2);
      }
      resizeBuffer(e) {
        let t = new ArrayBuffer(e), n = new Uint8Array(t), s = new DataView(t);
        n.set(this.bytes), this.view = s, this.bytes = n;
      }
      encodeNil() {
        this.writeU8(192);
      }
      encodeBoolean(e) {
        e === false ? this.writeU8(194) : this.writeU8(195);
      }
      encodeNumber(e) {
        Number.isSafeInteger(e) && !this.forceIntegerToFloat ? e >= 0 ? e < 128 ? this.writeU8(e) : e < 256 ? (this.writeU8(204), this.writeU8(e)) : e < 65536 ? (this.writeU8(205), this.writeU16(e)) : e < 4294967296 ? (this.writeU8(206), this.writeU32(e)) : (this.writeU8(207), this.writeU64(e)) : e >= -32 ? this.writeU8(224 | e + 32) : e >= -128 ? (this.writeU8(208), this.writeI8(e)) : e >= -32768 ? (this.writeU8(209), this.writeI16(e)) : e >= -2147483648 ? (this.writeU8(210), this.writeI32(e)) : (this.writeU8(211), this.writeI64(e)) : this.forceFloat32 ? (this.writeU8(202), this.writeF32(e)) : (this.writeU8(203), this.writeF64(e));
      }
      writeStringHeader(e) {
        if (e < 32) this.writeU8(160 + e);
        else if (e < 256) this.writeU8(217), this.writeU8(e);
        else if (e < 65536) this.writeU8(218), this.writeU16(e);
        else if (e < 4294967296) this.writeU8(219), this.writeU32(e);
        else throw new Error(`Too long string: ${e} bytes in UTF-8`);
      }
      encodeString(e) {
        if (e.length > De.TEXT_ENCODER_THRESHOLD) {
          let s = (0, De.utf8Count)(e);
          this.ensureBufferSizeToWrite(5 + s), this.writeStringHeader(s), (0, De.utf8EncodeTE)(e, this.bytes, this.pos), this.pos += s;
        } else {
          let s = (0, De.utf8Count)(e);
          this.ensureBufferSizeToWrite(5 + s), this.writeStringHeader(s), (0, De.utf8EncodeJs)(e, this.bytes, this.pos), this.pos += s;
        }
      }
      encodeObject(e, t) {
        let n = this.extensionCodec.tryToEncode(e, this.context);
        if (n != null) this.encodeExtension(n);
        else if (Array.isArray(e)) this.encodeArray(e, t);
        else if (ArrayBuffer.isView(e)) this.encodeBinary(e);
        else if (typeof e == "object") this.encodeMap(e, t);
        else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`);
      }
      encodeBinary(e) {
        let t = e.byteLength;
        if (t < 256) this.writeU8(196), this.writeU8(t);
        else if (t < 65536) this.writeU8(197), this.writeU16(t);
        else if (t < 4294967296) this.writeU8(198), this.writeU32(t);
        else throw new Error(`Too large binary: ${t}`);
        let n = (0, is.ensureUint8Array)(e);
        this.writeU8a(n);
      }
      encodeArray(e, t) {
        let n = e.length;
        if (n < 16) this.writeU8(144 + n);
        else if (n < 65536) this.writeU8(220), this.writeU16(n);
        else if (n < 4294967296) this.writeU8(221), this.writeU32(n);
        else throw new Error(`Too large array: ${n}`);
        for (let s of e) this.doEncode(s, t + 1);
      }
      countWithoutUndefined(e, t) {
        let n = 0;
        for (let s of t) e[s] !== void 0 && n++;
        return n;
      }
      encodeMap(e, t) {
        let n = Object.keys(e);
        this.sortKeys && n.sort();
        let s = this.ignoreUndefined ? this.countWithoutUndefined(e, n) : n.length;
        if (s < 16) this.writeU8(128 + s);
        else if (s < 65536) this.writeU8(222), this.writeU16(s);
        else if (s < 4294967296) this.writeU8(223), this.writeU32(s);
        else throw new Error(`Too large map object: ${s}`);
        for (let o of n) {
          let a = e[o];
          this.ignoreUndefined && a === void 0 || (this.encodeString(o), this.doEncode(a, t + 1));
        }
      }
      encodeExtension(e) {
        let t = e.data.length;
        if (t === 1) this.writeU8(212);
        else if (t === 2) this.writeU8(213);
        else if (t === 4) this.writeU8(214);
        else if (t === 8) this.writeU8(215);
        else if (t === 16) this.writeU8(216);
        else if (t < 256) this.writeU8(199), this.writeU8(t);
        else if (t < 65536) this.writeU8(200), this.writeU16(t);
        else if (t < 4294967296) this.writeU8(201), this.writeU32(t);
        else throw new Error(`Too large extension object: ${t}`);
        this.writeI8(e.type), this.writeU8a(e.data);
      }
      writeU8(e) {
        this.ensureBufferSizeToWrite(1), this.view.setUint8(this.pos, e), this.pos++;
      }
      writeU8a(e) {
        let t = e.length;
        this.ensureBufferSizeToWrite(t), this.bytes.set(e, this.pos), this.pos += t;
      }
      writeI8(e) {
        this.ensureBufferSizeToWrite(1), this.view.setInt8(this.pos, e), this.pos++;
      }
      writeU16(e) {
        this.ensureBufferSizeToWrite(2), this.view.setUint16(this.pos, e), this.pos += 2;
      }
      writeI16(e) {
        this.ensureBufferSizeToWrite(2), this.view.setInt16(this.pos, e), this.pos += 2;
      }
      writeU32(e) {
        this.ensureBufferSizeToWrite(4), this.view.setUint32(this.pos, e), this.pos += 4;
      }
      writeI32(e) {
        this.ensureBufferSizeToWrite(4), this.view.setInt32(this.pos, e), this.pos += 4;
      }
      writeF32(e) {
        this.ensureBufferSizeToWrite(4), this.view.setFloat32(this.pos, e), this.pos += 4;
      }
      writeF64(e) {
        this.ensureBufferSizeToWrite(8), this.view.setFloat64(this.pos, e), this.pos += 8;
      }
      writeU64(e) {
        this.ensureBufferSizeToWrite(8), (0, Hr.setUint64)(this.view, this.pos, e), this.pos += 8;
      }
      writeI64(e) {
        this.ensureBufferSizeToWrite(8), (0, Hr.setInt64)(this.view, this.pos, e), this.pos += 8;
      }
    };
    U.Encoder = ir;
  });
  var zr = P((yt) => {
    "use strict";
    Object.defineProperty(yt, "__esModule", { value: true });
    yt.encode = void 0;
    var as = ar(), ls = {};
    function cs(r, e = ls) {
      return new as.Encoder(e.extensionCodec, e.context, e.maxDepth, e.initialBufferSize, e.sortKeys, e.forceFloat32, e.ignoreUndefined, e.forceIntegerToFloat).encodeSharedRef(r);
    }
    yt.encode = cs;
  });
  var Xr = P((ft) => {
    "use strict";
    Object.defineProperty(ft, "__esModule", { value: true });
    ft.prettyByte = void 0;
    function us(r) {
      return `${r < 0 ? "-" : ""}0x${Math.abs(r).toString(16).padStart(2, "0")}`;
    }
    ft.prettyByte = us;
  });
  var Gr = P((Rt) => {
    "use strict";
    Object.defineProperty(Rt, "__esModule", { value: true });
    Rt.CachedKeyDecoder = void 0;
    var ps = at(), ds = 16, hs = 16, lr = class {
      constructor(e = ds, t = hs) {
        this.maxKeyLength = e, this.maxLengthPerKey = t, this.hit = 0, this.miss = 0, this.caches = [];
        for (let n = 0; n < this.maxKeyLength; n++) this.caches.push([]);
      }
      canBeCached(e) {
        return e > 0 && e <= this.maxKeyLength;
      }
      find(e, t, n) {
        let s = this.caches[n - 1];
        e: for (let o of s) {
          let a = o.bytes;
          for (let c = 0; c < n; c++) if (a[c] !== e[t + c]) continue e;
          return o.str;
        }
        return null;
      }
      store(e, t) {
        let n = this.caches[e.length - 1], s = { bytes: e, str: t };
        n.length >= this.maxLengthPerKey ? n[Math.random() * n.length | 0] = s : n.push(s);
      }
      decode(e, t, n) {
        let s = this.find(e, t, n);
        if (s != null) return this.hit++, s;
        this.miss++;
        let o = (0, ps.utf8DecodeJs)(e, t, n), a = Uint8Array.prototype.slice.call(e, t, t + n);
        return this.store(a, o), o;
      }
    };
    Rt.CachedKeyDecoder = lr;
  });
  var mt = P((q) => {
    "use strict";
    Object.defineProperty(q, "__esModule", { value: true });
    q.Decoder = q.DataViewIndexOutOfBoundsError = void 0;
    var cr = Xr(), ys = ht(), ee = _e(), ur = at(), pr = or(), fs = Gr(), F = ut(), Rs = (r) => {
      let e = typeof r;
      return e === "string" || e === "number";
    }, We = -1, hr = new DataView(new ArrayBuffer(0)), ms = new Uint8Array(hr.buffer);
    q.DataViewIndexOutOfBoundsError = (() => {
      try {
        hr.getInt8(0);
      } catch (r) {
        return r.constructor;
      }
      throw new Error("never reached");
    })();
    var $r = new q.DataViewIndexOutOfBoundsError("Insufficient data"), gs = new fs.CachedKeyDecoder(), dr = class {
      constructor(e = ys.ExtensionCodec.defaultCodec, t = void 0, n = ee.UINT32_MAX, s = ee.UINT32_MAX, o = ee.UINT32_MAX, a = ee.UINT32_MAX, c = ee.UINT32_MAX, p = gs) {
        this.extensionCodec = e, this.context = t, this.maxStrLength = n, this.maxBinLength = s, this.maxArrayLength = o, this.maxMapLength = a, this.maxExtLength = c, this.keyDecoder = p, this.totalPos = 0, this.pos = 0, this.view = hr, this.bytes = ms, this.headByte = We, this.stack = [];
      }
      reinitializeState() {
        this.totalPos = 0, this.headByte = We, this.stack.length = 0;
      }
      setBuffer(e) {
        this.bytes = (0, pr.ensureUint8Array)(e), this.view = (0, pr.createDataView)(this.bytes), this.pos = 0;
      }
      appendBuffer(e) {
        if (this.headByte === We && !this.hasRemaining(1)) this.setBuffer(e);
        else {
          let t = this.bytes.subarray(this.pos), n = (0, pr.ensureUint8Array)(e), s = new Uint8Array(t.length + n.length);
          s.set(t), s.set(n, t.length), this.setBuffer(s);
        }
      }
      hasRemaining(e) {
        return this.view.byteLength - this.pos >= e;
      }
      createExtraByteError(e) {
        let { view: t, pos: n } = this;
        return new RangeError(`Extra ${t.byteLength - n} of ${t.byteLength} byte(s) found at buffer[${e}]`);
      }
      decode(e) {
        this.reinitializeState(), this.setBuffer(e);
        let t = this.doDecodeSync();
        if (this.hasRemaining(1)) throw this.createExtraByteError(this.pos);
        return t;
      }
      *decodeMulti(e) {
        for (this.reinitializeState(), this.setBuffer(e); this.hasRemaining(1); ) yield this.doDecodeSync();
      }
      async decodeAsync(e) {
        let t = false, n;
        for await (let c of e) {
          if (t) throw this.createExtraByteError(this.totalPos);
          this.appendBuffer(c);
          try {
            n = this.doDecodeSync(), t = true;
          } catch (p) {
            if (!(p instanceof q.DataViewIndexOutOfBoundsError)) throw p;
          }
          this.totalPos += this.pos;
        }
        if (t) {
          if (this.hasRemaining(1)) throw this.createExtraByteError(this.totalPos);
          return n;
        }
        let { headByte: s, pos: o, totalPos: a } = this;
        throw new RangeError(`Insufficient data in parsing ${(0, cr.prettyByte)(s)} at ${a} (${o} in the current buffer)`);
      }
      decodeArrayStream(e) {
        return this.decodeMultiAsync(e, true);
      }
      decodeStream(e) {
        return this.decodeMultiAsync(e, false);
      }
      async *decodeMultiAsync(e, t) {
        let n = t, s = -1;
        for await (let o of e) {
          if (t && s === 0) throw this.createExtraByteError(this.totalPos);
          this.appendBuffer(o), n && (s = this.readArraySize(), n = false, this.complete());
          try {
            for (; yield this.doDecodeSync(), --s !== 0; ) ;
          } catch (a) {
            if (!(a instanceof q.DataViewIndexOutOfBoundsError)) throw a;
          }
          this.totalPos += this.pos;
        }
      }
      doDecodeSync() {
        e: for (; ; ) {
          let e = this.readHeadByte(), t;
          if (e >= 224) t = e - 256;
          else if (e < 192) if (e < 128) t = e;
          else if (e < 144) {
            let s = e - 128;
            if (s !== 0) {
              this.pushMapState(s), this.complete();
              continue e;
            } else t = {};
          } else if (e < 160) {
            let s = e - 144;
            if (s !== 0) {
              this.pushArrayState(s), this.complete();
              continue e;
            } else t = [];
          } else {
            let s = e - 160;
            t = this.decodeUtf8String(s, 0);
          }
          else if (e === 192) t = null;
          else if (e === 194) t = false;
          else if (e === 195) t = true;
          else if (e === 202) t = this.readF32();
          else if (e === 203) t = this.readF64();
          else if (e === 204) t = this.readU8();
          else if (e === 205) t = this.readU16();
          else if (e === 206) t = this.readU32();
          else if (e === 207) t = this.readU64();
          else if (e === 208) t = this.readI8();
          else if (e === 209) t = this.readI16();
          else if (e === 210) t = this.readI32();
          else if (e === 211) t = this.readI64();
          else if (e === 217) {
            let s = this.lookU8();
            t = this.decodeUtf8String(s, 1);
          } else if (e === 218) {
            let s = this.lookU16();
            t = this.decodeUtf8String(s, 2);
          } else if (e === 219) {
            let s = this.lookU32();
            t = this.decodeUtf8String(s, 4);
          } else if (e === 220) {
            let s = this.readU16();
            if (s !== 0) {
              this.pushArrayState(s), this.complete();
              continue e;
            } else t = [];
          } else if (e === 221) {
            let s = this.readU32();
            if (s !== 0) {
              this.pushArrayState(s), this.complete();
              continue e;
            } else t = [];
          } else if (e === 222) {
            let s = this.readU16();
            if (s !== 0) {
              this.pushMapState(s), this.complete();
              continue e;
            } else t = {};
          } else if (e === 223) {
            let s = this.readU32();
            if (s !== 0) {
              this.pushMapState(s), this.complete();
              continue e;
            } else t = {};
          } else if (e === 196) {
            let s = this.lookU8();
            t = this.decodeBinary(s, 1);
          } else if (e === 197) {
            let s = this.lookU16();
            t = this.decodeBinary(s, 2);
          } else if (e === 198) {
            let s = this.lookU32();
            t = this.decodeBinary(s, 4);
          } else if (e === 212) t = this.decodeExtension(1, 0);
          else if (e === 213) t = this.decodeExtension(2, 0);
          else if (e === 214) t = this.decodeExtension(4, 0);
          else if (e === 215) t = this.decodeExtension(8, 0);
          else if (e === 216) t = this.decodeExtension(16, 0);
          else if (e === 199) {
            let s = this.lookU8();
            t = this.decodeExtension(s, 1);
          } else if (e === 200) {
            let s = this.lookU16();
            t = this.decodeExtension(s, 2);
          } else if (e === 201) {
            let s = this.lookU32();
            t = this.decodeExtension(s, 4);
          } else throw new F.DecodeError(`Unrecognized type byte: ${(0, cr.prettyByte)(e)}`);
          this.complete();
          let n = this.stack;
          for (; n.length > 0; ) {
            let s = n[n.length - 1];
            if (s.type === 0) if (s.array[s.position] = t, s.position++, s.position === s.size) n.pop(), t = s.array;
            else continue e;
            else if (s.type === 1) {
              if (!Rs(t)) throw new F.DecodeError("The type of key must be string or number but " + typeof t);
              if (t === "__proto__") throw new F.DecodeError("The key __proto__ is not allowed");
              s.key = t, s.type = 2;
              continue e;
            } else if (s.map[s.key] = t, s.readCount++, s.readCount === s.size) n.pop(), t = s.map;
            else {
              s.key = null, s.type = 1;
              continue e;
            }
          }
          return t;
        }
      }
      readHeadByte() {
        return this.headByte === We && (this.headByte = this.readU8()), this.headByte;
      }
      complete() {
        this.headByte = We;
      }
      readArraySize() {
        let e = this.readHeadByte();
        switch (e) {
          case 220:
            return this.readU16();
          case 221:
            return this.readU32();
          default: {
            if (e < 160) return e - 144;
            throw new F.DecodeError(`Unrecognized array type byte: ${(0, cr.prettyByte)(e)}`);
          }
        }
      }
      pushMapState(e) {
        if (e > this.maxMapLength) throw new F.DecodeError(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);
        this.stack.push({ type: 1, size: e, key: null, readCount: 0, map: {} });
      }
      pushArrayState(e) {
        if (e > this.maxArrayLength) throw new F.DecodeError(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);
        this.stack.push({ type: 0, size: e, array: new Array(e), position: 0 });
      }
      decodeUtf8String(e, t) {
        var n;
        if (e > this.maxStrLength) throw new F.DecodeError(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);
        if (this.bytes.byteLength < this.pos + t + e) throw $r;
        let s = this.pos + t, o;
        return this.stateIsMapKey() && (!((n = this.keyDecoder) === null || n === void 0) && n.canBeCached(e)) ? o = this.keyDecoder.decode(this.bytes, s, e) : e > ur.TEXT_DECODER_THRESHOLD ? o = (0, ur.utf8DecodeTD)(this.bytes, s, e) : o = (0, ur.utf8DecodeJs)(this.bytes, s, e), this.pos += t + e, o;
      }
      stateIsMapKey() {
        return this.stack.length > 0 ? this.stack[this.stack.length - 1].type === 1 : false;
      }
      decodeBinary(e, t) {
        if (e > this.maxBinLength) throw new F.DecodeError(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);
        if (!this.hasRemaining(e + t)) throw $r;
        let n = this.pos + t, s = this.bytes.subarray(n, n + e);
        return this.pos += t + e, s;
      }
      decodeExtension(e, t) {
        if (e > this.maxExtLength) throw new F.DecodeError(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);
        let n = this.view.getInt8(this.pos + t), s = this.decodeBinary(e, t + 1);
        return this.extensionCodec.decode(s, n, this.context);
      }
      lookU8() {
        return this.view.getUint8(this.pos);
      }
      lookU16() {
        return this.view.getUint16(this.pos);
      }
      lookU32() {
        return this.view.getUint32(this.pos);
      }
      readU8() {
        let e = this.view.getUint8(this.pos);
        return this.pos++, e;
      }
      readI8() {
        let e = this.view.getInt8(this.pos);
        return this.pos++, e;
      }
      readU16() {
        let e = this.view.getUint16(this.pos);
        return this.pos += 2, e;
      }
      readI16() {
        let e = this.view.getInt16(this.pos);
        return this.pos += 2, e;
      }
      readU32() {
        let e = this.view.getUint32(this.pos);
        return this.pos += 4, e;
      }
      readI32() {
        let e = this.view.getInt32(this.pos);
        return this.pos += 4, e;
      }
      readU64() {
        let e = (0, ee.getUint64)(this.view, this.pos);
        return this.pos += 8, e;
      }
      readI64() {
        let e = (0, ee.getInt64)(this.view, this.pos);
        return this.pos += 8, e;
      }
      readF32() {
        let e = this.view.getFloat32(this.pos);
        return this.pos += 4, e;
      }
      readF64() {
        let e = this.view.getFloat64(this.pos);
        return this.pos += 8, e;
      }
    };
    q.Decoder = dr;
  });
  var yr = P((C) => {
    "use strict";
    Object.defineProperty(C, "__esModule", { value: true });
    C.decodeMulti = C.decode = C.defaultDecodeOptions = void 0;
    var Kr = mt();
    C.defaultDecodeOptions = {};
    function bs(r, e = C.defaultDecodeOptions) {
      return new Kr.Decoder(e.extensionCodec, e.context, e.maxStrLength, e.maxBinLength, e.maxArrayLength, e.maxMapLength, e.maxExtLength).decode(r);
    }
    C.decode = bs;
    function ws(r, e = C.defaultDecodeOptions) {
      return new Kr.Decoder(e.extensionCodec, e.context, e.maxStrLength, e.maxBinLength, e.maxArrayLength, e.maxMapLength, e.maxExtLength).decodeMulti(r);
    }
    C.decodeMulti = ws;
  });
  var Yr = P((X) => {
    "use strict";
    Object.defineProperty(X, "__esModule", { value: true });
    X.ensureAsyncIterable = X.asyncIterableFromStream = X.isAsyncIterable = void 0;
    function Qr(r) {
      return r[Symbol.asyncIterator] != null;
    }
    X.isAsyncIterable = Qr;
    function xs(r) {
      if (r == null) throw new Error("Assertion Failure: value must not be null nor undefined");
    }
    async function* Zr(r) {
      let e = r.getReader();
      try {
        for (; ; ) {
          let { done: t, value: n } = await e.read();
          if (t) return;
          xs(n), yield n;
        }
      } finally {
        e.releaseLock();
      }
    }
    X.asyncIterableFromStream = Zr;
    function Es(r) {
      return Qr(r) ? r : Zr(r);
    }
    X.ensureAsyncIterable = Es;
  });
  var tn = P((j) => {
    "use strict";
    Object.defineProperty(j, "__esModule", { value: true });
    j.decodeStream = j.decodeMultiStream = j.decodeArrayStream = j.decodeAsync = void 0;
    var fr = mt(), Rr = Yr(), gt = yr();
    async function vs(r, e = gt.defaultDecodeOptions) {
      let t = (0, Rr.ensureAsyncIterable)(r);
      return new fr.Decoder(e.extensionCodec, e.context, e.maxStrLength, e.maxBinLength, e.maxArrayLength, e.maxMapLength, e.maxExtLength).decodeAsync(t);
    }
    j.decodeAsync = vs;
    function Ts(r, e = gt.defaultDecodeOptions) {
      let t = (0, Rr.ensureAsyncIterable)(r);
      return new fr.Decoder(e.extensionCodec, e.context, e.maxStrLength, e.maxBinLength, e.maxArrayLength, e.maxMapLength, e.maxExtLength).decodeArrayStream(t);
    }
    j.decodeArrayStream = Ts;
    function en(r, e = gt.defaultDecodeOptions) {
      let t = (0, Rr.ensureAsyncIterable)(r);
      return new fr.Decoder(e.extensionCodec, e.context, e.maxStrLength, e.maxBinLength, e.maxArrayLength, e.maxMapLength, e.maxExtLength).decodeStream(t);
    }
    j.decodeMultiStream = en;
    function Ps(r, e = gt.defaultDecodeOptions) {
      return en(r, e);
    }
    j.decodeStream = Ps;
  });
  var wt = P((d) => {
    "use strict";
    Object.defineProperty(d, "__esModule", { value: true });
    d.decodeTimestampExtension = d.encodeTimestampExtension = d.decodeTimestampToTimeSpec = d.encodeTimeSpecToTimestamp = d.encodeDateToTimeSpec = d.EXT_TIMESTAMP = d.ExtData = d.ExtensionCodec = d.Encoder = d.DataViewIndexOutOfBoundsError = d.DecodeError = d.Decoder = d.decodeStream = d.decodeMultiStream = d.decodeArrayStream = d.decodeAsync = d.decodeMulti = d.decode = d.encode = void 0;
    var _s = zr();
    Object.defineProperty(d, "encode", { enumerable: true, get: function() {
      return _s.encode;
    } });
    var rn = yr();
    Object.defineProperty(d, "decode", { enumerable: true, get: function() {
      return rn.decode;
    } });
    Object.defineProperty(d, "decodeMulti", { enumerable: true, get: function() {
      return rn.decodeMulti;
    } });
    var bt = tn();
    Object.defineProperty(d, "decodeAsync", { enumerable: true, get: function() {
      return bt.decodeAsync;
    } });
    Object.defineProperty(d, "decodeArrayStream", { enumerable: true, get: function() {
      return bt.decodeArrayStream;
    } });
    Object.defineProperty(d, "decodeMultiStream", { enumerable: true, get: function() {
      return bt.decodeMultiStream;
    } });
    Object.defineProperty(d, "decodeStream", { enumerable: true, get: function() {
      return bt.decodeStream;
    } });
    var nn = mt();
    Object.defineProperty(d, "Decoder", { enumerable: true, get: function() {
      return nn.Decoder;
    } });
    Object.defineProperty(d, "DataViewIndexOutOfBoundsError", { enumerable: true, get: function() {
      return nn.DataViewIndexOutOfBoundsError;
    } });
    var Ss = ut();
    Object.defineProperty(d, "DecodeError", { enumerable: true, get: function() {
      return Ss.DecodeError;
    } });
    var ks = ar();
    Object.defineProperty(d, "Encoder", { enumerable: true, get: function() {
      return ks.Encoder;
    } });
    var Ds = ht();
    Object.defineProperty(d, "ExtensionCodec", { enumerable: true, get: function() {
      return Ds.ExtensionCodec;
    } });
    var Ws = nr();
    Object.defineProperty(d, "ExtData", { enumerable: true, get: function() {
      return Ws.ExtData;
    } });
    var de = sr();
    Object.defineProperty(d, "EXT_TIMESTAMP", { enumerable: true, get: function() {
      return de.EXT_TIMESTAMP;
    } });
    Object.defineProperty(d, "encodeDateToTimeSpec", { enumerable: true, get: function() {
      return de.encodeDateToTimeSpec;
    } });
    Object.defineProperty(d, "encodeTimeSpecToTimestamp", { enumerable: true, get: function() {
      return de.encodeTimeSpecToTimestamp;
    } });
    Object.defineProperty(d, "decodeTimestampToTimeSpec", { enumerable: true, get: function() {
      return de.decodeTimestampToTimeSpec;
    } });
    Object.defineProperty(d, "encodeTimestampExtension", { enumerable: true, get: function() {
      return de.encodeTimestampExtension;
    } });
    Object.defineProperty(d, "decodeTimestampExtension", { enumerable: true, get: function() {
      return de.decodeTimestampExtension;
    } });
  });
  var M = class extends Error {
    constructor(e) {
      super(e), this.name = this.constructor.name, Object.setPrototypeOf(this, new.target.prototype);
    }
  };
  var rt = class extends M {
  };
  var D = class extends M {
  };
  var z = class extends M {
  };
  var x = typeof process < "u" && process.release && process.release.name === "node";
  var Zt;
  if (globalThis.document) Zt = (r) => new Promise((e, t) => {
    let n = document.createElement("script");
    n.src = r, n.onload = () => e(), n.onerror = t, document.head.appendChild(n);
  });
  else if (globalThis.importScripts) Zt = async (r) => {
    try {
      globalThis.importScripts(r);
    } catch (e) {
      if (e instanceof TypeError) await Promise.resolve().then(() => Y(H(r)));
      else throw e;
    }
  };
  else if (x) Zt = async (r) => {
    let e = (await Promise.resolve().then(() => Y(H("path")))).default;
    await Promise.resolve().then(() => Y(H(e.resolve(r))));
  };
  else throw new M("Cannot determine runtime environment");
  function le() {
    let r = { resolve: (t) => {
    }, reject: (t) => {
    }, promise: null }, e = new Promise((t, n) => {
      r.resolve = t, r.reject = n;
    });
    return r.promise = e, r;
  }
  function Ur(r) {
    return new Promise((e) => setTimeout(e, r));
  }
  function I(r, e, t, ...n) {
    return r === null || typeof r != "object" ? r : e(r) ? t(r, ...n) : Array.isArray(r) || ArrayBuffer.isView(r) ? r.map((s) => I(s, e, t, ...n)) : Object.fromEntries(Object.entries(r).map(([s, o], a) => [s, I(o, e, t, ...n)]));
  }
  function nt(r, e) {
    let t = new XMLHttpRequest();
    t.open("get", r, true), t.onload = () => {
      let n = new Worker(URL.createObjectURL(new Blob([t.responseText])));
      e(n);
    }, t.send();
  }
  function ce(r) {
    if (x) return false;
    let e = new URL(location.href), t = new URL(r, location.origin);
    return !(e.host === t.host && e.port === t.port && e.protocol === t.protocol);
  }
  var Ln = /* @__PURE__ */ new WeakMap();
  function Cr(r, e) {
    return Ln.set(r, e), r;
  }
  var st = 63;
  function ot() {
    let r = Array.from({ length: 4 }, Fn).join("-");
    if (r.length !== st) throw new Error("comlink internal error: UUID has the wrong length");
    return r;
  }
  function Fn() {
    let r = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16), e = 15 - r.length;
    return e > 0 && (r = Array.from({ length: e }, () => 0).join("") + r), r;
  }
  var on = Y(wt());
  var As = new TextEncoder();
  async function an(r, e, t) {
    try {
      let { taskId: n, sizeBuffer: s, dataBuffer: o, signalBuffer: a } = e, c = (0, on.encode)(t), p = c.length <= o.length;
      if (Atomics.store(s, 0, c.length), Atomics.store(s, 1, +p), !p) {
        let [w, Z] = Ms(r);
        o.set(As.encode(w)), await sn(a, n), o = (await Z).dataBuffer;
      }
      o.set(c), Atomics.store(s, 1, 1), await sn(a, n);
    } catch (n) {
      console.warn(n);
    }
  }
  function Ms(r) {
    let e = ot();
    return [e, new Promise((t) => {
      x ? r.once("message", (n) => {
        !n.id || n.id !== e || t(n);
      }) : r.addEventListener("message", function n(s) {
        !s.data || !s.data.id || s.data.id !== e || (r.removeEventListener("message", n), t(s.data));
      }), r.start && r.start();
    })];
  }
  async function sn(r, e) {
    let t = (e >> 1) % 32, n = 1;
    for (; Atomics.compareExchange(r, t + 1, 0, e) !== 0; ) await Ur(n), n < 32 && (n *= 2);
    Atomics.or(r, 0, 1 << t), Atomics.notify(r, 0);
  }
  var N;
  var B;
  var Ae;
  var mr;
  var he = class {
    constructor() {
      u(this, Ae);
      u(this, N, void 0);
      u(this, B, void 0);
      h(this, B, []), h(this, N, []);
    }
    reset() {
      h(this, B, []), h(this, N, []);
    }
    put(e) {
      i(this, B).length || v(this, Ae, mr).call(this), i(this, B).shift()(e);
    }
    async get() {
      return i(this, N).length || v(this, Ae, mr).call(this), i(this, N).shift();
    }
    isEmpty() {
      return !i(this, N).length;
    }
    isBlocked() {
      return !!i(this, B).length;
    }
    get length() {
      return i(this, N).length - i(this, B).length;
    }
  };
  N = /* @__PURE__ */ new WeakMap(), B = /* @__PURE__ */ new WeakMap(), Ae = /* @__PURE__ */ new WeakSet(), mr = function() {
    i(this, N).push(new Promise((e) => {
      i(this, B).push(e);
    }));
  };
  function vt(r, e) {
    return ln({ type: "request", data: { uuid: ot(), msg: r } }, e);
  }
  function gr(r, e, t) {
    return ln({ type: "response", data: { uuid: r, resp: e } }, t);
  }
  function ln(r, e) {
    return e && Cr(r, e), r;
  }
  function un(r) {
    let e = new rt(r.obj.message);
    return r.obj.name !== "Error" && (e.name = r.obj.name), e.stack = r.obj.stack, e;
  }
  function Os(r) {
    return r && typeof r == "object" && "payloadType" in r && "obj" in r;
  }
  function Tt(r) {
    return Os(r) && r.payloadType === "ptr";
  }
  var ye;
  var fe = class {
    constructor() {
      this.inputQueue = new he();
      this.outputQueue = new he();
      this.systemQueue = new he();
      u(this, ye, /* @__PURE__ */ new Map());
    }
    async read() {
      return await this.outputQueue.get();
    }
    async flush() {
      let e = [];
      for (; !this.outputQueue.isEmpty(); ) e.push(await this.read());
      return e;
    }
    async readSystem() {
      return await this.systemQueue.get();
    }
    write(e) {
      this.inputQueue.put(e);
    }
    async request(e, t) {
      let n = vt(e, t), { resolve: s, reject: o, promise: a } = le();
      return i(this, ye).set(n.data.uuid, { resolve: s, reject: o }), this.write(n), a;
    }
    putClosedMessage() {
      this.outputQueue.put({ type: "closed" });
    }
    resolveResponse(e) {
      let t = e.data.uuid, n = i(this, ye).get(t);
      if (n) {
        let s = e.data.resp;
        i(this, ye).delete(t), s.payloadType === "err" ? n.reject(un(s)) : n.resolve(s);
      } else console.warn("Can't find request.");
    }
  };
  ye = /* @__PURE__ */ new WeakMap();
  var dn = Y(wt());
  var Us = new TextDecoder("utf-8");
  var Re;
  var me;
  var Me;
  var Oe;
  var ge;
  Re = /* @__PURE__ */ new WeakMap(), me = /* @__PURE__ */ new WeakMap(), Me = /* @__PURE__ */ new WeakMap(), Oe = /* @__PURE__ */ new WeakMap(), ge = /* @__PURE__ */ new WeakMap();
  var wr = new Int32Array(new ArrayBuffer(4));
  var l = {};
  function Rn(r) {
    Object.keys(r).forEach((e) => l._free(r[e]));
  }
  x && (globalThis.Worker = H("worker_threads").Worker);
  var be;
  var St;
  var mn;
  var Ue;
  var Ie = class extends fe {
    constructor(t) {
      super();
      u(this, St);
      u(this, be, void 0);
      this.close = () => {
      };
      u(this, Ue, async (t2, n2) => {
        if (!(!n2 || !n2.type)) switch (n2.type) {
          case "resolve":
            h(this, be, new Int32Array(n2.data)), this.resolve();
            return;
          case "response":
            this.resolveResponse(n2);
            return;
          case "system":
            this.systemQueue.put(n2.data);
            return;
          default:
            this.outputQueue.put(n2);
            return;
          case "sync-request": {
            let s = n2, o = s.data.msg, a = s.data.reqData;
            switch (o.type) {
              case "read": {
                let c = await this.inputQueue.get();
                await an(t2, a, c);
                break;
              }
              default:
                throw new D(`Unsupported request type '${o.type}'.`);
            }
            return;
          }
          case "request":
            throw new D("Can't send messages of type 'request' from a worker. Please Use 'sync-request' instead.");
        }
      });
      let n = (s) => {
        v(this, St, mn).call(this, s), this.close = () => {
          s.terminate(), this.putClosedMessage();
        };
        let o = { type: "init", data: { config: t, channelType: V.SharedArrayBuffer } };
        s.postMessage(o);
      };
      if (ce(t.baseUrl)) nt(`${t.baseUrl}webr-worker.js`, (s) => n(s));
      else {
        let s = new Worker(`${t.baseUrl}webr-worker.js`);
        n(s);
      }
      ({ resolve: this.resolve, promise: this.initialised } = le());
    }
    interrupt() {
      if (!i(this, be)) throw new D("Failed attempt to interrupt before initialising interruptBuffer");
      this.inputQueue.reset(), i(this, be)[0] = 1;
    }
  };
  be = /* @__PURE__ */ new WeakMap(), St = /* @__PURE__ */ new WeakSet(), mn = function(t) {
    x ? t.on("message", (n) => {
      i(this, Ue).call(this, t, n);
    }) : t.onmessage = (n) => i(this, Ue).call(this, t, n.data);
  }, Ue = /* @__PURE__ */ new WeakMap();
  var te;
  var Ce;
  var re;
  var je;
  te = /* @__PURE__ */ new WeakMap(), Ce = /* @__PURE__ */ new WeakMap(), re = /* @__PURE__ */ new WeakMap(), je = /* @__PURE__ */ new WeakMap();
  var At = Y(wt());
  x && (globalThis.Worker = H("worker_threads").Worker);
  var we;
  var ne;
  var xe;
  var kt;
  var gn;
  var Dt;
  var bn;
  var Wt;
  var wn;
  var Be;
  var Ne = class extends fe {
    constructor(t) {
      super();
      u(this, kt);
      u(this, Dt);
      u(this, Wt);
      this.close = () => {
      };
      u(this, we, /* @__PURE__ */ new Map());
      u(this, ne, void 0);
      u(this, xe, false);
      u(this, Be, async (t2, n2) => {
        if (!(!n2 || !n2.type)) switch (n2.type) {
          case "resolve":
            this.resolve();
            return;
          case "response":
            this.resolveResponse(n2);
            return;
          case "system":
            this.systemQueue.put(n2.data);
            return;
          default:
            this.outputQueue.put(n2);
            return;
          case "sync-request": {
            let s = n2.data;
            i(this, we).set(s.data.uuid, s.data.msg);
            return;
          }
          case "request":
            throw new D("Can't send messages of type 'request' from a worker.Use service worker fetch request instead.");
        }
      });
      let n = (s) => {
        v(this, Wt, wn).call(this, s), this.close = () => {
          s.terminate(), this.putClosedMessage();
        }, v(this, kt, gn).call(this, `${t.serviceWorkerUrl}webr-serviceworker.js`).then((o) => {
          let a = { type: "init", data: { config: t, channelType: V.ServiceWorker, clientId: o, location: window.location.href } };
          s.postMessage(a);
        });
      };
      if (ce(t.serviceWorkerUrl)) nt(`${t.serviceWorkerUrl}webr-worker.js`, (s) => n(s));
      else {
        let s = new Worker(`${t.serviceWorkerUrl}webr-worker.js`);
        n(s);
      }
      ({ resolve: this.resolve, promise: this.initialised } = le());
    }
    activeRegistration() {
      var t;
      if (!((t = i(this, ne)) != null && t.active)) throw new D("Attempted to obtain a non-existent active registration.");
      return i(this, ne).active;
    }
    interrupt() {
      h(this, xe, true);
    }
  };
  we = /* @__PURE__ */ new WeakMap(), ne = /* @__PURE__ */ new WeakMap(), xe = /* @__PURE__ */ new WeakMap(), kt = /* @__PURE__ */ new WeakSet(), gn = async function(t) {
    h(this, ne, await navigator.serviceWorker.register(t)), await navigator.serviceWorker.ready, window.addEventListener("beforeunload", () => {
      var s;
      (s = i(this, ne)) == null || s.unregister();
    });
    let n = await new Promise((s) => {
      navigator.serviceWorker.addEventListener("message", function o(a) {
        a.data.type === "registration-successful" && (navigator.serviceWorker.removeEventListener("message", o), s(a.data.clientId));
      }), this.activeRegistration().postMessage({ type: "register-client-main" });
    });
    return navigator.serviceWorker.addEventListener("message", (s) => {
      v(this, Dt, bn).call(this, s);
    }), n;
  }, Dt = /* @__PURE__ */ new WeakSet(), bn = async function(t) {
    if (t.data.type === "request") {
      let n = t.data.data, s = i(this, we).get(n);
      if (!s) throw new D("Request not found during service worker XHR request");
      switch (i(this, we).delete(n), s.type) {
        case "read": {
          let o = await this.inputQueue.get();
          this.activeRegistration().postMessage({ type: "wasm-webr-fetch-response", uuid: n, response: gr(n, o) });
          break;
        }
        case "interrupt": {
          let o = i(this, xe);
          this.activeRegistration().postMessage({ type: "wasm-webr-fetch-response", uuid: n, response: gr(n, o) }), this.inputQueue.reset(), h(this, xe, false);
          break;
        }
        default:
          throw new D(`Unsupported request type '${s.type}'.`);
      }
      return;
    }
  }, Wt = /* @__PURE__ */ new WeakSet(), wn = function(t) {
    x ? t.on("message", (n) => {
      i(this, Be).call(this, t, n);
    }) : t.onmessage = (n) => i(this, Be).call(this, t, n.data);
  }, Be = /* @__PURE__ */ new WeakMap();
  var Ee;
  var Le;
  var Fe;
  var qe;
  var Ve;
  var Je;
  Ee = /* @__PURE__ */ new WeakMap(), Le = /* @__PURE__ */ new WeakMap(), Fe = /* @__PURE__ */ new WeakMap(), qe = /* @__PURE__ */ new WeakMap(), Ve = /* @__PURE__ */ new WeakMap(), Je = /* @__PURE__ */ new WeakMap();
  var V = { Automatic: 0, SharedArrayBuffer: 1, ServiceWorker: 2 };
  function xn(r) {
    switch (r.channelType) {
      case V.SharedArrayBuffer:
        return new Ie(r);
      case V.ServiceWorker:
        return new Ne(r);
      case V.Automatic:
      default:
        if (typeof SharedArrayBuffer < "u") return new Ie(r);
        if ("serviceWorker" in navigator && !ce(r.serviceWorkerUrl)) return new Ne(r);
        throw new D("Can't initialise main thread communication channel");
    }
  }
  var En = x ? __dirname + "/" : "./";
  var vn = "https://repo.r-wasm.org";
  function g(r) {
    return r && (typeof r == "object" || typeof r == "function") && "payloadType" in r && Tt(r._payload);
  }
  function Tn(r) {
    var e;
    return !!(g(r) && ((e = r._payload.obj.methods) != null && e.includes("exec")));
  }
  var f = { null: 0, symbol: 1, pairlist: 2, closure: 3, environment: 4, promise: 5, call: 6, special: 7, builtin: 8, string: 9, logical: 10, integer: 13, double: 14, complex: 15, character: 16, dots: 17, any: 18, list: 19, expression: 20, bytecode: 21, pointer: 22, weakref: 23, raw: 24, s4: 25, new: 30, free: 31, function: 99 };
  function vr(r) {
    return r && typeof r == "object" && Object.keys(f).includes(r.type);
  }
  function Tr(r) {
    return r && typeof r == "object" && "re" in r && "im" in r;
  }
  function Mt(r) {
    return l._Rf_protect(L(r)), r;
  }
  function S(r, e) {
    return l._Rf_protect(L(r)), ++e.n, r;
  }
  function Pn(r) {
    let e = l._malloc(4);
    return l._R_ProtectWithIndex(L(r), e), { loc: l.getValue(e, "i32"), ptr: e };
  }
  function _n(r) {
    l._Rf_unprotect(1), l._free(r.ptr);
  }
  function Sn(r, e) {
    return l._R_Reprotect(L(r), e.loc), r;
  }
  function W(r) {
    l._Rf_unprotect(r);
  }
  function Pr(r, e, t) {
    l._Rf_defineVar(L(e), L(t), L(r));
  }
  function kn(r, e) {
    let t = {}, n = { n: 0 };
    try {
      let s = new ze(e);
      S(s, n), t.code = l.allocateUTF8(r);
      let o = l._R_ParseEvalString(t.code, s.ptr);
      return y.wrap(o);
    } finally {
      Rn(t), W(n.n);
    }
  }
  function He(r, e) {
    return l.getWasmTableEntry(l.GOT.ffi_safe_eval.value)(L(r), L(e));
  }
  function L(r) {
    return Ls(r) ? r.ptr : r;
  }
  function ae(r, e) {
    if (l._TYPEOF(r.ptr) !== f[e]) throw new Error(`Unexpected object type "${r.type()}" when expecting type "${e}"`);
  }
  function Ns(r) {
    if (vr(r)) return new (Dn(f[r.type]))(r);
    if (r && typeof r == "object" && "type" in r && r.type === "null") return new Ct();
    if (r === null) return new oe({ type: "logical", names: null, values: [null] });
    if (typeof r == "boolean") return new oe(r);
    if (typeof r == "number") return new Xe(r);
    if (typeof r == "string") return new G(r);
    if (Tr(r)) return new Ge(r);
    if (Array.isArray(r)) return Bs(r);
    throw new Error("Robj construction for this JS object is not yet supported");
  }
  function Bs(r) {
    let e = { n: 0 };
    try {
      let t = new ie([new $("c"), ...r]);
      return S(t, e), t.eval();
    } finally {
      W(e.n);
    }
  }
  var E = class {
    constructor(e) {
      this.ptr = e;
    }
    type() {
      let e = l._TYPEOF(this.ptr);
      return Object.keys(f).find((n) => f[n] === e);
    }
  };
  var Te;
  var Ot;
  var se = class extends E {
    constructor(t) {
      if (!(t instanceof E)) return Ns(t);
      super(t.ptr);
      u(this, Te);
    }
    static wrap(t) {
      let n = l._TYPEOF(t);
      return new (Dn(n))(new E(t));
    }
    get [Symbol.toStringTag]() {
      return `RObject:${this.type()}`;
    }
    static getPersistentObject(t) {
      return k[t];
    }
    getPropertyValue(t) {
      return this[t];
    }
    inspect() {
      kn(".Internal(inspect(x))", { x: this });
    }
    isNull() {
      return l._TYPEOF(this.ptr) === f.null;
    }
    isUnbound() {
      return this.ptr === k.unboundValue.ptr;
    }
    attrs() {
      return Pe.wrap(l._ATTRIB(this.ptr));
    }
    setNames(t) {
      let n;
      if (t === null) n = k.null;
      else if (Array.isArray(t) && t.every((s) => typeof s == "string" || s === null)) n = new G(t);
      else throw new Error("Argument to setNames must be null or an Array of strings or null");
      return l._Rf_setAttrib(this.ptr, k.namesSymbol.ptr, n.ptr), this;
    }
    names() {
      let t = G.wrap(l._Rf_getAttrib(this.ptr, k.namesSymbol.ptr));
      return t.isNull() ? null : t.toArray();
    }
    includes(t) {
      let n = this.names();
      return n && n.includes(t);
    }
    toJs(t = { depth: 0 }, n = 1) {
      throw new Error("This R object cannot be converted to JS");
    }
    subset(t) {
      return v(this, Te, Ot).call(this, t, k.bracketSymbol.ptr);
    }
    get(t) {
      return v(this, Te, Ot).call(this, t, k.bracket2Symbol.ptr);
    }
    getDollar(t) {
      return v(this, Te, Ot).call(this, t, k.dollarSymbol.ptr);
    }
    pluck(...t) {
      let n = Pn(k.null);
      try {
        let s = (a, c) => {
          let p = a.get(c);
          return Sn(p, n);
        }, o = t.reduce(s, this);
        return o.isNull() ? void 0 : o;
      } finally {
        _n(n);
      }
    }
    set(t, n) {
      let s = { n: 0 };
      try {
        let o = new se(t);
        S(o, s);
        let a = new se(n);
        S(a, s);
        let c = new $("[[<-"), p = l._Rf_lang4(c.ptr, this.ptr, o.ptr, a.ptr);
        return S(p, s), se.wrap(He(p, k.baseEnv));
      } finally {
        W(s.n);
      }
    }
    static getMethods(t) {
      let n = /* @__PURE__ */ new Set(), s = t;
      do
        Object.getOwnPropertyNames(s).map((o) => n.add(o));
      while (s = Object.getPrototypeOf(s));
      return [...n.keys()].filter((o) => typeof t[o] == "function");
    }
  };
  var y = se;
  Te = /* @__PURE__ */ new WeakSet(), Ot = function(t, n) {
    let s = { n: 0 };
    try {
      let o = new se(t);
      S(o, s);
      let a = l._Rf_lang3(n, this.ptr, o.ptr);
      return S(a, s), se.wrap(He(a, k.baseEnv));
    } finally {
      W(s.n);
    }
  };
  var Ct = class extends y {
    constructor() {
      return super(new E(l.getValue(l._R_NilValue, "*"))), this;
    }
    toJs() {
      return { type: "null" };
    }
  };
  var $ = class extends y {
    constructor(e) {
      if (e instanceof E) {
        ae(e, "symbol"), super(e);
        return;
      }
      let t = l.allocateUTF8(e);
      try {
        super(new E(l._Rf_install(t)));
      } finally {
        l._free(t);
      }
    }
    toJs() {
      let e = this.toObject();
      return { type: "symbol", printname: e.printname, symvalue: e.symvalue, internal: e.internal };
    }
    toObject() {
      return { printname: this.printname().isUnbound() ? null : this.printname().toString(), symvalue: this.symvalue().isUnbound() ? null : this.symvalue().ptr, internal: this.internal().isNull() ? null : this.internal().ptr };
    }
    toString() {
      return this.printname().toString();
    }
    printname() {
      return $e.wrap(l._PRINTNAME(this.ptr));
    }
    symvalue() {
      return y.wrap(l._SYMVALUE(this.ptr));
    }
    internal() {
      return y.wrap(l._INTERNAL(this.ptr));
    }
  };
  var Pe = class extends y {
    constructor(e) {
      if (e instanceof E) return ae(e, "pairlist"), super(e), this;
      let t = { n: 0 };
      try {
        let { names: n, values: s } = Ke(e), o = Pe.wrap(l._Rf_allocList(s.length));
        S(o, t);
        for (let [a, c] = [0, o]; !c.isNull(); [a, c] = [a + 1, c.cdr()]) c.setcar(new y(s[a]));
        o.setNames(n), super(o);
      } finally {
        W(t.n);
      }
    }
    get length() {
      return this.toArray().length;
    }
    toArray(e = { depth: 1 }) {
      return this.toJs(e).values;
    }
    toObject({ allowDuplicateKey: e = true, allowEmptyKey: t = false, depth: n = 1 } = {}) {
      let s = this.entries({ depth: n }), o = s.map(([a, c]) => a);
      if (!e && new Set(o).size !== o.length) throw new Error("Duplicate key when converting pairlist without allowDuplicateKey enabled");
      if (!t && o.some((a) => !a)) throw new Error("Empty or null key when converting pairlist without allowEmptyKey enabled");
      return Object.fromEntries(s.filter((a, c) => s.findIndex((p) => p[0] === a[0]) === c));
    }
    entries(e = { depth: 1 }) {
      let t = this.toJs(e);
      return t.values.map((n, s) => [t.names ? t.names[s] : null, n]);
    }
    toJs(e = { depth: 0 }, t = 1) {
      let n = [], s = false, o = [];
      for (let c = this; !c.isNull(); c = c.cdr()) {
        let p = c.tag();
        p.isNull() ? n.push("") : (s = true, n.push(p.toString())), e.depth && t >= e.depth ? o.push(c.car()) : o.push(c.car().toJs(e, t + 1));
      }
      return { type: "pairlist", names: s ? n : null, values: o };
    }
    includes(e) {
      return e in this.toObject();
    }
    setcar(e) {
      l._SETCAR(this.ptr, e.ptr);
    }
    car() {
      return y.wrap(l._CAR(this.ptr));
    }
    cdr() {
      return y.wrap(l._CDR(this.ptr));
    }
    tag() {
      return y.wrap(l._TAG(this.ptr));
    }
  };
  var ie = class extends y {
    constructor(e) {
      if (e instanceof E) return ae(e, "call"), super(e), this;
      let t = { n: 0 };
      try {
        let { values: n } = Ke(e), s = n.map((a) => S(new y(a), t)), o = ie.wrap(l._Rf_allocVector(f.call, n.length));
        S(o, t);
        for (let [a, c] = [0, o]; !c.isNull(); [a, c] = [a + 1, c.cdr()]) c.setcar(s[a]);
        super(o);
      } finally {
        W(t.n);
      }
    }
    setcar(e) {
      l._SETCAR(this.ptr, e.ptr);
    }
    car() {
      return y.wrap(l._CAR(this.ptr));
    }
    cdr() {
      return y.wrap(l._CDR(this.ptr));
    }
    eval() {
      return y.wrap(He(this.ptr, k.baseEnv));
    }
  };
  var _r = class extends y {
    constructor(e) {
      if (e instanceof E) return ae(e, "list"), super(e), this;
      let t = { n: 0 };
      try {
        let { names: n, values: s } = Ke(e), o = l._Rf_allocVector(f.list, s.length);
        S(o, t), s.forEach((a, c) => {
          l._SET_VECTOR_ELT(o, c, new y(a).ptr);
        }), y.wrap(o).setNames(n), super(new E(o));
      } finally {
        W(t.n);
      }
    }
    get length() {
      return l._LENGTH(this.ptr);
    }
    toArray(e = { depth: 1 }) {
      return this.toJs(e).values;
    }
    toObject({ allowDuplicateKey: e = true, allowEmptyKey: t = false, depth: n = 1 } = {}) {
      let s = this.entries({ depth: n }), o = s.map(([a, c]) => a);
      if (!e && new Set(o).size !== o.length) throw new Error("Duplicate key when converting list without allowDuplicateKey enabled");
      if (!t && o.some((a) => !a)) throw new Error("Empty or null key when converting list without allowEmptyKey enabled");
      return Object.fromEntries(s.filter((a, c) => s.findIndex((p) => p[0] === a[0]) === c));
    }
    entries(e = { depth: 1 }) {
      let t = this.toJs(e);
      return t.values.map((n, s) => [t.names ? t.names[s] : null, n]);
    }
    toJs(e = { depth: 0 }, t = 1) {
      return { type: "list", names: this.names(), values: [...Array(this.length).keys()].map((n) => e.depth && t >= e.depth ? this.get(n + 1) : this.get(n + 1).toJs(e, t + 1)) };
    }
  };
  var ve = class extends y {
    exec(...e) {
      let t = { n: 0 };
      try {
        let n = new ie([this, ...e]);
        return S(n, t), n.eval();
      } finally {
        W(t.n);
      }
    }
  };
  var $e = class extends y {
    constructor(e) {
      if (e instanceof E) {
        ae(e, "string"), super(e);
        return;
      }
      let t = l.allocateUTF8(e);
      try {
        super(new E(l._Rf_mkChar(t)));
      } finally {
        l._free(t);
      }
    }
    toString() {
      return l.UTF8ToString(l._R_CHAR(this.ptr));
    }
    toJs() {
      return { type: "string", value: this.toString() };
    }
  };
  var ze = class extends y {
    constructor(e = {}) {
      if (e instanceof E) return ae(e, "environment"), super(e), this;
      let t = 0;
      try {
        let { names: n, values: s } = Ke(e), o = Mt(l._R_NewEnv(k.globalEnv.ptr, 0, 0));
        ++t, s.forEach((a, c) => {
          let p = n ? n[c] : null;
          if (!p) throw new Error("Can't create object in new environment with empty symbol name");
          let w = new $(p), Z = Mt(new y(a));
          try {
            Pr(o, w, Z);
          } finally {
            W(1);
          }
        }), super(new E(o));
      } finally {
        W(t);
      }
    }
    ls(e = false, t = true) {
      return G.wrap(l._R_lsInternal3(this.ptr, Number(e), Number(t))).toArray();
    }
    bind(e, t) {
      let n = new $(e), s = Mt(new y(t));
      try {
        Pr(this, n, s);
      } finally {
        W(1);
      }
    }
    names() {
      return this.ls(true, true);
    }
    frame() {
      return y.wrap(l._FRAME(this.ptr));
    }
    subset(e) {
      if (typeof e == "number") throw new Error("Object of type environment is not subsettable");
      return this.getDollar(e);
    }
    toObject({ depth: e = 0 } = {}) {
      let t = this.names();
      return Object.fromEntries([...Array(t.length).keys()].map((n) => [t[n], this.getDollar(t[n]).toJs({ depth: e })]));
    }
    toJs(e = { depth: 0 }, t = 1) {
      let n = this.names(), s = [...Array(n.length).keys()].map((o) => e.depth && t >= e.depth ? this.getDollar(n[o]) : this.getDollar(n[o]).toJs(e, t + 1));
      return { type: "environment", names: n, values: s };
    }
  };
  var K = class extends y {
    constructor(e, t, n) {
      if (e instanceof E) return ae(e, t), super(e), this;
      let s = { n: 0 };
      try {
        let { names: o, values: a } = Ke(e), c = l._Rf_allocVector(f[t], a.length);
        S(c, s), a.forEach(n(c)), y.wrap(c).setNames(o), super(new E(c));
      } finally {
        W(s.n);
      }
    }
    get length() {
      return l._LENGTH(this.ptr);
    }
    get(e) {
      return super.get(e);
    }
    subset(e) {
      return super.subset(e);
    }
    getDollar(e) {
      throw new Error("$ operator is invalid for atomic vectors");
    }
    detectMissing() {
      let e = { n: 0 };
      try {
        let t = l._Rf_lang2(new $("is.na").ptr, this.ptr);
        S(t, e);
        let n = oe.wrap(He(t, k.baseEnv));
        S(n, e);
        let s = n.toTypedArray();
        return Array.from(s).map((o) => !!o);
      } finally {
        W(e.n);
      }
    }
    toArray() {
      let e = this.toTypedArray();
      return this.detectMissing().map((t, n) => t ? null : e[n]);
    }
    toObject({ allowDuplicateKey: e = true, allowEmptyKey: t = false } = {}) {
      let n = this.entries(), s = n.map(([o, a]) => o);
      if (!e && new Set(s).size !== s.length) throw new Error("Duplicate key when converting atomic vector without allowDuplicateKey enabled");
      if (!t && s.some((o) => !o)) throw new Error("Empty or null key when converting atomic vector without allowEmptyKey enabled");
      return Object.fromEntries(n.filter((o, a) => n.findIndex((c) => c[0] === o[0]) === a));
    }
    entries() {
      let e = this.toArray(), t = this.names();
      return e.map((n, s) => [t ? t[s] : null, n]);
    }
    toJs() {
      return { type: this.type(), names: this.names(), values: this.toArray() };
    }
  };
  var jt;
  var Sr = class extends K {
    constructor(e) {
      super(e, "logical", i(Sr, jt));
    }
    getBoolean(e) {
      return this.get(e).toArray()[0];
    }
    toBoolean() {
      if (this.length !== 1) throw new Error("Can't convert atomic vector of length > 1 to a scalar JS value");
      let e = this.getBoolean(1);
      if (e === null) throw new Error("Can't convert missing value `NA` to a JS boolean");
      return e;
    }
    toTypedArray() {
      return new Int32Array(l.HEAP32.subarray(l._LOGICAL(this.ptr) / 4, l._LOGICAL(this.ptr) / 4 + this.length));
    }
    toArray() {
      let e = this.toTypedArray();
      return this.detectMissing().map((t, n) => t ? null : !!e[n]);
    }
  };
  var oe = Sr;
  jt = /* @__PURE__ */ new WeakMap(), u(oe, jt, (e) => {
    let t = l._LOGICAL(e), n = l.getValue(l._R_NaInt, "i32");
    return (s, o) => {
      l.setValue(t + 4 * o, s === null ? n : !!s, "i32");
    };
  });
  var Nt;
  var kr = class extends K {
    constructor(e) {
      super(e, "integer", i(kr, Nt));
    }
    getNumber(e) {
      return this.get(e).toArray()[0];
    }
    toNumber() {
      if (this.length !== 1) throw new Error("Can't convert atomic vector of length > 1 to a scalar JS value");
      let e = this.getNumber(1);
      if (e === null) throw new Error("Can't convert missing value `NA` to a JS number");
      return e;
    }
    toTypedArray() {
      return new Int32Array(l.HEAP32.subarray(l._INTEGER(this.ptr) / 4, l._INTEGER(this.ptr) / 4 + this.length));
    }
  };
  var It = kr;
  Nt = /* @__PURE__ */ new WeakMap(), u(It, Nt, (e) => {
    let t = l._INTEGER(e), n = l.getValue(l._R_NaInt, "i32");
    return (s, o) => {
      l.setValue(t + 4 * o, s === null ? n : Math.round(Number(s)), "i32");
    };
  });
  var Bt;
  var Dr = class extends K {
    constructor(e) {
      super(e, "double", i(Dr, Bt));
    }
    getNumber(e) {
      return this.get(e).toArray()[0];
    }
    toNumber() {
      if (this.length !== 1) throw new Error("Can't convert atomic vector of length > 1 to a scalar JS value");
      let e = this.getNumber(1);
      if (e === null) throw new Error("Can't convert missing value `NA` to a JS number");
      return e;
    }
    toTypedArray() {
      return new Float64Array(l.HEAPF64.subarray(l._REAL(this.ptr) / 8, l._REAL(this.ptr) / 8 + this.length));
    }
  };
  var Xe = Dr;
  Bt = /* @__PURE__ */ new WeakMap(), u(Xe, Bt, (e) => {
    let t = l._REAL(e), n = l.getValue(l._R_NaReal, "double");
    return (s, o) => {
      l.setValue(t + 8 * o, s === null ? n : s, "double");
    };
  });
  var Lt;
  var Wr = class extends K {
    constructor(e) {
      super(e, "complex", i(Wr, Lt));
    }
    getComplex(e) {
      return this.get(e).toArray()[0];
    }
    toComplex() {
      if (this.length !== 1) throw new Error("Can't convert atomic vector of length > 1 to a scalar JS value");
      let e = this.getComplex(1);
      if (e === null) throw new Error("Can't convert missing value `NA` to a JS object");
      return e;
    }
    toTypedArray() {
      return new Float64Array(l.HEAPF64.subarray(l._COMPLEX(this.ptr) / 8, l._COMPLEX(this.ptr) / 8 + 2 * this.length));
    }
    toArray() {
      let e = this.toTypedArray();
      return this.detectMissing().map((t, n) => t ? null : { re: e[2 * n], im: e[2 * n + 1] });
    }
  };
  var Ge = Wr;
  Lt = /* @__PURE__ */ new WeakMap(), u(Ge, Lt, (e) => {
    let t = l._COMPLEX(e), n = l.getValue(l._R_NaReal, "double");
    return (s, o) => {
      l.setValue(t + 8 * (2 * o), s === null ? n : s.re, "double"), l.setValue(t + 8 * (2 * o + 1), s === null ? n : s.im, "double");
    };
  });
  var Ft;
  var Ar = class extends K {
    constructor(e) {
      super(e, "character", i(Ar, Ft));
    }
    getString(e) {
      return this.get(e).toArray()[0];
    }
    toString() {
      if (this.length !== 1) throw new Error("Can't convert atomic vector of length > 1 to a scalar JS value");
      let e = this.getString(1);
      if (e === null) throw new Error("Can't convert missing value `NA` to a JS string");
      return e;
    }
    toTypedArray() {
      return new Uint32Array(l.HEAPU32.subarray(l._STRING_PTR(this.ptr) / 4, l._STRING_PTR(this.ptr) / 4 + this.length));
    }
    toArray() {
      return this.detectMissing().map((e, t) => e ? null : l.UTF8ToString(l._R_CHAR(l._STRING_ELT(this.ptr, t))));
    }
  };
  var G = Ar;
  Ft = /* @__PURE__ */ new WeakMap(), u(G, Ft, (e) => (t, n) => {
    t === null ? l._SET_STRING_ELT(e, n, k.naString.ptr) : l._SET_STRING_ELT(e, n, new $e(t).ptr);
  });
  var qt;
  var Mr = class extends K {
    constructor(e) {
      super(e, "raw", i(Mr, qt));
    }
    getNumber(e) {
      return this.get(e).toArray()[0];
    }
    toNumber() {
      if (this.length !== 1) throw new Error("Can't convert atomic vector of length > 1 to a scalar JS value");
      let e = this.getNumber(1);
      if (e === null) throw new Error("Can't convert missing value `NA` to a JS number");
      return e;
    }
    toTypedArray() {
      return new Uint8Array(l.HEAPU8.subarray(l._RAW(this.ptr), l._RAW(this.ptr) + this.length));
    }
  };
  var Ut = Mr;
  qt = /* @__PURE__ */ new WeakMap(), u(Ut, qt, (e) => {
    let t = l._RAW(e);
    return (n, s) => {
      l.setValue(t + s, Number(n), "i8");
    };
  });
  function Ke(r) {
    return vr(r) ? r : Array.isArray(r) || ArrayBuffer.isView(r) ? { names: null, values: r } : r && typeof r == "object" && !Tr(r) ? { names: Object.keys(r), values: Object.values(r) } : { names: null, values: [r] };
  }
  function Dn(r) {
    let e = { [f.null]: Ct, [f.symbol]: $, [f.pairlist]: Pe, [f.closure]: ve, [f.environment]: ze, [f.call]: ie, [f.special]: ve, [f.builtin]: ve, [f.string]: $e, [f.logical]: oe, [f.integer]: It, [f.double]: Xe, [f.complex]: Ge, [f.character]: G, [f.list]: _r, [f.raw]: Ut, [f.function]: ve };
    return r in e ? e[r] : y;
  }
  function Ls(r) {
    return r instanceof y;
  }
  var k;
  function qs() {
  }
  function Vs(r, e) {
    return async function* () {
      let t = { type: "callRObjectMethod", data: { payload: e._payload, prop: "getPropertyValue", args: [{ payloadType: "raw", obj: "length" }], shelter: void 0 } }, n = await r.request(t);
      if (typeof n.obj != "number") throw new M("Cannot iterate over object, unexpected type for length property.");
      for (let s = 1; s <= n.obj; s++) yield e.get(s);
    };
  }
  function Wn(r, e, t) {
    return async (...n) => {
      let s = n.map((c) => g(c) ? c._payload : { obj: I(c, g, (p) => p._payload), payloadType: "raw" }), o = { type: "callRObjectMethod", data: { payload: t, prop: e, args: s } }, a = await r.request(o);
      switch (a.payloadType) {
        case "ptr":
          return Q(r, a);
        case "raw":
          return I(a, Tt, (p, w) => Q(w, p), r).obj;
      }
    };
  }
  async function Js(r, e, t, n) {
    let s = { type: "newRObject", data: { objType: e, obj: I(n, g, (a) => a._payload), shelter: t } }, o = await r.request(s);
    switch (o.payloadType) {
      case "raw":
        throw new z("Unexpected raw payload type returned from newRObject");
      case "ptr":
        return Q(r, o);
    }
  }
  function Q(r, e) {
    var n;
    let t = new Proxy((n = e.obj.methods) != null && n.includes("exec") ? Object.assign(qs, { ...e }) : e, { get: (s, o) => {
      var a;
      if (o === "_payload") return e;
      if (o === Symbol.asyncIterator) return Vs(r, t);
      if ((a = e.obj.methods) != null && a.includes(o.toString())) return Wn(r, o.toString(), e);
    }, apply: async (s, o, a) => {
      let c = await Q(r, e).exec(...a);
      return Tn(c) ? c : c.toJs();
    } });
    return t;
  }
  function A(r, e, t) {
    return new Proxy(y, { construct: (n, s) => Js(r, t, e, ...s), get: (n, s) => Wn(r, s.toString()) });
  }
  var Qe;
  var Ze;
  var Ye;
  var et;
  var Vt;
  var Jt;
  var Ht;
  var zt;
  var Xt;
  var An;
  Qe = /* @__PURE__ */ new WeakMap(), Ze = /* @__PURE__ */ new WeakMap(), Ye = /* @__PURE__ */ new WeakMap(), et = /* @__PURE__ */ new WeakMap(), Vt = /* @__PURE__ */ new WeakMap(), Jt = /* @__PURE__ */ new WeakMap(), Ht = /* @__PURE__ */ new WeakMap(), zt = /* @__PURE__ */ new WeakMap(), Xt = /* @__PURE__ */ new WeakSet(), An = async function() {
    for (; ; ) {
      let e = await this.webR.read();
      switch (e.type) {
        case "stdout":
          i(this, Qe).call(this, e.data);
          break;
        case "stderr":
          i(this, Ze).call(this, e.data);
          break;
        case "prompt":
          i(this, Ye).call(this, e.data);
          break;
        case "canvasImage":
          i(this, et).call(this, e.data.image);
          break;
        case "closed":
          return;
        default:
          console.warn(`Unhandled output type for webR Console: ${e.type}.`);
      }
    }
  };
  var Hs = { FONTCONFIG_PATH: "/etc/fonts", R_HOME: "/usr/lib/R", R_ENABLE_JIT: "0" };
  var Mn = { RArgs: [], REnv: Hs, baseUrl: En, serviceWorkerUrl: "", repoUrl: vn, homedir: "/home/web_user", interactive: true, channelType: V.Automatic, createLazyFilesystem: true };
  var b;
  var Kt;
  var On;
  var Gt = class {
    constructor(e = {}) {
      u(this, Kt);
      u(this, b, void 0);
      this.FS = { lookupPath: async (e2) => {
        let t2 = { type: "lookupPath", data: { path: e2 } };
        return (await i(this, b).request(t2)).obj;
      }, mkdir: async (e2) => {
        let t2 = { type: "mkdir", data: { path: e2 } };
        return (await i(this, b).request(t2)).obj;
      }, readFile: async (e2, t2) => {
        let n = { type: "readFile", data: { path: e2, flags: t2 } };
        return (await i(this, b).request(n)).obj;
      }, rmdir: async (e2) => {
        let t2 = { type: "rmdir", data: { path: e2 } };
        await i(this, b).request(t2);
      }, writeFile: async (e2, t2, n) => {
        let s = { type: "writeFile", data: { path: e2, data: t2, flags: n } };
        await i(this, b).request(s);
      }, unlink: async (e2) => {
        let t2 = { type: "unlink", data: { path: e2 } };
        await i(this, b).request(t2);
      } };
      let t = { ...Mn, ...e, REnv: { ...Mn.REnv, ...e.REnv } };
      h(this, b, xn(t)), this.objs = {}, this.Shelter = zs(i(this, b));
    }
    async init() {
      let e = await i(this, b).initialised;
      return this.globalShelter = await new this.Shelter(), this.RObject = this.globalShelter.RObject, this.RLogical = this.globalShelter.RLogical, this.RInteger = this.globalShelter.RInteger, this.RDouble = this.globalShelter.RDouble, this.RComplex = this.globalShelter.RComplex, this.RCharacter = this.globalShelter.RCharacter, this.RRaw = this.globalShelter.RRaw, this.RList = this.globalShelter.RList, this.RPairlist = this.globalShelter.RPairlist, this.REnvironment = this.globalShelter.REnvironment, this.RSymbol = this.globalShelter.RSymbol, this.RString = this.globalShelter.RString, this.RCall = this.globalShelter.RCall, this.objs = { baseEnv: await this.RObject.getPersistentObject("baseEnv"), globalEnv: await this.RObject.getPersistentObject("globalEnv"), null: await this.RObject.getPersistentObject("null"), true: await this.RObject.getPersistentObject("true"), false: await this.RObject.getPersistentObject("false"), na: await this.RObject.getPersistentObject("na") }, v(this, Kt, On).call(this), e;
    }
    close() {
      i(this, b).close();
    }
    async read() {
      return await i(this, b).read();
    }
    async flush() {
      return await i(this, b).flush();
    }
    write(e) {
      i(this, b).write(e);
    }
    writeConsole(e) {
      this.write({ type: "stdin", data: e + `
` });
    }
    interrupt() {
      i(this, b).interrupt();
    }
    async installPackages(e, t = false) {
      for (let n of e) {
        let s = { type: "installPackage", data: { name: n, quiet: t } };
        await i(this, b).request(s);
      }
    }
    async destroy(e) {
      await this.globalShelter.destroy(e);
    }
    async evalR(e, t) {
      return this.globalShelter.evalR(e, t);
    }
    async evalRVoid(e, t) {
      return this.evalRRaw(e, "void", t);
    }
    async evalRBoolean(e, t) {
      return this.evalRRaw(e, "boolean", t);
    }
    async evalRNumber(e, t) {
      return this.evalRRaw(e, "number", t);
    }
    async evalRString(e, t) {
      return this.evalRRaw(e, "string", t);
    }
    async evalRRaw(e, t, n = {}) {
      let s = I(n, g, (c) => c._payload), o = { type: "evalRRaw", data: { code: e, options: s, outputType: t } }, a = await i(this, b).request(o);
      switch (a.payloadType) {
        case "raw":
          return a.obj;
        case "ptr":
          throw new z("Unexpected ptr payload type returned from evalRVoid");
      }
    }
    async invokeWasmFunction(e, ...t) {
      let n = { type: "invokeWasmFunction", data: { ptr: e, args: t } };
      return (await i(this, b).request(n)).obj;
    }
  };
  b = /* @__PURE__ */ new WeakMap(), Kt = /* @__PURE__ */ new WeakSet(), On = async function() {
    for (; ; ) {
      let e = await i(this, b).readSystem();
      switch (e.type) {
        case "setTimeoutWasm":
          setTimeout((t, n) => {
            this.invokeWasmFunction(t, ...n);
          }, e.data.delay, e.data.ptr, e.data.args);
          break;
        case "console.log":
          console.log(e.data);
          break;
        case "console.warn":
          console.warn(e.data);
          break;
        case "console.error":
          console.error(e.data);
          break;
        default:
          throw new M("Unknown system message type `" + e.type + "`");
      }
    }
  };
  var m;
  var R;
  var tt;
  var $t = class {
    constructor(e) {
      u(this, m, "");
      u(this, R, void 0);
      u(this, tt, false);
      h(this, R, e);
    }
    async init() {
      if (i(this, tt)) return;
      let e = { type: "newShelter" }, t = await i(this, R).request(e);
      h(this, m, t.obj), this.RObject = A(i(this, R), i(this, m), "object"), this.RLogical = A(i(this, R), i(this, m), "logical"), this.RInteger = A(i(this, R), i(this, m), "integer"), this.RDouble = A(i(this, R), i(this, m), "double"), this.RComplex = A(i(this, R), i(this, m), "complex"), this.RCharacter = A(i(this, R), i(this, m), "character"), this.RRaw = A(i(this, R), i(this, m), "raw"), this.RList = A(i(this, R), i(this, m), "list"), this.RPairlist = A(i(this, R), i(this, m), "pairlist"), this.REnvironment = A(i(this, R), i(this, m), "environment"), this.RSymbol = A(i(this, R), i(this, m), "symbol"), this.RString = A(i(this, R), i(this, m), "string"), this.RCall = A(i(this, R), i(this, m), "call"), h(this, tt, true);
    }
    async purge() {
      let e = { type: "shelterPurge", data: i(this, m) };
      await i(this, R).request(e);
    }
    async destroy(e) {
      let t = { type: "shelterDestroy", data: { id: i(this, m), obj: e._payload } };
      await i(this, R).request(t);
    }
    async size() {
      let e = { type: "shelterSize", data: i(this, m) };
      return (await i(this, R).request(e)).obj;
    }
    async evalR(e, t = {}) {
      let n = I(t, g, (a) => a._payload), s = { type: "evalR", data: { code: e, options: n, shelter: i(this, m) } }, o = await i(this, R).request(s);
      switch (o.payloadType) {
        case "raw":
          throw new z("Unexpected payload type returned from evalR");
        default:
          return Q(i(this, R), o);
      }
    }
    async captureR(e, t = {}) {
      let n = I(t, g, (a) => a._payload), s = { type: "captureR", data: { code: e, options: n, shelter: i(this, m) } }, o = await i(this, R).request(s);
      switch (o.payloadType) {
        case "ptr":
          throw new z("Unexpected payload type returned from evalR");
        case "raw": {
          let a = o.obj, c = Q(i(this, R), a.result), p = a.output;
          for (let w = 0; w < p.length; ++w) p[w].type !== "stdout" && p[w].type !== "stderr" && (p[w].data = Q(i(this, R), p[w].data));
          return { result: c, output: p };
        }
      }
    }
  };
  m = /* @__PURE__ */ new WeakMap(), R = /* @__PURE__ */ new WeakMap(), tt = /* @__PURE__ */ new WeakMap();
  function zs(r) {
    return new Proxy($t, { construct: async () => {
      let e = new $t(r);
      return await e.init(), e;
    } });
  }

  // src/webr-runner.ts
  var PACKAGES = [
    "tidyverse",
    "mosaic",
    "moderndive",
    "infer",
    "broom",
    "ggplot2",
    "openssl",
    "base64enc"
  ];
  var webRPromise = null;
  function getWebR() {
    if (!webRPromise) {
      webRPromise = bootWebR();
    }
    return webRPromise;
  }
  async function bootWebR() {
    const webR = new Gt({
      baseUrl: chrome.runtime.getURL("webr/")
    });
    await webR.init();
    await webR.installPackages(PACKAGES, true);
    for (const pkg of PACKAGES) {
      await webR.evalRVoid(`suppressMessages(suppressWarnings(library(${pkg})))`);
    }
    await webR.evalRVoid('setwd("/")');
    return webR;
  }
  function initWebR() {
    return getWebR().then(() => void 0);
  }
  async function runR(code, dataFiles2) {
    const start = performance.now();
    const webR = await getWebR();
    const shelter = await new webR.Shelter();
    try {
      for (const f2 of dataFiles2) {
        const bytes = new TextEncoder().encode(f2.content);
        await webR.FS.writeFile(`/${f2.filename}`, bytes);
      }
      const { output } = await shelter.captureR(code, {
        captureStreams: true,
        captureConditions: true,
        withAutoprint: false,
        // Don't let R errors throw a JS exception — we want the error message
        // captured as stderr (with exitCode=1) so the caller can still POST
        // it to /api/interpret for the model to reason about, same as the old
        // sandbox's non-zero-exit-code behavior.
        throwJsException: false
      });
      const { stdout, stderr } = formatCaptureOutput(output);
      const durationMs = performance.now() - start;
      if (stdout.trim()) {
        return { stdout, exitCode: 0, durationMs };
      }
      if (stderr.trim()) {
        return { stdout: stderr, exitCode: 1, durationMs };
      }
      return { stdout: "", exitCode: 0, durationMs };
    } catch (e) {
      const durationMs = performance.now() - start;
      const message = e.message ?? "R execution failed.";
      return { stdout: message, exitCode: 1, durationMs };
    } finally {
      await shelter.purge();
    }
  }
  function formatCaptureOutput(output) {
    const stdoutLines = [];
    const stderrLines = [];
    for (const item of output) {
      switch (item.type) {
        case "stdout":
          stdoutLines.push(String(item.data));
          break;
        case "stderr":
          stderrLines.push(String(item.data));
          break;
        case "message":
        case "warning":
        case "error": {
          const data = item.data;
          const msg = typeof data === "string" ? data : data?.message ?? "";
          if (msg) stderrLines.push(`${item.type}: ${msg}`);
          break;
        }
        default:
          break;
      }
    }
    return { stdout: stdoutLines.join("\n"), stderr: stderrLines.join("\n") };
  }

  // src/content.ts
  var SELECTORS_QUESTION = [
    ".question_holder",
    ".display_question",
    "[data-testid='question-container']",
    "[data-testid='quiz-question']",
    ".question-container",
    ".QuestionItem",
    ".item-body"
  ];
  var SELECTORS_STEM = [
    ".question_text",
    ".user_content",
    "[data-testid='question-text']",
    "[data-testid='question-stem']",
    ".question-text-container",
    ".stem"
  ];
  var SELECTORS_HEADER = [
    ".question_name",
    // Classic Quizzes — the "Question 1" span
    ".header .question_name",
    ".question .header",
    "[data-testid='question-number']",
    // New Quizzes (guess)
    "[data-testid='question-header']"
  ];
  var QUESTION_SELECTOR = SELECTORS_QUESTION.join(",");
  var CHOICE_INPUT_SELECTOR = 'input[type="radio"], input[type="checkbox"]';
  var TEXT_INPUT_SELECTOR = [
    'input[type="text"]',
    'input[type="number"]',
    ".numerical_question_input",
    ".question_input"
  ].join(",");
  var STORAGE_KEY_FILES = "statshelpr.files";
  var FILE_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
  var dataFiles = [];
  function boot() {
    void loadFiles().then(() => scanAndInject());
    void applyButtonOpacityFromStorage();
    initWebR().catch(() => {
    });
    chrome.storage.onChanged.addListener((changes, area) => {
      if (area === "local" && changes[STORAGE_KEY_FILES]) {
        void loadFiles();
      }
      if (area === "sync" && changes["buttonOpacity"]) {
        const next = changes["buttonOpacity"].newValue;
        if (typeof next === "number") applyButtonOpacity(next);
      }
    });
    const observer = new MutationObserver(() => scanAndInject());
    observer.observe(document.body, { childList: true, subtree: true });
  }
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", boot);
  } else {
    boot();
  }
  var pendingScan = false;
  function scanAndInject() {
    if (pendingScan) return;
    pendingScan = true;
    setTimeout(() => {
      pendingScan = false;
      for (const sel of SELECTORS_QUESTION) {
        document.querySelectorAll(sel).forEach(injectButtonFor);
      }
    }, 100);
  }
  function injectButtonFor(question) {
    if (question.dataset["statshelprAttached"] === "1") return;
    if (hasQuestionAncestor(question)) return;
    if (!findStem(question)) return;
    const btn = mkEl("button", {
      className: "statshelpr-btn-tutor",
      type: "button",
      text: "\xB7",
      title: ""
    });
    btn.addEventListener("click", (e) => {
      e.stopPropagation();
      e.preventDefault();
      void onSolve(question, btn);
    });
    const anchor = findHeader(question);
    if (anchor) {
      anchor.appendChild(document.createTextNode(" "));
      anchor.appendChild(btn);
    } else {
      const wrap = mkEl("div", { className: "statshelpr-tutor-wrap" });
      wrap.appendChild(btn);
      question.insertBefore(wrap, question.firstChild);
    }
    question.dataset["statshelprAttached"] = "1";
  }
  function findHeader(question) {
    for (const sel of SELECTORS_HEADER) {
      const el = question.querySelector(sel);
      if (el) return el;
    }
    return null;
  }
  async function onSolve(question, btn) {
    if (btn.disabled) return;
    setBtnState(btn, "loading");
    question.querySelectorAll(".statshelpr-suggested").forEach(
      (el) => el.classList.remove("statshelpr-suggested")
    );
    await loadFiles();
    let scraped;
    try {
      scraped = await scrapeQuestion(question);
    } catch (e) {
      setBtnState(btn, "error", e.message);
      return;
    }
    const cfg = await getConfig();
    const apiUrl = (cfg.apiUrl ?? "https://api.statshelpr.com").replace(/\/$/, "");
    const licenseKey = cfg.licenseKey ?? "";
    const headers = {
      "Content-Type": "application/json",
      ...licenseKey ? { Authorization: `Bearer ${licenseKey}` } : {}
    };
    const apiChoices = scraped.choices.map((c) => ({
      label: c.label,
      text: c.text,
      type: choiceTypeForApi(c)
    }));
    const apiDataFiles = dataFiles.map((f2) => ({ filename: f2.filename, content: f2.content }));
    let final;
    try {
      const solveRes = await fetch(`${apiUrl}/api/solve`, {
        method: "POST",
        headers,
        body: JSON.stringify({
          questionText: scraped.text,
          choices: apiChoices,
          images: scraped.images,
          dataFiles: apiDataFiles
        })
      });
      if (!solveRes.ok) throw new Error(await readErrorBody(solveRes));
      const solveResult = await consumeSseResult(solveRes);
      if (solveResult.mode === "concept") {
        final = solveResult;
      } else if (solveResult.mode === "rcode") {
        btn.setAttribute("title", "Running R\u2026");
        const raceOutcome = await Promise.race([
          initWebR().then(() => "ready"),
          sleep(500).then(() => "slow")
        ]);
        if (raceOutcome === "slow") {
          btn.setAttribute("title", "First-time setup, ~15s\u2026");
          await initWebR();
          btn.setAttribute("title", "Running R\u2026");
        }
        const runResult = await runR(solveResult.rCode, apiDataFiles);
        btn.setAttribute("title", "Interpreting result\u2026");
        const interpretRes = await fetch(`${apiUrl}/api/interpret`, {
          method: "POST",
          headers,
          body: JSON.stringify({
            questionText: scraped.text,
            choices: apiChoices,
            images: scraped.images,
            dataFiles: apiDataFiles,
            rCode: solveResult.rCode,
            stdout: runResult.stdout,
            exitCode: runResult.exitCode,
            durationMs: runResult.durationMs,
            assistantBody: solveResult.assistantBody
          })
        });
        if (!interpretRes.ok) throw new Error(await readErrorBody(interpretRes));
        const interpretResult = await consumeSseResult(interpretRes);
        if (interpretResult.mode !== "calc") {
          throw new Error("Unexpected response from interpreter.");
        }
        final = interpretResult;
      } else {
        throw new Error("Unexpected response from solve.");
      }
    } catch (e) {
      setBtnState(btn, "error", e.message);
      return;
    }
    const cleaned = stripTags(final.answer);
    selectAnswerChoice(question, cleaned, final.selectedChoices ?? []);
    setBtnState(btn, "success");
  }
  async function readErrorBody(res) {
    const body = await res.text();
    let msg = body.slice(0, 200);
    try {
      const parsed = JSON.parse(body);
      if (parsed.error) msg = parsed.error;
    } catch {
    }
    return msg;
  }
  async function consumeSseResult(res) {
    const reader = res.body?.getReader();
    if (!reader) throw new Error("Empty response stream.");
    const decoder = new TextDecoder();
    let buf = "";
    let result = null;
    let errorMsg = null;
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      buf += decoder.decode(value, { stream: true });
      const frames = buf.split("\n\n");
      buf = frames.pop() ?? "";
      for (const frame of frames) {
        const dataLine = frame.split("\n").find((l2) => l2.startsWith("data:"));
        if (!dataLine) continue;
        const jsonStr = dataLine.slice(5).trim();
        if (!jsonStr) continue;
        let evt;
        try {
          evt = JSON.parse(jsonStr);
        } catch {
          continue;
        }
        if (evt.type === "result") result = evt.result;
        else if (evt.type === "error") errorMsg = evt.message;
      }
    }
    if (errorMsg) throw new Error(errorMsg);
    if (!result) throw new Error("No result received from server.");
    return result;
  }
  function sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }
  function setBtnState(btn, state, errorMsg) {
    btn.classList.remove("loading", "success", "error");
    btn.removeAttribute("title");
    switch (state) {
      case "loading":
        btn.classList.add("loading");
        btn.disabled = true;
        clear(btn);
        btn.appendChild(mkEl("span", { className: "statshelpr-spinner" }));
        return;
      case "success":
        btn.classList.add("success");
        btn.disabled = false;
        btn.textContent = "\u2713";
        setTimeout(() => {
          if (btn.classList.contains("success")) setBtnState(btn, "default");
        }, 1800);
        return;
      case "error":
        btn.classList.add("error");
        btn.disabled = false;
        btn.textContent = "!";
        btn.setAttribute("title", errorMsg ?? "");
        return;
      default:
        btn.disabled = false;
        btn.textContent = "\xB7";
        btn.setAttribute("title", "");
    }
  }
  async function scrapeQuestion(question) {
    const stem = findStem(question);
    if (!stem) throw new Error("Could not find question text.");
    const stemText = normalizeText(stem.innerText ?? stem.textContent ?? "");
    if (!stemText) throw new Error("Question text is empty.");
    const images = await collectImages(question);
    const choices = collectAnswerChoices(question);
    return { text: stemText, choices, images };
  }
  function selectAnswerChoice(question, answer, selectedLabels = []) {
    const choices = collectAnswerChoices(question);
    if (choices.length === 0) return;
    if (choices.length === 1 && choices[0]?.kind === "text-fill") {
      fillTextInput(choices[0].input, answer);
      return;
    }
    const selectedByBackend = selectedLabels.map((label) => choices.find((c2) => c2.label.toUpperCase() === label.toUpperCase())).filter((c2) => Boolean(c2));
    if (selectedByBackend.length > 0) {
      for (const c2 of selectedByBackend) applyChoice(c2);
      return;
    }
    const checkboxes = choices.filter((c2) => c2.kind === "checkbox");
    if (checkboxes.length > 0) {
      const selected = findSelectedChoices(answer, choices, true);
      for (const c2 of selected) applyChoice(c2);
      return;
    }
    const dropdown = choices.filter((c2) => c2.kind === "dropdown-option");
    if (dropdown.length > 0) {
      const c2 = pickByLetterOrText(answer, dropdown);
      if (c2) applyChoice(c2);
      return;
    }
    const radios = choices.filter((c2) => c2.kind === "radio");
    if (radios.length === 0) return;
    const c = pickByLetterOrText(answer, radios);
    if (c) applyChoice(c);
  }
  function pickByLetterOrText(answer, pool) {
    const letterMatch = answer.match(/^\s*(?:Answer\s*:?\s*)?\(?([A-Za-z]|\d{1,2})\)?[\s.,)]?/);
    if (letterMatch && letterMatch[1]) {
      const tok = letterMatch[1].toUpperCase();
      let idx = -1;
      if (/^[A-Z]$/.test(tok)) idx = tok.charCodeAt(0) - 65;
      else if (/^\d+$/.test(tok)) idx = parseInt(tok, 10) - 1;
      if (idx >= 0 && idx < pool.length) return pool[idx] ?? null;
    }
    const answerLower = answer.toLowerCase();
    let best = null;
    let bestScore = 0;
    for (const c of pool) {
      const choiceLower = c.text.toLowerCase().trim();
      if (!choiceLower) continue;
      let score = 0;
      if (answerLower.includes(choiceLower) && choiceLower.length >= 3) score = choiceLower.length;
      else if (choiceLower.includes(answerLower.slice(0, 40))) score = answerLower.length / 2;
      if (score > bestScore) {
        bestScore = score;
        best = c;
      }
    }
    return best;
  }
  function applyChoice(choice) {
    if (choice.kind === "dropdown-option") {
      selectDropdownOption(choice);
      return;
    }
    if (choice.kind === "text-fill") {
      return;
    }
    selectChoice(choice.input);
  }
  function selectDropdownOption(choice) {
    const sel = choice.input;
    if (sel.disabled) {
      sel.classList.add("statshelpr-suggested");
      return;
    }
    const proto = Object.getPrototypeOf(sel);
    const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
    if (setter && choice.optionValue !== void 0) {
      setter.call(sel, choice.optionValue);
    } else if (choice.optionIndex !== void 0) {
      sel.selectedIndex = choice.optionIndex;
    }
    sel.dispatchEvent(new Event("input", { bubbles: true }));
    sel.dispatchEvent(new Event("change", { bubbles: true }));
    sel.classList.add("statshelpr-suggested");
  }
  function fillTextInput(input, answer) {
    if (input.disabled || input.readOnly) {
      input.classList.add("statshelpr-suggested");
      return;
    }
    const m2 = answer.match(/(?:Answer|Final answer)\s*:?\s*(.+?)(?:\n|$)/i);
    let value = (m2?.[1] ?? answer).trim();
    value = value.replace(/[.,;]\s*$/, "").trim();
    value = value.replace(/^["'`]|["'`]$/g, "");
    const proto = Object.getPrototypeOf(input);
    const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
    if (setter) setter.call(input, value);
    else input.value = value;
    input.dispatchEvent(new Event("input", { bubbles: true }));
    input.dispatchEvent(new Event("change", { bubbles: true }));
    input.classList.add("statshelpr-suggested");
  }
  function collectAnswerChoices(question) {
    const inputs = [...question.querySelectorAll(CHOICE_INPUT_SELECTOR)];
    const choices = [];
    const seenRows = /* @__PURE__ */ new Set();
    inputs.forEach((input, index) => {
      const row = getChoiceRow(input);
      if (row && seenRows.has(row)) return;
      if (row) seenRows.add(row);
      const text = normalizeText(getChoiceText(input));
      if (!text) return;
      choices.push({
        input,
        label: choiceLabel(index),
        text,
        kind: input.type === "checkbox" ? "checkbox" : "radio"
      });
    });
    if (choices.length > 0) return choices;
    const selects = [...question.querySelectorAll("select")].filter(
      (sel) => isAnswerSelect(sel)
    );
    if (selects.length > 0) {
      const sel = selects[0];
      let idx = 0;
      for (const opt of [...sel.querySelectorAll("option")]) {
        const text = normalizeText(opt.textContent ?? "");
        if (!text || /^\[?\s*(select|choose)\s*\]?\s*\.{0,3}$/i.test(text)) continue;
        choices.push({
          input: sel,
          label: choiceLabel(idx),
          text,
          kind: "dropdown-option",
          optionValue: opt.value,
          optionIndex: [...sel.options].indexOf(opt)
        });
        idx += 1;
      }
      if (choices.length > 0) return choices;
    }
    const textInputs = [...question.querySelectorAll(TEXT_INPUT_SELECTOR)].filter(
      (i2) => !i2.disabled && !i2.readOnly
    );
    if (textInputs.length === 1) {
      const t = textInputs[0];
      choices.push({
        input: t,
        label: "A",
        text: t.placeholder || "(fill in your answer)",
        kind: "text-fill"
      });
    }
    return choices;
  }
  function choiceTypeForApi(c) {
    switch (c.kind) {
      case "checkbox":
        return "checkbox";
      case "dropdown-option":
        return "dropdown";
      case "text-fill":
        return "text";
      default:
        return "radio";
    }
  }
  function isAnswerSelect(sel) {
    const name = sel.name || "";
    if (/^answer_for_/i.test(name)) return true;
    if (sel.closest(".answers, .answer, .question_text, [data-testid*='question']")) return true;
    if (sel.classList.contains("question_input")) return true;
    return false;
  }
  function findSelectedChoices(answer, choices, allowMultiple) {
    const byLabel = new Map(choices.map((c) => [c.label.toUpperCase(), c]));
    const selected = /* @__PURE__ */ new Map();
    const answerLine = answer.match(/^\s*Answer\s*:?\s*(.+)$/im)?.[1] ?? answer.match(/correct(?:\s+interpretation)?(?:\(s\))?\s*:?\s*(.+)$/im)?.[1] ?? answer;
    for (const m2 of answerLine.matchAll(/\b([A-Z])\b/g)) {
      const letter = m2[1];
      if (!letter) continue;
      const c = byLabel.get(letter.toUpperCase());
      if (c) {
        selected.set(c.input, c);
        if (!allowMultiple) return [c];
      }
    }
    const answerLower = answer.toLowerCase();
    for (const c of choices) {
      const choiceLower = c.text.toLowerCase();
      if (choiceLower.length >= 12 && answerLower.includes(choiceLower)) {
        selected.set(c.input, c);
      }
    }
    return [...selected.values()];
  }
  function getChoiceText(input) {
    if (input.id) {
      const label = document.querySelector(`label[for="${cssEscape(input.id)}"]`);
      if (label) return label.textContent ?? "";
    }
    const row = getChoiceRow(input);
    if (row) {
      const at2 = row.querySelector(".answer_text, .answer_html");
      if (at2?.textContent) return at2.textContent;
      return row.textContent ?? "";
    }
    return "";
  }
  function getChoiceRow(input) {
    return input.closest(".answer") ?? input.closest(".answer_row") ?? input.closest("label") ?? input.parentElement;
  }
  function selectChoice(input) {
    const row = getChoiceRow(input);
    if (input.disabled) {
      row?.classList.add("statshelpr-suggested");
      return;
    }
    if (!input.checked) input.click();
    if (!input.checked) {
      const proto = Object.getPrototypeOf(input);
      const setter = Object.getOwnPropertyDescriptor(proto, "checked")?.set;
      setter?.call(input, true);
      input.dispatchEvent(new Event("input", { bubbles: true }));
      input.dispatchEvent(new Event("change", { bubbles: true }));
    }
    row?.classList.add("statshelpr-suggested");
  }
  function hasQuestionAncestor(question) {
    const ancestor = question.parentElement?.closest(QUESTION_SELECTOR);
    return Boolean(ancestor && findStem(ancestor));
  }
  function choiceLabel(index) {
    return String.fromCharCode(65 + index);
  }
  function normalizeText(text) {
    return text.replace(/\s+/g, " ").trim();
  }
  function cssEscape(s) {
    if (typeof CSS !== "undefined" && CSS.escape) return CSS.escape(s);
    return s.replace(/[^a-zA-Z0-9_-]/g, (c) => `\\${c}`);
  }
  function stripTags(s) {
    return s.replace(/^\s*\[(CONCEPT|RCODE|CALC)\]\s*\n?/i, "").trim();
  }
  async function loadFiles() {
    const r = await chrome.storage.local.get(STORAGE_KEY_FILES);
    const stored = r[STORAGE_KEY_FILES] ?? [];
    const now = Date.now();
    dataFiles = stored.filter((f2) => now - f2.addedAt < FILE_TTL_MS);
  }
  async function applyButtonOpacityFromStorage() {
    const r = await chrome.storage.sync.get(["buttonOpacity"]);
    applyButtonOpacity(typeof r.buttonOpacity === "number" ? r.buttonOpacity : 0.2);
  }
  function applyButtonOpacity(value) {
    const clamped = Math.min(1, Math.max(0.05, value));
    document.documentElement.style.setProperty("--sh-idle-opacity", String(clamped));
  }
  async function getConfig() {
    const r = await chrome.storage.sync.get(["apiUrl", "licenseKey"]);
    return r;
  }
  async function collectImages(root) {
    const out = [];
    const seen = /* @__PURE__ */ new Set();
    for (const img of [...root.querySelectorAll("img")]) {
      const src = img.currentSrc || img.src;
      if (!src) continue;
      if (src.startsWith("data:") && src.length < 200) continue;
      if (/avatar|spinner|loading|icon-/.test(src)) continue;
      if (seen.has(src)) continue;
      seen.add(src);
      try {
        const block = await urlToImageBlock(src);
        if (block) out.push(block);
      } catch {
      }
    }
    for (const c of [...root.querySelectorAll("canvas")]) {
      try {
        const dataUrl = c.toDataURL("image/png");
        const data = dataUrl.split(",")[1];
        if (!data) continue;
        const key = `canvas:${data.length}`;
        if (seen.has(key)) continue;
        seen.add(key);
        out.push({ data, mediaType: "image/png" });
      } catch {
      }
    }
    return out;
  }
  async function urlToImageBlock(url) {
    const res = await fetch(url, { credentials: "include" });
    if (!res.ok) return null;
    const blob = await res.blob();
    const t = blob.type.toLowerCase();
    let mediaType = null;
    if (t === "image/png") mediaType = "image/png";
    else if (t === "image/jpeg" || t === "image/jpg") mediaType = "image/jpeg";
    else if (t === "image/webp") mediaType = "image/webp";
    if (!mediaType) return null;
    const data = await new Promise((resolve, reject) => {
      const r = new FileReader();
      r.onload = () => {
        const result = r.result;
        if (typeof result !== "string") return reject(new Error("read failed"));
        const idx = result.indexOf(",");
        resolve(idx >= 0 ? result.slice(idx + 1) : result);
      };
      r.onerror = () => reject(r.error);
      r.readAsDataURL(blob);
    });
    return { data, mediaType };
  }
  function findStem(question) {
    for (const sel of SELECTORS_STEM) {
      const el = question.querySelector(sel);
      if (el && (el.innerText || el.textContent)?.trim()) return el;
    }
    return null;
  }
  function mkEl(tag, opts = {}, children = []) {
    const node = document.createElement(tag);
    if (opts.className) node.className = opts.className;
    if (opts.id) node.id = opts.id;
    if (opts.title) node.title = opts.title;
    if (opts.style) node.setAttribute("style", opts.style);
    if (opts.type && tag === "button")
      node.type = opts.type;
    if (opts.text !== void 0) node.textContent = opts.text;
    for (const c of children) {
      node.appendChild(typeof c === "string" ? document.createTextNode(c) : c);
    }
    return node;
  }
  function clear(node) {
    while (node.firstChild) node.removeChild(node.firstChild);
  }
})();
