
Deno.env = {
  get: function() {
    return undefined;
  }
}

// shared/ipc/ipc-service.js
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
var minimal$1 = {
  exports: {}
};
var indexMinimal = {};
var minimal = {};
var aspromise;
var hasRequiredAspromise;
function requireAspromise() {
  if (hasRequiredAspromise) {
    return aspromise;
  }
  hasRequiredAspromise = 1;
  aspromise = asPromise;
  function asPromise(fn, ctx) {
    var params = new Array(arguments.length - 1), offset = 0, index = 2, pending = true;
    while (index < arguments.length) {
      params[offset++] = arguments[index++];
    }
    return new Promise(function executor(resolve, reject) {
      params[offset] = function callback(err) {
        if (pending) {
          pending = false;
          if (err) {
            reject(err);
          } else {
            var params2 = new Array(arguments.length - 1), offset2 = 0;
            while (offset2 < params2.length) {
              params2[offset2++] = arguments[offset2];
            }
            resolve.apply(null, params2);
          }
        }
      };
      try {
        fn.apply(ctx || null, params);
      } catch (err) {
        if (pending) {
          pending = false;
          reject(err);
        }
      }
    });
  }
  return aspromise;
}
var base64$1 = {};
var hasRequiredBase64;
function requireBase64() {
  if (hasRequiredBase64) {
    return base64$1;
  }
  hasRequiredBase64 = 1;
  (function(exports) {
    var base642 = exports;
    base642.length = function length(string) {
      var p = string.length;
      if (!p) {
        return 0;
      }
      var n = 0;
      while (--p % 4 > 1 && string.charAt(p) === "=") {
        ++n;
      }
      return Math.ceil(string.length * 3) / 4 - n;
    };
    var b64 = new Array(64);
    var s64 = new Array(123);
    for (var i = 0; i < 64; ) {
      s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
    }
    base642.encode = function encode(buffer, start, end2) {
      var parts = null, chunk = [];
      var i2 = 0, j = 0, t;
      while (start < end2) {
        var b = buffer[start++];
        switch (j) {
          case 0:
            chunk[i2++] = b64[b >> 2];
            t = (b & 3) << 4;
            j = 1;
            break;
          case 1:
            chunk[i2++] = b64[t | b >> 4];
            t = (b & 15) << 2;
            j = 2;
            break;
          case 2:
            chunk[i2++] = b64[t | b >> 6];
            chunk[i2++] = b64[b & 63];
            j = 0;
            break;
        }
        if (i2 > 8191) {
          (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
          i2 = 0;
        }
      }
      if (j) {
        chunk[i2++] = b64[t];
        chunk[i2++] = 61;
        if (j === 1) {
          chunk[i2++] = 61;
        }
      }
      if (parts) {
        if (i2) {
          parts.push(String.fromCharCode.apply(String, chunk.slice(0, i2)));
        }
        return parts.join("");
      }
      return String.fromCharCode.apply(String, chunk.slice(0, i2));
    };
    var invalidEncoding = "invalid encoding";
    base642.decode = function decode(string, buffer, offset) {
      var start = offset;
      var j = 0, t;
      for (var i2 = 0; i2 < string.length; ) {
        var c = string.charCodeAt(i2++);
        if (c === 61 && j > 1) {
          break;
        }
        if ((c = s64[c]) === void 0) {
          throw Error(invalidEncoding);
        }
        switch (j) {
          case 0:
            t = c;
            j = 1;
            break;
          case 1:
            buffer[offset++] = t << 2 | (c & 48) >> 4;
            t = c;
            j = 2;
            break;
          case 2:
            buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;
            t = c;
            j = 3;
            break;
          case 3:
            buffer[offset++] = (t & 3) << 6 | c;
            j = 0;
            break;
        }
      }
      if (j === 1) {
        throw Error(invalidEncoding);
      }
      return offset - start;
    };
    base642.test = function test(string) {
      return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);
    };
  })(base64$1);
  return base64$1;
}
var eventemitter;
var hasRequiredEventemitter;
function requireEventemitter() {
  if (hasRequiredEventemitter) {
    return eventemitter;
  }
  hasRequiredEventemitter = 1;
  eventemitter = EventEmitter;
  function EventEmitter() {
    this._listeners = {};
  }
  EventEmitter.prototype.on = function on(evt, fn, ctx) {
    (this._listeners[evt] || (this._listeners[evt] = [])).push({
      fn,
      ctx: ctx || this
    });
    return this;
  };
  EventEmitter.prototype.off = function off(evt, fn) {
    if (evt === void 0) {
      this._listeners = {};
    } else {
      if (fn === void 0) {
        this._listeners[evt] = [];
      } else {
        var listeners = this._listeners[evt];
        for (var i = 0; i < listeners.length; ) {
          if (listeners[i].fn === fn) {
            listeners.splice(i, 1);
          } else {
            ++i;
          }
        }
      }
    }
    return this;
  };
  EventEmitter.prototype.emit = function emit(evt) {
    var listeners = this._listeners[evt];
    if (listeners) {
      var args = [], i = 1;
      for (; i < arguments.length; ) {
        args.push(arguments[i++]);
      }
      for (i = 0; i < listeners.length; ) {
        listeners[i].fn.apply(listeners[i++].ctx, args);
      }
    }
    return this;
  };
  return eventemitter;
}
var float;
var hasRequiredFloat;
function requireFloat() {
  if (hasRequiredFloat) {
    return float;
  }
  hasRequiredFloat = 1;
  float = factory(factory);
  function factory(exports) {
    if (typeof Float32Array !== "undefined") {
      (function() {
        var f32 = new Float32Array([
          -0
        ]), f8b = new Uint8Array(f32.buffer), le = f8b[3] === 128;
        function writeFloat_f32_cpy(val, buf, pos) {
          f32[0] = val;
          buf[pos] = f8b[0];
          buf[pos + 1] = f8b[1];
          buf[pos + 2] = f8b[2];
          buf[pos + 3] = f8b[3];
        }
        function writeFloat_f32_rev(val, buf, pos) {
          f32[0] = val;
          buf[pos] = f8b[3];
          buf[pos + 1] = f8b[2];
          buf[pos + 2] = f8b[1];
          buf[pos + 3] = f8b[0];
        }
        exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;
        exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;
        function readFloat_f32_cpy(buf, pos) {
          f8b[0] = buf[pos];
          f8b[1] = buf[pos + 1];
          f8b[2] = buf[pos + 2];
          f8b[3] = buf[pos + 3];
          return f32[0];
        }
        function readFloat_f32_rev(buf, pos) {
          f8b[3] = buf[pos];
          f8b[2] = buf[pos + 1];
          f8b[1] = buf[pos + 2];
          f8b[0] = buf[pos + 3];
          return f32[0];
        }
        exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;
        exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;
      })();
    } else {
      (function() {
        function writeFloat_ieee754(writeUint, val, buf, pos) {
          var sign = val < 0 ? 1 : 0;
          if (sign) {
            val = -val;
          }
          if (val === 0) {
            writeUint(1 / val > 0 ? (
              /* positive */
              0
            ) : (
              /* negative 0 */
              2147483648
            ), buf, pos);
          } else if (isNaN(val)) {
            writeUint(2143289344, buf, pos);
          } else if (val > 34028234663852886e22) {
            writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);
          } else if (val < 11754943508222875e-54) {
            writeUint((sign << 31 | Math.round(val / 1401298464324817e-60)) >>> 0, buf, pos);
          } else {
            var exponent = Math.floor(Math.log(val) / Math.LN2), mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;
            writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);
          }
        }
        exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);
        exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);
        function readFloat_ieee754(readUint, buf, pos) {
          var uint = readUint(buf, pos), sign = (uint >> 31) * 2 + 1, exponent = uint >>> 23 & 255, mantissa = uint & 8388607;
          return exponent === 255 ? mantissa ? NaN : sign * Infinity : exponent === 0 ? sign * 1401298464324817e-60 * mantissa : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);
        }
        exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);
        exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);
      })();
    }
    if (typeof Float64Array !== "undefined") {
      (function() {
        var f64 = new Float64Array([
          -0
        ]), f8b = new Uint8Array(f64.buffer), le = f8b[7] === 128;
        function writeDouble_f64_cpy(val, buf, pos) {
          f64[0] = val;
          buf[pos] = f8b[0];
          buf[pos + 1] = f8b[1];
          buf[pos + 2] = f8b[2];
          buf[pos + 3] = f8b[3];
          buf[pos + 4] = f8b[4];
          buf[pos + 5] = f8b[5];
          buf[pos + 6] = f8b[6];
          buf[pos + 7] = f8b[7];
        }
        function writeDouble_f64_rev(val, buf, pos) {
          f64[0] = val;
          buf[pos] = f8b[7];
          buf[pos + 1] = f8b[6];
          buf[pos + 2] = f8b[5];
          buf[pos + 3] = f8b[4];
          buf[pos + 4] = f8b[3];
          buf[pos + 5] = f8b[2];
          buf[pos + 6] = f8b[1];
          buf[pos + 7] = f8b[0];
        }
        exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;
        exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;
        function readDouble_f64_cpy(buf, pos) {
          f8b[0] = buf[pos];
          f8b[1] = buf[pos + 1];
          f8b[2] = buf[pos + 2];
          f8b[3] = buf[pos + 3];
          f8b[4] = buf[pos + 4];
          f8b[5] = buf[pos + 5];
          f8b[6] = buf[pos + 6];
          f8b[7] = buf[pos + 7];
          return f64[0];
        }
        function readDouble_f64_rev(buf, pos) {
          f8b[7] = buf[pos];
          f8b[6] = buf[pos + 1];
          f8b[5] = buf[pos + 2];
          f8b[4] = buf[pos + 3];
          f8b[3] = buf[pos + 4];
          f8b[2] = buf[pos + 5];
          f8b[1] = buf[pos + 6];
          f8b[0] = buf[pos + 7];
          return f64[0];
        }
        exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;
        exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;
      })();
    } else {
      (function() {
        function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {
          var sign = val < 0 ? 1 : 0;
          if (sign) {
            val = -val;
          }
          if (val === 0) {
            writeUint(0, buf, pos + off0);
            writeUint(1 / val > 0 ? (
              /* positive */
              0
            ) : (
              /* negative 0 */
              2147483648
            ), buf, pos + off1);
          } else if (isNaN(val)) {
            writeUint(0, buf, pos + off0);
            writeUint(2146959360, buf, pos + off1);
          } else if (val > 17976931348623157e292) {
            writeUint(0, buf, pos + off0);
            writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);
          } else {
            var mantissa;
            if (val < 22250738585072014e-324) {
              mantissa = val / 5e-324;
              writeUint(mantissa >>> 0, buf, pos + off0);
              writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);
            } else {
              var exponent = Math.floor(Math.log(val) / Math.LN2);
              if (exponent === 1024) {
                exponent = 1023;
              }
              mantissa = val * Math.pow(2, -exponent);
              writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);
              writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);
            }
          }
        }
        exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);
        exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);
        function readDouble_ieee754(readUint, off0, off1, buf, pos) {
          var lo = readUint(buf, pos + off0), hi = readUint(buf, pos + off1);
          var sign = (hi >> 31) * 2 + 1, exponent = hi >>> 20 & 2047, mantissa = 4294967296 * (hi & 1048575) + lo;
          return exponent === 2047 ? mantissa ? NaN : sign * Infinity : exponent === 0 ? sign * 5e-324 * mantissa : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);
        }
        exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);
        exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);
      })();
    }
    return exports;
  }
  function writeUintLE(val, buf, pos) {
    buf[pos] = val & 255;
    buf[pos + 1] = val >>> 8 & 255;
    buf[pos + 2] = val >>> 16 & 255;
    buf[pos + 3] = val >>> 24;
  }
  function writeUintBE(val, buf, pos) {
    buf[pos] = val >>> 24;
    buf[pos + 1] = val >>> 16 & 255;
    buf[pos + 2] = val >>> 8 & 255;
    buf[pos + 3] = val & 255;
  }
  function readUintLE(buf, pos) {
    return (buf[pos] | buf[pos + 1] << 8 | buf[pos + 2] << 16 | buf[pos + 3] << 24) >>> 0;
  }
  function readUintBE(buf, pos) {
    return (buf[pos] << 24 | buf[pos + 1] << 16 | buf[pos + 2] << 8 | buf[pos + 3]) >>> 0;
  }
  return float;
}
var inquire_1;
var hasRequiredInquire;
function requireInquire() {
  if (hasRequiredInquire) {
    return inquire_1;
  }
  hasRequiredInquire = 1;
  inquire_1 = inquire;
  function inquire(moduleName) {
    try {
      var mod = eval("quire".replace(/^/, "re"))(moduleName);
      if (mod && (mod.length || Object.keys(mod).length)) {
        return mod;
      }
    } catch (e) {
    }
    return null;
  }
  return inquire_1;
}
var utf8$2 = {};
var hasRequiredUtf8;
function requireUtf8() {
  if (hasRequiredUtf8) {
    return utf8$2;
  }
  hasRequiredUtf8 = 1;
  (function(exports) {
    var utf82 = exports;
    utf82.length = function utf8_length(string) {
      var len = 0, c = 0;
      for (var i = 0; i < string.length; ++i) {
        c = string.charCodeAt(i);
        if (c < 128) {
          len += 1;
        } else if (c < 2048) {
          len += 2;
        } else if ((c & 64512) === 55296 && (string.charCodeAt(i + 1) & 64512) === 56320) {
          ++i;
          len += 4;
        } else {
          len += 3;
        }
      }
      return len;
    };
    utf82.read = function utf8_read(buffer, start, end2) {
      var len = end2 - start;
      if (len < 1) {
        return "";
      }
      var parts = null, chunk = [], i = 0, t;
      while (start < end2) {
        t = buffer[start++];
        if (t < 128) {
          chunk[i++] = t;
        } else if (t > 191 && t < 224) {
          chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;
        } else if (t > 239 && t < 365) {
          t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 65536;
          chunk[i++] = 55296 + (t >> 10);
          chunk[i++] = 56320 + (t & 1023);
        } else {
          chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;
        }
        if (i > 8191) {
          (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
          i = 0;
        }
      }
      if (parts) {
        if (i) {
          parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
        }
        return parts.join("");
      }
      return String.fromCharCode.apply(String, chunk.slice(0, i));
    };
    utf82.write = function utf8_write(string, buffer, offset) {
      var start = offset, c1, c2;
      for (var i = 0; i < string.length; ++i) {
        c1 = string.charCodeAt(i);
        if (c1 < 128) {
          buffer[offset++] = c1;
        } else if (c1 < 2048) {
          buffer[offset++] = c1 >> 6 | 192;
          buffer[offset++] = c1 & 63 | 128;
        } else if ((c1 & 64512) === 55296 && ((c2 = string.charCodeAt(i + 1)) & 64512) === 56320) {
          c1 = 65536 + ((c1 & 1023) << 10) + (c2 & 1023);
          ++i;
          buffer[offset++] = c1 >> 18 | 240;
          buffer[offset++] = c1 >> 12 & 63 | 128;
          buffer[offset++] = c1 >> 6 & 63 | 128;
          buffer[offset++] = c1 & 63 | 128;
        } else {
          buffer[offset++] = c1 >> 12 | 224;
          buffer[offset++] = c1 >> 6 & 63 | 128;
          buffer[offset++] = c1 & 63 | 128;
        }
      }
      return offset - start;
    };
  })(utf8$2);
  return utf8$2;
}
var pool_1;
var hasRequiredPool;
function requirePool() {
  if (hasRequiredPool) {
    return pool_1;
  }
  hasRequiredPool = 1;
  pool_1 = pool;
  function pool(alloc3, slice2, size) {
    var SIZE = size || 8192;
    var MAX = SIZE >>> 1;
    var slab = null;
    var offset = SIZE;
    return function pool_alloc(size2) {
      if (size2 < 1 || size2 > MAX) {
        return alloc3(size2);
      }
      if (offset + size2 > SIZE) {
        slab = alloc3(SIZE);
        offset = 0;
      }
      var buf = slice2.call(slab, offset, offset += size2);
      if (offset & 7) {
        offset = (offset | 7) + 1;
      }
      return buf;
    };
  }
  return pool_1;
}
var longbits;
var hasRequiredLongbits;
function requireLongbits() {
  if (hasRequiredLongbits) {
    return longbits;
  }
  hasRequiredLongbits = 1;
  longbits = LongBits2;
  var util2 = requireMinimal();
  function LongBits2(lo, hi) {
    this.lo = lo >>> 0;
    this.hi = hi >>> 0;
  }
  var zero = LongBits2.zero = new LongBits2(0, 0);
  zero.toNumber = function() {
    return 0;
  };
  zero.zzEncode = zero.zzDecode = function() {
    return this;
  };
  zero.length = function() {
    return 1;
  };
  var zeroHash = LongBits2.zeroHash = "\0\0\0\0\0\0\0\0";
  LongBits2.fromNumber = function fromNumber(value) {
    if (value === 0) {
      return zero;
    }
    var sign = value < 0;
    if (sign) {
      value = -value;
    }
    var lo = value >>> 0, hi = (value - lo) / 4294967296 >>> 0;
    if (sign) {
      hi = ~hi >>> 0;
      lo = ~lo >>> 0;
      if (++lo > 4294967295) {
        lo = 0;
        if (++hi > 4294967295) {
          hi = 0;
        }
      }
    }
    return new LongBits2(lo, hi);
  };
  LongBits2.from = function from2(value) {
    if (typeof value === "number") {
      return LongBits2.fromNumber(value);
    }
    if (util2.isString(value)) {
      if (util2.Long) {
        value = util2.Long.fromString(value);
      } else {
        return LongBits2.fromNumber(parseInt(value, 10));
      }
    }
    return value.low || value.high ? new LongBits2(value.low >>> 0, value.high >>> 0) : zero;
  };
  LongBits2.prototype.toNumber = function toNumber(unsigned) {
    if (!unsigned && this.hi >>> 31) {
      var lo = ~this.lo + 1 >>> 0, hi = ~this.hi >>> 0;
      if (!lo) {
        hi = hi + 1 >>> 0;
      }
      return -(lo + hi * 4294967296);
    }
    return this.lo + this.hi * 4294967296;
  };
  LongBits2.prototype.toLong = function toLong(unsigned) {
    return util2.Long ? new util2.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) : {
      low: this.lo | 0,
      high: this.hi | 0,
      unsigned: Boolean(unsigned)
    };
  };
  var charCodeAt = String.prototype.charCodeAt;
  LongBits2.fromHash = function fromHash(hash) {
    if (hash === zeroHash) {
      return zero;
    }
    return new LongBits2((charCodeAt.call(hash, 0) | charCodeAt.call(hash, 1) << 8 | charCodeAt.call(hash, 2) << 16 | charCodeAt.call(hash, 3) << 24) >>> 0, (charCodeAt.call(hash, 4) | charCodeAt.call(hash, 5) << 8 | charCodeAt.call(hash, 6) << 16 | charCodeAt.call(hash, 7) << 24) >>> 0);
  };
  LongBits2.prototype.toHash = function toHash() {
    return String.fromCharCode(this.lo & 255, this.lo >>> 8 & 255, this.lo >>> 16 & 255, this.lo >>> 24, this.hi & 255, this.hi >>> 8 & 255, this.hi >>> 16 & 255, this.hi >>> 24);
  };
  LongBits2.prototype.zzEncode = function zzEncode() {
    var mask = this.hi >> 31;
    this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;
    this.lo = (this.lo << 1 ^ mask) >>> 0;
    return this;
  };
  LongBits2.prototype.zzDecode = function zzDecode() {
    var mask = -(this.lo & 1);
    this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;
    this.hi = (this.hi >>> 1 ^ mask) >>> 0;
    return this;
  };
  LongBits2.prototype.length = function length() {
    var part0 = this.lo, part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, part2 = this.hi >>> 24;
    return part2 === 0 ? part1 === 0 ? part0 < 16384 ? part0 < 128 ? 1 : 2 : part0 < 2097152 ? 3 : 4 : part1 < 16384 ? part1 < 128 ? 5 : 6 : part1 < 2097152 ? 7 : 8 : part2 < 128 ? 9 : 10;
  };
  return longbits;
}
var hasRequiredMinimal;
function requireMinimal() {
  if (hasRequiredMinimal) {
    return minimal;
  }
  hasRequiredMinimal = 1;
  (function(exports) {
    var util2 = exports;
    util2.asPromise = requireAspromise();
    util2.base64 = requireBase64();
    util2.EventEmitter = requireEventemitter();
    util2.float = requireFloat();
    util2.inquire = requireInquire();
    util2.utf8 = requireUtf8();
    util2.pool = requirePool();
    util2.LongBits = requireLongbits();
    util2.isNode = Boolean(typeof commonjsGlobal !== "undefined" && commonjsGlobal && commonjsGlobal.process && commonjsGlobal.process.versions && commonjsGlobal.process.versions.node);
    util2.global = util2.isNode && commonjsGlobal || typeof window !== "undefined" && window || typeof self !== "undefined" && self || commonjsGlobal;
    util2.emptyArray = Object.freeze ? Object.freeze([]) : (
      /* istanbul ignore next */
      []
    );
    util2.emptyObject = Object.freeze ? Object.freeze({}) : (
      /* istanbul ignore next */
      {}
    );
    util2.isInteger = Number.isInteger || /* istanbul ignore next */
    function isInteger(value) {
      return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
    };
    util2.isString = function isString(value) {
      return typeof value === "string" || value instanceof String;
    };
    util2.isObject = function isObject(value) {
      return value && typeof value === "object";
    };
    util2.isset = /**
    * Checks if a property on a message is considered to be present.
    * @param {Object} obj Plain object or message instance
    * @param {string} prop Property name
    * @returns {boolean} `true` if considered to be present, otherwise `false`
    */
    util2.isSet = function isSet(obj, prop) {
      var value = obj[prop];
      if (value != null && obj.hasOwnProperty(prop)) {
        return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;
      }
      return false;
    };
    util2.Buffer = function() {
      try {
        var Buffer2 = util2.inquire("buffer").Buffer;
        return Buffer2.prototype.utf8Write ? Buffer2 : (
          /* istanbul ignore next */
          null
        );
      } catch (e) {
        return null;
      }
    }();
    util2._Buffer_from = null;
    util2._Buffer_allocUnsafe = null;
    util2.newBuffer = function newBuffer(sizeOrArray) {
      return typeof sizeOrArray === "number" ? util2.Buffer ? util2._Buffer_allocUnsafe(sizeOrArray) : new util2.Array(sizeOrArray) : util2.Buffer ? util2._Buffer_from(sizeOrArray) : typeof Uint8Array === "undefined" ? sizeOrArray : new Uint8Array(sizeOrArray);
    };
    util2.Array = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
    util2.Long = /* istanbul ignore next */
    util2.global.dcodeIO && /* istanbul ignore next */
    util2.global.dcodeIO.Long || /* istanbul ignore next */
    util2.global.Long || util2.inquire("long");
    util2.key2Re = /^true|false|0|1$/;
    util2.key32Re = /^-?(?:0|[1-9][0-9]*)$/;
    util2.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;
    util2.longToHash = function longToHash(value) {
      return value ? util2.LongBits.from(value).toHash() : util2.LongBits.zeroHash;
    };
    util2.longFromHash = function longFromHash(hash, unsigned) {
      var bits = util2.LongBits.fromHash(hash);
      if (util2.Long) {
        return util2.Long.fromBits(bits.lo, bits.hi, unsigned);
      }
      return bits.toNumber(Boolean(unsigned));
    };
    function merge(dst, src, ifNotSet) {
      for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) {
        if (dst[keys[i]] === void 0 || !ifNotSet) {
          dst[keys[i]] = src[keys[i]];
        }
      }
      return dst;
    }
    util2.merge = merge;
    util2.lcFirst = function lcFirst(str) {
      return str.charAt(0).toLowerCase() + str.substring(1);
    };
    function newError(name) {
      function CustomError(message, properties) {
        if (!(this instanceof CustomError)) {
          return new CustomError(message, properties);
        }
        Object.defineProperty(this, "message", {
          get: function() {
            return message;
          }
        });
        if (Error.captureStackTrace) {
          Error.captureStackTrace(this, CustomError);
        } else {
          Object.defineProperty(this, "stack", {
            value: new Error().stack || ""
          });
        }
        if (properties) {
          merge(this, properties);
        }
      }
      CustomError.prototype = Object.create(Error.prototype, {
        constructor: {
          value: CustomError,
          writable: true,
          enumerable: false,
          configurable: true
        },
        name: {
          get() {
            return name;
          },
          set: void 0,
          enumerable: false,
          // configurable: false would accurately preserve the behavior of
          // the original, but I'm guessing that was not intentional.
          // For an actual error subclass, this property would
          // be configurable.
          configurable: true
        },
        toString: {
          value() {
            return this.name + ": " + this.message;
          },
          writable: true,
          enumerable: false,
          configurable: true
        }
      });
      return CustomError;
    }
    util2.newError = newError;
    util2.ProtocolError = newError("ProtocolError");
    util2.oneOfGetter = function getOneOf(fieldNames) {
      var fieldMap = {};
      for (var i = 0; i < fieldNames.length; ++i) {
        fieldMap[fieldNames[i]] = 1;
      }
      return function() {
        for (var keys = Object.keys(this), i2 = keys.length - 1; i2 > -1; --i2) {
          if (fieldMap[keys[i2]] === 1 && this[keys[i2]] !== void 0 && this[keys[i2]] !== null) {
            return keys[i2];
          }
        }
      };
    };
    util2.oneOfSetter = function setOneOf(fieldNames) {
      return function(name) {
        for (var i = 0; i < fieldNames.length; ++i) {
          if (fieldNames[i] !== name) {
            delete this[fieldNames[i]];
          }
        }
      };
    };
    util2.toJSONOptions = {
      longs: String,
      enums: String,
      bytes: String,
      json: true
    };
    util2._configure = function() {
      var Buffer2 = util2.Buffer;
      if (!Buffer2) {
        util2._Buffer_from = util2._Buffer_allocUnsafe = null;
        return;
      }
      util2._Buffer_from = Buffer2.from !== Uint8Array.from && Buffer2.from || /* istanbul ignore next */
      function Buffer_from(value, encoding) {
        return new Buffer2(value, encoding);
      };
      util2._Buffer_allocUnsafe = Buffer2.allocUnsafe || /* istanbul ignore next */
      function Buffer_allocUnsafe(size) {
        return new Buffer2(size);
      };
    };
  })(minimal);
  return minimal;
}
var writer = Writer$1;
var util$4 = requireMinimal();
var BufferWriter$1;
var LongBits$1 = util$4.LongBits;
var base64 = util$4.base64;
var utf8$1 = util$4.utf8;
function Op(fn, len, val) {
  this.fn = fn;
  this.len = len;
  this.next = void 0;
  this.val = val;
}
function noop() {
}
function State(writer2) {
  this.head = writer2.head;
  this.tail = writer2.tail;
  this.len = writer2.len;
  this.next = writer2.states;
}
function Writer$1() {
  this.len = 0;
  this.head = new Op(noop, 0, 0);
  this.tail = this.head;
  this.states = null;
}
var create$1 = function create() {
  return util$4.Buffer ? function create_buffer_setup() {
    return (Writer$1.create = function create_buffer() {
      return new BufferWriter$1();
    })();
  } : function create_array3() {
    return new Writer$1();
  };
};
Writer$1.create = create$1();
Writer$1.alloc = function alloc(size) {
  return new util$4.Array(size);
};
if (util$4.Array !== Array) {
  Writer$1.alloc = util$4.pool(Writer$1.alloc, util$4.Array.prototype.subarray);
}
Writer$1.prototype._push = function push(fn, len, val) {
  this.tail = this.tail.next = new Op(fn, len, val);
  this.len += len;
  return this;
};
function writeByte(val, buf, pos) {
  buf[pos] = val & 255;
}
function writeVarint32(val, buf, pos) {
  while (val > 127) {
    buf[pos++] = val & 127 | 128;
    val >>>= 7;
  }
  buf[pos] = val;
}
function VarintOp(len, val) {
  this.len = len;
  this.next = void 0;
  this.val = val;
}
VarintOp.prototype = Object.create(Op.prototype);
VarintOp.prototype.fn = writeVarint32;
Writer$1.prototype.uint32 = function write_uint32(value) {
  this.len += (this.tail = this.tail.next = new VarintOp((value = value >>> 0) < 128 ? 1 : value < 16384 ? 2 : value < 2097152 ? 3 : value < 268435456 ? 4 : 5, value)).len;
  return this;
};
Writer$1.prototype.int32 = function write_int32(value) {
  return value < 0 ? this._push(writeVarint64, 10, LongBits$1.fromNumber(value)) : this.uint32(value);
};
Writer$1.prototype.sint32 = function write_sint32(value) {
  return this.uint32((value << 1 ^ value >> 31) >>> 0);
};
function writeVarint64(val, buf, pos) {
  while (val.hi) {
    buf[pos++] = val.lo & 127 | 128;
    val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;
    val.hi >>>= 7;
  }
  while (val.lo > 127) {
    buf[pos++] = val.lo & 127 | 128;
    val.lo = val.lo >>> 7;
  }
  buf[pos++] = val.lo;
}
Writer$1.prototype.uint64 = function write_uint64(value) {
  var bits = LongBits$1.from(value);
  return this._push(writeVarint64, bits.length(), bits);
};
Writer$1.prototype.int64 = Writer$1.prototype.uint64;
Writer$1.prototype.sint64 = function write_sint64(value) {
  var bits = LongBits$1.from(value).zzEncode();
  return this._push(writeVarint64, bits.length(), bits);
};
Writer$1.prototype.bool = function write_bool(value) {
  return this._push(writeByte, 1, value ? 1 : 0);
};
function writeFixed32(val, buf, pos) {
  buf[pos] = val & 255;
  buf[pos + 1] = val >>> 8 & 255;
  buf[pos + 2] = val >>> 16 & 255;
  buf[pos + 3] = val >>> 24;
}
Writer$1.prototype.fixed32 = function write_fixed32(value) {
  return this._push(writeFixed32, 4, value >>> 0);
};
Writer$1.prototype.sfixed32 = Writer$1.prototype.fixed32;
Writer$1.prototype.fixed64 = function write_fixed64(value) {
  var bits = LongBits$1.from(value);
  return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);
};
Writer$1.prototype.sfixed64 = Writer$1.prototype.fixed64;
Writer$1.prototype.float = function write_float(value) {
  return this._push(util$4.float.writeFloatLE, 4, value);
};
Writer$1.prototype.double = function write_double(value) {
  return this._push(util$4.float.writeDoubleLE, 8, value);
};
var writeBytes = util$4.Array.prototype.set ? function writeBytes_set(val, buf, pos) {
  buf.set(val, pos);
} : function writeBytes_for(val, buf, pos) {
  for (var i = 0; i < val.length; ++i) {
    buf[pos + i] = val[i];
  }
};
Writer$1.prototype.bytes = function write_bytes(value) {
  var len = value.length >>> 0;
  if (!len) {
    return this._push(writeByte, 1, 0);
  }
  if (util$4.isString(value)) {
    var buf = Writer$1.alloc(len = base64.length(value));
    base64.decode(value, buf, 0);
    value = buf;
  }
  return this.uint32(len)._push(writeBytes, len, value);
};
Writer$1.prototype.string = function write_string(value) {
  var len = utf8$1.length(value);
  return len ? this.uint32(len)._push(utf8$1.write, len, value) : this._push(writeByte, 1, 0);
};
Writer$1.prototype.fork = function fork() {
  this.states = new State(this);
  this.head = this.tail = new Op(noop, 0, 0);
  this.len = 0;
  return this;
};
Writer$1.prototype.reset = function reset() {
  if (this.states) {
    this.head = this.states.head;
    this.tail = this.states.tail;
    this.len = this.states.len;
    this.states = this.states.next;
  } else {
    this.head = this.tail = new Op(noop, 0, 0);
    this.len = 0;
  }
  return this;
};
Writer$1.prototype.ldelim = function ldelim() {
  var head = this.head, tail = this.tail, len = this.len;
  this.reset().uint32(len);
  if (len) {
    this.tail.next = head.next;
    this.tail = tail;
    this.len += len;
  }
  return this;
};
Writer$1.prototype.finish = function finish() {
  var head = this.head.next, buf = this.constructor.alloc(this.len), pos = 0;
  while (head) {
    head.fn(head.val, buf, pos);
    pos += head.len;
    head = head.next;
  }
  return buf;
};
Writer$1._configure = function(BufferWriter_) {
  BufferWriter$1 = BufferWriter_;
  Writer$1.create = create$1();
  BufferWriter$1._configure();
};
var writer_buffer = BufferWriter;
var Writer = writer;
(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;
var util$3 = requireMinimal();
function BufferWriter() {
  Writer.call(this);
}
BufferWriter._configure = function() {
  BufferWriter.alloc = util$3._Buffer_allocUnsafe;
  BufferWriter.writeBytesBuffer = util$3.Buffer && util$3.Buffer.prototype instanceof Uint8Array && util$3.Buffer.prototype.set.name === "set" ? function writeBytesBuffer_set(val, buf, pos) {
    buf.set(val, pos);
  } : function writeBytesBuffer_copy(val, buf, pos) {
    if (val.copy) {
      val.copy(buf, pos, 0, val.length);
    } else {
      for (var i = 0; i < val.length; ) {
        buf[pos++] = val[i++];
      }
    }
  };
};
BufferWriter.prototype.bytes = function write_bytes_buffer(value) {
  if (util$3.isString(value)) {
    value = util$3._Buffer_from(value, "base64");
  }
  var len = value.length >>> 0;
  this.uint32(len);
  if (len) {
    this._push(BufferWriter.writeBytesBuffer, len, value);
  }
  return this;
};
function writeStringBuffer(val, buf, pos) {
  if (val.length < 40) {
    util$3.utf8.write(val, buf, pos);
  } else if (buf.utf8Write) {
    buf.utf8Write(val, pos);
  } else {
    buf.write(val, pos);
  }
}
BufferWriter.prototype.string = function write_string_buffer(value) {
  var len = util$3.Buffer.byteLength(value);
  this.uint32(len);
  if (len) {
    this._push(writeStringBuffer, len, value);
  }
  return this;
};
BufferWriter._configure();
var reader = Reader$1;
var util$2 = requireMinimal();
var BufferReader$1;
var LongBits = util$2.LongBits;
var utf8 = util$2.utf8;
function indexOutOfRange(reader2, writeLength) {
  return RangeError("index out of range: " + reader2.pos + " + " + (writeLength || 1) + " > " + reader2.len);
}
function Reader$1(buffer) {
  this.buf = buffer;
  this.pos = 0;
  this.len = buffer.length;
}
var create_array = typeof Uint8Array !== "undefined" ? function create_typed_array(buffer) {
  if (buffer instanceof Uint8Array || Array.isArray(buffer)) {
    return new Reader$1(buffer);
  }
  throw Error("illegal buffer");
} : function create_array2(buffer) {
  if (Array.isArray(buffer)) {
    return new Reader$1(buffer);
  }
  throw Error("illegal buffer");
};
var create2 = function create3() {
  return util$2.Buffer ? function create_buffer_setup(buffer) {
    return (Reader$1.create = function create_buffer(buffer2) {
      return util$2.Buffer.isBuffer(buffer2) ? new BufferReader$1(buffer2) : create_array(buffer2);
    })(buffer);
  } : create_array;
};
Reader$1.create = create2();
Reader$1.prototype._slice = util$2.Array.prototype.subarray || /* istanbul ignore next */
util$2.Array.prototype.slice;
Reader$1.prototype.uint32 = /* @__PURE__ */ function read_uint32_setup() {
  var value = 4294967295;
  return function read_uint32() {
    value = (this.buf[this.pos] & 127) >>> 0;
    if (this.buf[this.pos++] < 128) {
      return value;
    }
    value = (value | (this.buf[this.pos] & 127) << 7) >>> 0;
    if (this.buf[this.pos++] < 128) {
      return value;
    }
    value = (value | (this.buf[this.pos] & 127) << 14) >>> 0;
    if (this.buf[this.pos++] < 128) {
      return value;
    }
    value = (value | (this.buf[this.pos] & 127) << 21) >>> 0;
    if (this.buf[this.pos++] < 128) {
      return value;
    }
    value = (value | (this.buf[this.pos] & 15) << 28) >>> 0;
    if (this.buf[this.pos++] < 128) {
      return value;
    }
    if ((this.pos += 5) > this.len) {
      this.pos = this.len;
      throw indexOutOfRange(this, 10);
    }
    return value;
  };
}();
Reader$1.prototype.int32 = function read_int32() {
  return this.uint32() | 0;
};
Reader$1.prototype.sint32 = function read_sint32() {
  var value = this.uint32();
  return value >>> 1 ^ -(value & 1) | 0;
};
function readLongVarint() {
  var bits = new LongBits(0, 0);
  var i = 0;
  if (this.len - this.pos > 4) {
    for (; i < 4; ++i) {
      bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
      if (this.buf[this.pos++] < 128) {
        return bits;
      }
    }
    bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;
    bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;
    if (this.buf[this.pos++] < 128) {
      return bits;
    }
    i = 0;
  } else {
    for (; i < 3; ++i) {
      if (this.pos >= this.len) {
        throw indexOutOfRange(this);
      }
      bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
      if (this.buf[this.pos++] < 128) {
        return bits;
      }
    }
    bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;
    return bits;
  }
  if (this.len - this.pos > 4) {
    for (; i < 5; ++i) {
      bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
      if (this.buf[this.pos++] < 128) {
        return bits;
      }
    }
  } else {
    for (; i < 5; ++i) {
      if (this.pos >= this.len) {
        throw indexOutOfRange(this);
      }
      bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
      if (this.buf[this.pos++] < 128) {
        return bits;
      }
    }
  }
  throw Error("invalid varint encoding");
}
Reader$1.prototype.bool = function read_bool() {
  return this.uint32() !== 0;
};
function readFixed32_end(buf, end2) {
  return (buf[end2 - 4] | buf[end2 - 3] << 8 | buf[end2 - 2] << 16 | buf[end2 - 1] << 24) >>> 0;
}
Reader$1.prototype.fixed32 = function read_fixed32() {
  if (this.pos + 4 > this.len) {
    throw indexOutOfRange(this, 4);
  }
  return readFixed32_end(this.buf, this.pos += 4);
};
Reader$1.prototype.sfixed32 = function read_sfixed32() {
  if (this.pos + 4 > this.len) {
    throw indexOutOfRange(this, 4);
  }
  return readFixed32_end(this.buf, this.pos += 4) | 0;
};
function readFixed64() {
  if (this.pos + 8 > this.len) {
    throw indexOutOfRange(this, 8);
  }
  return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));
}
Reader$1.prototype.float = function read_float() {
  if (this.pos + 4 > this.len) {
    throw indexOutOfRange(this, 4);
  }
  var value = util$2.float.readFloatLE(this.buf, this.pos);
  this.pos += 4;
  return value;
};
Reader$1.prototype.double = function read_double() {
  if (this.pos + 8 > this.len) {
    throw indexOutOfRange(this, 4);
  }
  var value = util$2.float.readDoubleLE(this.buf, this.pos);
  this.pos += 8;
  return value;
};
Reader$1.prototype.bytes = function read_bytes() {
  var length = this.uint32(), start = this.pos, end2 = this.pos + length;
  if (end2 > this.len) {
    throw indexOutOfRange(this, length);
  }
  this.pos += length;
  if (Array.isArray(this.buf)) {
    return this.buf.slice(start, end2);
  }
  return start === end2 ? new this.buf.constructor(0) : this._slice.call(this.buf, start, end2);
};
Reader$1.prototype.string = function read_string() {
  var bytes = this.bytes();
  return utf8.read(bytes, 0, bytes.length);
};
Reader$1.prototype.skip = function skip(length) {
  if (typeof length === "number") {
    if (this.pos + length > this.len) {
      throw indexOutOfRange(this, length);
    }
    this.pos += length;
  } else {
    do {
      if (this.pos >= this.len) {
        throw indexOutOfRange(this);
      }
    } while (this.buf[this.pos++] & 128);
  }
  return this;
};
Reader$1.prototype.skipType = function(wireType) {
  switch (wireType) {
    case 0:
      this.skip();
      break;
    case 1:
      this.skip(8);
      break;
    case 2:
      this.skip(this.uint32());
      break;
    case 3:
      while ((wireType = this.uint32() & 7) !== 4) {
        this.skipType(wireType);
      }
      break;
    case 5:
      this.skip(4);
      break;
    /* istanbul ignore next */
    default:
      throw Error("invalid wire type " + wireType + " at offset " + this.pos);
  }
  return this;
};
Reader$1._configure = function(BufferReader_) {
  BufferReader$1 = BufferReader_;
  Reader$1.create = create2();
  BufferReader$1._configure();
  var fn = util$2.Long ? "toLong" : (
    /* istanbul ignore next */
    "toNumber"
  );
  util$2.merge(Reader$1.prototype, {
    int64: function read_int64() {
      return readLongVarint.call(this)[fn](false);
    },
    uint64: function read_uint64() {
      return readLongVarint.call(this)[fn](true);
    },
    sint64: function read_sint64() {
      return readLongVarint.call(this).zzDecode()[fn](false);
    },
    fixed64: function read_fixed64() {
      return readFixed64.call(this)[fn](true);
    },
    sfixed64: function read_sfixed64() {
      return readFixed64.call(this)[fn](false);
    }
  });
};
var reader_buffer = BufferReader;
var Reader = reader;
(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;
var util$1 = requireMinimal();
function BufferReader(buffer) {
  Reader.call(this, buffer);
}
BufferReader._configure = function() {
  if (util$1.Buffer) {
    BufferReader.prototype._slice = util$1.Buffer.prototype.slice;
  }
};
BufferReader.prototype.string = function read_string_buffer() {
  var len = this.uint32();
  return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len));
};
BufferReader._configure();
var rpc = {};
var service = Service;
var util = requireMinimal();
(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;
function Service(rpcImpl, requestDelimited, responseDelimited) {
  if (typeof rpcImpl !== "function") {
    throw TypeError("rpcImpl must be a function");
  }
  util.EventEmitter.call(this);
  this.rpcImpl = rpcImpl;
  this.requestDelimited = Boolean(requestDelimited);
  this.responseDelimited = Boolean(responseDelimited);
}
Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {
  if (!request) {
    throw TypeError("request must be specified");
  }
  var self2 = this;
  if (!callback) {
    return util.asPromise(rpcCall, self2, method, requestCtor, responseCtor, request);
  }
  if (!self2.rpcImpl) {
    setTimeout(function() {
      callback(Error("already ended"));
    }, 0);
    return void 0;
  }
  try {
    return self2.rpcImpl(method, requestCtor[self2.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), function rpcCallback(err, response) {
      if (err) {
        self2.emit("error", err, method);
        return callback(err);
      }
      if (response === null) {
        self2.end(
          /* endedByRPC */
          true
        );
        return void 0;
      }
      if (!(response instanceof responseCtor)) {
        try {
          response = responseCtor[self2.responseDelimited ? "decodeDelimited" : "decode"](response);
        } catch (err2) {
          self2.emit("error", err2, method);
          return callback(err2);
        }
      }
      self2.emit("data", response, method);
      return callback(null, response);
    });
  } catch (err) {
    self2.emit("error", err, method);
    setTimeout(function() {
      callback(err);
    }, 0);
    return void 0;
  }
};
Service.prototype.end = function end(endedByRPC) {
  if (this.rpcImpl) {
    if (!endedByRPC) {
      this.rpcImpl(null, null, null);
    }
    this.rpcImpl = null;
    this.emit("end").off();
  }
  return this;
};
(function(exports) {
  var rpc2 = exports;
  rpc2.Service = service;
})(rpc);
var roots = {};
(function(exports) {
  var protobuf = exports;
  protobuf.build = "minimal";
  protobuf.Writer = writer;
  protobuf.BufferWriter = writer_buffer;
  protobuf.Reader = reader;
  protobuf.BufferReader = reader_buffer;
  protobuf.util = requireMinimal();
  protobuf.rpc = rpc;
  protobuf.roots = roots;
  protobuf.configure = configure;
  function configure() {
    protobuf.util._configure();
    protobuf.Writer._configure(protobuf.BufferWriter);
    protobuf.Reader._configure(protobuf.BufferReader);
  }
  configure();
})(indexMinimal);
(function(module) {
  module.exports = indexMinimal;
})(minimal$1);
var $protobuf = minimal$1.exports;
var $Reader = $protobuf.Reader;
var $Writer = $protobuf.Writer;
var $util = $protobuf.util;
var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {});
$root.json_ipc = function() {
  var json_ipc = {};
  json_ipc.ValuesSequence = function() {
    function ValuesSequence(properties) {
      this.values = [];
      if (properties) {
        for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) {
          if (properties[keys[i]] != null) {
            this[keys[i]] = properties[keys[i]];
          }
        }
      }
    }
    ValuesSequence.prototype.values = $util.emptyArray;
    ValuesSequence.create = function create4(properties) {
      return new ValuesSequence(properties);
    };
    ValuesSequence.encode = function encode(message, writer2) {
      if (!writer2) {
        writer2 = $Writer.create();
      }
      if (message.values != null && message.values.length) {
        for (var i = 0; i < message.values.length; ++i) {
          $root.json_ipc.ValuesSequence.Value.encode(message.values[i], writer2.uint32(
            /* id 1, wireType 2 =*/
            10
          ).fork()).ldelim();
        }
      }
      return writer2;
    };
    ValuesSequence.encodeDelimited = function encodeDelimited(message, writer2) {
      return this.encode(message, writer2).ldelim();
    };
    ValuesSequence.decode = function decode(reader2, length) {
      if (!(reader2 instanceof $Reader)) {
        reader2 = $Reader.create(reader2);
      }
      var end2 = length === void 0 ? reader2.len : reader2.pos + length, message = new $root.json_ipc.ValuesSequence();
      while (reader2.pos < end2) {
        var tag = reader2.uint32();
        switch (tag >>> 3) {
          case 1: {
            if (!(message.values && message.values.length)) {
              message.values = [];
            }
            message.values.push($root.json_ipc.ValuesSequence.Value.decode(reader2, reader2.uint32()));
            break;
          }
          default:
            reader2.skipType(tag & 7);
            break;
        }
      }
      return message;
    };
    ValuesSequence.decodeDelimited = function decodeDelimited(reader2) {
      if (!(reader2 instanceof $Reader)) {
        reader2 = new $Reader(reader2);
      }
      return this.decode(reader2, reader2.uint32());
    };
    ValuesSequence.verify = function verify(message) {
      if (typeof message !== "object" || message === null) {
        return "object expected";
      }
      if (message.values != null && message.hasOwnProperty("values")) {
        if (!Array.isArray(message.values)) {
          return "values: array expected";
        }
        for (var i = 0; i < message.values.length; ++i) {
          var error = $root.json_ipc.ValuesSequence.Value.verify(message.values[i]);
          if (error) {
            return "values." + error;
          }
        }
      }
      return null;
    };
    ValuesSequence.fromObject = function fromObject2(object) {
      if (object instanceof $root.json_ipc.ValuesSequence) {
        return object;
      }
      var message = new $root.json_ipc.ValuesSequence();
      if (object.values) {
        if (!Array.isArray(object.values)) {
          throw TypeError(".json_ipc.ValuesSequence.values: array expected");
        }
        message.values = [];
        for (var i = 0; i < object.values.length; ++i) {
          if (typeof object.values[i] !== "object") {
            throw TypeError(".json_ipc.ValuesSequence.values: object expected");
          }
          message.values[i] = $root.json_ipc.ValuesSequence.Value.fromObject(object.values[i]);
        }
      }
      return message;
    };
    ValuesSequence.toObject = function toObject(message, options) {
      if (!options) {
        options = {};
      }
      var object = {};
      if (options.arrays || options.defaults) {
        object.values = [];
      }
      if (message.values && message.values.length) {
        object.values = [];
        for (var j = 0; j < message.values.length; ++j) {
          object.values[j] = $root.json_ipc.ValuesSequence.Value.toObject(message.values[j], options);
        }
      }
      return object;
    };
    ValuesSequence.prototype.toJSON = function toJSON2() {
      return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
    };
    ValuesSequence.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
      if (typeUrlPrefix === void 0) {
        typeUrlPrefix = "type.googleapis.com";
      }
      return typeUrlPrefix + "/json_ipc.ValuesSequence";
    };
    ValuesSequence.BinaryValue = function() {
      function BinaryValue(properties) {
        this.objLocation = [];
        if (properties) {
          for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) {
            if (properties[keys[i]] != null) {
              this[keys[i]] = properties[keys[i]];
            }
          }
        }
      }
      BinaryValue.prototype.arr = $util.newBuffer([]);
      BinaryValue.prototype.objLocation = $util.emptyArray;
      BinaryValue.create = function create4(properties) {
        return new BinaryValue(properties);
      };
      BinaryValue.encode = function encode(message, writer2) {
        if (!writer2) {
          writer2 = $Writer.create();
        }
        if (message.arr != null && Object.hasOwnProperty.call(message, "arr")) {
          writer2.uint32(
            /* id 1, wireType 2 =*/
            10
          ).bytes(message.arr);
        }
        if (message.objLocation != null && message.objLocation.length) {
          for (var i = 0; i < message.objLocation.length; ++i) {
            writer2.uint32(
              /* id 2, wireType 2 =*/
              18
            ).string(message.objLocation[i]);
          }
        }
        return writer2;
      };
      BinaryValue.encodeDelimited = function encodeDelimited(message, writer2) {
        return this.encode(message, writer2).ldelim();
      };
      BinaryValue.decode = function decode(reader2, length) {
        if (!(reader2 instanceof $Reader)) {
          reader2 = $Reader.create(reader2);
        }
        var end2 = length === void 0 ? reader2.len : reader2.pos + length, message = new $root.json_ipc.ValuesSequence.BinaryValue();
        while (reader2.pos < end2) {
          var tag = reader2.uint32();
          switch (tag >>> 3) {
            case 1: {
              message.arr = reader2.bytes();
              break;
            }
            case 2: {
              if (!(message.objLocation && message.objLocation.length)) {
                message.objLocation = [];
              }
              message.objLocation.push(reader2.string());
              break;
            }
            default:
              reader2.skipType(tag & 7);
              break;
          }
        }
        return message;
      };
      BinaryValue.decodeDelimited = function decodeDelimited(reader2) {
        if (!(reader2 instanceof $Reader)) {
          reader2 = new $Reader(reader2);
        }
        return this.decode(reader2, reader2.uint32());
      };
      BinaryValue.verify = function verify(message) {
        if (typeof message !== "object" || message === null) {
          return "object expected";
        }
        if (message.arr != null && message.hasOwnProperty("arr")) {
          if (!(message.arr && typeof message.arr.length === "number" || $util.isString(message.arr))) {
            return "arr: buffer expected";
          }
        }
        if (message.objLocation != null && message.hasOwnProperty("objLocation")) {
          if (!Array.isArray(message.objLocation)) {
            return "objLocation: array expected";
          }
          for (var i = 0; i < message.objLocation.length; ++i) {
            if (!$util.isString(message.objLocation[i])) {
              return "objLocation: string[] expected";
            }
          }
        }
        return null;
      };
      BinaryValue.fromObject = function fromObject2(object) {
        if (object instanceof $root.json_ipc.ValuesSequence.BinaryValue) {
          return object;
        }
        var message = new $root.json_ipc.ValuesSequence.BinaryValue();
        if (object.arr != null) {
          if (typeof object.arr === "string") {
            $util.base64.decode(object.arr, message.arr = $util.newBuffer($util.base64.length(object.arr)), 0);
          } else if (object.arr.length >= 0) {
            message.arr = object.arr;
          }
        }
        if (object.objLocation) {
          if (!Array.isArray(object.objLocation)) {
            throw TypeError(".json_ipc.ValuesSequence.BinaryValue.objLocation: array expected");
          }
          message.objLocation = [];
          for (var i = 0; i < object.objLocation.length; ++i) {
            message.objLocation[i] = String(object.objLocation[i]);
          }
        }
        return message;
      };
      BinaryValue.toObject = function toObject(message, options) {
        if (!options) {
          options = {};
        }
        var object = {};
        if (options.arrays || options.defaults) {
          object.objLocation = [];
        }
        if (options.defaults) {
          if (options.bytes === String) {
            object.arr = "";
          } else {
            object.arr = [];
            if (options.bytes !== Array) {
              object.arr = $util.newBuffer(object.arr);
            }
          }
        }
        if (message.arr != null && message.hasOwnProperty("arr")) {
          object.arr = options.bytes === String ? $util.base64.encode(message.arr, 0, message.arr.length) : options.bytes === Array ? Array.prototype.slice.call(message.arr) : message.arr;
        }
        if (message.objLocation && message.objLocation.length) {
          object.objLocation = [];
          for (var j = 0; j < message.objLocation.length; ++j) {
            object.objLocation[j] = message.objLocation[j];
          }
        }
        return object;
      };
      BinaryValue.prototype.toJSON = function toJSON2() {
        return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
      };
      BinaryValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
        if (typeUrlPrefix === void 0) {
          typeUrlPrefix = "type.googleapis.com";
        }
        return typeUrlPrefix + "/json_ipc.ValuesSequence.BinaryValue";
      };
      return BinaryValue;
    }();
    ValuesSequence.TransferredObj = function() {
      function TransferredObj(properties) {
        this.objLocation = [];
        if (properties) {
          for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) {
            if (properties[keys[i]] != null) {
              this[keys[i]] = properties[keys[i]];
            }
          }
        }
      }
      TransferredObj.prototype.indexInPassed = 0;
      TransferredObj.prototype.objLocation = $util.emptyArray;
      TransferredObj.create = function create4(properties) {
        return new TransferredObj(properties);
      };
      TransferredObj.encode = function encode(message, writer2) {
        if (!writer2) {
          writer2 = $Writer.create();
        }
        if (message.indexInPassed != null && Object.hasOwnProperty.call(message, "indexInPassed")) {
          writer2.uint32(
            /* id 1, wireType 0 =*/
            8
          ).uint32(message.indexInPassed);
        }
        if (message.objLocation != null && message.objLocation.length) {
          for (var i = 0; i < message.objLocation.length; ++i) {
            writer2.uint32(
              /* id 2, wireType 2 =*/
              18
            ).string(message.objLocation[i]);
          }
        }
        return writer2;
      };
      TransferredObj.encodeDelimited = function encodeDelimited(message, writer2) {
        return this.encode(message, writer2).ldelim();
      };
      TransferredObj.decode = function decode(reader2, length) {
        if (!(reader2 instanceof $Reader)) {
          reader2 = $Reader.create(reader2);
        }
        var end2 = length === void 0 ? reader2.len : reader2.pos + length, message = new $root.json_ipc.ValuesSequence.TransferredObj();
        while (reader2.pos < end2) {
          var tag = reader2.uint32();
          switch (tag >>> 3) {
            case 1: {
              message.indexInPassed = reader2.uint32();
              break;
            }
            case 2: {
              if (!(message.objLocation && message.objLocation.length)) {
                message.objLocation = [];
              }
              message.objLocation.push(reader2.string());
              break;
            }
            default:
              reader2.skipType(tag & 7);
              break;
          }
        }
        return message;
      };
      TransferredObj.decodeDelimited = function decodeDelimited(reader2) {
        if (!(reader2 instanceof $Reader)) {
          reader2 = new $Reader(reader2);
        }
        return this.decode(reader2, reader2.uint32());
      };
      TransferredObj.verify = function verify(message) {
        if (typeof message !== "object" || message === null) {
          return "object expected";
        }
        if (message.indexInPassed != null && message.hasOwnProperty("indexInPassed")) {
          if (!$util.isInteger(message.indexInPassed)) {
            return "indexInPassed: integer expected";
          }
        }
        if (message.objLocation != null && message.hasOwnProperty("objLocation")) {
          if (!Array.isArray(message.objLocation)) {
            return "objLocation: array expected";
          }
          for (var i = 0; i < message.objLocation.length; ++i) {
            if (!$util.isString(message.objLocation[i])) {
              return "objLocation: string[] expected";
            }
          }
        }
        return null;
      };
      TransferredObj.fromObject = function fromObject2(object) {
        if (object instanceof $root.json_ipc.ValuesSequence.TransferredObj) {
          return object;
        }
        var message = new $root.json_ipc.ValuesSequence.TransferredObj();
        if (object.indexInPassed != null) {
          message.indexInPassed = object.indexInPassed >>> 0;
        }
        if (object.objLocation) {
          if (!Array.isArray(object.objLocation)) {
            throw TypeError(".json_ipc.ValuesSequence.TransferredObj.objLocation: array expected");
          }
          message.objLocation = [];
          for (var i = 0; i < object.objLocation.length; ++i) {
            message.objLocation[i] = String(object.objLocation[i]);
          }
        }
        return message;
      };
      TransferredObj.toObject = function toObject(message, options) {
        if (!options) {
          options = {};
        }
        var object = {};
        if (options.arrays || options.defaults) {
          object.objLocation = [];
        }
        if (options.defaults) {
          object.indexInPassed = 0;
        }
        if (message.indexInPassed != null && message.hasOwnProperty("indexInPassed")) {
          object.indexInPassed = message.indexInPassed;
        }
        if (message.objLocation && message.objLocation.length) {
          object.objLocation = [];
          for (var j = 0; j < message.objLocation.length; ++j) {
            object.objLocation[j] = message.objLocation[j];
          }
        }
        return object;
      };
      TransferredObj.prototype.toJSON = function toJSON2() {
        return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
      };
      TransferredObj.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
        if (typeUrlPrefix === void 0) {
          typeUrlPrefix = "type.googleapis.com";
        }
        return typeUrlPrefix + "/json_ipc.ValuesSequence.TransferredObj";
      };
      return TransferredObj;
    }();
    ValuesSequence.Value = function() {
      function Value(properties) {
        this.binaryInJson = [];
        this.transferredInJson = [];
        if (properties) {
          for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) {
            if (properties[keys[i]] != null) {
              this[keys[i]] = properties[keys[i]];
            }
          }
        }
      }
      Value.prototype.json = "";
      Value.prototype.binaryInJson = $util.emptyArray;
      Value.prototype.transferredInJson = $util.emptyArray;
      Value.prototype.arr = null;
      Value.prototype.transferred = null;
      Value.create = function create4(properties) {
        return new Value(properties);
      };
      Value.encode = function encode(message, writer2) {
        if (!writer2) {
          writer2 = $Writer.create();
        }
        if (message.json != null && Object.hasOwnProperty.call(message, "json")) {
          writer2.uint32(
            /* id 1, wireType 2 =*/
            10
          ).string(message.json);
        }
        if (message.binaryInJson != null && message.binaryInJson.length) {
          for (var i = 0; i < message.binaryInJson.length; ++i) {
            $root.json_ipc.ValuesSequence.BinaryValue.encode(message.binaryInJson[i], writer2.uint32(
              /* id 2, wireType 2 =*/
              18
            ).fork()).ldelim();
          }
        }
        if (message.transferredInJson != null && message.transferredInJson.length) {
          for (var i = 0; i < message.transferredInJson.length; ++i) {
            $root.json_ipc.ValuesSequence.TransferredObj.encode(message.transferredInJson[i], writer2.uint32(
              /* id 3, wireType 2 =*/
              26
            ).fork()).ldelim();
          }
        }
        if (message.arr != null && Object.hasOwnProperty.call(message, "arr")) {
          $root.json_ipc.ValuesSequence.BinaryValue.encode(message.arr, writer2.uint32(
            /* id 4, wireType 2 =*/
            34
          ).fork()).ldelim();
        }
        if (message.transferred != null && Object.hasOwnProperty.call(message, "transferred")) {
          $root.json_ipc.ValuesSequence.TransferredObj.encode(message.transferred, writer2.uint32(
            /* id 5, wireType 2 =*/
            42
          ).fork()).ldelim();
        }
        return writer2;
      };
      Value.encodeDelimited = function encodeDelimited(message, writer2) {
        return this.encode(message, writer2).ldelim();
      };
      Value.decode = function decode(reader2, length) {
        if (!(reader2 instanceof $Reader)) {
          reader2 = $Reader.create(reader2);
        }
        var end2 = length === void 0 ? reader2.len : reader2.pos + length, message = new $root.json_ipc.ValuesSequence.Value();
        while (reader2.pos < end2) {
          var tag = reader2.uint32();
          switch (tag >>> 3) {
            case 1: {
              message.json = reader2.string();
              break;
            }
            case 2: {
              if (!(message.binaryInJson && message.binaryInJson.length)) {
                message.binaryInJson = [];
              }
              message.binaryInJson.push($root.json_ipc.ValuesSequence.BinaryValue.decode(reader2, reader2.uint32()));
              break;
            }
            case 3: {
              if (!(message.transferredInJson && message.transferredInJson.length)) {
                message.transferredInJson = [];
              }
              message.transferredInJson.push($root.json_ipc.ValuesSequence.TransferredObj.decode(reader2, reader2.uint32()));
              break;
            }
            case 4: {
              message.arr = $root.json_ipc.ValuesSequence.BinaryValue.decode(reader2, reader2.uint32());
              break;
            }
            case 5: {
              message.transferred = $root.json_ipc.ValuesSequence.TransferredObj.decode(reader2, reader2.uint32());
              break;
            }
            default:
              reader2.skipType(tag & 7);
              break;
          }
        }
        return message;
      };
      Value.decodeDelimited = function decodeDelimited(reader2) {
        if (!(reader2 instanceof $Reader)) {
          reader2 = new $Reader(reader2);
        }
        return this.decode(reader2, reader2.uint32());
      };
      Value.verify = function verify(message) {
        if (typeof message !== "object" || message === null) {
          return "object expected";
        }
        if (message.json != null && message.hasOwnProperty("json")) {
          if (!$util.isString(message.json)) {
            return "json: string expected";
          }
        }
        if (message.binaryInJson != null && message.hasOwnProperty("binaryInJson")) {
          if (!Array.isArray(message.binaryInJson)) {
            return "binaryInJson: array expected";
          }
          for (var i = 0; i < message.binaryInJson.length; ++i) {
            var error = $root.json_ipc.ValuesSequence.BinaryValue.verify(message.binaryInJson[i]);
            if (error) {
              return "binaryInJson." + error;
            }
          }
        }
        if (message.transferredInJson != null && message.hasOwnProperty("transferredInJson")) {
          if (!Array.isArray(message.transferredInJson)) {
            return "transferredInJson: array expected";
          }
          for (var i = 0; i < message.transferredInJson.length; ++i) {
            var error = $root.json_ipc.ValuesSequence.TransferredObj.verify(message.transferredInJson[i]);
            if (error) {
              return "transferredInJson." + error;
            }
          }
        }
        if (message.arr != null && message.hasOwnProperty("arr")) {
          var error = $root.json_ipc.ValuesSequence.BinaryValue.verify(message.arr);
          if (error) {
            return "arr." + error;
          }
        }
        if (message.transferred != null && message.hasOwnProperty("transferred")) {
          var error = $root.json_ipc.ValuesSequence.TransferredObj.verify(message.transferred);
          if (error) {
            return "transferred." + error;
          }
        }
        return null;
      };
      Value.fromObject = function fromObject2(object) {
        if (object instanceof $root.json_ipc.ValuesSequence.Value) {
          return object;
        }
        var message = new $root.json_ipc.ValuesSequence.Value();
        if (object.json != null) {
          message.json = String(object.json);
        }
        if (object.binaryInJson) {
          if (!Array.isArray(object.binaryInJson)) {
            throw TypeError(".json_ipc.ValuesSequence.Value.binaryInJson: array expected");
          }
          message.binaryInJson = [];
          for (var i = 0; i < object.binaryInJson.length; ++i) {
            if (typeof object.binaryInJson[i] !== "object") {
              throw TypeError(".json_ipc.ValuesSequence.Value.binaryInJson: object expected");
            }
            message.binaryInJson[i] = $root.json_ipc.ValuesSequence.BinaryValue.fromObject(object.binaryInJson[i]);
          }
        }
        if (object.transferredInJson) {
          if (!Array.isArray(object.transferredInJson)) {
            throw TypeError(".json_ipc.ValuesSequence.Value.transferredInJson: array expected");
          }
          message.transferredInJson = [];
          for (var i = 0; i < object.transferredInJson.length; ++i) {
            if (typeof object.transferredInJson[i] !== "object") {
              throw TypeError(".json_ipc.ValuesSequence.Value.transferredInJson: object expected");
            }
            message.transferredInJson[i] = $root.json_ipc.ValuesSequence.TransferredObj.fromObject(object.transferredInJson[i]);
          }
        }
        if (object.arr != null) {
          if (typeof object.arr !== "object") {
            throw TypeError(".json_ipc.ValuesSequence.Value.arr: object expected");
          }
          message.arr = $root.json_ipc.ValuesSequence.BinaryValue.fromObject(object.arr);
        }
        if (object.transferred != null) {
          if (typeof object.transferred !== "object") {
            throw TypeError(".json_ipc.ValuesSequence.Value.transferred: object expected");
          }
          message.transferred = $root.json_ipc.ValuesSequence.TransferredObj.fromObject(object.transferred);
        }
        return message;
      };
      Value.toObject = function toObject(message, options) {
        if (!options) {
          options = {};
        }
        var object = {};
        if (options.arrays || options.defaults) {
          object.binaryInJson = [];
          object.transferredInJson = [];
        }
        if (options.defaults) {
          object.json = "";
          object.arr = null;
          object.transferred = null;
        }
        if (message.json != null && message.hasOwnProperty("json")) {
          object.json = message.json;
        }
        if (message.binaryInJson && message.binaryInJson.length) {
          object.binaryInJson = [];
          for (var j = 0; j < message.binaryInJson.length; ++j) {
            object.binaryInJson[j] = $root.json_ipc.ValuesSequence.BinaryValue.toObject(message.binaryInJson[j], options);
          }
        }
        if (message.transferredInJson && message.transferredInJson.length) {
          object.transferredInJson = [];
          for (var j = 0; j < message.transferredInJson.length; ++j) {
            object.transferredInJson[j] = $root.json_ipc.ValuesSequence.TransferredObj.toObject(message.transferredInJson[j], options);
          }
        }
        if (message.arr != null && message.hasOwnProperty("arr")) {
          object.arr = $root.json_ipc.ValuesSequence.BinaryValue.toObject(message.arr, options);
        }
        if (message.transferred != null && message.hasOwnProperty("transferred")) {
          object.transferred = $root.json_ipc.ValuesSequence.TransferredObj.toObject(message.transferred, options);
        }
        return object;
      };
      Value.prototype.toJSON = function toJSON2() {
        return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
      };
      Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
        if (typeUrlPrefix === void 0) {
          typeUrlPrefix = "type.googleapis.com";
        }
        return typeUrlPrefix + "/json_ipc.ValuesSequence.Value";
      };
      return Value;
    }();
    return ValuesSequence;
  }();
  return json_ipc;
}();
var jsonIpc_proto = $root;
var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
var lookup = [];
var revLookup = [];
var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
var inited = false;
function init() {
  inited = true;
  var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  for (var i = 0, len = code.length; i < len; ++i) {
    lookup[i] = code[i];
    revLookup[code.charCodeAt(i)] = i;
  }
  revLookup["-".charCodeAt(0)] = 62;
  revLookup["_".charCodeAt(0)] = 63;
}
function toByteArray(b64) {
  if (!inited) {
    init();
  }
  var i, j, l, tmp, placeHolders, arr;
  var len = b64.length;
  if (len % 4 > 0) {
    throw new Error("Invalid string. Length must be a multiple of 4");
  }
  placeHolders = b64[len - 2] === "=" ? 2 : b64[len - 1] === "=" ? 1 : 0;
  arr = new Arr(len * 3 / 4 - placeHolders);
  l = placeHolders > 0 ? len - 4 : len;
  var L = 0;
  for (i = 0, j = 0; i < l; i += 4, j += 3) {
    tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
    arr[L++] = tmp >> 16 & 255;
    arr[L++] = tmp >> 8 & 255;
    arr[L++] = tmp & 255;
  }
  if (placeHolders === 2) {
    tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
    arr[L++] = tmp & 255;
  } else if (placeHolders === 1) {
    tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
    arr[L++] = tmp >> 8 & 255;
    arr[L++] = tmp & 255;
  }
  return arr;
}
function tripletToBase64(num) {
  return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
}
function encodeChunk(uint8, start, end2) {
  var tmp;
  var output = [];
  for (var i = start; i < end2; i += 3) {
    tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2];
    output.push(tripletToBase64(tmp));
  }
  return output.join("");
}
function fromByteArray(uint8) {
  if (!inited) {
    init();
  }
  var tmp;
  var len = uint8.length;
  var extraBytes = len % 3;
  var output = "";
  var parts = [];
  var maxChunkLength = 16383;
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
  }
  if (extraBytes === 1) {
    tmp = uint8[len - 1];
    output += lookup[tmp >> 2];
    output += lookup[tmp << 4 & 63];
    output += "==";
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1];
    output += lookup[tmp >> 10];
    output += lookup[tmp >> 4 & 63];
    output += lookup[tmp << 2 & 63];
    output += "=";
  }
  parts.push(output);
  return parts.join("");
}
function read(buffer, offset, isLE, mLen, nBytes) {
  var e, m;
  var eLen = nBytes * 8 - mLen - 1;
  var eMax = (1 << eLen) - 1;
  var eBias = eMax >> 1;
  var nBits = -7;
  var i = isLE ? nBytes - 1 : 0;
  var d = isLE ? -1 : 1;
  var s = buffer[offset + i];
  i += d;
  e = s & (1 << -nBits) - 1;
  s >>= -nBits;
  nBits += eLen;
  for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {
  }
  m = e & (1 << -nBits) - 1;
  e >>= -nBits;
  nBits += mLen;
  for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {
  }
  if (e === 0) {
    e = 1 - eBias;
  } else if (e === eMax) {
    return m ? NaN : (s ? -1 : 1) * Infinity;
  } else {
    m = m + Math.pow(2, mLen);
    e = e - eBias;
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
}
function write(buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c;
  var eLen = nBytes * 8 - mLen - 1;
  var eMax = (1 << eLen) - 1;
  var eBias = eMax >> 1;
  var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
  var i = isLE ? 0 : nBytes - 1;
  var d = isLE ? 1 : -1;
  var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
  value = Math.abs(value);
  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0;
    e = eMax;
  } else {
    e = Math.floor(Math.log(value) / Math.LN2);
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--;
      c *= 2;
    }
    if (e + eBias >= 1) {
      value += rt / c;
    } else {
      value += rt * Math.pow(2, 1 - eBias);
    }
    if (value * c >= 2) {
      e++;
      c /= 2;
    }
    if (e + eBias >= eMax) {
      m = 0;
      e = eMax;
    } else if (e + eBias >= 1) {
      m = (value * c - 1) * Math.pow(2, mLen);
      e = e + eBias;
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
      e = 0;
    }
  }
  for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
  }
  e = e << mLen | m;
  eLen += mLen;
  for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
  }
  buffer[offset + i - d] |= s * 128;
}
var toString = {}.toString;
var isArray = Array.isArray || function(arr) {
  return toString.call(arr) == "[object Array]";
};
var INSPECT_MAX_BYTES = 50;
Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== void 0 ? global$1.TYPED_ARRAY_SUPPORT : true;
kMaxLength();
function kMaxLength() {
  return Buffer.TYPED_ARRAY_SUPPORT ? 2147483647 : 1073741823;
}
function createBuffer(that, length) {
  if (kMaxLength() < length) {
    throw new RangeError("Invalid typed array length");
  }
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    that = new Uint8Array(length);
    that.__proto__ = Buffer.prototype;
  } else {
    if (that === null) {
      that = new Buffer(length);
    }
    that.length = length;
  }
  return that;
}
function Buffer(arg, encodingOrOffset, length) {
  if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
    return new Buffer(arg, encodingOrOffset, length);
  }
  if (typeof arg === "number") {
    if (typeof encodingOrOffset === "string") {
      throw new Error("If encoding is specified then the first argument must be a string");
    }
    return allocUnsafe(this, arg);
  }
  return from(this, arg, encodingOrOffset, length);
}
Buffer.poolSize = 8192;
Buffer._augment = function(arr) {
  arr.__proto__ = Buffer.prototype;
  return arr;
};
function from(that, value, encodingOrOffset, length) {
  if (typeof value === "number") {
    throw new TypeError('"value" argument must not be a number');
  }
  if (typeof ArrayBuffer !== "undefined" && value instanceof ArrayBuffer) {
    return fromArrayBuffer(that, value, encodingOrOffset, length);
  }
  if (typeof value === "string") {
    return fromString(that, value, encodingOrOffset);
  }
  return fromObject(that, value);
}
Buffer.from = function(value, encodingOrOffset, length) {
  return from(null, value, encodingOrOffset, length);
};
if (Buffer.TYPED_ARRAY_SUPPORT) {
  Buffer.prototype.__proto__ = Uint8Array.prototype;
  Buffer.__proto__ = Uint8Array;
  if (typeof Symbol !== "undefined" && Symbol.species && Buffer[Symbol.species] === Buffer) {
    ;
  }
}
function assertSize(size) {
  if (typeof size !== "number") {
    throw new TypeError('"size" argument must be a number');
  } else if (size < 0) {
    throw new RangeError('"size" argument must not be negative');
  }
}
function alloc2(that, size, fill2, encoding) {
  assertSize(size);
  if (size <= 0) {
    return createBuffer(that, size);
  }
  if (fill2 !== void 0) {
    return typeof encoding === "string" ? createBuffer(that, size).fill(fill2, encoding) : createBuffer(that, size).fill(fill2);
  }
  return createBuffer(that, size);
}
Buffer.alloc = function(size, fill2, encoding) {
  return alloc2(null, size, fill2, encoding);
};
function allocUnsafe(that, size) {
  assertSize(size);
  that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
  if (!Buffer.TYPED_ARRAY_SUPPORT) {
    for (var i = 0; i < size; ++i) {
      that[i] = 0;
    }
  }
  return that;
}
Buffer.allocUnsafe = function(size) {
  return allocUnsafe(null, size);
};
Buffer.allocUnsafeSlow = function(size) {
  return allocUnsafe(null, size);
};
function fromString(that, string, encoding) {
  if (typeof encoding !== "string" || encoding === "") {
    encoding = "utf8";
  }
  if (!Buffer.isEncoding(encoding)) {
    throw new TypeError('"encoding" must be a valid string encoding');
  }
  var length = byteLength(string, encoding) | 0;
  that = createBuffer(that, length);
  var actual = that.write(string, encoding);
  if (actual !== length) {
    that = that.slice(0, actual);
  }
  return that;
}
function fromArrayLike(that, array) {
  var length = array.length < 0 ? 0 : checked(array.length) | 0;
  that = createBuffer(that, length);
  for (var i = 0; i < length; i += 1) {
    that[i] = array[i] & 255;
  }
  return that;
}
function fromArrayBuffer(that, array, byteOffset, length) {
  array.byteLength;
  if (byteOffset < 0 || array.byteLength < byteOffset) {
    throw new RangeError("'offset' is out of bounds");
  }
  if (array.byteLength < byteOffset + (length || 0)) {
    throw new RangeError("'length' is out of bounds");
  }
  if (byteOffset === void 0 && length === void 0) {
    array = new Uint8Array(array);
  } else if (length === void 0) {
    array = new Uint8Array(array, byteOffset);
  } else {
    array = new Uint8Array(array, byteOffset, length);
  }
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    that = array;
    that.__proto__ = Buffer.prototype;
  } else {
    that = fromArrayLike(that, array);
  }
  return that;
}
function fromObject(that, obj) {
  if (internalIsBuffer(obj)) {
    var len = checked(obj.length) | 0;
    that = createBuffer(that, len);
    if (that.length === 0) {
      return that;
    }
    obj.copy(that, 0, 0, len);
    return that;
  }
  if (obj) {
    if (typeof ArrayBuffer !== "undefined" && obj.buffer instanceof ArrayBuffer || "length" in obj) {
      if (typeof obj.length !== "number" || isnan(obj.length)) {
        return createBuffer(that, 0);
      }
      return fromArrayLike(that, obj);
    }
    if (obj.type === "Buffer" && isArray(obj.data)) {
      return fromArrayLike(that, obj.data);
    }
  }
  throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.");
}
function checked(length) {
  if (length >= kMaxLength()) {
    throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + kMaxLength().toString(16) + " bytes");
  }
  return length | 0;
}
Buffer.isBuffer = isBuffer;
function internalIsBuffer(b) {
  return !!(b != null && b._isBuffer);
}
Buffer.compare = function compare(a, b) {
  if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
    throw new TypeError("Arguments must be Buffers");
  }
  if (a === b) {
    return 0;
  }
  var x = a.length;
  var y = b.length;
  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i];
      y = b[i];
      break;
    }
  }
  if (x < y) {
    return -1;
  }
  if (y < x) {
    return 1;
  }
  return 0;
};
Buffer.isEncoding = function isEncoding(encoding) {
  switch (String(encoding).toLowerCase()) {
    case "hex":
    case "utf8":
    case "utf-8":
    case "ascii":
    case "latin1":
    case "binary":
    case "base64":
    case "ucs2":
    case "ucs-2":
    case "utf16le":
    case "utf-16le":
      return true;
    default:
      return false;
  }
};
Buffer.concat = function concat(list, length) {
  if (!isArray(list)) {
    throw new TypeError('"list" argument must be an Array of Buffers');
  }
  if (list.length === 0) {
    return Buffer.alloc(0);
  }
  var i;
  if (length === void 0) {
    length = 0;
    for (i = 0; i < list.length; ++i) {
      length += list[i].length;
    }
  }
  var buffer = Buffer.allocUnsafe(length);
  var pos = 0;
  for (i = 0; i < list.length; ++i) {
    var buf = list[i];
    if (!internalIsBuffer(buf)) {
      throw new TypeError('"list" argument must be an Array of Buffers');
    }
    buf.copy(buffer, pos);
    pos += buf.length;
  }
  return buffer;
};
function byteLength(string, encoding) {
  if (internalIsBuffer(string)) {
    return string.length;
  }
  if (typeof ArrayBuffer !== "undefined" && typeof ArrayBuffer.isView === "function" && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
    return string.byteLength;
  }
  if (typeof string !== "string") {
    string = "" + string;
  }
  var len = string.length;
  if (len === 0) {
    return 0;
  }
  var loweredCase = false;
  for (; ; ) {
    switch (encoding) {
      case "ascii":
      case "latin1":
      case "binary":
        return len;
      case "utf8":
      case "utf-8":
      case void 0:
        return utf8ToBytes(string).length;
      case "ucs2":
      case "ucs-2":
      case "utf16le":
      case "utf-16le":
        return len * 2;
      case "hex":
        return len >>> 1;
      case "base64":
        return base64ToBytes(string).length;
      default:
        if (loweredCase) {
          return utf8ToBytes(string).length;
        }
        encoding = ("" + encoding).toLowerCase();
        loweredCase = true;
    }
  }
}
Buffer.byteLength = byteLength;
function slowToString(encoding, start, end2) {
  var loweredCase = false;
  if (start === void 0 || start < 0) {
    start = 0;
  }
  if (start > this.length) {
    return "";
  }
  if (end2 === void 0 || end2 > this.length) {
    end2 = this.length;
  }
  if (end2 <= 0) {
    return "";
  }
  end2 >>>= 0;
  start >>>= 0;
  if (end2 <= start) {
    return "";
  }
  if (!encoding) {
    encoding = "utf8";
  }
  while (true) {
    switch (encoding) {
      case "hex":
        return hexSlice(this, start, end2);
      case "utf8":
      case "utf-8":
        return utf8Slice(this, start, end2);
      case "ascii":
        return asciiSlice(this, start, end2);
      case "latin1":
      case "binary":
        return latin1Slice(this, start, end2);
      case "base64":
        return base64Slice(this, start, end2);
      case "ucs2":
      case "ucs-2":
      case "utf16le":
      case "utf-16le":
        return utf16leSlice(this, start, end2);
      default:
        if (loweredCase) {
          throw new TypeError("Unknown encoding: " + encoding);
        }
        encoding = (encoding + "").toLowerCase();
        loweredCase = true;
    }
  }
}
Buffer.prototype._isBuffer = true;
function swap(b, n, m) {
  var i = b[n];
  b[n] = b[m];
  b[m] = i;
}
Buffer.prototype.swap16 = function swap16() {
  var len = this.length;
  if (len % 2 !== 0) {
    throw new RangeError("Buffer size must be a multiple of 16-bits");
  }
  for (var i = 0; i < len; i += 2) {
    swap(this, i, i + 1);
  }
  return this;
};
Buffer.prototype.swap32 = function swap32() {
  var len = this.length;
  if (len % 4 !== 0) {
    throw new RangeError("Buffer size must be a multiple of 32-bits");
  }
  for (var i = 0; i < len; i += 4) {
    swap(this, i, i + 3);
    swap(this, i + 1, i + 2);
  }
  return this;
};
Buffer.prototype.swap64 = function swap64() {
  var len = this.length;
  if (len % 8 !== 0) {
    throw new RangeError("Buffer size must be a multiple of 64-bits");
  }
  for (var i = 0; i < len; i += 8) {
    swap(this, i, i + 7);
    swap(this, i + 1, i + 6);
    swap(this, i + 2, i + 5);
    swap(this, i + 3, i + 4);
  }
  return this;
};
Buffer.prototype.toString = function toString2() {
  var length = this.length | 0;
  if (length === 0) {
    return "";
  }
  if (arguments.length === 0) {
    return utf8Slice(this, 0, length);
  }
  return slowToString.apply(this, arguments);
};
Buffer.prototype.equals = function equals(b) {
  if (!internalIsBuffer(b)) {
    throw new TypeError("Argument must be a Buffer");
  }
  if (this === b) {
    return true;
  }
  return Buffer.compare(this, b) === 0;
};
Buffer.prototype.inspect = function inspect() {
  var str = "";
  var max = INSPECT_MAX_BYTES;
  if (this.length > 0) {
    str = this.toString("hex", 0, max).match(/.{2}/g).join(" ");
    if (this.length > max) {
      str += " ... ";
    }
  }
  return "<Buffer " + str + ">";
};
Buffer.prototype.compare = function compare2(target, start, end2, thisStart, thisEnd) {
  if (!internalIsBuffer(target)) {
    throw new TypeError("Argument must be a Buffer");
  }
  if (start === void 0) {
    start = 0;
  }
  if (end2 === void 0) {
    end2 = target ? target.length : 0;
  }
  if (thisStart === void 0) {
    thisStart = 0;
  }
  if (thisEnd === void 0) {
    thisEnd = this.length;
  }
  if (start < 0 || end2 > target.length || thisStart < 0 || thisEnd > this.length) {
    throw new RangeError("out of range index");
  }
  if (thisStart >= thisEnd && start >= end2) {
    return 0;
  }
  if (thisStart >= thisEnd) {
    return -1;
  }
  if (start >= end2) {
    return 1;
  }
  start >>>= 0;
  end2 >>>= 0;
  thisStart >>>= 0;
  thisEnd >>>= 0;
  if (this === target) {
    return 0;
  }
  var x = thisEnd - thisStart;
  var y = end2 - start;
  var len = Math.min(x, y);
  var thisCopy = this.slice(thisStart, thisEnd);
  var targetCopy = target.slice(start, end2);
  for (var i = 0; i < len; ++i) {
    if (thisCopy[i] !== targetCopy[i]) {
      x = thisCopy[i];
      y = targetCopy[i];
      break;
    }
  }
  if (x < y) {
    return -1;
  }
  if (y < x) {
    return 1;
  }
  return 0;
};
function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
  if (buffer.length === 0) {
    return -1;
  }
  if (typeof byteOffset === "string") {
    encoding = byteOffset;
    byteOffset = 0;
  } else if (byteOffset > 2147483647) {
    byteOffset = 2147483647;
  } else if (byteOffset < -2147483648) {
    byteOffset = -2147483648;
  }
  byteOffset = +byteOffset;
  if (isNaN(byteOffset)) {
    byteOffset = dir ? 0 : buffer.length - 1;
  }
  if (byteOffset < 0) {
    byteOffset = buffer.length + byteOffset;
  }
  if (byteOffset >= buffer.length) {
    if (dir) {
      return -1;
    } else {
      byteOffset = buffer.length - 1;
    }
  } else if (byteOffset < 0) {
    if (dir) {
      byteOffset = 0;
    } else {
      return -1;
    }
  }
  if (typeof val === "string") {
    val = Buffer.from(val, encoding);
  }
  if (internalIsBuffer(val)) {
    if (val.length === 0) {
      return -1;
    }
    return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
  } else if (typeof val === "number") {
    val = val & 255;
    if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === "function") {
      if (dir) {
        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
      } else {
        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
      }
    }
    return arrayIndexOf(buffer, [
      val
    ], byteOffset, encoding, dir);
  }
  throw new TypeError("val must be string, number or Buffer");
}
function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
  var indexSize = 1;
  var arrLength = arr.length;
  var valLength = val.length;
  if (encoding !== void 0) {
    encoding = String(encoding).toLowerCase();
    if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
      if (arr.length < 2 || val.length < 2) {
        return -1;
      }
      indexSize = 2;
      arrLength /= 2;
      valLength /= 2;
      byteOffset /= 2;
    }
  }
  function read2(buf, i2) {
    if (indexSize === 1) {
      return buf[i2];
    } else {
      return buf.readUInt16BE(i2 * indexSize);
    }
  }
  var i;
  if (dir) {
    var foundIndex = -1;
    for (i = byteOffset; i < arrLength; i++) {
      if (read2(arr, i) === read2(val, foundIndex === -1 ? 0 : i - foundIndex)) {
        if (foundIndex === -1) {
          foundIndex = i;
        }
        if (i - foundIndex + 1 === valLength) {
          return foundIndex * indexSize;
        }
      } else {
        if (foundIndex !== -1) {
          i -= i - foundIndex;
        }
        foundIndex = -1;
      }
    }
  } else {
    if (byteOffset + valLength > arrLength) {
      byteOffset = arrLength - valLength;
    }
    for (i = byteOffset; i >= 0; i--) {
      var found = true;
      for (var j = 0; j < valLength; j++) {
        if (read2(arr, i + j) !== read2(val, j)) {
          found = false;
          break;
        }
      }
      if (found) {
        return i;
      }
    }
  }
  return -1;
}
Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
  return this.indexOf(val, byteOffset, encoding) !== -1;
};
Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
};
Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
};
function hexWrite(buf, string, offset, length) {
  offset = Number(offset) || 0;
  var remaining = buf.length - offset;
  if (!length) {
    length = remaining;
  } else {
    length = Number(length);
    if (length > remaining) {
      length = remaining;
    }
  }
  var strLen = string.length;
  if (strLen % 2 !== 0) {
    throw new TypeError("Invalid hex string");
  }
  if (length > strLen / 2) {
    length = strLen / 2;
  }
  for (var i = 0; i < length; ++i) {
    var parsed = parseInt(string.substr(i * 2, 2), 16);
    if (isNaN(parsed)) {
      return i;
    }
    buf[offset + i] = parsed;
  }
  return i;
}
function utf8Write(buf, string, offset, length) {
  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
}
function asciiWrite(buf, string, offset, length) {
  return blitBuffer(asciiToBytes(string), buf, offset, length);
}
function latin1Write(buf, string, offset, length) {
  return asciiWrite(buf, string, offset, length);
}
function base64Write(buf, string, offset, length) {
  return blitBuffer(base64ToBytes(string), buf, offset, length);
}
function ucs2Write(buf, string, offset, length) {
  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
}
Buffer.prototype.write = function write2(string, offset, length, encoding) {
  if (offset === void 0) {
    encoding = "utf8";
    length = this.length;
    offset = 0;
  } else if (length === void 0 && typeof offset === "string") {
    encoding = offset;
    length = this.length;
    offset = 0;
  } else if (isFinite(offset)) {
    offset = offset | 0;
    if (isFinite(length)) {
      length = length | 0;
      if (encoding === void 0) {
        encoding = "utf8";
      }
    } else {
      encoding = length;
      length = void 0;
    }
  } else {
    throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");
  }
  var remaining = this.length - offset;
  if (length === void 0 || length > remaining) {
    length = remaining;
  }
  if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
    throw new RangeError("Attempt to write outside buffer bounds");
  }
  if (!encoding) {
    encoding = "utf8";
  }
  var loweredCase = false;
  for (; ; ) {
    switch (encoding) {
      case "hex":
        return hexWrite(this, string, offset, length);
      case "utf8":
      case "utf-8":
        return utf8Write(this, string, offset, length);
      case "ascii":
        return asciiWrite(this, string, offset, length);
      case "latin1":
      case "binary":
        return latin1Write(this, string, offset, length);
      case "base64":
        return base64Write(this, string, offset, length);
      case "ucs2":
      case "ucs-2":
      case "utf16le":
      case "utf-16le":
        return ucs2Write(this, string, offset, length);
      default:
        if (loweredCase) {
          throw new TypeError("Unknown encoding: " + encoding);
        }
        encoding = ("" + encoding).toLowerCase();
        loweredCase = true;
    }
  }
};
Buffer.prototype.toJSON = function toJSON() {
  return {
    type: "Buffer",
    data: Array.prototype.slice.call(this._arr || this, 0)
  };
};
function base64Slice(buf, start, end2) {
  if (start === 0 && end2 === buf.length) {
    return fromByteArray(buf);
  } else {
    return fromByteArray(buf.slice(start, end2));
  }
}
function utf8Slice(buf, start, end2) {
  end2 = Math.min(buf.length, end2);
  var res = [];
  var i = start;
  while (i < end2) {
    var firstByte = buf[i];
    var codePoint = null;
    var bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
    if (i + bytesPerSequence <= end2) {
      var secondByte, thirdByte, fourthByte, tempCodePoint;
      switch (bytesPerSequence) {
        case 1:
          if (firstByte < 128) {
            codePoint = firstByte;
          }
          break;
        case 2:
          secondByte = buf[i + 1];
          if ((secondByte & 192) === 128) {
            tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
            if (tempCodePoint > 127) {
              codePoint = tempCodePoint;
            }
          }
          break;
        case 3:
          secondByte = buf[i + 1];
          thirdByte = buf[i + 2];
          if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
            tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
            if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
              codePoint = tempCodePoint;
            }
          }
          break;
        case 4:
          secondByte = buf[i + 1];
          thirdByte = buf[i + 2];
          fourthByte = buf[i + 3];
          if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
            tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
            if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
              codePoint = tempCodePoint;
            }
          }
      }
    }
    if (codePoint === null) {
      codePoint = 65533;
      bytesPerSequence = 1;
    } else if (codePoint > 65535) {
      codePoint -= 65536;
      res.push(codePoint >>> 10 & 1023 | 55296);
      codePoint = 56320 | codePoint & 1023;
    }
    res.push(codePoint);
    i += bytesPerSequence;
  }
  return decodeCodePointsArray(res);
}
var MAX_ARGUMENTS_LENGTH = 4096;
function decodeCodePointsArray(codePoints) {
  var len = codePoints.length;
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints);
  }
  var res = "";
  var i = 0;
  while (i < len) {
    res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
  }
  return res;
}
function asciiSlice(buf, start, end2) {
  var ret = "";
  end2 = Math.min(buf.length, end2);
  for (var i = start; i < end2; ++i) {
    ret += String.fromCharCode(buf[i] & 127);
  }
  return ret;
}
function latin1Slice(buf, start, end2) {
  var ret = "";
  end2 = Math.min(buf.length, end2);
  for (var i = start; i < end2; ++i) {
    ret += String.fromCharCode(buf[i]);
  }
  return ret;
}
function hexSlice(buf, start, end2) {
  var len = buf.length;
  if (!start || start < 0) {
    start = 0;
  }
  if (!end2 || end2 < 0 || end2 > len) {
    end2 = len;
  }
  var out = "";
  for (var i = start; i < end2; ++i) {
    out += toHex(buf[i]);
  }
  return out;
}
function utf16leSlice(buf, start, end2) {
  var bytes = buf.slice(start, end2);
  var res = "";
  for (var i = 0; i < bytes.length; i += 2) {
    res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  }
  return res;
}
Buffer.prototype.slice = function slice(start, end2) {
  var len = this.length;
  start = ~~start;
  end2 = end2 === void 0 ? len : ~~end2;
  if (start < 0) {
    start += len;
    if (start < 0) {
      start = 0;
    }
  } else if (start > len) {
    start = len;
  }
  if (end2 < 0) {
    end2 += len;
    if (end2 < 0) {
      end2 = 0;
    }
  } else if (end2 > len) {
    end2 = len;
  }
  if (end2 < start) {
    end2 = start;
  }
  var newBuf;
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    newBuf = this.subarray(start, end2);
    newBuf.__proto__ = Buffer.prototype;
  } else {
    var sliceLen = end2 - start;
    newBuf = new Buffer(sliceLen, void 0);
    for (var i = 0; i < sliceLen; ++i) {
      newBuf[i] = this[i + start];
    }
  }
  return newBuf;
};
function checkOffset(offset, ext, length) {
  if (offset % 1 !== 0 || offset < 0) {
    throw new RangeError("offset is not uint");
  }
  if (offset + ext > length) {
    throw new RangeError("Trying to access beyond buffer length");
  }
}
Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) {
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert) {
    checkOffset(offset, byteLength2, this.length);
  }
  var val = this[offset];
  var mul = 1;
  var i = 0;
  while (++i < byteLength2 && (mul *= 256)) {
    val += this[offset + i] * mul;
  }
  return val;
};
Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) {
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert) {
    checkOffset(offset, byteLength2, this.length);
  }
  var val = this[offset + --byteLength2];
  var mul = 1;
  while (byteLength2 > 0 && (mul *= 256)) {
    val += this[offset + --byteLength2] * mul;
  }
  return val;
};
Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
  if (!noAssert) {
    checkOffset(offset, 1, this.length);
  }
  return this[offset];
};
Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
  if (!noAssert) {
    checkOffset(offset, 2, this.length);
  }
  return this[offset] | this[offset + 1] << 8;
};
Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
  if (!noAssert) {
    checkOffset(offset, 2, this.length);
  }
  return this[offset] << 8 | this[offset + 1];
};
Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
  if (!noAssert) {
    checkOffset(offset, 4, this.length);
  }
  return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
};
Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
  if (!noAssert) {
    checkOffset(offset, 4, this.length);
  }
  return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
};
Buffer.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) {
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert) {
    checkOffset(offset, byteLength2, this.length);
  }
  var val = this[offset];
  var mul = 1;
  var i = 0;
  while (++i < byteLength2 && (mul *= 256)) {
    val += this[offset + i] * mul;
  }
  mul *= 128;
  if (val >= mul) {
    val -= Math.pow(2, 8 * byteLength2);
  }
  return val;
};
Buffer.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) {
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert) {
    checkOffset(offset, byteLength2, this.length);
  }
  var i = byteLength2;
  var mul = 1;
  var val = this[offset + --i];
  while (i > 0 && (mul *= 256)) {
    val += this[offset + --i] * mul;
  }
  mul *= 128;
  if (val >= mul) {
    val -= Math.pow(2, 8 * byteLength2);
  }
  return val;
};
Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
  if (!noAssert) {
    checkOffset(offset, 1, this.length);
  }
  if (!(this[offset] & 128)) {
    return this[offset];
  }
  return (255 - this[offset] + 1) * -1;
};
Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
  if (!noAssert) {
    checkOffset(offset, 2, this.length);
  }
  var val = this[offset] | this[offset + 1] << 8;
  return val & 32768 ? val | 4294901760 : val;
};
Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
  if (!noAssert) {
    checkOffset(offset, 2, this.length);
  }
  var val = this[offset + 1] | this[offset] << 8;
  return val & 32768 ? val | 4294901760 : val;
};
Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
  if (!noAssert) {
    checkOffset(offset, 4, this.length);
  }
  return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
};
Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
  if (!noAssert) {
    checkOffset(offset, 4, this.length);
  }
  return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
};
Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
  if (!noAssert) {
    checkOffset(offset, 4, this.length);
  }
  return read(this, offset, true, 23, 4);
};
Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
  if (!noAssert) {
    checkOffset(offset, 4, this.length);
  }
  return read(this, offset, false, 23, 4);
};
Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
  if (!noAssert) {
    checkOffset(offset, 8, this.length);
  }
  return read(this, offset, true, 52, 8);
};
Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
  if (!noAssert) {
    checkOffset(offset, 8, this.length);
  }
  return read(this, offset, false, 52, 8);
};
function checkInt(buf, value, offset, ext, max, min) {
  if (!internalIsBuffer(buf)) {
    throw new TypeError('"buffer" argument must be a Buffer instance');
  }
  if (value > max || value < min) {
    throw new RangeError('"value" argument is out of bounds');
  }
  if (offset + ext > buf.length) {
    throw new RangeError("Index out of range");
  }
}
Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) {
  value = +value;
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength2) - 1;
    checkInt(this, value, offset, byteLength2, maxBytes, 0);
  }
  var mul = 1;
  var i = 0;
  this[offset] = value & 255;
  while (++i < byteLength2 && (mul *= 256)) {
    this[offset + i] = value / mul & 255;
  }
  return offset + byteLength2;
};
Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) {
  value = +value;
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength2) - 1;
    checkInt(this, value, offset, byteLength2, maxBytes, 0);
  }
  var i = byteLength2 - 1;
  var mul = 1;
  this[offset + i] = value & 255;
  while (--i >= 0 && (mul *= 256)) {
    this[offset + i] = value / mul & 255;
  }
  return offset + byteLength2;
};
Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert) {
    checkInt(this, value, offset, 1, 255, 0);
  }
  if (!Buffer.TYPED_ARRAY_SUPPORT) {
    value = Math.floor(value);
  }
  this[offset] = value & 255;
  return offset + 1;
};
function objectWriteUInt16(buf, value, offset, littleEndian) {
  if (value < 0) {
    value = 65535 + value + 1;
  }
  for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
    buf[offset + i] = (value & 255 << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8;
  }
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert) {
    checkInt(this, value, offset, 2, 65535, 0);
  }
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = value & 255;
    this[offset + 1] = value >>> 8;
  } else {
    objectWriteUInt16(this, value, offset, true);
  }
  return offset + 2;
};
Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert) {
    checkInt(this, value, offset, 2, 65535, 0);
  }
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = value >>> 8;
    this[offset + 1] = value & 255;
  } else {
    objectWriteUInt16(this, value, offset, false);
  }
  return offset + 2;
};
function objectWriteUInt32(buf, value, offset, littleEndian) {
  if (value < 0) {
    value = 4294967295 + value + 1;
  }
  for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
    buf[offset + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 255;
  }
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert) {
    checkInt(this, value, offset, 4, 4294967295, 0);
  }
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset + 3] = value >>> 24;
    this[offset + 2] = value >>> 16;
    this[offset + 1] = value >>> 8;
    this[offset] = value & 255;
  } else {
    objectWriteUInt32(this, value, offset, true);
  }
  return offset + 4;
};
Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert) {
    checkInt(this, value, offset, 4, 4294967295, 0);
  }
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = value >>> 24;
    this[offset + 1] = value >>> 16;
    this[offset + 2] = value >>> 8;
    this[offset + 3] = value & 255;
  } else {
    objectWriteUInt32(this, value, offset, false);
  }
  return offset + 4;
};
Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert) {
    var limit = Math.pow(2, 8 * byteLength2 - 1);
    checkInt(this, value, offset, byteLength2, limit - 1, -limit);
  }
  var i = 0;
  var mul = 1;
  var sub = 0;
  this[offset] = value & 255;
  while (++i < byteLength2 && (mul *= 256)) {
    if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
      sub = 1;
    }
    this[offset + i] = (value / mul >> 0) - sub & 255;
  }
  return offset + byteLength2;
};
Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert) {
    var limit = Math.pow(2, 8 * byteLength2 - 1);
    checkInt(this, value, offset, byteLength2, limit - 1, -limit);
  }
  var i = byteLength2 - 1;
  var mul = 1;
  var sub = 0;
  this[offset + i] = value & 255;
  while (--i >= 0 && (mul *= 256)) {
    if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
      sub = 1;
    }
    this[offset + i] = (value / mul >> 0) - sub & 255;
  }
  return offset + byteLength2;
};
Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert) {
    checkInt(this, value, offset, 1, 127, -128);
  }
  if (!Buffer.TYPED_ARRAY_SUPPORT) {
    value = Math.floor(value);
  }
  if (value < 0) {
    value = 255 + value + 1;
  }
  this[offset] = value & 255;
  return offset + 1;
};
Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert) {
    checkInt(this, value, offset, 2, 32767, -32768);
  }
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = value & 255;
    this[offset + 1] = value >>> 8;
  } else {
    objectWriteUInt16(this, value, offset, true);
  }
  return offset + 2;
};
Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert) {
    checkInt(this, value, offset, 2, 32767, -32768);
  }
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = value >>> 8;
    this[offset + 1] = value & 255;
  } else {
    objectWriteUInt16(this, value, offset, false);
  }
  return offset + 2;
};
Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert) {
    checkInt(this, value, offset, 4, 2147483647, -2147483648);
  }
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = value & 255;
    this[offset + 1] = value >>> 8;
    this[offset + 2] = value >>> 16;
    this[offset + 3] = value >>> 24;
  } else {
    objectWriteUInt32(this, value, offset, true);
  }
  return offset + 4;
};
Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert) {
    checkInt(this, value, offset, 4, 2147483647, -2147483648);
  }
  if (value < 0) {
    value = 4294967295 + value + 1;
  }
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = value >>> 24;
    this[offset + 1] = value >>> 16;
    this[offset + 2] = value >>> 8;
    this[offset + 3] = value & 255;
  } else {
    objectWriteUInt32(this, value, offset, false);
  }
  return offset + 4;
};
function checkIEEE754(buf, value, offset, ext, max, min) {
  if (offset + ext > buf.length) {
    throw new RangeError("Index out of range");
  }
  if (offset < 0) {
    throw new RangeError("Index out of range");
  }
}
function writeFloat(buf, value, offset, littleEndian, noAssert) {
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 4);
  }
  write(buf, value, offset, littleEndian, 23, 4);
  return offset + 4;
}
Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
  return writeFloat(this, value, offset, true, noAssert);
};
Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
  return writeFloat(this, value, offset, false, noAssert);
};
function writeDouble(buf, value, offset, littleEndian, noAssert) {
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 8);
  }
  write(buf, value, offset, littleEndian, 52, 8);
  return offset + 8;
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
  return writeDouble(this, value, offset, true, noAssert);
};
Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
  return writeDouble(this, value, offset, false, noAssert);
};
Buffer.prototype.copy = function copy(target, targetStart, start, end2) {
  if (!start) {
    start = 0;
  }
  if (!end2 && end2 !== 0) {
    end2 = this.length;
  }
  if (targetStart >= target.length) {
    targetStart = target.length;
  }
  if (!targetStart) {
    targetStart = 0;
  }
  if (end2 > 0 && end2 < start) {
    end2 = start;
  }
  if (end2 === start) {
    return 0;
  }
  if (target.length === 0 || this.length === 0) {
    return 0;
  }
  if (targetStart < 0) {
    throw new RangeError("targetStart out of bounds");
  }
  if (start < 0 || start >= this.length) {
    throw new RangeError("sourceStart out of bounds");
  }
  if (end2 < 0) {
    throw new RangeError("sourceEnd out of bounds");
  }
  if (end2 > this.length) {
    end2 = this.length;
  }
  if (target.length - targetStart < end2 - start) {
    end2 = target.length - targetStart + start;
  }
  var len = end2 - start;
  var i;
  if (this === target && start < targetStart && targetStart < end2) {
    for (i = len - 1; i >= 0; --i) {
      target[i + targetStart] = this[i + start];
    }
  } else if (len < 1e3 || !Buffer.TYPED_ARRAY_SUPPORT) {
    for (i = 0; i < len; ++i) {
      target[i + targetStart] = this[i + start];
    }
  } else {
    Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart);
  }
  return len;
};
Buffer.prototype.fill = function fill(val, start, end2, encoding) {
  if (typeof val === "string") {
    if (typeof start === "string") {
      encoding = start;
      start = 0;
      end2 = this.length;
    } else if (typeof end2 === "string") {
      encoding = end2;
      end2 = this.length;
    }
    if (val.length === 1) {
      var code = val.charCodeAt(0);
      if (code < 256) {
        val = code;
      }
    }
    if (encoding !== void 0 && typeof encoding !== "string") {
      throw new TypeError("encoding must be a string");
    }
    if (typeof encoding === "string" && !Buffer.isEncoding(encoding)) {
      throw new TypeError("Unknown encoding: " + encoding);
    }
  } else if (typeof val === "number") {
    val = val & 255;
  }
  if (start < 0 || this.length < start || this.length < end2) {
    throw new RangeError("Out of range index");
  }
  if (end2 <= start) {
    return this;
  }
  start = start >>> 0;
  end2 = end2 === void 0 ? this.length : end2 >>> 0;
  if (!val) {
    val = 0;
  }
  var i;
  if (typeof val === "number") {
    for (i = start; i < end2; ++i) {
      this[i] = val;
    }
  } else {
    var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString());
    var len = bytes.length;
    for (i = 0; i < end2 - start; ++i) {
      this[i + start] = bytes[i % len];
    }
  }
  return this;
};
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
function base64clean(str) {
  str = stringtrim(str).replace(INVALID_BASE64_RE, "");
  if (str.length < 2) {
    return "";
  }
  while (str.length % 4 !== 0) {
    str = str + "=";
  }
  return str;
}
function stringtrim(str) {
  if (str.trim) {
    return str.trim();
  }
  return str.replace(/^\s+|\s+$/g, "");
}
function toHex(n) {
  if (n < 16) {
    return "0" + n.toString(16);
  }
  return n.toString(16);
}
function utf8ToBytes(string, units) {
  units = units || Infinity;
  var codePoint;
  var length = string.length;
  var leadSurrogate = null;
  var bytes = [];
  for (var i = 0; i < length; ++i) {
    codePoint = string.charCodeAt(i);
    if (codePoint > 55295 && codePoint < 57344) {
      if (!leadSurrogate) {
        if (codePoint > 56319) {
          if ((units -= 3) > -1) {
            bytes.push(239, 191, 189);
          }
          continue;
        } else if (i + 1 === length) {
          if ((units -= 3) > -1) {
            bytes.push(239, 191, 189);
          }
          continue;
        }
        leadSurrogate = codePoint;
        continue;
      }
      if (codePoint < 56320) {
        if ((units -= 3) > -1) {
          bytes.push(239, 191, 189);
        }
        leadSurrogate = codePoint;
        continue;
      }
      codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
    } else if (leadSurrogate) {
      if ((units -= 3) > -1) {
        bytes.push(239, 191, 189);
      }
    }
    leadSurrogate = null;
    if (codePoint < 128) {
      if ((units -= 1) < 0) {
        break;
      }
      bytes.push(codePoint);
    } else if (codePoint < 2048) {
      if ((units -= 2) < 0) {
        break;
      }
      bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128);
    } else if (codePoint < 65536) {
      if ((units -= 3) < 0) {
        break;
      }
      bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
    } else if (codePoint < 1114112) {
      if ((units -= 4) < 0) {
        break;
      }
      bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
    } else {
      throw new Error("Invalid code point");
    }
  }
  return bytes;
}
function asciiToBytes(str) {
  var byteArray = [];
  for (var i = 0; i < str.length; ++i) {
    byteArray.push(str.charCodeAt(i) & 255);
  }
  return byteArray;
}
function utf16leToBytes(str, units) {
  var c, hi, lo;
  var byteArray = [];
  for (var i = 0; i < str.length; ++i) {
    if ((units -= 2) < 0) {
      break;
    }
    c = str.charCodeAt(i);
    hi = c >> 8;
    lo = c % 256;
    byteArray.push(lo);
    byteArray.push(hi);
  }
  return byteArray;
}
function base64ToBytes(str) {
  return toByteArray(base64clean(str));
}
function blitBuffer(src, dst, offset, length) {
  for (var i = 0; i < length; ++i) {
    if (i + offset >= dst.length || i >= src.length) {
      break;
    }
    dst[i + offset] = src[i];
  }
  return i;
}
function isnan(val) {
  return val !== val;
}
function isBuffer(obj) {
  return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj));
}
function isFastBuffer(obj) {
  return !!obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj);
}
function isSlowBuffer(obj) {
  return typeof obj.readFloatLE === "function" && typeof obj.slice === "function" && isFastBuffer(obj.slice(0, 0));
}
var ProtoType = class _ProtoType {
  constructor(type) {
    this.type = type;
    this.type = type;
    Object.freeze(this);
  }
  static for(type) {
    return new _ProtoType(type);
  }
  pack(msg) {
    const err = this.type.verify(msg);
    if (err) {
      throw new Error(err);
    }
    return this.type.encode(msg).finish();
  }
  unpack(bytes) {
    if (!bytes) {
      throw {
        runtimeException: true,
        type: "ipc",
        missingBodyBytes: true
      };
    }
    return this.type.decode(bytes);
  }
  packToBase64(msg) {
    return this.pack(msg).toString("base64");
  }
  unpackFromBase64(str) {
    return this.unpack(Buffer.from(str, "base64"));
  }
};
Object.freeze(ProtoType.prototype);
Object.freeze(ProtoType);
function copyJSON(orig, excludeTopFields) {
  const origType = typeof orig;
  if (origType !== "object") {
    return origType !== "function" ? orig : void 0;
  }
  if (orig === null) {
    return null;
  }
  if (ArrayBuffer.isView(orig)) {
    return orig;
  }
  if (Array.isArray(orig)) {
    const arr = orig;
    const c = [];
    for (let i = 0; i < arr.length; i += 1) {
      c[i] = copyJSON(arr[i]);
    }
    return c;
  } else {
    const c = {};
    const fields = Object.keys(orig);
    if (excludeTopFields) {
      for (const f of fields) {
        if (excludeTopFields.includes(f)) {
          continue;
        }
        c[f] = copyJSON(orig[f]);
      }
    } else {
      for (const f of fields) {
        c[f] = copyJSON(orig[f]);
      }
    }
    return c;
  }
}
var valuesType = ProtoType.for(jsonIpc_proto.json_ipc.ValuesSequence);
function serializeArgs(args) {
  const { seq, passedByReference } = argsToValuesSequence(args);
  return {
    bytes: valuesType.pack(seq),
    passedByReference
  };
}
function argsToValuesSequence(args) {
  const seq = {
    values: []
  };
  const passedByReference = [];
  for (const arg of args) {
    if (arg && typeof arg === "object") {
      if (ArrayBuffer.isView(arg)) {
        seq.values.push({
          arr: {
            arr: arg,
            objLocation: []
          }
        });
      } else if (arg._isObjectFromCore) {
        const indexInPassed = addToArray(passedByReference, arg);
        seq.values.push({
          transferred: {
            indexInPassed,
            objLocation: []
          }
        });
      } else {
        seq.values.push(turnToJsonExtractingBinaryAndTransferable(arg, passedByReference));
      }
    } else {
      seq.values.push({
        json: JSON.stringify(arg)
      });
    }
  }
  return {
    seq,
    passedByReference: passedByReference.length > 0 ? passedByReference : void 0
  };
}
function addToArray(arr, o) {
  let foundIndex = arr.indexOf(o);
  if (foundIndex < 0) {
    arr.push(o);
    return arr.length - 1;
  } else {
    return foundIndex;
  }
}
function turnToJsonExtractingBinaryAndTransferable(arg, passedByReference) {
  const parts = extractNonJsonableFrom(arg, passedByReference);
  if (parts) {
    const { copy: copy2, binaryInJson, transferredInJson } = parts;
    return {
      json: JSON.stringify(copy2),
      binaryInJson: binaryInJson.length > 0 ? binaryInJson : void 0,
      transferredInJson: transferredInJson.length > 0 ? transferredInJson : void 0
    };
  } else {
    return {
      json: JSON.stringify(arg)
    };
  }
}
function extractNonJsonableFrom(arg, passedByReference) {
  const nonJsonLocations = findAllNonJsonable(arg);
  if (!nonJsonLocations) {
    return;
  }
  const copy2 = copyJSON(arg);
  const binaryInJson = [];
  const transferredInJson = [];
  for (const objLocation of nonJsonLocations) {
    const nonJson = getValueAtObjLocation(arg, objLocation);
    setNewValueAtObjLocation(copy2, objLocation, null);
    if (nonJson._isObjectFromCore) {
      const indexInPassed = addToArray(passedByReference, nonJson);
      transferredInJson.push({
        indexInPassed,
        objLocation
      });
    } else {
      binaryInJson.push({
        arr: nonJson,
        objLocation
      });
    }
  }
  return {
    copy: copy2,
    binaryInJson,
    transferredInJson
  };
}
function findAllNonJsonable(o) {
  const foundObjLocations = [];
  if (ArrayBuffer.isView(o) || o._isObjectFromCore) {
    return [
      []
    ];
  }
  if (Array.isArray(o)) {
    for (let i = 0; i < o.length; i += 1) {
      const child = o[i];
      if (child && typeof child === "object") {
        const inChild = findAllNonJsonable(child);
        if (inChild) {
          for (const objLocation of inChild) {
            foundObjLocations.push([
              `${i}`,
              ...objLocation
            ]);
          }
        }
      }
    }
  } else {
    for (const [field, child] of Object.entries(o)) {
      if (child && typeof child === "object") {
        const inChild = findAllNonJsonable(child);
        if (inChild) {
          for (const objLocation of inChild) {
            foundObjLocations.push([
              field,
              ...objLocation
            ]);
          }
        }
      }
    }
  }
  return foundObjLocations.length > 0 ? foundObjLocations : void 0;
}
function getValueAtObjLocation(o, objLocation) {
  const value = o[objLocation[0]];
  if (objLocation.length > 1) {
    return getValueAtObjLocation(value, objLocation.slice(1));
  } else {
    return value;
  }
}
function setNewValueAtObjLocation(o, objLocation, newValue) {
  const value = o[objLocation[0]];
  if (objLocation.length > 1) {
    setNewValueAtObjLocation(value, objLocation.slice(1), newValue);
  } else {
    o[objLocation[0]] = newValue;
  }
}
function deserializeArgs(bytes, passedByReference) {
  const values = valuesType.unpack(bytes);
  const args = [];
  for (const val of values.values) {
    const { json, binaryInJson, transferredInJson, arr, transferred } = val;
    if (arr) {
      args.push(arr.arr);
    } else if (transferred) {
      args.push(getTransferred(transferred.indexInPassed, passedByReference));
    } else if (typeof json === "string" && json.length > 0) {
      const arg = JSON.parse(json);
      if (binaryInJson) {
        attachBinaryArrays(arg, binaryInJson);
      }
      if (transferredInJson) {
        attachTransferred(arg, transferredInJson, passedByReference);
      }
      args.push(arg);
    } else {
      ;
    }
  }
  return args;
}
function attachBinaryArrays(arg, binaryInJson) {
  for (const { arr, objLocation } of binaryInJson) {
    setNewValueAtObjLocation(arg, objLocation, arr);
  }
}
function getTransferred(indexInPassed, passedByReference) {
  if (!passedByReference) {
    throw new Error(`need better error`);
  }
  const o = passedByReference[indexInPassed];
  if (!o || !o._isObjectFromCore) {
    throw new Error(`need better error`);
  }
  return o;
}
function attachTransferred(arg, transferredInJson, passedByReference) {
  for (const { indexInPassed, objLocation } of transferredInJson) {
    setNewValueAtObjLocation(arg, objLocation, getTransferred(indexInPassed, passedByReference));
  }
}
function surroundWithReqReplySerialization(srv, func, transforms) {
  return async (requestData) => {
    const args = argsFromPassedDatum(requestData, transforms === null || transforms === void 0 ? void 0 : transforms.unpackRequest);
    const result = args ? await func.call(srv, ...args) : await func.call(srv);
    return toPassedDatum(result, transforms === null || transforms === void 0 ? void 0 : transforms.packReply);
  };
}
function argsFromPassedDatum(data, unpack) {
  if (!data) {
    return;
  }
  if (unpack) {
    if (unpack === "noop") {
      return [
        data.bytes
      ];
    } else {
      return unpack(data);
    }
  } else {
    const { bytes, passedByReference } = data;
    return bytes ? deserializeArgs(bytes, passedByReference) : void 0;
  }
}
function toPassedDatum(data, pack) {
  if (data === void 0) {
    return;
  }
  if (pack) {
    if (pack === "noop") {
      if (!ArrayBuffer.isView(data)) {
        throw new Error(`Method returned non-binary, while no serialization is set`);
      }
      return {
        bytes: data
      };
    }
    return pack(data);
  } else {
    return serializeArgs([
      data
    ]);
  }
}
function surroundObsWithSerialization(srv, func, transforms) {
  return (requestData, obs) => {
    const args = argsFromPassedDatum(requestData, transforms === null || transforms === void 0 ? void 0 : transforms.unpackRequest);
    const obsWrap = {
      next: (ev) => obs.next(toPassedDatum(ev, transforms === null || transforms === void 0 ? void 0 : transforms.packReply)),
      complete: obs.complete,
      error: obs.error
    };
    return args ? func.call(srv, obsWrap, ...args) : func.call(srv, obsWrap);
  };
}
var ConnectionState = class {
  constructor(disconnect) {
    this.disconnect = disconnect;
    this.calls = /* @__PURE__ */ new Map();
    this.isRunning = true;
  }
  acceptsMsgs() {
    return this.isRunning;
  }
  stop() {
    if (!this.isRunning) {
      return;
    }
    this.isRunning = false;
    this.disconnect();
    for (const { cancel } of this.calls.values()) {
      if (cancel) {
        cancel();
      }
    }
    this.calls.clear();
  }
  hasCall(callNum) {
    return this.calls.has(callNum);
  }
  cancelCall(callNum) {
    const call = this.calls.get(callNum);
    if (!call) {
      return;
    }
    this.calls.delete(callNum);
    if (call.cancel) {
      call.cancel();
    }
  }
  completeCall(callNum) {
    this.calls.delete(callNum);
  }
  registerReqReplyCall(callNum) {
    this.calls.set(callNum, {});
  }
  registerObservableCall(callNum, cancel) {
    this.calls.set(callNum, {
      cancel
    });
  }
};
var IPCWrap = class {
  constructor(srvName) {
    this.srvName = srvName;
    this.connections = /* @__PURE__ */ new Map();
    this.methods = /* @__PURE__ */ new Map();
  }
  addReqReplyMethod(method, srv, func, transforms) {
    this.methods.set(method, {
      reqRep: surroundWithReqReplySerialization(srv, func, transforms)
    });
  }
  exposeReqReplyMethods(srv, methods, transforms) {
    for (const method of methods) {
      const func = srv[method];
      if (typeof func !== "function") {
        throw new Error(`Given service object has no method ${method}`);
      }
      this.addReqReplyMethod(method, srv, func, transforms ? transforms[method] : void 0);
    }
  }
  addObservableMethod(method, srv, func, transforms) {
    this.methods.set(method, {
      obs: surroundObsWithSerialization(srv, func, transforms)
    });
  }
  exposeObservableMethods(srv, methods, transforms) {
    for (const method of methods) {
      const func = srv[method];
      if (typeof func !== "function") {
        throw new Error(`Given service object has no method ${method}`);
      }
      this.addObservableMethod(method, srv, func, transforms ? transforms[method] : void 0);
    }
  }
  async onMsg(connection, connectionState, msg) {
    if (!connectionState.acceptsMsgs()) {
      return;
    }
    if (msg.msgType === "start") {
      const { callNum, method, data: requestData } = msg;
      if (connectionState.hasCall(callNum)) {
        return;
      }
      const m = this.methods.get(method);
      if (!m) {
        await connection.send({
          callNum,
          callStatus: "error",
          err: `Method ${method} not found`
        });
        return;
      }
      const { obs, reqRep } = m;
      if (reqRep) {
        connectionState.registerReqReplyCall(callNum);
        await this.callReqReplyHandler(connection, connectionState, reqRep, callNum, requestData);
      } else if (obs) {
        const cancelCall = this.callObsHandler(connection, connectionState, obs, callNum, requestData);
        connectionState.registerObservableCall(callNum, cancelCall);
      }
    } else if (msg.msgType === "cancel") {
      const { callNum } = msg;
      connectionState.cancelCall(callNum);
    }
  }
  async callReqReplyHandler(connection, connectionState, reqRep, callNum, requestData) {
    let reply;
    try {
      const data = await reqRep(requestData);
      reply = {
        callNum,
        callStatus: "end",
        data
      };
    } catch (err) {
      reply = {
        callNum,
        callStatus: "error",
        err
      };
    }
    if (!connectionState.hasCall(callNum)) {
      return;
    }
    connectionState.completeCall(callNum);
    await connection.send(reply);
  }
  callObsHandler(connection, connectionState, obs, callNum, requestData) {
    return obs(requestData, {
      next: (data) => connection.send({
        callNum,
        callStatus: "interim",
        data
      }),
      complete: async () => {
        if (!connectionState.hasCall(callNum)) {
          return;
        }
        connectionState.completeCall(callNum);
        await connection.send({
          callNum,
          callStatus: "end"
        });
      },
      error: async (err) => {
        if (!connectionState.hasCall(callNum)) {
          return;
        }
        connectionState.completeCall(callNum);
        await connection.send({
          callNum,
          callStatus: "error",
          err
        });
      }
    });
  }
  startIPC() {
    return w3n.rpc.exposeService(this.srvName, {
      next: (connection) => this.onConnection(connection),
      complete: () => this.onListeningCompletion(),
      error: (err) => this.onListeningError(err)
    });
  }
  stopIPC() {
    for (const connectionState of this.connections.values()) {
      connectionState.stop();
    }
    this.connections.clear();
  }
  async onConnection(connection) {
    const disconnect = connection.watch({
      next: (msg) => this.onMsg(connection, connectionState, msg),
      complete: () => this.onConnectionCompletion(connection, connectionState),
      error: (err) => this.onConnectionError(connection, connectionState, err)
    });
    const connectionState = new ConnectionState(() => {
      this.connections.delete(connection);
      disconnect();
    });
    this.connections.set(connection, connectionState);
  }
  async onConnectionCompletion(connection, connectionState) {
    this.connections.delete(connection);
    connectionState.stop();
  }
  async onConnectionError(connection, connectionState, err) {
    this.connections.delete(connection);
    connectionState.stop();
  }
};
var SingleConnectionIPCWrap = class extends IPCWrap {
  constructor(srvName) {
    super(srvName);
  }
  async onListeningCompletion() {
    w3n.closeSelf();
  }
  async onListeningError(err) {
    if (w3n.log) {
      await w3n.log("error", `Error in listening for incoming connections`, err);
    }
    w3n.closeSelf();
  }
  async onConnectionCompletion(connection, connectionState) {
    super.onConnectionCompletion(connection, connectionState);
    w3n.closeSelf();
  }
  async onConnectionError(connection, connectionState, err) {
    super.onConnectionError(connection, connectionState, err);
    if (w3n.log) {
      await w3n.log("error", `Error in listening for calls`, err);
    }
    w3n.closeSelf();
  }
};
var MultiConnectionIPCWrap = class extends IPCWrap {
  constructor(srvName) {
    super(srvName);
  }
  async onListeningCompletion() {
  }
  async onListeningError(err) {
    if (w3n.log) {
      await w3n.log("error", `Error in listening for incoming connections`, err);
    }
  }
  async onConnectionError(connection, connectionState, err) {
    super.onConnectionError(connection, connectionState, err);
    if (w3n.log) {
      await w3n.log("error", `Error in listening for calls`, err);
    }
  }
};

// shared/processes/sleep.ts
function sleep(millis) {
  return new Promise((resolve) => {
    setTimeout(resolve, millis);
  });
}

// shared/utils/observer-utils.ts
var ObserversSet = class {
  observers = /* @__PURE__ */ new Set();
  add(obs) {
    this.observers.add(obs);
  }
  next = (value) => {
    for (const obs of this.observers) {
      try {
        obs.next?.(value);
      } catch (err) {
      }
    }
  };
  error = (err) => {
    for (const obs of this.observers) {
      try {
        obs.error?.(err);
      } catch (err2) {
      }
    }
    this.observers.clear();
  };
  complete = () => {
    for (const obs of this.observers) {
      try {
        obs.complete?.();
      } catch (err) {
      }
    }
    this.observers.clear();
  };
  delete(obs) {
    this.observers.delete(obs);
  }
  isEmpty() {
    return this.observers.size === 0;
  }
};

// shared/utils/round.ts
function round(num, precision) {
  let tmpNum = num.toString().split("e");
  tmpNum = Math.round(+(tmpNum[0] + "e" + (tmpNum[1] ? +tmpNum[1] - precision : -precision)));
  tmpNum = tmpNum.toString().split("e");
  return +(tmpNum[0] + "e" + (tmpNum[1] ? +tmpNum[1] - +precision : precision));
}

// shared/constants.ts
var RECENT_FILE_NAME = "recent";
var GROUPS_FILE_NAME = "groups";
var IMAGES_FOLDER = "images";
var DEFAULT_GROUP = {
  RECENT: "recent",
  CARDS: "cards",
  BANK_CARDS: "bank_cards",
  FAVORITES: "favorites"
};
var DEFAULT_GROUPS = [
  {
    id: "",
    icon: "round-home",
    title: "list.all"
  },
  {
    id: DEFAULT_GROUP.RECENT,
    icon: "schedule",
    title: "list.recent"
  },
  {
    id: DEFAULT_GROUP.CARDS,
    icon: "cards-star-outline",
    title: "list.cards"
  },
  {
    id: DEFAULT_GROUP.BANK_CARDS,
    icon: "cards-star-outline",
    title: "list.bank_cards"
  },
  {
    id: DEFAULT_GROUP.FAVORITES,
    icon: "round-bookmark",
    title: "list.favorites"
  }
];
var RECORD_TYPE = {
  PASSWORD: "password",
  CARD: "card",
  BANK_CARD: "bank_card"
};
var RECORD_TYPES = [
  {
    id: RECORD_TYPE.PASSWORD,
    name: "recordDialog.record_type.password"
  },
  {
    id: RECORD_TYPE.CARD,
    name: "recordDialog.record_type.card"
  },
  {
    id: RECORD_TYPE.BANK_CARD,
    name: "recordDialog.record_type.bank_card"
  }
];

// shared/utils/debounce.ts
function debounce(fn, delay, options = {}) {
  let timeoutId;
  const debounced = function(...args) {
    const context = this;
    const callNow = options.immediate && timeoutId === void 0;
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(() => {
      timeoutId = void 0;
      if (!options.immediate) {
        fn.apply(context, args);
      }
    }, delay);
    if (callNow) {
      fn.apply(context, args);
    }
  };
  debounced.cancel = () => {
    clearTimeout(timeoutId);
    timeoutId = void 0;
  };
  return debounced;
}

// src-deno/utils/error-handling.ts
function setupGlobalReportingOfUnhandledErrors(skipDefaultHandling = false) {
  self.onunhandledrejection = (ev) => {
    w3n.log?.("error", `Captured unhandled promise rejection/error event`, ev.reason);
    if (skipDefaultHandling) {
      ev.preventDefault();
    }
  };
  self.onerror = (ev) => {
    if (typeof ev === "string") {
      w3n.log?.("error", `Captured unhandled error event (string value)`, ev);
    } else {
      w3n.log?.("error", `Captured unhandled error event`, ev.error);
      if (skipDefaultHandling) {
        ev.preventDefault();
      }
    }
  };
}

// src-deno/utils/sync-upload.ts
async function syncUpload({ fs, path, opts, emitEvent, immediately }) {
  try {
    if (immediately) {
      emitEvent({
        event: "sync:start",
        payload: {
          path: path || "root",
          type: "upload"
        }
      });
      const res = await fs.v?.sync?.upload(path, opts);
      emitEvent({
        event: "sync:end",
        payload: {
          path: path || "root",
          type: "upload"
        }
      });
      return res;
    }
    return fs.v?.sync?.startUpload(path, opts);
  } catch (err) {
    if (err.type === "connect") {
      return void 0;
    }
    if (err.type === "fs-sync" && err.childNeverUploaded) {
      setTimeout(() => {
        syncUpload({
          fs,
          path,
          opts,
          emitEvent,
          immediately
        });
      }, 1e4);
      return void 0;
    }
    emitEvent({
      event: "sync:end",
      payload: {
        path: path || "root",
        type: "upload",
        ...!!err && {
          error: err.message || JSON.stringify(err)
        }
      }
    });
    throw err;
  }
}

// src-deno/utils/check-server-connection.ts
async function checkServerConnection(fs) {
  try {
    const res = await fs.v?.sync?.status("");
    return !!res;
  } catch (err) {
    if (err.type !== "connect") {
      console.error("\u{1F525} Error while checking server connection. ", err);
    }
    return false;
  }
}

// shared/processes/single.ts
var SingleProc = class {
  promise = void 0;
  constructor() {
    Object.seal(this);
  }
  insertPromise(promise) {
    promise = promise.finally(() => {
      if (this.promise === promise) {
        this.promise = void 0;
      }
    });
    this.promise = promise;
    return promise;
  }
  getP() {
    return this.promise;
  }
  addStarted(promise) {
    if (this.promise) {
      throw new Error("Process is already in progress.");
    }
    return this.insertPromise(promise);
  }
  start(action) {
    if (this.promise) {
      throw new Error("Process is already in progress.");
    }
    return this.insertPromise(action());
  }
  startOrChain(action) {
    if (this.promise) {
      const next = this.promise.then(() => {
        return action();
      });
      return this.insertPromise(next);
    } else {
      return this.insertPromise(action());
    }
  }
};
Object.freeze(SingleProc.prototype);
Object.freeze(SingleProc);
var SingleCyclicProc = class {
  cycleWhile;
  action;
  proc;
  /**
   * @param cycleWhile is a "while" predicate. When it returns true, process
   * continues to cycle, and when it returns false, process goes to idle.
   * @param action is an async cycle body to run at each iteration.
   */
  constructor(cycleWhile, action) {
    this.cycleWhile = cycleWhile;
    this.action = action;
    this.proc = void 0;
    this.cycleOrIdle = () => {
      if (this.cycleWhile()) {
        this.proc = this.action();
      } else {
        this.proc = void 0;
      }
    };
    Object.seal(this);
  }
  /**
   * This starts process, if it is idle.
   */
  startIfIdle() {
    if (this.proc) {
      return;
    }
    this.proc = this.action();
    this.proc.then(this.cycleOrIdle);
  }
  cycleOrIdle;
  isRunning() {
    return !!this.proc;
  }
  /**
   * This makes process unusable and unstartable. Waiting on a return promise,
   * awaits the completion of the last iteration this process is in (if any).
   */
  async close() {
    this.cycleWhile = () => false;
    this.action = () => {
      throw new Error("This cyclic process has already been closed");
    };
    await this.proc;
  }
};
Object.freeze(SingleCyclicProc.prototype);
Object.freeze(SingleCyclicProc);

// shared/utils/base64.ts
var base64abc = [
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "O",
  "P",
  "Q",
  "R",
  "S",
  "T",
  "U",
  "V",
  "W",
  "X",
  "Y",
  "Z",
  "a",
  "b",
  "c",
  "d",
  "e",
  "f",
  "g",
  "h",
  "i",
  "j",
  "k",
  "l",
  "m",
  "n",
  "o",
  "p",
  "q",
  "r",
  "s",
  "t",
  "u",
  "v",
  "w",
  "x",
  "y",
  "z",
  "0",
  "1",
  "2",
  "3",
  "4",
  "5",
  "6",
  "7",
  "8",
  "9",
  "+",
  "/"
];
function bytesToBase64(bytes) {
  let result = "";
  let i;
  const l = bytes.length;
  for (i = 2; i < l; i += 3) {
    result += base64abc[bytes[i - 2] >> 2];
    result += base64abc[(bytes[i - 2] & 3) << 4 | bytes[i - 1] >> 4];
    result += base64abc[(bytes[i - 1] & 15) << 2 | bytes[i] >> 6];
    result += base64abc[bytes[i] & 63];
  }
  if (i === l + 1) {
    result += base64abc[bytes[i - 2] >> 2];
    result += base64abc[(bytes[i - 2] & 3) << 4];
    result += "==";
  }
  if (i === l) {
    result += base64abc[bytes[i - 2] >> 2];
    result += base64abc[(bytes[i - 2] & 3) << 4 | bytes[i - 1] >> 4];
    result += base64abc[(bytes[i - 1] & 15) << 2];
    result += "=";
  }
  return result;
}
function bytesToUrlSafeBase64(bytes) {
  return bytesToBase64(bytes).replaceAll("+", "-").replaceAll("/", "_");
}

// shared/utils/random-str.ts
function randomStr(numOfChars) {
  if (numOfChars < 1) {
    throw new Error(`number of chars is less than one`);
  }
  const byteLen = 3 * (Math.floor(numOfChars / 4) + 1);
  const bytes = randomBytes(byteLen);
  const str = bytes.toBase64 ? bytes.toBase64({
    alphabet: "base64url"
  }) : bytesToUrlSafeBase64(bytes);
  return str.slice(0, numOfChars);
}
function randomBytes(numOfBytes) {
  if (!!globalThis.crypto?.getRandomValues) {
    const bytes = new Uint8Array(numOfBytes);
    crypto.getRandomValues(bytes);
    return bytes;
  } else {
    console.warn(`Using math to get random value, in when crypto is missing.`);
    const numOfRandU32s = Math.floor(numOfBytes / 4) + (numOfBytes % 4 > 0 ? 1 : 0);
    const u32s = new Uint32Array(numOfRandU32s);
    for (let i = 0; i < u32s.length; i += 1) {
      u32s[i] = Math.floor(4294967295 * Math.random());
    }
    const u8s = new Uint8Array(u32s.buffer);
    return u8s.length > numOfBytes ? u8s.slice(0, numOfBytes) : u8s;
  }
}

// src-deno/treasure-file-srv.ts
async function treasureFileSrv(fs, fsLocal) {
  const fileProc = new SingleProc();
  async function saveRecentFile(data) {
    return fsLocal.writeJSONFile(RECENT_FILE_NAME, data);
  }
  async function loadRecentFile() {
    return fsLocal.readJSONFile(RECENT_FILE_NAME);
  }
  async function saveFile(data, fileName) {
    if (!data) {
      w3n.log("error", "There is no data to save to the file");
      throw new Error("There is no data to save to the file");
    }
    const itemId = !data.id || data.id === "new" ? randomStr(20) : data.id;
    const fileNameUsed = fileName || itemId;
    try {
      await fileProc.startOrChain(async () => {
        const savedData = Array.isArray(data) ? data : {
          ...data,
          id: itemId
        };
        await fs.writeJSONFile(fileNameUsed, savedData);
      });
      return fileNameUsed;
    } catch (err) {
      w3n.log("error", `Error saving the file ${fileNameUsed}. `, err);
      throw new Error(`Error saving the file ${fileNameUsed}.`, {
        cause: err
      });
    }
  }
  async function updateFile(data, fileName) {
    if (!data.id && !fileName) {
      w3n.log("error", "The filename argument is missing");
      throw new Error("The filename argument is missing");
    }
    const fileNameUsed = fileName || data.id || GROUPS_FILE_NAME;
    await fileProc.startOrChain(async () => fs.writeJSONFile(fileNameUsed, data));
  }
  async function getFile(fileName) {
    try {
      return fileProc.startOrChain(async () => await fs.readJSONFile(fileName).catch((err) => {
        if (err.notFound) {
          if (fileName === GROUPS_FILE_NAME) {
            return [];
          }
          return null;
        }
        throw err;
      }));
    } catch (err) {
      w3n.log("error", `Error getting file ${fileName}. `, err);
      throw new Error(`Error getting file ${fileName}`, {
        cause: err
      });
    }
  }
  async function saveImage(data) {
    const fileId = data.id || randomStr(20);
    try {
      await fileProc.startOrChain(async () => await fs.writeBytes(`${IMAGES_FOLDER}/${fileId}`, data.bytes));
      return fileId;
    } catch (err) {
      w3n.log("error", `Error saving the file ${fileId}. `, err);
      throw new Error(`Error saving the file ${fileId}.`, {
        cause: err
      });
    }
  }
  async function loadImage(fileId) {
    try {
      return fileProc.startOrChain(async () => fs.readBytes(`${IMAGES_FOLDER}/${fileId}`));
    } catch (err) {
      w3n.log("error", `Error getting image file ${fileId}. `, err);
      throw new Error(`Error getting image file ${fileId}`, {
        cause: err
      });
    }
  }
  async function deleteFile(fileName) {
    try {
      const doesFileExist = await fs.checkFilePresence(fileName);
      if (doesFileExist) {
        await fileProc.startOrChain(async () => await fs.deleteFile(fileName));
      }
    } catch (err) {
      w3n.log("error", `Error deleting file ${fileName}. `, err);
      throw new Error(`Error deleting file ${fileName}`, {
        cause: err
      });
    }
  }
  async function deleteFiles(currentFileNames) {
    const promiseToPerformWorks = currentFileNames.map((fileName) => deleteFile(fileName));
    await Promise.allSettled(promiseToPerformWorks);
  }
  return {
    loadRecentFile,
    saveRecentFile,
    saveFile,
    saveImage,
    updateFile,
    getFile,
    loadImage,
    deleteFile,
    deleteFiles
  };
}

// src-deno/utils/sync-download.ts
async function syncDownload({ fs, path, version, emitEvent }) {
  try {
    return fs.v?.sync?.startDownload(path, version);
  } catch (err) {
    if (err.type === "connect") {
      return void 0;
    }
    emitEvent({
      event: "sync:end",
      payload: {
        path: path || "root",
        type: "download",
        ...!!err && {
          error: err.message || JSON.stringify(err)
        }
      }
    });
    throw err;
  }
}

// src-deno/utils/handle-diff-sys-statuses/handle-file-synced-status.ts
async function handleFileSyncedStatus({ fs, path, syncStatus, emitEvent }) {
  const isServerConnection = await checkServerConnection(fs);
  if (!isServerConnection) {
    return void 0;
  }
  const isFileOnFs = await fs.v?.sync?.isRemoteVersionOnDisk(path, syncStatus.synced.latest);
  if (isFileOnFs !== "complete") {
    return syncDownload({
      fs,
      path,
      version: syncStatus.synced.latest,
      emitEvent
    });
  }
}

// src-deno/utils/sync-adopt.ts
async function syncAdopt({ fs, path, opts, emitEvent, actionIfSuccess }) {
  if (actionIfSuccess && typeof actionIfSuccess !== "function") {
    throw new Error(`[syncAdopt] The argument 'actionIfSuccess' is not a function`);
  }
  let error;
  try {
    emitEvent({
      event: "sync:start",
      payload: {
        path: path || "root",
        type: "adopt"
      }
    });
    await fs.v?.sync?.adoptRemote(path, opts);
    if (actionIfSuccess) {
      await actionIfSuccess();
    }
  } catch (err) {
    error = err;
    if (err.type === "connect") {
      return void 0;
    }
    throw err;
  } finally {
    emitEvent({
      event: "sync:end",
      payload: {
        path: path || "root",
        type: "adopt",
        ...!!error && {
          error: error.message || JSON.stringify(error)
        }
      }
    });
  }
}

// src-deno/utils/handle-diff-sys-statuses/handle-file-behind-status.ts
async function handleFileBehindStatus({ fs, path, syncStatus, emitEvent }) {
  const isServerConnection = await checkServerConnection(fs);
  if (!isServerConnection) {
    return void 0;
  }
  await syncAdopt({
    fs,
    path,
    opts: {
      remoteVersion: syncStatus.remote.latest
    },
    emitEvent
  });
  return syncDownload({
    fs,
    path,
    version: syncStatus.remote.latest,
    emitEvent
  });
}

// src-deno/utils/handle-diff-sys-statuses/handle-file-unsynced-status.ts
async function handleFileUnsyncedStatus({ fs, path, emitEvent }) {
  const isServerConnection = await checkServerConnection(fs);
  if (!isServerConnection) {
    return void 0;
  }
  return syncUpload({
    fs,
    path,
    emitEvent
  });
}

// src-deno/utils/handle-diff-sys-statuses/handle-record-conflicting-status.ts
async function handleRecordConflictingStatus({ fs, fileSrv, fileName, syncStatus, emitEvent }) {
  const isServerConnection = await checkServerConnection(fs);
  if (!isServerConnection) {
    return void 0;
  }
  const remoteFileData = await fs.v?.readJSONFile(fileName, {
    remoteVersion: syncStatus.remote.latest
  });
  if (!remoteFileData) {
    throw `The remote file ${fileName} is missing`;
  }
  const localFileData = await fs.readJSONFile(fileName);
  const newFileId = randomStr(20);
  await fileSrv.saveFile({
    ...remoteFileData.json,
    id: newFileId,
    source: fileName
  });
  if (localFileData) {
    await fileSrv.saveFile({
      ...localFileData,
      reference: newFileId
    });
    await syncUpload({
      fs,
      path: fileName,
      emitEvent
    });
  }
  return syncUpload({
    fs,
    path: newFileId,
    emitEvent
  });
}

// src-deno/utils/handle-diff-sys-statuses/handle-groups-conflicting-status.ts
async function handleGroupsConflictingStatus({ fs, fileSrv, syncStatus, emitEvent }) {
  const isServerConnection = await checkServerConnection(fs);
  if (!isServerConnection) {
    return void 0;
  }
  const remoteFileData = await fs.v?.readJSONFile(GROUPS_FILE_NAME, {
    remoteVersion: syncStatus.remote.latest
  });
  if (!remoteFileData) {
    throw `The remote file ${GROUPS_FILE_NAME} is missing`;
  }
  const currentFileData = await fs.readJSONFile(GROUPS_FILE_NAME);
  const currentFileDataIds = new Set((currentFileData || []).map((item) => item.id));
  const updatedData = [
    ...currentFileData,
    ...(remoteFileData?.json || []).filter((item) => !currentFileDataIds.has(item.id))
  ];
  await fileSrv.updateFile(updatedData, GROUPS_FILE_NAME);
  return syncUpload({
    fs,
    path: GROUPS_FILE_NAME,
    opts: {
      uploadVersion: syncStatus.remote.latest + 1
    },
    emitEvent
  });
}

// src-deno/utils/handle-diff-sys-statuses/handle-folder-unsynced-status.ts
async function handleFolderUnsyncedStatus({ path, fs, emitEvent }) {
  const isServerConnection = await checkServerConnection(fs);
  if (!isServerConnection) {
    return void 0;
  }
  return syncUpload({
    fs,
    path,
    emitEvent,
    immediately: true
  });
}

// src-deno/utils/handle-diff-sys-statuses/handle-folder-behind-status.ts
async function handleFolderBehindStatus({ path, fs, syncStatus, emitEvent }) {
  const isServerConnection = await checkServerConnection(fs);
  if (!isServerConnection) {
    return;
  }
  return syncAdopt({
    fs,
    path,
    opts: {
      remoteVersion: syncStatus.remote.latest
    },
    emitEvent
  });
}

// src-deno/utils/handle-diff-sys-statuses/handle-folder-conflicting-status.ts
async function handleFolderConflictingStatus({ path, fs, emitEvent }) {
  const isServerConnection = await checkServerConnection(fs);
  if (!isServerConnection) {
    return void 0;
  }
  const newVersion = await fs.v?.sync?.absorbRemoteFolderChanges(path, {
    postfixForNameOverlaps: "_[ keep ]"
  });
  return syncUpload({
    fs,
    path,
    emitEvent,
    opts: {
      uploadVersion: newVersion
    },
    immediately: true
  });
}

// src-deno/utils/check-sync-fs-state.ts
async function checkItemSyncState({ path, fs, fileSrv, emitEvent }) {
  const syncStatus = await fs.v?.sync?.status(path);
  if (syncStatus) {
    switch (syncStatus.state) {
      case "synced": {
        return handleFileSyncedStatus({
          fs,
          path,
          syncStatus,
          emitEvent
        });
      }
      case "unsynced": {
        return handleFileUnsyncedStatus({
          fs,
          path,
          emitEvent
        });
      }
      case "behind": {
        return handleFileBehindStatus({
          fs,
          path,
          syncStatus,
          emitEvent
        });
      }
      case "conflicting": {
        if (path === GROUPS_FILE_NAME) {
          return handleGroupsConflictingStatus({
            fs,
            fileSrv,
            syncStatus,
            emitEvent
          });
        }
        return handleRecordConflictingStatus({
          fs,
          fileSrv,
          fileName: path,
          syncStatus,
          emitEvent
        });
      }
    }
  }
}
async function checkFolderSyncState({ path, fs, emitEvent }) {
  try {
    const folderSyncStatus = await fs.v?.sync?.status("");
    if (folderSyncStatus) {
      switch (folderSyncStatus.state) {
        case "unsynced": {
          return handleFolderUnsyncedStatus({
            path,
            fs,
            emitEvent
          });
        }
        case "behind": {
          return handleFolderBehindStatus({
            path,
            fs,
            syncStatus: folderSyncStatus,
            emitEvent
          });
        }
        case "conflicting": {
          return handleFolderConflictingStatus({
            path,
            fs,
            emitEvent
          });
        }
      }
    }
  } catch (err) {
    if (err.type === "fs-sync" && err.childNeverUploaded) {
      setTimeout(async () => {
        await checkFolderSyncState({
          path,
          fs,
          emitEvent
        });
      }, 1e4);
      return;
    }
    throw err;
  }
}
async function checkSyncFsState({ fs, fileSrv, emitEvent }) {
  try {
    const rootFolderList = await fs.listFolder("");
    for (const entity of rootFolderList) {
      const { name, isFile } = entity;
      if (isFile) {
        await checkItemSyncState({
          path: name,
          fs,
          fileSrv,
          emitEvent
        });
      }
    }
    const imagesFolderList = await fs.listFolder(IMAGES_FOLDER);
    for (const entity of imagesFolderList) {
      const { name, isFile } = entity;
      if (isFile) {
        await checkItemSyncState({
          path: `${IMAGES_FOLDER}/${name}`,
          fs,
          fileSrv,
          emitEvent
        });
      }
    }
    await checkFolderSyncState({
      path: IMAGES_FOLDER,
      fs,
      emitEvent
    });
    await checkFolderSyncState({
      path: "",
      fs,
      emitEvent
    });
    emitEvent({
      event: "update:records"
    });
  } catch (err) {
    w3n.log("error", "\u{1F525} Error while initial checking sync state. ", err);
  }
}

// src-deno/treasure-sync-srv.ts
async function isConnectionOnline() {
  return (await w3n.connectivity?.isOnline() || "").includes("online");
}
async function treasureSyncSrv({ fs, fileSrv, emitEvent }) {
  let isOnlinePrev = await isConnectionOnline();
  w3n.connectivity.watch({
    next: async (event) => {
      const { isOnline } = event;
      if (isOnline && !isOnlinePrev) {
        checkSyncFsState({
          fs,
          fileSrv,
          emitEvent
        });
      }
      isOnlinePrev = isOnline;
    },
    error: (err) => {
      console.error("\u{1F525} CONNECTIVITY WATCHING ERROR. ", err);
    }
  });
}

// src-deno/utils/handle-folder-change-sync-status.ts
async function handleFolderChangeSyncStatus({ path, fs, emitTreasureEvent }) {
  try {
    const folderSyncStatus = await fs.v?.sync?.status(path);
    if (folderSyncStatus) {
      switch (folderSyncStatus.state) {
        case "behind": {
          emitTreasureEvent({
            event: "sync:start",
            payload: {
              path: "root",
              type: "download"
            }
          });
          const diff = await fs.v?.sync?.diffCurrentAndRemoteFolderVersions(path);
          const newFiles = diff && diff.added && diff.added.inRemote && Array.isArray(diff.added.inRemote) && diff.added.inRemote.length > 0 ? [
            ...diff.added.inRemote
          ] : [];
          const deletedFiles = diff && diff.removed && diff.removed.inRemote && Array.isArray(diff.removed.inRemote) && diff.removed.inRemote.length > 0 ? [
            ...diff.removed.inRemote
          ] : [];
          await fs.v?.sync?.adoptRemote(path, {
            remoteVersion: folderSyncStatus.remote.latest
          });
          if (!path && newFiles.length > 0) {
            emitTreasureEvent({
              event: "add:record",
              payload: {
                data: newFiles
              }
            });
          }
          if (!path && deletedFiles.length > 0) {
            emitTreasureEvent({
              event: "remove:record",
              payload: {
                data: deletedFiles
              }
            });
          }
          emitTreasureEvent({
            event: "sync:end",
            payload: {
              path: path || "root",
              type: "download"
            }
          });
          break;
        }
      }
    }
  } catch (err) {
    if (err.type === "fs-sync" && err.childNeverUploaded) {
      return;
    }
    throw err;
  }
}

// src-deno/utils/handle-diff-sys-statuses/handle-image-conflicting-status.ts
async function handleImageConflictingStatus({ fs, fileName, syncStatus, emitEvent }) {
  const isServerConnection = await checkServerConnection(fs);
  if (!isServerConnection) {
    return void 0;
  }
  const remoteFileStat = await fs.v?.stat(fileName);
  if (!remoteFileStat) {
    throw `The remote file ${fileName} is missing`;
  }
  const fileStat = await fs.stat(fileName);
  const remoteFileMtime = remoteFileStat.mtime ? new Date(remoteFileStat.mtime).getTime() : Date.now();
  const fileMtime = fileStat?.mtime ? new Date(fileStat.mtime).getTime() : Date.now();
  if (fileMtime > remoteFileMtime) {
    await syncUpload({
      fs,
      path: fileName,
      emitEvent,
      opts: {
        uploadVersion: syncStatus.remote.latest + 1
      }
    });
  } else {
    await fs.v?.sync?.adoptRemote(fileName, {
      remoteVersion: syncStatus.remote.latest
    });
    await syncDownload({
      fs,
      path: fileName,
      version: syncStatus.remote.latest,
      emitEvent
    });
  }
}

// src-deno/utils/handle-file-change-sync-status.ts
async function handleFileChangeSyncStatus(currentFileName, fs, fileSrv, emitEvent) {
  try {
    const fileSyncStatus = await fs.v?.sync?.status(currentFileName);
    if (!fileSyncStatus) {
      return void 0;
    }
    switch (fileSyncStatus.state) {
      case "synced": {
        return handleFileSyncedStatus({
          fs,
          path: currentFileName,
          syncStatus: fileSyncStatus,
          emitEvent
        });
      }
      case "unsynced": {
        return handleFileUnsyncedStatus({
          fs,
          path: currentFileName,
          emitEvent
        });
      }
      case "behind": {
        return handleFileBehindStatus({
          fs,
          path: currentFileName,
          syncStatus: fileSyncStatus,
          emitEvent
        });
      }
      case "conflicting": {
        if (currentFileName === GROUPS_FILE_NAME) {
          return handleGroupsConflictingStatus({
            fs,
            fileSrv,
            syncStatus: fileSyncStatus,
            emitEvent
          });
        }
        if (currentFileName.includes(IMAGES_FOLDER)) {
          return handleImageConflictingStatus({
            fs,
            fileName: currentFileName,
            syncStatus: fileSyncStatus,
            emitEvent
          });
        }
        return handleRecordConflictingStatus({
          fs,
          fileSrv,
          fileName: currentFileName,
          syncStatus: fileSyncStatus,
          emitEvent
        });
      }
    }
  } catch (err) {
    console.error(`\u{1F525} Error handling ${currentFileName} file sync status. `, err);
    throw err;
  }
}

// src-deno/treasure-deno-srv.ts
async function treasureDenoSrv() {
  setupGlobalReportingOfUnhandledErrors(true);
  const fs = await w3n.storage.getAppSyncedFS();
  const fsLocal = await w3n.storage.getAppLocalFS();
  if (!await fs.checkFolderPresence(IMAGES_FOLDER)) {
    await fs.makeFolder(IMAGES_FOLDER);
    await fs.v?.sync?.upload(IMAGES_FOLDER);
    await fs.v?.sync?.upload("");
  }
  if (!await fsLocal.checkFilePresence(RECENT_FILE_NAME)) {
    await fsLocal.writeJSONFile(RECENT_FILE_NAME, []);
  }
  const fileSrv = await treasureFileSrv(fs, fsLocal);
  const eventsObservers = new ObserversSet();
  function emitTreasureEvent(event) {
    eventsObservers.next(event);
  }
  function watchEvent(obs) {
    eventsObservers.add(obs);
    return () => eventsObservers.delete(obs);
  }
  await treasureSyncSrv({
    fs,
    fileSrv,
    emitEvent: emitTreasureEvent
  });
  fs.watchTree("", 3, {
    next: async (event) => {
      const { type, path } = event;
      const processedPath = path.replace("./", "").replace(".", "");
      switch (type) {
        case "upload-started": {
          emitTreasureEvent({
            event: "sync:start",
            payload: {
              path: processedPath || "root",
              type: "upload"
            }
          });
          break;
        }
        case "upload-progress": {
          const { bytesLeftToUpload, totalBytesToUpload } = event;
          const progress = round((totalBytesToUpload - bytesLeftToUpload) / totalBytesToUpload, -3);
          emitTreasureEvent({
            event: "sync:update",
            payload: {
              path: processedPath || "root",
              type: "upload",
              value: progress
            }
          });
          break;
        }
        case "upload-done": {
          emitTreasureEvent({
            event: "sync:end",
            payload: {
              path: processedPath || "root",
              type: "upload"
            }
          });
          if (!processedPath) {
            await syncUpload({
              fs,
              path: "",
              emitEvent: emitTreasureEvent,
              immediately: true
            });
          }
          break;
        }
        case "download-started": {
          emitTreasureEvent({
            event: "sync:start",
            payload: {
              path: processedPath || "root",
              type: "download"
            }
          });
          break;
        }
        case "download-progress": {
          const { bytesLeftToDownload, totalBytesToDownload } = event;
          const progress = round((totalBytesToDownload - bytesLeftToDownload) / totalBytesToDownload, -3);
          emitTreasureEvent({
            event: "sync:update",
            payload: {
              path: processedPath || "root",
              type: "download",
              value: progress
            }
          });
          break;
        }
        case "download-done": {
          emitTreasureEvent({
            event: "sync:end",
            payload: {
              path: processedPath || "root",
              type: "download"
            }
          });
          break;
        }
        case "remote-change": {
          if (!processedPath) {
            await handleFolderChangeSyncStatus({
              path: "",
              fs,
              emitTreasureEvent
            });
            return;
          }
          if (processedPath === IMAGES_FOLDER) {
            await handleFolderChangeSyncStatus({
              path: IMAGES_FOLDER,
              fs,
              emitTreasureEvent
            });
            return;
          }
          if (processedPath.includes(IMAGES_FOLDER)) {
            await handleFileChangeSyncStatus(processedPath, fs, fileSrv, emitTreasureEvent);
            return;
          }
          if (processedPath === GROUPS_FILE_NAME) {
            await handleFileChangeSyncStatus(GROUPS_FILE_NAME, fs, fileSrv, emitTreasureEvent);
            emitTreasureEvent({
              event: "update:group"
            });
            return;
          }
          await handleFileChangeSyncStatus(processedPath, fs, fileSrv, emitTreasureEvent);
          emitTreasureEvent({
            event: "update:record",
            payload: {
              data: processedPath
            }
          });
          break;
        }
        case "remote-removal": {
          emitTreasureEvent({
            event: "remove:record",
            payload: {
              data: [
                processedPath
              ]
            }
          });
          break;
        }
      }
    },
    error: (err) => w3n.log("error", "Error watching the root folder. ", err)
  });
  async function rewriteGroups(data, withoutSync) {
    await fileSrv.saveFile(data, GROUPS_FILE_NAME);
    const isConnectionAvailable = await checkServerConnection(fs);
    if (!withoutSync && isConnectionAvailable) {
      await syncUpload({
        fs,
        path: GROUPS_FILE_NAME,
        emitEvent: emitTreasureEvent
      });
      return true;
    }
    return false;
  }
  async function getAllTreasureGroups() {
    try {
      return fileSrv.getFile(GROUPS_FILE_NAME);
    } catch (err) {
      if (err.notFound) {
        return [];
      }
      w3n.log("error", "Error getting treasure groups", err);
    }
  }
  async function loadImage(imageId) {
    return fileSrv.loadImage(imageId);
  }
  async function saveImage(data) {
    return fileSrv.saveImage(data);
  }
  async function deleteImages(imageIds) {
    const fileNames = imageIds.map((id) => `${IMAGES_FOLDER}/${id}`);
    return fileSrv.deleteFiles(fileNames);
  }
  async function addRecord(data, withoutUploadParentFolder) {
    const id = await fileSrv.saveFile(data);
    const isConnectionAvailable = await checkServerConnection(fs);
    if (isConnectionAvailable) {
      await syncUpload({
        fs,
        path: id,
        emitEvent: emitTreasureEvent
      });
      if (!withoutUploadParentFolder) {
        await syncUpload({
          fs,
          path: "",
          emitEvent: emitTreasureEvent,
          immediately: true
        });
      }
      return {
        id,
        wasSync: true
      };
    }
    return {
      id,
      wasSync: false
    };
  }
  async function updateRecord(data) {
    await fileSrv.updateFile(data);
    const isConnectionAvailable = await checkServerConnection(fs);
    if (isConnectionAvailable) {
      await syncUpload({
        fs,
        path: data.id,
        emitEvent: emitTreasureEvent
      });
      return true;
    }
    return false;
  }
  async function deleteRecord(data, withoutUploadParentFolder) {
    const reference = data.reference;
    const source = data.source;
    const images = JSON.parse(JSON.stringify(data.images || []));
    await fileSrv.deleteFile(data.id);
    if (reference) {
      const record = await getRecord(reference);
      if (record) {
        record.source && delete record.source;
        await updateRecord(record);
      }
    }
    if (source) {
      const record = await getRecord(source);
      if (record) {
        record.reference && delete record.reference;
        await updateRecord(record);
      }
    }
    if (images.length) {
      const processedImagesPath = images.map((fileId) => `${IMAGES_FOLDER}/${fileId}`);
      await fileSrv.deleteFiles(processedImagesPath);
    }
    const isConnectionAvailable = await checkServerConnection(fs);
    if (isConnectionAvailable && !withoutUploadParentFolder) {
      await syncUpload({
        fs,
        path: "",
        emitEvent: emitTreasureEvent,
        immediately: true
      });
      if (images.length) {
        await syncUpload({
          fs,
          path: IMAGES_FOLDER,
          emitEvent: emitTreasureEvent,
          immediately: true
        });
      }
      return true;
    }
    return false;
  }
  async function deleteRecords(ids) {
    const pr = [];
    for (let i = 0; i < ids.length; i++) {
      const record = await getRecord(ids[i]);
      if (record) {
        pr.push(deleteRecord(record, i < ids.length - 1));
      }
    }
    const res = await Promise.allSettled(pr);
    return !res.some((item) => item.status === "fulfilled" && !item.value);
  }
  async function getRecord(id) {
    const record = await fileSrv.getFile(id);
    if (!record) {
      return null;
    }
    const fileStat = await fs.stat(id);
    return {
      ...record,
      mtime: fileStat.mtime
    };
  }
  async function getRecordSyncStatus(id) {
    const isRecordFilePresent = await fs.checkFilePresence(id);
    if (!isRecordFilePresent) {
      return void 0;
    }
    return fs.v?.sync?.status(id);
  }
  async function getAllRecords() {
    const list = await fs.listFolder("");
    const workResultsPromises = [];
    for (const item of list) {
      if (item.isFile && item.name !== GROUPS_FILE_NAME) {
        workResultsPromises.push(getRecord(item.name));
      }
    }
    const res = await Promise.allSettled(workResultsPromises);
    return res.reduce((res2, item) => {
      if (item.status === "fulfilled") {
        item.value && res2.records.push(item.value);
      } else {
        res2.errors.push(item.reason);
      }
      return res2;
    }, {
      records: [],
      errors: []
    });
  }
  const debouncedSave = debounce((data) => {
    fileSrv.saveRecentFile(data);
  }, 2e3);
  async function saveRecentFile(data) {
    debouncedSave(data);
  }
  async function initial() {
    const doesGroupsFileExist = await fs.checkFilePresence(GROUPS_FILE_NAME);
    if (!doesGroupsFileExist) {
      await rewriteGroups([]);
    }
    const isThereConnection = await checkServerConnection(fs);
    if (!isThereConnection) {
      setTimeout(() => {
        initial();
        return;
      }, 6e4);
    }
    try {
      await checkSyncFsState({
        fs,
        fileSrv,
        emitEvent: emitTreasureEvent
      });
    } catch (err) {
      w3n.log("error", "\u{1F525} Error while initial synchronization process. ", err);
    }
  }
  return {
    emitTreasureEvent,
    watchEvent,
    rewriteGroups,
    getAllTreasureGroups,
    loadRecentFile: fileSrv.loadRecentFile,
    saveRecentFile,
    loadImage,
    saveImage,
    deleteImages,
    addRecord,
    updateRecord,
    deleteRecord,
    deleteRecords,
    getRecord,
    getRecordSyncStatus,
    getAllRecords,
    initial
  };
}
treasureDenoSrv().then((srv) => {
  const srvWrapInternal = new MultiConnectionIPCWrap("AppTreasureInternal");
  srvWrapInternal.exposeReqReplyMethods(srv, [
    "rewriteGroups",
    "getAllTreasureGroups",
    "loadRecentFile",
    "saveRecentFile",
    "loadImage",
    "saveImage",
    "deleteImages",
    "addRecord",
    "updateRecord",
    "deleteRecord",
    "deleteRecords",
    "getRecord",
    "getRecordSyncStatus",
    "getAllRecords",
    "initial"
  ]);
  srvWrapInternal.exposeObservableMethods(srv, [
    "watchEvent"
  ]);
  srvWrapInternal.startIPC();
}).catch(async (err) => {
  await w3n.log("error", "\u{1F525} Error in a startup of treasure deno service component. ", err);
  await sleep(10);
  w3n.closeSelf();
});
