@liascript/exporter 3.0.0--1.0.3 → 3.0.2--1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/assets/capacitor/{index.bfe7363b.js → index.44a6a9b3.js} +1 -1
  2. package/dist/assets/capacitor/index.html +1 -1
  3. package/dist/assets/capacitor/{jszip.min.f6eda75b.js → jszip.min.2f991499.js} +1 -1
  4. package/dist/assets/capacitor/{trystero-ipfs.min.b27a61d7.js → trystero-ipfs.min.f25fe3e7.js} +1 -1
  5. package/dist/assets/indexeddb/{index.599a57d6.js → index.4aceca2f.js} +1 -1
  6. package/dist/assets/indexeddb/index.html +1 -1
  7. package/dist/assets/pdf/{index.aa124b49.js → index.49b3a4d9.js} +1 -1
  8. package/dist/assets/pdf/index.html +1 -1
  9. package/dist/assets/scorm2004/{index.45f7501b.js → index.031764e4.js} +1 -1
  10. package/dist/assets/scorm2004/index.html +1 -1
  11. package/dist/assets/{xapi/jszip.min.eaecf580.js → scorm2004/jszip.min.19c66d77.js} +1 -1
  12. package/dist/assets/web/{index.39a3e3eb.js → index.98993ded.js} +1 -1
  13. package/dist/assets/web/{index.1062f2c5.js → index.e84d3f3b.js} +1 -1
  14. package/dist/assets/web/index.html +1 -1
  15. package/dist/assets/web/{jszip.min.eaecf580.js → jszip.min.19c66d77.js} +1 -1
  16. package/dist/assets/xapi/{index.018a032a.js → index.f2e89e49.js} +1 -1
  17. package/dist/assets/xapi/{index.780a0ec3.js → index.f5402f58.js} +1 -1
  18. package/dist/assets/xapi/index.html +1 -1
  19. package/dist/assets/{scorm2004/jszip.min.eaecf580.js → xapi/jszip.min.19c66d77.js} +1 -1
  20. package/dist/index.js +3 -3
  21. package/dist/server/presets.json +94 -0
  22. package/dist/server/presets.yaml +120 -0
  23. package/dist/server/public/app.js +1 -0
  24. package/dist/server/public/assets/android.svg +38 -0
  25. package/dist/server/public/assets/cmi.svg +154 -0
  26. package/dist/server/public/assets/docx.svg +20 -0
  27. package/dist/server/public/assets/edX.svg +75 -0
  28. package/dist/server/public/assets/edx.svg +75 -0
  29. package/dist/server/public/assets/epub.svg +18 -0
  30. package/dist/server/public/assets/icon.svg +82 -0
  31. package/dist/server/public/assets/ilias.png +0 -0
  32. package/dist/server/public/assets/json.svg +4 -0
  33. package/dist/server/public/assets/learnworlds.png +0 -0
  34. package/dist/server/public/assets/moodle.svg +190 -0
  35. package/dist/server/public/assets/opal.png +0 -0
  36. package/dist/server/public/assets/openolat.png +0 -0
  37. package/dist/server/public/assets/pdf.svg +4 -0
  38. package/dist/server/public/assets/rdf.svg +4 -0
  39. package/dist/server/public/assets/scorm.png +0 -0
  40. package/dist/server/public/assets/web.png +0 -0
  41. package/dist/server/public/assets/xapi.png +0 -0
  42. package/dist/server/public/i18n.js +1 -0
  43. package/dist/server/public/index.html +1587 -0
  44. package/dist/server/public/locales/de.json +247 -0
  45. package/dist/server/public/locales/en.json +247 -0
  46. package/dist/server/public/status.html +251 -0
  47. package/dist/server/public/styles.css +712 -0
  48. package/package.json +5 -1
  49. package/.parcelrc +0 -3
  50. package/DESKTOP_APP_README.md +0 -58
  51. package/DOCKERHUB_DESCRIPTION.md +0 -52
  52. package/Dockerfile +0 -129
  53. package/PLAYSTORE_GUIDE.md +0 -172
  54. package/action.yml +0 -157
  55. package/custom.css +0 -10
  56. package/electron-builder.json +0 -149
  57. package/src/cli.ts +0 -69
  58. package/src/colorize.ts +0 -115
  59. package/src/export/android.ts +0 -419
  60. package/src/export/docx.ts +0 -1025
  61. package/src/export/epub.ts +0 -1306
  62. package/src/export/h5p.ts +0 -390
  63. package/src/export/helper.ts +0 -360
  64. package/src/export/ims.ts +0 -191
  65. package/src/export/pdf.ts +0 -406
  66. package/src/export/presets.ts +0 -220
  67. package/src/export/project.ts +0 -829
  68. package/src/export/rdf.ts +0 -551
  69. package/src/export/scorm12.ts +0 -167
  70. package/src/export/scorm2004.ts +0 -140
  71. package/src/export/web.ts +0 -306
  72. package/src/export/xapi.ts +0 -424
  73. package/src/exporter.ts +0 -296
  74. package/src/index.ts +0 -96
  75. package/src/parser.ts +0 -373
  76. package/src/presets.yaml +0 -219
  77. package/src/types.ts +0 -82
  78. package/tsconfig.json +0 -24
  79. /package/dist/assets/{pdf → indexeddb}/jszip.min.4fbcc13f.js +0 -0
  80. /package/dist/assets/{indexeddb → pdf}/jszip.min.63142cc8.js +0 -0
  81. /package/dist/assets/{xapi → web}/jszip.min.63142cc8.js +0 -0
  82. /package/dist/assets/{web → xapi}/jszip.min.4fbcc13f.js +0 -0
@@ -1 +1 @@
1
- !function(e,t,r,n,s){var i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},o="function"==typeof i[n]&&i[n],a=o.cache||{},c="undefined"!=typeof module&&"function"==typeof module.require&&module.require.bind(module);function l(t,r){if(!a[t]){if(!e[t]){var s="function"==typeof i[n]&&i[n];if(!r&&s)return s(t,!0);if(o)return o(t,!0);if(c&&"string"==typeof t)return c(t);var u=new Error("Cannot find module '"+t+"'");throw u.code="MODULE_NOT_FOUND",u}d.resolve=function(r){var n=e[t][1][r];return null!=n?n:r},d.cache={};var h=a[t]=new l.Module(t);e[t][0].call(h.exports,d,h,h.exports,this)}return a[t].exports;function d(e){var t=d.resolve(e);return!1===t?{}:l(t)}}l.isParcelRequire=!0,l.Module=function(e){this.id=e,this.bundle=l,this.exports={}},l.modules=e,l.cache=a,l.parent=o,l.register=function(t,r){e[t]=[function(e,t){t.exports=r},{}]},Object.defineProperty(l,"root",{get:function(){return i[n]}}),i[n]=l;for(var u=0;u<t.length;u++)l(t[u])}({aZqqK:[function(e,t,r){var n=e("@parcel/transformer-js/src/esmodule-helpers.js");n.defineInteropFlag(r),n.export(r,"joinRoom",(()=>bA)),n.export(r,"selfId",(()=>US));var s=e("c1f15e2440b26488"),i=arguments[3];function o(e=0){return new Uint8Array(e)}function a(e=0){return new Uint8Array(e)}const c=268435456,l=34359738368,u=4398046511104,h=Math.pow(2,49),d=128,p=127;function f(e){if(e<128)return 1;if(e<16384)return 2;if(e<2097152)return 3;if(e<c)return 4;if(e<l)return 5;if(e<u)return 6;if(e<h)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function g(e,t,r=0){switch(f(e)){case 8:t[r++]=255&e|d,e/=128;case 7:t[r++]=255&e|d,e/=128;case 6:t[r++]=255&e|d,e/=128;case 5:t[r++]=255&e|d,e/=128;case 4:t[r++]=255&e|d,e>>>=7;case 3:t[r++]=255&e|d,e>>>=7;case 2:t[r++]=255&e|d,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw Error("unreachable")}return t}function m(e,t){let r=e[t],n=0;if(n+=r&p,r<d)return n;if(r=e[t+1],n+=(r&p)<<7,r<d)return n;if(r=e[t+2],n+=(r&p)<<14,r<d)return n;if(r=e[t+3],n+=(r&p)<<21,r<d)return n;if(r=e[t+4],n+=(r&p)*c,r<d)return n;if(r=e[t+5],n+=(r&p)*l,r<d)return n;if(r=e[t+6],n+=(r&p)*u,r<d)return n;if(r=e[t+7],n+=(r&p)*h,r<d)return n;throw new RangeError("Could not decode varint")}function y(e,t,r=0){return null==t&&(t=a(f(e))),t instanceof Uint8Array?g(e,t,r):function(e,t,r=0){switch(f(e)){case 8:t.set(r++,255&e|d),e/=128;case 7:t.set(r++,255&e|d),e/=128;case 6:t.set(r++,255&e|d),e/=128;case 5:t.set(r++,255&e|d),e/=128;case 4:t.set(r++,255&e|d),e>>>=7;case 3:t.set(r++,255&e|d),e>>>=7;case 2:t.set(r++,255&e|d),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw Error("unreachable")}return t}(e,t,r)}function b(e,t=0){return e instanceof Uint8Array?m(e,t):function(e,t){let r=e.get(t),n=0;if(n+=r&p,r<d)return n;if(r=e.get(t+1),n+=(r&p)<<7,r<d)return n;if(r=e.get(t+2),n+=(r&p)<<14,r<d)return n;if(r=e.get(t+3),n+=(r&p)<<21,r<d)return n;if(r=e.get(t+4),n+=(r&p)*c,r<d)return n;if(r=e.get(t+5),n+=(r&p)*l,r<d)return n;if(r=e.get(t+6),n+=(r&p)*u,r<d)return n;if(r=e.get(t+7),n+=(r&p)*h,r<d)return n;throw new RangeError("Could not decode varint")}(e,t)}const w=new Float32Array([-0]),v=new Uint8Array(w.buffer);function E(e,t,r){w[0]=e,t[r]=v[0],t[r+1]=v[1],t[r+2]=v[2],t[r+3]=v[3]}const S=new Float64Array([-0]),A=new Uint8Array(S.buffer);function I(e,t,r){S[0]=e,t[r]=A[0],t[r+1]=A[1],t[r+2]=A[2],t[r+3]=A[3],t[r+4]=A[4],t[r+5]=A[5],t[r+6]=A[6],t[r+7]=A[7]}const _=BigInt(Number.MAX_SAFE_INTEGER),C=BigInt(Number.MIN_SAFE_INTEGER);class x{lo;hi;constructor(e,t){this.lo=0|e,this.hi=0|t}toNumber(e=!1){if(!e&&this.hi>>>31>0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(0n===e)return k;if(e<_&&e>C)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let r=e>>32n,n=e-(r<<32n);return t&&(r=0n|~r,n=0n|~n,++n>T&&(n=0n,++r>T&&(r=0n))),new x(Number(n),Number(r))}static fromNumber(e){if(0===e)return k;const t=e<0;t&&(e=-e);let r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new x(r,n)}static from(e){return"number"==typeof e?x.fromNumber(e):"bigint"==typeof e?x.fromBigInt(e):"string"==typeof e?x.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new x(e.low>>>0,e.high>>>0):k}}const k=new x(0,0);k.toBigInt=()=>0n,k.zzEncode=k.zzDecode=function(){return this},k.length=()=>1;const T=4294967296n;function P(e,t,r){const n=r;let s,i;for(let n=0;n<e.length;++n)s=e.charCodeAt(n),s<128?t[r++]=s:s<2048?(t[r++]=s>>6|192,t[r++]=63&s|128):55296==(64512&s)&&56320==(64512&(i=e.charCodeAt(n+1)))?(s=65536+((1023&s)<<10)+(1023&i),++n,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128);return r-n}function R(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function L(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class D{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,R(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw R(this,4);return L(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw R(this,4);return 0|L(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw R(this,4);const e=(t=this.buf,r=this.pos,v[0]=t[r],v[1]=t[r+1],v[2]=t[r+2],v[3]=t[r+3],w[0]);var t,r;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw R(this,4);const e=(t=this.buf,r=this.pos,A[0]=t[r],A[1]=t[r+1],A[2]=t[r+2],A[3]=t[r+3],A[4]=t[r+4],A[5]=t[r+5],A[6]=t[r+6],A[7]=t[r+7],S[0]);var t,r;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw R(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){const e=this.bytes();return function(e,t,r){if(r-t<1)return"";let n;const s=[];let i,o=0;for(;t<r;)i=e[t++],i<128?s[o++]=i:i>191&&i<224?s[o++]=(31&i)<<6|63&e[t++]:i>239&&i<365?(i=((7&i)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[o++]=55296+(i>>10),s[o++]=56320+(1023&i)):s[o++]=(15&i)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,s)),o=0);return null!=n?(o>0&&n.push(String.fromCharCode.apply(String,s.slice(0,o))),n.join("")):String.fromCharCode.apply(String,s.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw R(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw R(this)}while(128&this.buf[this.pos++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new x(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw R(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw R(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw R(this,8);const e=L(this.buf,this.pos+=4),t=L(this.buf,this.pos+=4);return new x(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=m(this.buf,this.pos);return this.pos+=f(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function M(e,t,r){const n=function(e){return new D(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}function N(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error("Unknown type, must be binary type")}var O=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var s=0;s<e.length;s++){var i=e.charAt(s),o=i.charCodeAt(0);if(255!==r[o])throw new TypeError(i+" is ambiguous");r[o]=s}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var n=0,s=0;e[t]===c;)n++,t++;for(var i=(e.length-t)*l+1>>>0,o=new Uint8Array(i);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var h=0,d=i-1;(0!==u||h<s)&&-1!==d;d--,h++)u+=a*o[d]>>>0,o[d]=u%256>>>0,u=u/256>>>0;if(0!==u)throw Error("Non-zero carry");s=h,t++}if(" "!==e[t]){for(var p=i-s;p!==i&&0===o[p];)p++;for(var f=new Uint8Array(n+(i-p)),g=n;p!==i;)f[g++]=o[p++];return f}}}return{encode(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,s=0,i=t.length;s!==i&&0===t[s];)s++,r++;for(var o=(i-s)*u+1>>>0,l=new Uint8Array(o);s!==i;){for(var h=t[s],d=0,p=o-1;(0!==h||d<n)&&-1!==p;p--,d++)h+=256*l[p]>>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw Error("Non-zero carry");n=d,s++}for(var f=o-n;f!==o&&0===l[f];)f++;for(var g=c.repeat(r);f<o;++f)g+=e.charAt(l[f]);return g},decodeUnsafe:h,decode(e){var r=h(e);if(r)return r;throw Error(`Non-${t} character`)}}};class U{decoders;constructor(e){this.decoders=e}or(e){return F(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(null!=r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function F(e,t){return new U({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}class B{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,r,n){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new class{name;prefix;baseEncode;constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}(e,t,r),this.decoder=new class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){this.name=e,this.prefix=t;const n=t.codePointAt(0);if(void 0===n)throw Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return F(this,e)}}(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function $({name:e,prefix:t,encode:r,decode:n}){return new B(e,t,r,n)}function q({name:e,prefix:t,alphabet:r}){const{encode:n,decode:s}=O(r,e);return $({prefix:t,name:e,encode:n,decode:e=>N(s(e))})}function z({name:e,prefix:t,bitsPerChar:r,alphabet:n}){const s=function(e){const t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}(n);return $({prefix:t,name:e,encode:e=>function(e,t,r){const n="="===t[t.length-1],s=(1<<r)-1;let i="",o=0,a=0;for(let n=0;n<e.length;++n)for(a=a<<8|e[n],o+=8;o>r;)o-=r,i+=t[s&a>>o];if(0!==o&&(i+=t[s&a<<r-o]),n)for(;i.length*r&7;)i+="=";return i}(e,n,r),decode:t=>function(e,t,r,n){let s=e.length;for(;"="===e[s-1];)--s;const i=new Uint8Array(s*r/8|0);let o=0,a=0,c=0;for(let l=0;l<s;++l){const s=t[e[l]];if(void 0===s)throw new SyntaxError(`Non-${n} character`);a=a<<r|s,o+=r,o>=8&&(o-=8,i[c++]=255&a>>o)}if(o>=r||255&a<<8-o)throw new SyntaxError("Unexpected end of data");return i}(t,s,r,e)})}const j=q({prefix:"9",name:"base10",alphabet:"0123456789"});var K=Object.freeze({__proto__:null,base10:j});const V=z({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),H=z({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var G=Object.freeze({__proto__:null,base16:V,base16upper:H});const W=z({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var X=Object.freeze({__proto__:null,base2:W});const Z=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Y=Z.reduce(((e,t,r)=>(e[r]=t,e)),[]),Q=Z.reduce(((e,t,r)=>{const n=t.codePointAt(0);if(null==n)throw Error("Invalid character: "+t);return e[n]=r,e}),[]),J=$({prefix:"🚀",name:"base256emoji",encode:e=>e.reduce(((e,t)=>e+Y[t]),""),decode(e){const t=[];for(const r of e){const e=r.codePointAt(0);if(null==e)throw Error("Invalid character: "+r);const n=Q[e];if(null==n)throw Error("Non-base256emoji character: "+r);t.push(n)}return new Uint8Array(t)}});var ee=Object.freeze({__proto__:null,base256emoji:J});const te=z({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),re=z({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ne=z({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),se=z({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ie=z({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),oe=z({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ae=z({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ce=z({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),le=z({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ue=Object.freeze({__proto__:null,base32:te,base32hex:ie,base32hexpad:ae,base32hexpadupper:ce,base32hexupper:oe,base32pad:ne,base32padupper:se,base32upper:re,base32z:le});const he=q({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),de=q({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var pe=Object.freeze({__proto__:null,base36:he,base36upper:de});const fe=q({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ge=q({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var me=Object.freeze({__proto__:null,base58btc:fe,base58flickr:ge});const ye=z({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),be=z({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),we=z({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ve=z({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ee=Object.freeze({__proto__:null,base64:ye,base64pad:be,base64url:we,base64urlpad:ve});const Se=z({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ae=Object.freeze({__proto__:null,base8:Se});const Ie=$({prefix:"\0",name:"identity",encode(e){var t;return t=e,(new TextDecoder).decode(t)},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)});var _e=Object.freeze({__proto__:null,identity:Ie});new TextEncoder,new TextDecoder;var Ce=Math.pow(2,63),xe={encode:function e(t,r,n){r=r||[];for(var s=n=n||0;t>=2147483648;)r[n++]=255&t|128,t/=128;for(;-128&t;)r[n++]=255&t|128,t>>>=7;return r[n]=0|t,e.bytes=n-s+1,r},decode:function e(t,r){var n,s=0,i=0,o=r=r||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[o++],s+=i<28?(127&n)<<i:(127&n)*Math.pow(2,i),i+=7}while(n>=128);return e.bytes=o-r,s},encodingLength:e=>e<128?1:e<16384?2:e<2097152?3:e<268435456?4:e<34359738368?5:e<4398046511104?6:e<562949953421312?7:e<72057594037927940?8:e<Ce?9:10};function ke(e,t=0){return[xe.decode(e,t),xe.decode.bytes]}function Te(e,t,r=0){return xe.encode(e,t,r),t}function Pe(e){return xe.encodingLength(e)}function Re(e,t){const r=t.byteLength,n=Pe(e),s=n+Pe(r),i=new Uint8Array(s+r);return Te(e,i,0),Te(r,i,n),i.set(t,s),new De(e,r,t,i)}function Le(e){const t=N(e),[r,n]=ke(t),[s,i]=ke(t.subarray(n)),o=t.subarray(n+i);if(o.byteLength!==s)throw Error("Incorrect length");return new De(r,s,o,t)}class De{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}}const Me=N,Ne={code:0,name:"identity",encode:Me,digest:e=>Re(0,Me(e))};class Oe{name;code;encode;constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Re(this.code,t):t.then((e=>Re(this.code,e)))}throw Error("Unknown type, must be binary type")}}const Ue=function({name:e,code:t,encode:r}){return new Oe(e,t,r)}({name:"sha2-256",code:18,encode:async e=>new Uint8Array(await crypto.subtle.digest("SHA-256",e))});function Fe(e,t){const{bytes:r,version:n}=e;return 0===n?function(e,t,r){const{prefix:n}=r;if(n!==fe.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const s=t.get(n);if(null==s){const s=r.encode(e).slice(1);return t.set(n,s),s}return s}(r,$e(e),t??fe.encoder):function(e,t,r){const{prefix:n}=r,s=t.get(n);if(null==s){const s=r.encode(e);return t.set(n,s),s}return s}(r,$e(e),t??te.encoder)}const Be=new WeakMap;function $e(e){const t=Be.get(e);if(null==t){const t=new Map;return Be.set(e,t),t}return t}class qe{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=n,this["/"]=n}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:e,multihash:t}=this;if(e!==ze)throw Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==je)throw Error("Cannot convert non sha2-256 multihash CID to CIDv0");return qe.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:e,digest:t}=this.multihash,r=Re(e,t);return qe.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return qe.equals(this,e)}static equals(e,t){const r=t;return null!=r&&e.code===r.code&&e.version===r.version&&function(e,t){if(e===t)return!0;{const r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&((e,t)=>{if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0})(e.bytes,r.bytes)}}(e.multihash,r.multihash)}toString(e){return Fe(this,e)}toJSON(){return{"/":Fe(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(null==e)return null;const t=e;if(t instanceof qe)return t;if(null!=t["/"]&&t["/"]===t.bytes||t.asCID===t){const{version:e,code:r,multihash:n,bytes:s}=t;return new qe(e,r,n,s??Ke(e,r,n.bytes))}if(!0===t[Ve]){const{version:e,multihash:r,code:n}=t,s=Le(r);return qe.create(e,n,s)}return null}static create(e,t,r){if("number"!=typeof t)throw Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw Error("Invalid digest");switch(e){case 0:if(t!==ze)throw Error(`Version 0 CID must use dag-pb (code: ${ze}) block encoding`);return new qe(e,t,r,r.bytes);case 1:{const n=Ke(e,t,r.bytes);return new qe(e,t,r,n)}default:throw Error("Invalid version")}}static createV0(e){return qe.create(0,ze,e)}static createV1(e,t){return qe.create(1,e,t)}static decode(e){const[t,r]=qe.decodeFirst(e);if(0!==r.length)throw Error("Incorrect length");return t}static decodeFirst(e){const t=qe.inspectBytes(e),r=t.size-t.multihashSize,n=N(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw Error("Incorrect length");const s=n.subarray(t.multihashSize-t.digestSize),i=new De(t.multihashCode,t.digestSize,s,n);return[0===t.version?qe.createV0(i):qe.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0;const r=()=>{const[r,n]=ke(e.subarray(t));return t+=n,r};let n=r(),s=ze;if(18===n?(n=0,t=0):s=r(),0!==n&&1!==n)throw new RangeError("Invalid CID version "+n);const i=t,o=r(),a=r(),c=t+a;return{version:n,codec:s,multihashCode:o,digestSize:a,multihashSize:c-i,size:c}}static parse(e,t){const[r,n]=function(e,t){switch(e[0]){case"Q":{const r=t??fe;return[fe.prefix,r.decode(`${fe.prefix}${e}`)]}case fe.prefix:{const r=t??fe;return[fe.prefix,r.decode(e)]}case te.prefix:{const r=t??te;return[te.prefix,r.decode(e)]}case he.prefix:{const r=t??he;return[he.prefix,r.decode(e)]}default:if(null==t)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(e,t),s=qe.decode(n);if(0===s.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return $e(s).set(r,e),s}}const ze=112,je=18;function Ke(e,t,r){const n=Pe(e),s=n+Pe(t),i=new Uint8Array(s+r.byteLength);return Te(e,i,0),Te(t,i,n),i.set(r,s),i}const Ve=Symbol.for("@ipld/js-cid/CID"),He={..._e,...X,...Ae,...K,...G,...ue,...pe,...me,...Ee,...ee};function Ge(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}const We=Ge("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Xe=Ge("ascii","a",(e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}),(e=>{const t=a((e=e.substring(1)).length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t})),Ze={utf8:We,"utf-8":We,hex:He.base16,latin1:Xe,ascii:Xe,binary:Xe,...He};function Ye(e,t="utf8"){const r=Ze[t];if(null==r)throw Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}class Qe{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}}function Je(){}class et{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const tt=function(){const e=8192;let t,r=e;return function(n){if(n<1||n>4096)return a(n);r+n>e&&(t=a(e),r=0);const s=t.subarray(r,r+=n);return 7&r&&(r=1+(7|r)),s}}();class rt{len;head;tail;states;constructor(){this.len=0,this.head=new Qe(Je,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new Qe(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new it((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(ot,10,x.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=x.fromBigInt(e);return this._push(ot,t.length(),t)}uint64Number(e){return this._push(g,f(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const t=x.fromBigInt(e).zzEncode();return this._push(ot,t.length(),t)}sint64Number(e){const t=x.fromNumber(e).zzEncode();return this._push(ot,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(nt,1,e?1:0)}fixed32(e){return this._push(at,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=x.fromBigInt(e);return this._push(at,4,t.lo)._push(at,4,t.hi)}fixed64Number(e){const t=x.fromNumber(e);return this._push(at,4,t.lo)._push(at,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(E,4,e)}double(e){return this._push(I,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(nt,1,0):this.uint32(t)._push(ct,t,e)}string(e){const t=function(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(n+1))?(++n,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(P,t,e):this._push(nt,1,0)}fork(){return this.states=new et(this),this.head=this.tail=new Qe(Je,0,0),this.len=0,this}reset(){return null!=this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Qe(Je,0,0),this.len=0),this}ldelim(){const e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),0!==r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this}finish(){let e=this.head.next;const t=(r=this.len,null!=globalThis.Buffer?a(r):tt(r));var r;let n=0;for(;null!=e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}}function nt(e,t,r){t[r]=255&e}function st(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class it extends Qe{next;constructor(e,t){super(st,e,t),this.next=void 0}}function ot(e,t,r){for(;0!==e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function at(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function ct(e,t,r){t.set(e,r)}function lt(e,t,r){t.set(e,r)}function ut(e,t,r){e.length<40?P(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set(Ye(e),r)}function ht(e,t){const r=new rt;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var dt,pt,ft,gt,mt,yt,bt,wt,vt,Et,St,At,It,_t,Ct,xt,kt,Tt,Pt,Rt,Lt,Dt,Mt,Nt,Ot,Ut,Ft,Bt,$t,qt,zt,jt,Kt,Vt;function Ht(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function Gt(e){function t(t){if(null==e[t.toString()])throw Error("Invalid enum value");return e[t]}return Ht("enum",dt.VARINT,(function(e,r){const n=t(e);r.int32(n)}),(function(e){return t(e.int32())}))}function Wt(e,t){return Ht("message",dt.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(rt.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(lt,t,e),this},rt.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(ut,t,e),this}),(e=>{e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(dt||(dt={}));class Xt extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}class Zt extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}function Yt(e){return!!e}(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(pt||(pt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),pt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=pt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(ft||(ft={})),(e=>{let t;(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(10),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={contentTopic:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.contentTopic=e.string():e.skipType(7&t)}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(e.ContentFilter||(e.ContentFilter={})),e.codec=()=>(null==t&&(t=Wt(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.subscribe&&!1!==t.subscribe&&(r.uint32(8),r.bool(t.subscribe)),null!=t.topic&&""!==t.topic&&(r.uint32(18),r.string(t.topic)),null!=t.contentFilters)for(const n of t.contentFilters)r.uint32(26),e.ContentFilter.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={subscribe:!1,topic:"",contentFilters:[]},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:s.subscribe=t.bool();break;case 2:s.topic=t.string();break;case 3:if(null!=n.limits?.contentFilters&&s.contentFilters.length===n.limits.contentFilters)throw new Xt('Decode error - map field "contentFilters" had too many elements');s.contentFilters.push(e.ContentFilter.codec().decode(t,t.uint32(),{limits:n.limits?.contentFilters$}));break;default:t.skipType(7&r)}}return s}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(gt||(gt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(const r of e.messages)t.uint32(10),wt.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messages:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();if(t>>>3==1){if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new Xt('Decode error - map field "messages" had too many elements');n.messages.push(wt.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(mt||(mt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),gt.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),mt.codec().encode(e.push,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.request=gt.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=mt.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(yt||(yt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(bt||(bt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),bt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=bt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(wt||(wt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={contentTopic:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==2?r.contentTopic=e.string():e.skipType(7&t)}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(vt||(vt={})),(e=>{let t,r,n;(e=>{e.SUBSCRIBER_PING="SUBSCRIBER_PING",e.SUBSCRIBE="SUBSCRIBE",e.UNSUBSCRIBE="UNSUBSCRIBE",e.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL"})(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),(e=>{e[e.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",e[e.SUBSCRIBE=1]="SUBSCRIBE",e[e.UNSUBSCRIBE=2]="UNSUBSCRIBE",e[e.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL"})(r||(r={})),(e=>{e.codec=()=>Gt(r)})(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),e.codec=()=>(null==n&&(n=Wt(((t,n,s={})=>{if(!1!==s.lengthDelimited&&n.fork(),null!=t.requestId&&""!==t.requestId&&(n.uint32(10),n.string(t.requestId)),null!=t.filterSubscribeType&&0!==r[t.filterSubscribeType]&&(n.uint32(16),e.FilterSubscribeType.codec().encode(t.filterSubscribeType,n)),null!=t.pubsubTopic&&(n.uint32(82),n.string(t.pubsubTopic)),null!=t.contentTopics)for(const e of t.contentTopics)n.uint32(90),n.string(e);!1!==s.lengthDelimited&&n.ldelim()}),((r,n,s={})=>{const i={requestId:"",filterSubscribeType:t.SUBSCRIBER_PING,contentTopics:[]},o=null==n?r.len:r.pos+n;for(;r.pos<o;){const t=r.uint32();switch(t>>>3){case 1:i.requestId=r.string();break;case 2:i.filterSubscribeType=e.FilterSubscribeType.codec().decode(r);break;case 10:i.pubsubTopic=r.string();break;case 11:if(null!=s.limits?.contentTopics&&i.contentTopics.length===s.limits.contentTopics)throw new Xt('Decode error - map field "contentTopics" had too many elements');i.contentTopics.push(r.string());break;default:r.skipType(7&t)}}return i}))),n),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Et||(Et={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&0!==e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={requestId:"",statusCode:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.requestId=e.string();break;case 10:r.statusCode=e.uint32();break;case 11:r.statusDesc=e.string();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(St||(St={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),_t.codec().encode(e.wakuMessage,t)),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.wakuMessage=_t.codec().decode(e,e.uint32(),{limits:r.limits?.wakuMessage});break;case 2:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(At||(At={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(It||(It={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),It.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=It.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(_t||(_t={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.pubsubTopic&&""!==e.pubsubTopic&&(t.uint32(10),t.string(e.pubsubTopic)),null!=e.message&&(t.uint32(18),Lt.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={pubsubTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.pubsubTopic=e.string();break;case 2:n.message=Lt.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ct||(Ct={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.isSuccess&&!1!==e.isSuccess&&(t.uint32(8),t.bool(e.isSuccess)),null!=e.info&&(t.uint32(18),t.string(e.info)),null!=e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.relayPeerCount&&(t.uint32(96),t.uint32(e.relayPeerCount)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={isSuccess:!1},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.isSuccess=e.bool();break;case 2:r.info=e.string();break;case 10:r.statusCode=e.uint32();break;case 11:r.statusDesc=e.string();break;case 12:r.relayPeerCount=e.uint32();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(xt||(xt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),Ct.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),xt.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.request=Ct.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=xt.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(kt||(kt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.pubsubTopic&&(t.uint32(162),t.string(e.pubsubTopic)),null!=e.message&&(t.uint32(170),Lt.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 20:n.pubsubTopic=e.string();break;case 21:n.message=Lt.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Tt||(Tt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&0!==e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.relayPeerCount&&(t.uint32(96),t.uint32(e.relayPeerCount)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={requestId:"",statusCode:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.requestId=e.string();break;case 10:r.statusCode=e.uint32();break;case 11:r.statusDesc=e.string();break;case 12:r.relayPeerCount=e.uint32();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Pt||(Pt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Rt||(Rt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),Rt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=Rt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Lt||(Lt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.messageHash&&(t.uint32(10),t.bytes(e.messageHash)),null!=e.message&&(t.uint32(18),Ut.codec().encode(e.message,t)),null!=e.pubsubTopic&&(t.uint32(26),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.messageHash=e.bytes();break;case 2:n.message=Ut.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;case 3:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Dt||(Dt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.includeData&&!1!==e.includeData&&(t.uint32(16),t.bool(e.includeData)),null!=e.pubsubTopic&&(t.uint32(82),t.string(e.pubsubTopic)),null!=e.contentTopics)for(const r of e.contentTopics)t.uint32(90),t.string(r);if(null!=e.timeStart&&(t.uint32(96),t.sint64(e.timeStart)),null!=e.timeEnd&&(t.uint32(104),t.sint64(e.timeEnd)),null!=e.messageHashes)for(const r of e.messageHashes)t.uint32(162),t.bytes(r);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),null!=e.paginationForward&&!1!==e.paginationForward&&(t.uint32(416),t.bool(e.paginationForward)),null!=e.paginationLimit&&(t.uint32(424),t.uint64(e.paginationLimit)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",includeData:!1,contentTopics:[],messageHashes:[],paginationForward:!1},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.includeData=e.bool();break;case 10:n.pubsubTopic=e.string();break;case 11:if(null!=r.limits?.contentTopics&&n.contentTopics.length===r.limits.contentTopics)throw new Xt('Decode error - map field "contentTopics" had too many elements');n.contentTopics.push(e.string());break;case 12:n.timeStart=e.sint64();break;case 13:n.timeEnd=e.sint64();break;case 20:if(null!=r.limits?.messageHashes&&n.messageHashes.length===r.limits.messageHashes)throw new Xt('Decode error - map field "messageHashes" had too many elements');n.messageHashes.push(e.bytes());break;case 51:n.paginationCursor=e.bytes();break;case 52:n.paginationForward=e.bool();break;case 53:n.paginationLimit=e.uint64();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Mt||(Mt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.messages)for(const r of e.messages)t.uint32(162),Dt.codec().encode(r,t);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",messages:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;case 20:if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new Xt('Decode error - map field "messages" had too many elements');n.messages.push(Dt.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}));break;case 51:n.paginationCursor=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Nt||(Nt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ot||(Ot={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),Ot.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=Ot.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ut||(Ut={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.enr&&(t.uint32(10),t.bytes(e.enr)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.enr=e.bytes():e.skipType(7&t)}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ft||(Ft={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.numPeers&&(t.uint32(8),t.uint64(e.numPeers)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.numPeers=e.uint64():e.skipType(7&t)}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Bt||(Bt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(const r of e.peerInfos)t.uint32(10),Ft.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={peerInfos:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();if(t>>>3==1){if(null!=r.limits?.peerInfos&&n.peerInfos.length===r.limits.peerInfos)throw new Xt('Decode error - map field "peerInfos" had too many elements');n.peerInfos.push(Ft.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})($t||($t={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),Bt.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),$t.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.query=Bt.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=$t.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(qt||(qt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new Xt('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(zt||(zt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new Xt('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(jt||(jt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.messageId&&""!==e.messageId&&(t.uint32(10),t.string(e.messageId)),null!=e.retrievalHint&&(t.uint32(18),t.bytes(e.retrievalHint)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={messageId:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.messageId=e.string();break;case 2:r.retrievalHint=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Kt||(Kt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.senderId&&""!==e.senderId&&(t.uint32(10),t.string(e.senderId)),null!=e.messageId&&""!==e.messageId&&(t.uint32(18),t.string(e.messageId)),null!=e.channelId&&""!==e.channelId&&(t.uint32(26),t.string(e.channelId)),null!=e.lamportTimestamp&&(t.uint32(80),t.int32(e.lamportTimestamp)),null!=e.causalHistory)for(const r of e.causalHistory)t.uint32(90),Kt.codec().encode(r,t);null!=e.bloomFilter&&(t.uint32(98),t.bytes(e.bloomFilter)),null!=e.content&&(t.uint32(162),t.bytes(e.content)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={senderId:"",messageId:"",channelId:"",causalHistory:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.senderId=e.string();break;case 2:n.messageId=e.string();break;case 3:n.channelId=e.string();break;case 10:n.lamportTimestamp=e.int32();break;case 11:if(null!=r.limits?.causalHistory&&n.causalHistory.length===r.limits.causalHistory)throw new Xt('Decode error - map field "causalHistory" had too many elements');n.causalHistory.push(Kt.codec().decode(e,e.uint32(),{limits:r.limits?.causalHistory$}));break;case 12:n.bloomFilter=e.bytes();break;case 20:n.content=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Vt||(Vt={}));const Qt="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Jt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function er(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function tr(e,...t){if(!Jt(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function rr(e){if("function"!=typeof e||"function"!=typeof e.create)throw Error("Hash should be wrapped by utils.createHasher");er(e.outputLen),er(e.blockLen)}function nr(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function sr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ir(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function or(e,t){return e<<32-t|e>>>t}const ar="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,cr=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function lr(e){if(tr(e),ar)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=cr[e[r]];return t}const ur=48,hr=57,dr=65,pr=70,fr=97,gr=102;function mr(e){return e>=ur&&e<=hr?e-ur:e>=dr&&e<=pr?e-(dr-10):e>=fr&&e<=gr?e-(fr-10):void 0}function yr(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);if(ar)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,s=0;t<r;t++,s+=2){const r=mr(e.charCodeAt(s)),i=mr(e.charCodeAt(s+1));if(void 0===r||void 0===i){const t=e[s]+e[s+1];throw Error('hex string expected, got non-hex character "'+t+'" at index '+s)}n[t]=16*r+i}return n}function br(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),tr(e),e}function wr(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];tr(n),t+=n.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}class vr{}function Er(e){const t=t=>e().update(br(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Sr(e=32){if(Qt&&"function"==typeof Qt.getRandomValues)return Qt.getRandomValues(new Uint8Array(e));if(Qt&&"function"==typeof Qt.randomBytes)return Uint8Array.from(Qt.randomBytes(e));throw Error("crypto.getRandomValues must be defined")}function Ar(e,t,r){return e&t^e&r^t&r}class Ir extends vr{constructor(e,t,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=ir(this.buffer)}update(e){nr(this),tr(e=br(e));const{view:t,buffer:r,blockLen:n}=this,s=e.length;for(let i=0;i<s;){const o=Math.min(n-this.pos,s-i);if(o!==n)r.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===n&&(this.process(t,0),this.pos=0);else{const t=ir(e);for(;n<=s-i;i+=n)this.process(t,i)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){nr(this),function(e,t){tr(e);const r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:s}=this;let{pos:i}=this;t[i++]=128,sr(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(r,0),i=0);for(let e=i;e<n;e++)t[e]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}(r,n-8,BigInt(8*this.length),s),this.process(r,0);const o=ir(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],s)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:s,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=s,e.length=n,e.pos=o,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const _r=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Cr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),xr=BigInt(2**32-1),kr=BigInt(32);function Tr(e,t=!1){return t?{h:Number(e&xr),l:Number(e>>kr&xr)}:{h:0|Number(e>>kr&xr),l:0|Number(e&xr)}}const Pr=(e,t,r)=>e>>>r,Rr=(e,t,r)=>e<<32-r|t>>>r,Lr=(e,t,r)=>e>>>r|t<<32-r,Dr=(e,t,r)=>e<<32-r|t>>>r,Mr=(e,t,r)=>e<<64-r|t>>>r-32,Nr=(e,t,r)=>e>>>r-32|t<<64-r;function Or(e,t,r,n){const s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:0|s}}const Ur=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Fr=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,Br=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),$r=(e,t,r,n,s)=>t+r+n+s+(e/2**32|0)|0,qr=(e,t,r,n,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(s>>>0),zr=(e,t,r,n,s,i)=>t+r+n+s+i+(e/2**32|0)|0,jr=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Kr=new Uint32Array(64);class Vr extends Ir{constructor(e=32){super(64,e,8,!1),this.A=0|_r[0],this.B=0|_r[1],this.C=0|_r[2],this.D=0|_r[3],this.E=0|_r[4],this.F=0|_r[5],this.G=0|_r[6],this.H=0|_r[7]}get(){const{A:e,B:t,C:r,D:n,E:s,F:i,G:o,H:a}=this;return[e,t,r,n,s,i,o,a]}set(e,t,r,n,s,i,o,a){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|s,this.F=0|i,this.G=0|o,this.H=0|a}process(e,t){for(let r=0;r<16;r++,t+=4)Kr[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Kr[e-15],r=Kr[e-2],n=or(t,7)^or(t,18)^t>>>3,s=or(r,17)^or(r,19)^r>>>10;Kr[e]=s+Kr[e-7]+n+Kr[e-16]|0}let{A:r,B:n,C:s,D:i,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(or(o,6)^or(o,11)^or(o,25))+((u=o)&a^~u&c)+jr[e]+Kr[e]|0,h=(or(r,2)^or(r,13)^or(r,22))+Ar(r,n,s)|0;l=c,c=a,a=o,o=i+t|0,i=s,s=n,n=r,r=t+h|0}var u;r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,s,i,o,a,c,l)}roundClean(){sr(Kr)}destroy(){this.set(0,0,0,0,0,0,0,0),sr(this.buffer)}}const Hr=function(e,t=!1){const r=e.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:r,l:o}=Tr(e[i],t);[n[i],s[i]]=[r,o]}return[n,s]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))),Gr=Hr[0],Wr=Hr[1],Xr=new Uint32Array(80),Zr=new Uint32Array(80);class Yr extends Ir{constructor(e=64){super(128,e,16,!1),this.Ah=0|Cr[0],this.Al=0|Cr[1],this.Bh=0|Cr[2],this.Bl=0|Cr[3],this.Ch=0|Cr[4],this.Cl=0|Cr[5],this.Dh=0|Cr[6],this.Dl=0|Cr[7],this.Eh=0|Cr[8],this.El=0|Cr[9],this.Fh=0|Cr[10],this.Fl=0|Cr[11],this.Gh=0|Cr[12],this.Gl=0|Cr[13],this.Hh=0|Cr[14],this.Hl=0|Cr[15]}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:s,Cl:i,Dh:o,Dl:a,Eh:c,El:l,Fh:u,Fl:h,Gh:d,Gl:p,Hh:f,Hl:g}=this;return[e,t,r,n,s,i,o,a,c,l,u,h,d,p,f,g]}set(e,t,r,n,s,i,o,a,c,l,u,h,d,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|s,this.Cl=0|i,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|h,this.Gh=0|d,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let r=0;r<16;r++,t+=4)Xr[r]=e.getUint32(t),Zr[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Xr[e-15],r=0|Zr[e-15],n=Lr(t,r,1)^Lr(t,r,8)^Pr(t,0,7),s=Dr(t,r,1)^Dr(t,r,8)^Rr(t,r,7),i=0|Xr[e-2],o=0|Zr[e-2],a=Lr(i,o,19)^Mr(i,o,61)^Pr(i,0,6),c=Dr(i,o,19)^Nr(i,o,61)^Rr(i,o,6),l=Br(s,c,Zr[e-7],Zr[e-16]),u=$r(l,n,a,Xr[e-7],Xr[e-16]);Xr[e]=0|u,Zr[e]=0|l}let{Ah:r,Al:n,Bh:s,Bl:i,Ch:o,Cl:a,Dh:c,Dl:l,Eh:u,El:h,Fh:d,Fl:p,Gh:f,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=Lr(u,h,14)^Lr(u,h,18)^Mr(u,h,41),b=Dr(u,h,14)^Dr(u,h,18)^Nr(u,h,41),w=u&d^~u&f,v=qr(y,b,h&p^~h&g,Wr[e],Zr[e]),E=zr(v,m,t,w,Gr[e],Xr[e]),S=0|v,A=Lr(r,n,28)^Mr(r,n,34)^Mr(r,n,39),I=Dr(r,n,28)^Nr(r,n,34)^Nr(r,n,39),_=r&s^r&o^s&o,C=n&i^n&a^i&a;m=0|f,y=0|g,f=0|d,g=0|p,d=0|u,p=0|h,({h:u,l:h}=Or(0|c,0|l,0|E,0|S)),c=0|o,l=0|a,o=0|s,a=0|i,s=0|r,i=0|n;const x=Ur(S,I,C);r=Fr(x,E,A,_),n=0|x}({h:r,l:n}=Or(0|this.Ah,0|this.Al,0|r,0|n)),({h:s,l:i}=Or(0|this.Bh,0|this.Bl,0|s,0|i)),({h:o,l:a}=Or(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=Or(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=Or(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:p}=Or(0|this.Fh,0|this.Fl,0|d,0|p)),({h:f,l:g}=Or(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=Or(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(r,n,s,i,o,a,c,l,u,h,d,p,f,g,m,y)}roundClean(){sr(Xr,Zr)}destroy(){sr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Qr=Er((()=>new Vr)),Jr=Er((()=>new Yr)),en=Qr;function tn(e,t="utf8"){const r=Ze[t];if(null==r)throw Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}function rn(e){return"string"==typeof e?Ye(e.replace(/^0x/i,"").toLowerCase(),"base16"):e}function nn(e){const t=new ArrayBuffer(8),r=new DataView(t);return"number"==typeof e?r.setFloat64(0,e,!1):r.setBigInt64(0,e,!1),new Uint8Array(t)}const sn=e=>tn(e,"base16"),on=e=>tn(e,"utf8"),an=e=>Ye(e,"utf8");function cn(e){const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}const ln=(e,t)=>`/waku/2/rs/${e}/${t}`,un=e=>{const t=e.split("/");if(6!=t.length||"waku"!==t[1]||"2"!==t[2]||"rs"!==t[3])throw Error("Invalid pubsub topic");const r=parseInt(t[4]),n=parseInt(t[5]);if(isNaN(r)||isNaN(n))throw Error("Invalid clusterId or shard");return{clusterId:r,shard:n}};function hn(e){const t=e.split("/");if(t.length<5||t.length>6)throw Error("Content topic format is invalid: "+e);let r=0;if(6==t.length){if(r=parseInt(t[1]),isNaN(r))throw Error("Invalid generation field in content topic: "+e);if(r>0)throw Error("Generation greater than 0 is not supported: "+e)}const n=t.splice(-4);if(0==n[0].length)throw Error("Application field cannot be empty: "+e);if(0==n[1].length)throw Error("Version field cannot be empty: "+e);if(0==n[2].length)throw Error("Topic name field cannot be empty: "+e);if(0==n[3].length)throw Error("Encoding field cannot be empty: "+e);return{generation:r,application:n[0],version:n[1],topicName:n[2],encoding:n[3]}}class dn{networkConfig;pubsubTopic;shardId;constructor(e,t,r){this.networkConfig=e,this.pubsubTopic=t,this.shardId=r}}class pn extends dn{networkConfig;pubsubTopic;shardId;contentTopic;static fromContentTopic(e,t){hn(e);const r=function(e,t){const{application:r,version:n}=hn(e),s=en(cn([an(r),an(n)])),i=new DataView(s.buffer.slice(-8));return Number(i.getBigUint64(0,!1)%BigInt(t))}(e,t.numShardsInCluster),n=ln(t.clusterId,r);return new pn(t,n,r,e)}constructor(e,t,r,n){super(e,t,r),this.networkConfig=e,this.pubsubTopic=t,this.shardId=r,this.contentTopic=n}get clusterId(){return this.networkConfig.clusterId}get isAutoSharding(){return!0}get isStaticSharding(){return!1}}class fn extends dn{networkConfig;pubsubTopic;shardId;static fromShard(e,t){const r=ln(t.clusterId,e);return new fn(t,r,e)}static fromPubsubTopic(e,t){const{clusterId:r,shard:n}=un(e);if(r!=t.clusterId)throw"Pubsub topic does not match network config's cluster id";return new fn(t,e,n)}constructor(e,t,r){super(e,t,r),this.networkConfig=e,this.pubsubTopic=t,this.shardId=r}get clusterId(){return this.networkConfig.clusterId}get isAutoSharding(){return!1}get isStaticSharding(){return!0}}function gn(e,t){if("clusterId"in(r=e)&&"numShardsInCluster"in r){if(t.contentTopic)return pn.fromContentTopic(t.contentTopic,e);throw Error("AutoSharding requires contentTopic")}if(void 0!==t.shardId)return fn.fromShard(t.shardId,e);if(t.pubsubTopic)return fn.fromPubsubTopic(t.pubsubTopic,e);var r;throw Error("StaticSharding requires shardId or pubsubTopic")}const mn=e=>{if((e=new Uint8Array(e)).length<3)throw Error("Insufficient data");const t=new DataView(e.buffer),r=t.getUint16(0),n=[];if(130===e.length)for(let e=0;e<1024;e++){const r=Math.floor(e/8)+2,s=7-e%8;t.getUint8(r)&1<<s&&n.push(e)}else{const r=t.getUint8(2);for(let s=0,i=3;s<r;s++,i+=2){if(i+1>=e.length)throw Error("Unexpected end of data");n.push(t.getUint16(i))}}return{clusterId:r,shards:n}},yn=e=>{const{clusterId:t,shards:r}=e,n=r.length>=64?130:3+2*r.length,s=new ArrayBuffer(n),i=new DataView(s);if(i.setUint16(0,t),r.length>=64)for(const e of r){const t=Math.floor(e/8)+2,r=7-e%8;i.setUint8(t,i.getUint8(t)|1<<r)}else{i.setUint8(2,r.length);for(let e=0,t=3;e<r.length;e++,t+=2)i.setUint16(t,r[e])}return new Uint8Array(s)},bn=Symbol.for("@libp2p/connection"),wn=Symbol.for("@libp2p/content-routing"),vn=Symbol.for("@libp2p/peer-discovery"),En=Symbol.for("@libp2p/peer-id");function Sn(e){return!!e?.[En]}const An=Symbol.for("@libp2p/peer-routing"),In="keep-alive",_n=Symbol.for("@libp2p/transport");var Cn;(e=>{e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(Cn||(Cn={}));let xn=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};class kn extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let Tn=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},Pn=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class Rn extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Ln extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}}class Dn extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}}class Mn extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}}class Nn extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}}class On extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class Un extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}let Fn=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};class Bn extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}}let $n=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}};class qn extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class zn extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class jn extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}}class Kn extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}}let Vn=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Hn=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}};class Gn extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}}class Wn extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}}class Xn extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}}class Zn extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}}class Yn extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}}class Qn extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}class Jn extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const t=this.#e.get(e);return null==t?0:t.length}addEventListener(e,t,r){super.addEventListener(e,t,r);let n=this.#e.get(e);null==n&&(n=[],this.#e.set(e,n)),n.push({callback:t,once:(!0!==r&&!1!==r&&r?.once)??!1})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let n=this.#e.get(e);null!=n&&(n=n.filter((({callback:e})=>e!==t)),this.#e.set(e,n))}dispatchEvent(e){const t=super.dispatchEvent(e);let r=this.#e.get(e.type);return null==r||(r=r.filter((({once:e})=>!e)),this.#e.set(e.type,r)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}}function es(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}const ts=Symbol.for("@libp2p/service-capabilities"),rs=Symbol.for("@libp2p/service-dependencies");var ns="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==i?i:"undefined"!=typeof self?self:{};function ss(e){return e&&e.__esModule&&{}.hasOwnProperty.call(e,"default")?e.default:e}var is,os,as,cs,ls,us={exports:{}},hs=(ls||(ls=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),t.splice(s,0,r)},t.save=e=>{try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=()=>{let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}return!e&&void 0!==s&&"env"in s&&(e=void 0),e},t.useColors=()=>{if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=(()=>{try{return localStorage}catch(e){}})(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=(cs||(cs=1,as=function(e){function t(e){let n,s,i,o=null;function a(...e){if(!a.enabled)return;const r=a,s=Number(new Date),i=s-(n||s);r.diff=i,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];n=i.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set(e){o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e,t){let r=0,n=0,s=-1,i=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(s=n,i=r,n++):(r++,n++);else{if(-1===s)return!1;n=s+1,i++,r=i}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=e=>e instanceof Error?e.stack||e.message:e,t.disable=()=>{const e=[...t.names,...t.skips.map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=e=>{t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=e=>{for(const r of t.skips)if(n(e,r))return!1;for(const r of t.names)if(n(e,r))return!0;return!1},t.humanize=function(){if(os)return is;os=1;var e=1e3,t=60*e,r=60*t,n=24*r;function s(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}return is=(i,o)=>{o=o||{};var a=typeof i;if("string"===a&&i.length>0)return function(s){if(!((s+="").length>100)){var i=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(i){var o=parseFloat(i[1]);switch((i[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*o;case"weeks":case"week":case"w":return 6048e5*o;case"days":case"day":case"d":return o*n;case"hours":case"hour":case"hrs":case"hr":case"h":return o*r;case"minutes":case"minute":case"mins":case"min":case"m":return o*t;case"seconds":case"second":case"secs":case"sec":case"s":return o*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}(i);if("number"===a&&isFinite(i))return o.long?function(i){var o=Math.abs(i);return o>=n?s(i,o,n,"day"):o>=r?s(i,o,r,"hour"):o>=t?s(i,o,t,"minute"):o>=e?s(i,o,e,"second"):i+" ms"}(i):function(s){var i=Math.abs(s);return i>=n?Math.round(s/n)+"d":i>=r?Math.round(s/r)+"h":i>=t?Math.round(s/t)+"m":i>=e?Math.round(s/e)+"s":s+"ms"}(i);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(i))},is}(),t.destroy=()=>{console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=e=>{let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}),as)(t);const{formatters:r}=e.exports;r.j=e=>{try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(us,us.exports)),us.exports),ds=ss(hs);const ps="waku";let fs=class e{_info;_warn;_error;static createDebugNamespace(e,t){return t?`${ps}:${t}:${e}`:`${ps}:${e}`}constructor(t){this._info=ds(e.createDebugNamespace("info",t)),this._warn=ds(e.createDebugNamespace("warn",t)),this._error=ds(e.createDebugNamespace("error",t))}get info(){return this._info}get warn(){return this._warn}get error(){return this._error}log(e,...t){(this[e]||this.log)(...t)}};function gs(e,t){const r=an(e),n=an(t.contentTopic),s=function(e){if(!e)return;let t;return t="bigint"==typeof e?e:1000000n*BigInt(e.valueOf()),nn(t)}(t.timestamp),i=cn([r,t.payload,n,t.meta,s].filter(Yt));return en(i)}const ms=new fs("message:version-0"),ys=BigInt(1e6);class bs{pubsubTopic;proto;_hash;_hashStr;constructor(e,t){this.pubsubTopic=e,this.proto=t}get ephemeral(){return!!this.proto.ephemeral}get payload(){return this.proto.payload}get contentTopic(){return this.proto.contentTopic}get hash(){return void 0===this._hash&&(this._hash=gs(this.pubsubTopic,this.proto)),this._hash}get hashStr(){return void 0===this._hashStr&&(this._hashStr=sn(this.hash)),this._hashStr}get timestamp(){try{if(this.proto.timestamp){const e=this.proto.timestamp/ys;return new Date(Number(e))}return}catch(e){return}}get meta(){return this.proto.meta}get version(){return this.proto.version??0}get rateLimitProof(){return this.proto.rateLimitProof}}let ws=class{contentTopic;ephemeral;routingInfo;metaSetter;constructor(e,t=!1,r,n){if(this.contentTopic=e,this.ephemeral=t,this.routingInfo=r,this.metaSetter=n,!e||""===e)throw Error("Content topic must be specified")}get pubsubTopic(){return this.routingInfo.pubsubTopic}async toWire(e){return ft.encode(await this.toProtoObj(e))}async toProtoObj(e){const t=e.timestamp??new Date,r={payload:e.payload,version:0,contentTopic:this.contentTopic,timestamp:BigInt(t.valueOf())*ys,meta:void 0,rateLimitProof:e.rateLimitProof,ephemeral:this.ephemeral};if(this.metaSetter){const e=this.metaSetter(r);return{...r,meta:e}}return r}};function vs({contentTopic:e,routingInfo:t,ephemeral:r,metaSetter:n}){return new ws(e,r,t,n)}var Es,Ss,As,Is,_s,Cs,xs;(e=>{e[e.SUCCESS=200]="SUCCESS",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",e[e.INVALID_MESSAGE=420]="INVALID_MESSAGE",e[e.UNSUPPORTED_TOPIC=421]="UNSUPPORTED_TOPIC",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.INTERNAL_ERROR=500]="INTERNAL_ERROR",e[e.UNAVAILABLE=503]="UNAVAILABLE",e[e.NO_RLN_PROOF=504]="NO_RLN_PROOF",e[e.NO_PEERS=505]="NO_PEERS"})(Es||(Es={})),Es.SUCCESS,Es.BAD_REQUEST,Es.PAYLOAD_TOO_LARGE,Es.INVALID_MESSAGE,Es.UNSUPPORTED_TOPIC,Es.TOO_MANY_REQUESTS,Es.INTERNAL_ERROR,Es.UNAVAILABLE,Es.NO_RLN_PROOF,Es.NO_PEERS,(e=>{e.Relay="relay",e.Store="store",e.LightPush="lightpush",e.Filter="filter"})(Ss||(Ss={})),(e=>{e.GENERIC_FAIL="Generic error",e.DECODE_FAILED="Failed to decode",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.STREAM_ABORTED="Stream aborted",e.ENCODE_FAILED="Failed to encode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.RLN_PROOF_GENERATION="Proof generation failed",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.BAD_REQUEST="Bad request format",e.PAYLOAD_TOO_LARGE="Message payload exceeds maximum size",e.INVALID_MESSAGE="Message validation failed",e.UNSUPPORTED_TOPIC="Unsupported pubsub topic",e.TOO_MANY_REQUESTS="Rate limit exceeded",e.INTERNAL_ERROR="Internal server error",e.UNAVAILABLE="Service temporarily unavailable",e.NO_RLN_PROOF="RLN proof generation failed",e.NO_PEERS="No relay peers available"})(As||(As={})),(e=>{e.GENERIC_FAIL="Generic error",e.DECODE_FAILED="Failed to decode",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.STREAM_ABORTED="Stream aborted",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.SUBSCRIPTION_FAILED="Subscription failed",e.UNSUBSCRIBE_FAILED="Unsubscribe failed",e.PING_FAILED="Ping failed",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.INVALID_DECODER_TOPICS="Invalid decoder topics",e.SUBSCRIPTION_LIMIT_EXCEEDED="Subscription limit exceeded",e.INVALID_CONTENT_TOPIC="Invalid content topic",e.PUSH_MESSAGE_FAILED="Push message failed",e.EMPTY_MESSAGE="Empty message received",e.MISSING_PUBSUB_TOPIC="Pubsub topic missing from push message"})(Is||(Is={})),(e=>{e.GENERIC_FAIL="Generic error",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.DECODE_FAILED="Failed to decode",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.ENCODE_FAILED="Failed to encode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.STREAM_ABORTED="Stream aborted",e.RLN_PROOF_GENERATION="Proof generation failed",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.INVALID_DECODER_TOPICS="Invalid decoder topics"})(_s||(_s={})),(e=>{e.Connection="waku:connection",e.Health="waku:health"})(Cs||(Cs={})),(e=>{e.BOOTSTRAP="bootstrap",e.PEER_EXCHANGE="peer-exchange",e.PEER_CACHE="peer-cache"})(xs||(xs={}));const ks="locked",Ts={clusterId:1,numShardsInCluster:8};var Ps;function Rs(e){if(null!=e[Symbol.asyncIterator])return(async()=>{const t=[];for await(const r of e)t.push(r);return t})();const t=[];for(const r of e)t.push(r);return t}function Ls(e,t){null==t&&(t=e.reduce(((e,t)=>e+t.length),0));const r=a(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}function Ds(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}(e=>{e.Unhealthy="Unhealthy",e.MinimallyHealthy="MinimallyHealthy",e.SufficientlyHealthy="SufficientlyHealthy"})(Ps||(Ps={}));const Ms=Symbol.for("@achingbrain/uint8arraylist");function Ns(e,t){if(null==t||t<0)throw new RangeError("index is out of bounds");let r=0;for(const n of e){const e=r+n.byteLength;if(t<e)return{buf:n,index:t-r};r=e}throw new RangeError("index is out of bounds")}function Os(e){return!!e?.[Ms]}class Us{bufs;length;[Ms]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(const r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else{if(!Os(r))throw Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.push(...r.bufs)}this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(const r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else{if(!Os(r))throw Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.unshift(...r.bufs)}this.length+=t}get(e){const t=Ns(this.bufs,e);return t.buf[t.index]}set(e,t){const r=Ns(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else{if(!Os(e))throw Error("Could not write value, must be an Uint8Array or a Uint8ArrayList");for(let r=0;r<e.length;r++)this.set(t+r,e.get(r))}}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength)return this.bufs=[],void(this.length=0);for(;this.bufs.length>0;){if(!(e>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}}slice(e,t){const{bufs:r,length:n}=this._subList(e,t);return Ls(r,n)}subarray(e,t){const{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:Ls(r,n)}sublist(e,t){const{bufs:r,length:n}=this._subList(e,t),s=new Us;return s.length=n,s.bufs=[...r],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};const r=[];let n=0;for(let s=0;s<this.bufs.length;s++){const i=this.bufs[s],o=n,a=o+i.byteLength;if(n=a,e>=a)continue;const c=e>=o&&e<a,l=t>o&&t<=a;if(c&&l){if(e===o&&t===a){r.push(i);break}const n=e-o;r.push(i.subarray(n,n+(t-e)));break}if(c){if(0===e){r.push(i);continue}r.push(i.subarray(e-o))}else{if(l){if(t===a){r.push(i);break}r.push(i.subarray(0,t-o));break}r.push(i)}}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!(Os(e)||e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(isNaN(t=Number(t??0))&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const n=r.byteLength;if(0===n)throw new TypeError("search must be at least 1 byte long");const s=new Int32Array(256);for(let e=0;e<256;e++)s[e]=-1;for(let e=0;e<n;e++)s[r[e]]=e;const i=s,o=this.byteLength-r.byteLength,a=r.byteLength-1;let c;for(let e=t;e<=o;e+=c){c=0;for(let t=a;t>=0;t--){const n=this.get(e+t);if(r[t]!==n){c=Math.max(1,t-i[n]);break}}if(0===c)return e}return-1}getInt8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){const r=a(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){const n=o(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){const n=o(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){const n=o(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){const r=a(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){const n=o(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){const n=o(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){const n=o(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){const n=o(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){const n=o(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(null==e)return!1;if(!(e instanceof Us))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Ds(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){const r=new Us;return r.bufs=e,null==t&&(t=e.reduce(((e,t)=>e+t.byteLength),0)),r.length=t,r}}function Fs(e){return null!=e[Symbol.asyncIterator]}const Bs=e=>{const t=f(e),r=a(t);return y(e,r),Bs.bytes=t,r};function $s(e,t){const r=(t=t??{}).lengthEncoder??Bs;function*n(e){const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return Fs(e)?async function*(){for await(const t of e)yield*n(t)}():function*(){for(const t of e)yield*n(t)}()}Bs.bytes=0,$s.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??Bs;return new Us(r(e.byteLength),e)};let qs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},zs=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},js=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Ks=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Vs;(e=>{e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(Vs||(Vs={}));const Hs=e=>{const t=b(e);return Hs.bytes=f(t),t};function Gs(e,t){const r=new Us;let n=Vs.LENGTH,s=-1;const i=t?.lengthDecoder??Hs,o=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===Vs.LENGTH)try{if(s=i(r),s<0)throw new qs("Invalid message length");if(s>a)throw new zs("Message length too long");const e=i.bytes;r.consume(e),null!=t?.onLength&&t.onLength(s),n=Vs.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>o)throw new js("Message length length too long");break}throw e}if(n===Vs.DATA){if(r.byteLength<s)break;const e=r.sublist(0,s);r.consume(s),null!=t?.onData&&t.onData(e),yield e,n=Vs.LENGTH}}}return Fs(e)?async function*(){for await(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Ks("Unexpected end of input")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Ks("Unexpected end of input")}()}function Ws(){const e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}Hs.bytes=0,Gs.fromReader=(e,t)=>{let r=1;return Gs(async function*(){for(;;)try{const{done:t,value:n}=await e.next(r);if(!0===t)return;null!=n&&(yield n)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{r=1}}(),{...t??{},onLength(e){r=e}})};class Xs{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw Error("Max size for a FixedFIFO should be a power of two");this.buffer=Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return void 0===this.buffer[this.btm]}}class Zs{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Xs(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return null!=e?.byteLength?e.byteLength:1}push(e){if(null!=e?.value&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const t=this.head;this.head=t.next=new Xs(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(void 0===e&&null!=this.tail.next){const t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return null!=e?.value&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}let Ys=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Qs(e={}){return function(e,t){let r,n,s,i=(t=t??{}).onEnd,o=new Zs,a=Ws();const c=e=>null!=n?n(e):(o.push(e),r),l=e=>{if(s)return r;if(!0!==t?.objectMode&&null==e?.byteLength)throw Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:e})},u=e=>s?r:(s=!0,null!=e?(e=>(o=new Zs,null!=n?n({error:e}):(o.push({error:e}),r)))(e):c({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:async()=>{try{return o.isEmpty()?s?{done:!0}:await new Promise(((t,s)=>{n=i=>{n=null,o.push(i);try{t(e(o))}catch(e){s(e)}return r}})):e(o)}finally{o.isEmpty()&&queueMicrotask((()=>{a.resolve(),a=Ws()}))}},return:()=>(o=new Zs,u(),{done:!0}),throw:e=>(u(e),{done:!0}),push:l,end:u,get readableLength(){return o.size},async onEmpty(e){const t=e?.signal;if(t?.throwIfAborted(),o.isEmpty())return;let r,n;null!=t&&(r=new Promise(((e,r)=>{n=()=>{r(new Ys)},t.addEventListener("abort",n)})));try{await Promise.race([a.promise,r])}finally{null!=n&&null!=t&&t?.removeEventListener("abort",n)}}},null==i)return r;const h=r;return r={[Symbol.asyncIterator](){return this},next:()=>h.next(),throw:e=>(h.throw(e),null!=i&&(i(e),i=void 0),{done:!0}),return:()=>(h.return(),null!=i&&(i(),i=void 0),{done:!0}),push:l,end:e=>(h.end(e),null!=i&&(i(e),i=void 0),r),get readableLength(){return h.readableLength},onEmpty:e=>h.onEmpty(e)},r}((e=>{const t=e.shift();if(null==t)return{done:!0};if(null!=t.error)throw t.error;return{done:!0===t.done,value:t.value}}),e)}let Js=class extends Error{type;code;constructor(e,t,r){super(e??"The operation was aborted"),this.type="aborted",this.name=r??"AbortError",this.code=t??"ABORT_ERR"}};async function ei(e,t,r){if(null==t)return e;if(t.aborted)return e.catch((()=>{})),Promise.reject(new Js(r?.errorMessage,r?.errorCode,r?.errorName));let n;const s=new Js(r?.errorMessage,r?.errorCode,r?.errorName);try{return await Promise.race([e,new Promise(((e,r)=>{n=()=>{r(s)},t.addEventListener("abort",n)}))])}finally{null!=n&&t.removeEventListener("abort",n)}}class ti{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ws(),this.haveNext=Ws()}[Symbol.asyncIterator](){return this}async next(){if(null==this.nextResult&&await this.haveNext.promise,null==this.nextResult)throw Error("HaveNext promise resolved but nextResult was undefined");const e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Ws(),e}async throw(e){return this.ended=!0,this.error=e,null!=e&&(this.haveNext.promise.catch((()=>{})),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){const e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){null!=e?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(null!=e&&this.ended)throw this.error??Error("Cannot push value onto an ended pushable");for(;null!=this.nextResult;)await this.readNext.promise;null!=e?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Ws(),await ei(this.readNext.promise,t?.signal,t)}}function ri(){return new ti}function ni(...e){const t=[];for(const r of e)null==r[Symbol.asyncIterator]&&t.push(r);return t.length===e.length?function*(e){for(const t of e)yield*t}(t):async function*(e){const t=new AbortController,r=ri();(async function(e,t,r){try{await Promise.all(e.map((async e=>{for await(const n of e)await t.push(n,{signal:r}),r.throwIfAborted()}))),await t.end(void 0,{signal:r})}catch(e){await t.end(e,{signal:r}).catch((()=>{}))}})(e,r,t.signal).catch((()=>{}));try{yield*r}finally{t.abort()}}(e)}function si(e,...t){if(null==e)throw Error("Empty pipeline");if(ci(e)){const t=e;e=()=>t.source}else if(ai(e)||oi(e)){const t=e;e=()=>t}const r=[e,...t];if(r.length>1&&ci(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let e=1;e<r.length-1;e++)ci(r[e])&&(r[e]=li(r[e]));return ii(...r)}const ii=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},oi=e=>null!=e?.[Symbol.asyncIterator],ai=e=>null!=e?.[Symbol.iterator],ci=e=>null!=e&&null!=e.sink&&null!=e.source,li=e=>t=>{const r=e.sink(t);if(null!=r?.then){const t=Qs({objectMode:!0});let n;r.then((()=>{t.end()}),(e=>{t.end(e)}));const s=e.source;if(oi(s))n=async function*(){yield*s,t.end()};else{if(!ai(s))throw Error("Unknown duplex source type - must be Iterable or AsyncIterable");n=function*(){yield*s,t.end()}}return ni(t,n())}return e.source};function ui(e){return e.filter((e=>"open"===e.status)).sort(((e,t)=>t.timeline.open-e.timeline.open)).at(0)}const hi="consumed";class di{multicodec;libp2p;log;ongoingCreation=new Set;streamPool=new Map;constructor(e,t){this.multicodec=e,this.libp2p=t,this.log=new fs("stream-manager:"+e),this.libp2p.events.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(e){try{const t=e.toString(),r=this.streamPool.get(t);r&&(this.streamPool.delete(t),await r);const n=this.getOpenStreamForCodec(e)||await this.createStream(e);if(!n)return;return this.log.info(`Using stream for peerId=${t} multicodec=${this.multicodec}`),this.lockStream(t,n),n}catch(e){return void this.log.error("Failed to getStream:",e)}}async createStream(e,t=0){const r=ui(this.libp2p.connectionManager.getConnections(e));if(!r)return void this.log.error(`Failed to get a connection to the peer peerId=${e.toString()} multicodec=${this.multicodec}`);let n,s;for(let i=0;i<t+1;i++)try{this.log.info(`Attempting to create a stream for peerId=${e.toString()} multicodec=${this.multicodec}`),s=await r.newStream(this.multicodec),this.log.info(`Created stream for peerId=${e.toString()} multicodec=${this.multicodec}`);break}catch(e){n=e}if(s)return s;this.log.error(`Failed to create a new stream for ${e.toString()} -- `+n)}async createStreamWithLock(e){const t=e.id.toString();if(this.ongoingCreation.has(t))this.log.info(`Skipping creation of a stream due to lock for peerId=${t} multicodec=${this.multicodec}`);else try{this.ongoingCreation.add(t),await this.createStream(e.id)}catch(e){this.log.error("Failed to createStreamWithLock:",e)}finally{this.ongoingCreation.delete(t)}}handlePeerUpdateStreamPool=e=>{const{peer:t}=e.detail;t.protocols.includes(this.multicodec)&&(this.getOpenStreamForCodec(t.id)||this.scheduleNewStream(t))};scheduleNewStream(e){this.log.info(`Scheduling creation of a stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.streamPool.has(e.id.toString())&&this.streamPool.delete(e.id.toString()),this.streamPool.set(e.id.toString(),this.createStreamWithLock(e))}getOpenStreamForCodec(e){const t=ui(this.libp2p.connectionManager.getConnections(e));if(!t)return void this.log.info(`No open connection found for peerId=${e.toString()} multicodec=${this.multicodec}`);const r=t.streams.find((e=>e.protocol===this.multicodec));if(r)return["done","closed","closing"].includes(r.writeStatus||"")||this.isStreamLocked(r)?void this.log.info(`Stream for peerId=${e.toString()} multicodec=${this.multicodec} is unusable`):(this.log.info(`Found open stream for peerId=${e.toString()} multicodec=${this.multicodec}`),r);this.log.info(`No open stream found for peerId=${e.toString()} multicodec=${this.multicodec}`)}lockStream(e,t){this.log.info(`Locking stream for peerId:${e}\tstreamId:${t.id}`),t.metadata[hi]=!0}isStreamLocked(e){return!!e.metadata[hi]}}let pi;const fi=new Uint8Array(16);function gi(){if(!pi&&(pi="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!pi))throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return pi(fi)}const mi=[];for(let e=0;e<256;++e)mi.push((e+256).toString(16).slice(1));var yi={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function bi(e){if(yi.randomUUID&&!e)return yi.randomUUID();const t=(e=e||{}).random||(e.rng||gi)();return t[6]=15&t[6]|64,t[8]=63&t[8]|128,function(e,t=0){return mi[e[t+0]]+mi[e[t+1]]+mi[e[t+2]]+mi[e[t+3]]+"-"+mi[e[t+4]]+mi[e[t+5]]+"-"+mi[e[t+6]]+mi[e[t+7]]+"-"+mi[e[t+8]]+mi[e[t+9]]+"-"+mi[e[t+10]]+mi[e[t+11]]+mi[e[t+12]]+mi[e[t+13]]+mi[e[t+14]]+mi[e[t+15]]}(t)}class wi{proto;constructor(e){this.proto=e}static decode(e){const t=At.decode(e);return new wi(t)}encode(){return At.encode(this.proto)}get wakuMessage(){return this.proto.wakuMessage}get pubsubTopic(){return this.proto.pubsubTopic}}class vi{proto;constructor(e){this.proto=e}static createSubscribeRequest(e,t){return new vi({requestId:bi(),filterSubscribeType:Et.FilterSubscribeType.SUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeRequest(e,t){return new vi({requestId:bi(),filterSubscribeType:Et.FilterSubscribeType.UNSUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeAllRequest(e){return new vi({requestId:bi(),filterSubscribeType:Et.FilterSubscribeType.UNSUBSCRIBE_ALL,pubsubTopic:e,contentTopics:[]})}static createSubscriberPingRequest(){return new vi({requestId:bi(),filterSubscribeType:Et.FilterSubscribeType.SUBSCRIBER_PING,pubsubTopic:"",contentTopics:[]})}static decode(e){const t=Et.decode(e);return new vi(t)}encode(){return Et.encode(this.proto)}get filterSubscribeType(){return this.proto.filterSubscribeType}get requestId(){return this.proto.requestId}get pubsubTopic(){return this.proto.pubsubTopic}get contentTopics(){return this.proto.contentTopics}}class Ei{proto;constructor(e){this.proto=e}static decode(e){const t=St.decode(e);return new Ei(t)}encode(){return St.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get requestId(){return this.proto.requestId}}const Si=new fs("filter-core"),Ai="/vac/waku/filter-subscribe/2.0.0-beta1",Ii="/vac/waku/filter-push/2.0.0-beta1";class _i{handleIncomingMessage;libp2p;streamManager;multicodec=Ai;constructor(e,t){this.handleIncomingMessage=e,this.libp2p=t,this.streamManager=new di(Ai,t.components)}async start(){try{await this.libp2p.handle(Ii,this.onRequest.bind(this),{maxInboundStreams:100})}catch(e){Si.error("Failed to register ",Ii,e)}}async stop(){try{await this.libp2p.unhandle(Ii)}catch(e){Si.error("Failed to unregister ",Ii,e)}}async subscribe(e,t,r){const n=await this.streamManager.getStream(t);if(!n)return{success:null,failure:{error:Is.NO_STREAM_AVAILABLE,peerId:t}};const s=vi.createSubscribeRequest(e,r);let i;try{if(i=await si([s.encode()],$s,n,Gs,(async e=>await Rs(e))),!i?.length)throw Error("Received no response from subscription request.")}catch(e){return Si.error("Failed to send subscribe request",e),{success:null,failure:{error:Is.GENERIC_FAIL,peerId:t}}}const{statusCode:o,requestId:a,statusDesc:c}=Ei.decode(i[0].slice());return o<200||o>=300?(Si.error(`Filter subscribe request ${a} failed with status code ${o}: ${c}`),{failure:{error:Is.REMOTE_PEER_REJECTED,peerId:t},success:null}):{failure:null,success:t}}async unsubscribe(e,t,r){const n=await this.streamManager.getStream(t);if(!n)return Si.error("Failed to get a stream for remote peer:"+t.toString()),{success:null,failure:{error:Is.NO_STREAM_AVAILABLE,peerId:t}};const s=vi.createUnsubscribeRequest(e,r);try{await si([s.encode()],$s,n.sink)}catch(e){return Si.error("Failed to send unsubscribe request",e),{success:null,failure:{error:Is.GENERIC_FAIL,peerId:t}}}return{success:t,failure:null}}async unsubscribeAll(e,t){const r=await this.streamManager.getStream(t);if(!r)return Si.error("Failed to get a stream for remote peer:"+t.toString()),{success:null,failure:{error:Is.NO_STREAM_AVAILABLE,peerId:t}};const n=vi.createUnsubscribeAllRequest(e),s=await si([n.encode()],$s,r,Gs,(async e=>await Rs(e)));if(!s||!s.length)return{failure:{error:Is.NO_RESPONSE,peerId:t},success:null};const{statusCode:i,requestId:o,statusDesc:a}=Ei.decode(s[0].slice());return i<200||i>=300?(Si.error(`Filter unsubscribe all request ${o} failed with status code ${i}: ${a}`),{failure:{error:Is.REMOTE_PEER_REJECTED,peerId:t},success:null}):{failure:null,success:t}}async ping(e){const t=await this.streamManager.getStream(e);if(!t)return Si.error("Failed to get a stream for remote peer:"+e.toString()),{success:null,failure:{error:Is.NO_STREAM_AVAILABLE,peerId:e}};const r=vi.createSubscriberPingRequest();let n;try{n=await si([r.encode()],$s,t,Gs,(async e=>await Rs(e)))}catch(t){return Si.error("Failed to send ping request",t),{success:null,failure:{error:Is.GENERIC_FAIL,peerId:e}}}if(!n||!n.length)return{success:null,failure:{error:Is.NO_RESPONSE,peerId:e}};const{statusCode:s,requestId:i,statusDesc:o}=Ei.decode(n[0].slice());return s<200||s>=300?(Si.error(`Filter ping request ${i} failed with status code ${s}: ${o}`),{success:null,failure:{error:Is.REMOTE_PEER_REJECTED,peerId:e}}):{success:e,failure:null}}onRequest(e){const{connection:t,stream:r}=e,{remotePeer:n}=t;Si.info("Received message from "+n.toString());try{si(r,Gs,(async e=>{for await(const r of e){const e=wi.decode(r.slice()),{pubsubTopic:n,wakuMessage:s}=e;if(!s)return void Si.error("Received empty message");if(!n)return void Si.error("Pubsub topic missing from push message");await this.handleIncomingMessage(n,s,t.remotePeer.toString())}})).then((()=>{Si.info("Receiving pipe closed.")}),(async e=>{Si.error(`Error with receiving pipe on peer:${t.remotePeer.toString()} -- stream:${r.id} -- protocol:${r.protocol}: `,e)}))}catch(e){Si.error("Error decoding message",e)}}}const Ci="/vac/waku/lightpush/2.0.0-beta1",xi="/vac/waku/lightpush/3.0.0",ki=Ci,Ti=xi;class Pi{proto;constructor(e){this.proto=e}static createRequest(e,t){return new Pi({requestId:bi(),request:{message:e,pubsubTopic:t},response:void 0})}static decode(e){const t=kt.decode(e);return new Pi(t)}encode(){return kt.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}class Ri{proto;constructor(e){this.proto=e}static createRequest(e,t){return new Ri({requestId:bi(),pubsubTopic:t,message:e})}static createResponse(e,t,r,n){return new Ri({requestId:e,statusCode:t,statusDesc:r,relayPeerCount:n})}static decodeRequest(e){const t=Tt.decode(e);return new Ri(t)}static decodeResponse(e){const t=Pt.decode(e);return new Ri(t)}encode(){return this.isRequest()?Tt.encode(this.proto):Pt.encode(this.proto)}get request(){return this.isRequest()?this.proto:void 0}get response(){return this.isResponse()?this.proto:void 0}get requestId(){return this.proto.requestId}get pubsubTopic(){return this.isRequest()?this.proto.pubsubTopic:void 0}get message(){return this.isRequest()?this.proto.message:void 0}get statusCode(){return this.isResponse()?this.proto.statusCode:void 0}get statusDesc(){return this.isResponse()?this.proto.statusDesc:void 0}get relayPeerCount(){return this.isResponse()?this.proto.relayPeerCount:void 0}isRequest(){return"pubsubTopic"in this.proto&&"message"in this.proto}isResponse(){return"statusCode"in this.proto}}const Li=new fs("light-push:protocol-handler");class Di{static async preparePushMessage(e,t,r){try{if(!t.payload||0===t.payload.length)return Li.error("Failed to send waku light push: payload is empty"),{rpc:null,error:As.EMPTY_PAYLOAD};if(!await async function(e,t){const r=await e.toWire(t);return!!r&&(e=>e.length/1048576<=1)(r)}(e,t))return Li.error("Failed to send waku light push: message is bigger than 1MB"),{rpc:null,error:As.SIZE_TOO_BIG};const n=await e.toProtoObj(t);return n?r===xi?(Li.info("Creating v3 RPC message"),{rpc:Di.createV3Rpc(n,e.pubsubTopic),error:null}):(Li.info("Creating v2 RPC message"),{rpc:Di.createV2Rpc(n,e.pubsubTopic),error:null}):(Li.error("Failed to encode to protoMessage, aborting push"),{rpc:null,error:As.ENCODE_FAILED})}catch(e){return Li.error("Failed to prepare push message",e),{rpc:null,error:As.GENERIC_FAIL}}}static handleResponse(e,t,r){return t===xi?Di.handleV3Response(e,r):Di.handleV2Response(e,r)}static handleV3Response(e,t){try{const r=Ri.decodeResponse(e),n=r.statusCode,s=r.statusDesc;if(n!==Es.SUCCESS){const e=As.REMOTE_PEER_REJECTED;return Li.error(`Remote peer rejected with v3 status code ${n}: ${s}`),{success:null,failure:{error:e,peerId:t}}}return void 0!==r.relayPeerCount&&Li.info(`Message relayed to ${r.relayPeerCount} peers`),{success:t,failure:null}}catch(e){return{success:null,failure:{error:As.DECODE_FAILED,peerId:t}}}}static handleV2Response(e,t){let r;try{r=Pi.decode(e).response}catch(e){return{success:null,failure:{error:As.DECODE_FAILED,peerId:t}}}var n;return r?(n=r.info)&&(n.includes("could not generate rln proof")||n.includes("could not get new message id to generate an rln proof")||n.includes("RLN validation failed"))?(Li.error("Remote peer fault: RLN generation"),{success:null,failure:{error:As.RLN_PROOF_GENERATION,peerId:t}}):r.isSuccess?{success:t,failure:null}:(Li.error("Remote peer rejected the message: ",r.info),{success:null,failure:{error:As.REMOTE_PEER_REJECTED,peerId:t}}):{success:null,failure:{error:As.NO_RESPONSE,peerId:t}}}static createV2Rpc(e,t){const r=Pi.createRequest(e,t);return Object.assign(r,{version:"v2"})}static createV3Rpc(e,t){e.timestamp||(e.timestamp=BigInt(Date.now())*BigInt(1e6));const r=Ri.createRequest(e,t);return Object.assign(r,{version:"v3"})}}const Mi=new fs("light-push");class Ni{libp2p;streamManager;streamManagerV2;multicodec=[xi,Ci];constructor(e){this.libp2p=e,this.streamManagerV2=new di(Ci,e.components),this.streamManager=new di(xi,e.components)}async send(e,t,r,n=!1){const s=await this.getProtocol(r,n);if(Mi.info(`Sending light push request to peer:${r.toString()}, protocol:${s}`),!s)return{success:null,failure:{error:As.GENERIC_FAIL,peerId:r}};const{rpc:i,error:o}=await Di.preparePushMessage(e,t,s);if(o)return{success:null,failure:{error:o,peerId:r}};const a=await this.getStream(r,s);if(!a)return Mi.error("Failed to get a stream for remote peer:"+r.toString()),{success:null,failure:{error:As.NO_STREAM_AVAILABLE,peerId:r}};let c;try{c=await si([i.encode()],$s,a,Gs,(async e=>await Rs(e)))}catch(e){return Mi.error("Failed to send waku light push request",e),{success:null,failure:{error:As.STREAM_ABORTED,peerId:r}}}const l=new Us;return c.forEach((e=>l.append(e))),0===l.length?{success:null,failure:{error:As.NO_RESPONSE,peerId:r}}:Di.handleResponse(l,s,r)}async getProtocol(e,t){try{const r=await this.libp2p.peerStore.get(e);if(t||!r.protocols.includes(xi)&&r.protocols.includes(Ci))return Ci;if(r.protocols.includes(xi))return xi;throw Error("No supported protocol found")}catch(e){return void Mi.error("Failed to get protocol",e)}}async getStream(e,t){switch(t){case Ci:return this.streamManagerV2.getStream(e);case xi:return this.streamManager.getStream(e);default:return}}}const Oi={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},Ui=864e5,Fi=1e6;class Bi{proto;constructor(e){this.proto=e}static create(e){const t=new Bi({...e,contentTopics:e.contentTopics||[],requestId:bi(),timeStart:e.timeStart?BigInt(e.timeStart.getTime()*Fi):void 0,timeEnd:e.timeEnd?BigInt(e.timeEnd.getTime()*Fi):void 0,messageHashes:e.messageHashes||[],paginationLimit:e.paginationLimit?BigInt(e.paginationLimit):void 0}),r=e.messageHashes&&e.messageHashes.length>0,n=e.contentTopics&&e.contentTopics.length>0,s=e.timeStart||e.timeEnd;if(r){if(n||s)throw Error("Message hash lookup queries cannot include content filter criteria (contentTopics, timeStart, or timeEnd)")}else if(e.pubsubTopic&&(!e.contentTopics||0===e.contentTopics.length)||!e.pubsubTopic&&e.contentTopics&&e.contentTopics.length>0)throw Error("Both pubsubTopic and contentTopics must be set together for content-filtered queries");return t}static decode(e){const t=Mt.decode(e);return new Bi(t)}encode(){return Mt.encode(this.proto)}}class $i{proto;constructor(e){this.proto=e}static decode(e){const t=Nt.decode(e);return new $i(t)}encode(){return Nt.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get messages(){return this.proto.messages}get paginationCursor(){return this.proto.paginationCursor}}const qi=new fs("store"),zi="/vac/waku/store-query/3.0.0";class ji{streamManager;multicodec=zi;constructor(e){this.streamManager=new di(zi,e.components)}get maxTimeLimit(){return Ui}async*queryPerPage(e,t,r){if(e.timeStart&&e.timeEnd&&e.timeEnd.getTime()-e.timeStart.getTime()>Ui)throw Error("Time range bigger than 24h");if(!(e.messageHashes&&e.messageHashes.length>0)&&e.contentTopics&&e.contentTopics.toString()!==Array.from(t.keys()).toString())throw Error("Internal error, the decoders should match the query's content topics");let n=e.paginationCursor;for(;;){const s=Bi.create({...e,paginationCursor:n});qi.info("Sending store query request:",{hasMessageHashes:!!e.messageHashes?.length,messageHashCount:e.messageHashes?.length,pubsubTopic:e.pubsubTopic,contentTopics:e.contentTopics});const i=await this.streamManager.getStream(r);if(!i){qi.error("Failed to get a stream for remote peer:"+r.toString());break}const o=await si([s.encode()],$s,i,Gs,(async e=>await Rs(e))),a=new Us;o.forEach((e=>{a.append(e)}));const c=$i.decode(a);if(!c.statusCode||c.statusCode>=300){const e=`Store query failed with status code: ${c.statusCode}, description: ${c.statusDesc}`;throw qi.error(e),Error(e)}if(!c.messages||!c.messages.length){qi.warn("Stopping pagination due to empty messages in response");break}qi.info(c.messages.length+" messages retrieved from store");const l=c.messages.map((e=>{if(!e.message)return Promise.resolve(void 0);const r=e.message.contentTopic;if(r){const s=t.get(r);if(s)return s.fromProtoObj(e.pubsubTopic||"",(n=e.message,{...Oi,...n}))}var n;return Promise.resolve(void 0)}));if(yield l,n=e.paginationForward?c.messages[c.messages.length-1].messageHash:c.messages[0].messageHash,c.messages.length>100&&c.messages.length<(e.paginationLimit||20))break}}}const Ki=parseInt("11111",2),Vi=parseInt("10000000",2),Hi=parseInt("01111111",2),Gi={0:Zi,1:Zi,2(e,t){const r=Xi(e,t),n=t.offset,s=t.offset+r,i=[];for(let t=n;t<s;t++)t===n&&0===e[t]||i.push(e[t]);return t.offset+=r,Uint8Array.from(i)},3(e,t){const r=Xi(e,t),n=e[t.offset];t.offset++;const s=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,0!==n)throw Error("Unused bits in bit string is unimplemented");return s},4(e,t){const r=Xi(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n},5:(e,t)=>(t.offset++,null),6(e,t){const r=Xi(e,t),n=t.offset+r,s=e[t.offset];t.offset++;let i=0,o=0;s<40?(i=0,o=s):s<80?(i=1,o=s-40):(i=2,o=s-80);let a=`${i}.${o}`,c=[];for(;t.offset<n;){const r=e[t.offset];if(t.offset++,c.push(127&r),r<128){c.reverse();let e=0;for(let t=0;t<c.length;t++)e+=c[t]<<7*t;a+="."+e,c=[]}}return a},16:Zi,22:Zi,48:Zi};function Wi(e,t={offset:0}){const r=e[t.offset]&Ki;if(t.offset++,null!=Gi[r])return Gi[r](e,t);throw Error("No decoder for tag "+r)}function Xi(e,t){let r=0;if((e[t.offset]&Vi)===Vi){const n=e[t.offset]&Hi;let s="0x";t.offset++;for(let r=0;r<n;r++,t.offset++)s+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(s,16)}else r=e[t.offset],t.offset++;return r}function Zi(e,t){Xi(e,t);const r=[];for(;!(t.offset>=e.byteLength);){const n=Wi(e,t);if(null===n)break;r.push(n)}return r}function Yi(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);const t=function(e){let t=e.toString(16);t.length%2==1&&(t="0"+t);const r=new Us;for(let e=0;e<t.length;e+=2)r.append(Uint8Array.from([parseInt(`${t[e]}${t[e+1]}`,16)]));return r}(e.byteLength);return new Us(Uint8Array.from([t.byteLength|Vi]),t)}function Qi(e){const t=new Us;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new Us(Uint8Array.from([2]),Yi(t),t)}function Ji(e){const t=Uint8Array.from([0]),r=new Us(t,e);return new Us(Uint8Array.from([3]),Yi(r),r)}function eo(e,t=48){const r=new Us;for(const t of e)r.append(t);return new Us(Uint8Array.from([t]),Yi(r),r)}const to=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),ro=Uint8Array.from([6,5,43,129,4,0,34]),no=Uint8Array.from([6,5,43,129,4,0,35]),so={ext:!0,kty:"EC",crv:"P-256"},io={ext:!0,kty:"EC",crv:"P-384"},oo={ext:!0,kty:"EC",crv:"P-521"},ao=32,co=48,lo=66;function uo(e){return function(e){const t=e[1][1][0];let r,n;if(65===t.byteLength)return r=tn(t.subarray(1,1+ao),"base64url"),n=tn(t.subarray(1+ao),"base64url"),new po({...so,key_ops:["verify"],x:r,y:n});if(97===t.byteLength)return r=tn(t.subarray(1,1+co),"base64url"),n=tn(t.subarray(1+co),"base64url"),new po({...io,key_ops:["verify"],x:r,y:n});if(133===t.byteLength)return r=tn(t.subarray(1,1+lo),"base64url"),n=tn(t.subarray(1+lo),"base64url"),new po({...oo,key_ops:["verify"],x:r,y:n});throw new Pn(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}(Wi(e))}function ho(e){if("P-256"===e)return to;if("P-384"===e)return ro;if("P-521"===e)return no;throw new Pn("Invalid curve "+e)}let po=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){var e;return null==this._raw&&(this._raw=(e=this.jwk,eo([Qi(Uint8Array.from([1])),eo([ho(e.crv)],160),eo([Ji(new Us(Uint8Array.from([4]),Ye(e.x??"","base64url"),Ye(e.y??"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return Ne.digest(Ac(this))}toCID(){return qe.createV1(114,this.toMultihash())}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}async verify(e,t,r){return async function(e,t,r,n){const s=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();const i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}};const fo=BigInt(0),go=BigInt(1);function mo(e,t=""){if("boolean"!=typeof e)throw Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e);return e}function yo(e,t,r=""){const n=Jt(e),s=e?.length,i=void 0!==t;if(!n||i&&s!==t)throw Error((r&&`"${r}" `)+"expected Uint8Array"+(i?" of length "+t:"")+", got "+(n?"length="+s:"type="+typeof e));return e}function bo(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function wo(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);return""===e?fo:BigInt("0x"+e)}function vo(e){return wo(lr(e))}function Eo(e){return tr(e),wo(lr(Uint8Array.from(e).reverse()))}function So(e,t){return yr(e.toString(16).padStart(2*t,"0"))}function Ao(e,t){return So(e,t).reverse()}function Io(e,t,r){let n;if("string"==typeof t)try{n=yr(t)}catch(t){throw Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Jt(t))throw Error(e+" must be hex string or Uint8Array");n=Uint8Array.from(t)}const s=n.length;if("number"==typeof r&&s!==r)throw Error(e+" of length "+r+" expected, got "+s);return n}function _o(e){return Uint8Array.from(e)}const Co=e=>"bigint"==typeof e&&fo<=e;function xo(e,t,r,n){if(!function(e,t,r){return Co(e)&&Co(t)&&Co(r)&&t<=e&&e<r}(t,r,n))throw Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function ko(e){let t;for(t=0;e>fo;e>>=go,t+=1);return t}const To=e=>(go<<BigInt(e))-go;function Po(e,t,r={}){if(!e||"object"!=typeof e)throw Error("expected valid options object");function n(t,r,n){const s=e[t];if(n&&void 0===s)return;const i=typeof s;if(i!==r||null===s)throw Error(`param "${t}" is invalid: expected ${r}, got ${i}`)}Object.entries(t).forEach((([e,t])=>n(e,t,!1))),Object.entries(r).forEach((([e,t])=>n(e,t,!0)))}function Ro(e){const t=new WeakMap;return(r,...n)=>{const s=t.get(r);if(void 0!==s)return s;const i=e(r,...n);return t.set(r,i),i}}const Lo=BigInt(0),Do=BigInt(1),Mo=BigInt(2),No=BigInt(3),Oo=BigInt(4),Uo=BigInt(5),Fo=BigInt(7),Bo=BigInt(8),$o=BigInt(9),qo=BigInt(16);function zo(e,t){const r=e%t;return r>=Lo?r:t+r}function jo(e,t,r){let n=e;for(;t-- >Lo;)n*=n,n%=r;return n}function Ko(e,t){if(e===Lo)throw Error("invert: expected non-zero number");if(t<=Lo)throw Error("invert: expected positive modulus, got "+t);let r=zo(e,t),n=t,s=Lo,i=Do;for(;r!==Lo;){const e=n%r,t=s-i*(n/r);n=r,r=e,s=i,i=t}if(n!==Do)throw Error("invert: does not exist");return zo(s,t)}function Vo(e,t,r){if(!e.eql(e.sqr(t),r))throw Error("Cannot find square root")}function Ho(e,t){const r=(e.ORDER+Do)/Oo,n=e.pow(t,r);return Vo(e,n,t),n}function Go(e,t){const r=(e.ORDER-Uo)/Bo,n=e.mul(t,Mo),s=e.pow(n,r),i=e.mul(t,s),o=e.mul(e.mul(i,Mo),s),a=e.mul(i,e.sub(o,e.ONE));return Vo(e,a,t),a}function Wo(e){if(e<No)throw Error("sqrt is not defined for small field");let t=e-Do,r=0;for(;t%Mo===Lo;)t/=Mo,r++;let n=Mo;const s=Jo(e);for(;1===Yo(s,n);)if(n++>1e3)throw Error("Cannot find square root: probably non-prime P");if(1===r)return Ho;let i=s.pow(n,t);const o=(t+Do)/Mo;return function(e,n){if(e.is0(n))return n;if(1!==Yo(e,n))throw Error("Cannot find square root");let s=r,a=e.mul(e.ONE,i),c=e.pow(n,t),l=e.pow(n,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,r=e.sqr(c);for(;!e.eql(r,e.ONE);)if(t++,r=e.sqr(r),t===s)throw Error("Cannot find square root");const n=Do<<BigInt(s-t-1),i=e.pow(a,n);s=t,a=e.sqr(i),c=e.mul(c,a),l=e.mul(l,i)}return l}}const Xo=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Zo(e,t,r=!1){const n=Array(t.length).fill(r?e.ZERO:void 0),s=t.reduce(((t,r,s)=>e.is0(r)?t:(n[s]=t,e.mul(t,r))),e.ONE),i=e.inv(s);return t.reduceRight(((t,r,s)=>e.is0(r)?t:(n[s]=e.mul(t,n[s]),e.mul(t,r))),i),n}function Yo(e,t){const r=(e.ORDER-Do)/Mo,n=e.pow(t,r),s=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),o=e.eql(n,e.neg(e.ONE));if(!s&&!i&&!o)throw Error("invalid Legendre symbol result");return s?1:i?0:-1}function Qo(e,t){void 0!==t&&er(t);const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function Jo(e,t,r=!1,n={}){if(e<=Lo)throw Error("invalid field: expected ORDER > 0, got "+e);let s,i,o,a=!1;if("object"==typeof t&&null!=t){if(n.sqrt||r)throw Error("cannot specify opts in two arguments");const e=t;e.BITS&&(s=e.BITS),e.sqrt&&(i=e.sqrt),"boolean"==typeof e.isLE&&(r=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),o=e.allowedLengths}else"number"==typeof t&&(s=t),n.sqrt&&(i=n.sqrt);const{nBitLength:c,nByteLength:l}=Qo(e,s);if(l>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");let u;const h=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:l,MASK:To(c),ZERO:Lo,ONE:Do,allowedLengths:o,create:t=>zo(t,e),isValid(t){if("bigint"!=typeof t)throw Error("invalid field element: expected bigint, got "+typeof t);return Lo<=t&&t<e},is0:e=>e===Lo,isValidNot0:e=>!h.is0(e)&&h.isValid(e),isOdd:e=>(e&Do)===Do,neg:t=>zo(-t,e),eql:(e,t)=>e===t,sqr:t=>zo(t*t,e),add:(t,r)=>zo(t+r,e),sub:(t,r)=>zo(t-r,e),mul:(t,r)=>zo(t*r,e),pow:(e,t)=>function(e,t,r){if(r<Lo)throw Error("invalid exponent, negatives unsupported");if(r===Lo)return e.ONE;if(r===Do)return t;let n=e.ONE,s=t;for(;r>Lo;)r&Do&&(n=e.mul(n,s)),s=e.sqr(s),r>>=Do;return n}(h,e,t),div:(t,r)=>zo(t*Ko(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Ko(t,e),sqrt:i||(t=>(u||(u=function(e){return e%Oo===No?Ho:e%Bo===Uo?Go:e%qo===$o?function(e){const t=Jo(e),r=Wo(e),n=r(t,t.neg(t.ONE)),s=r(t,n),i=r(t,t.neg(n)),o=(e+Fo)/qo;return(e,t)=>{let r=e.pow(t,o),a=e.mul(r,n);const c=e.mul(r,s),l=e.mul(r,i),u=e.eql(e.sqr(a),t),h=e.eql(e.sqr(c),t);r=e.cmov(r,a,u),a=e.cmov(l,c,h);const d=e.eql(e.sqr(a),t),p=e.cmov(r,a,d);return Vo(e,p,t),p}}(e):Wo(e)}(e)),u(h,t))),toBytes:e=>r?Ao(e,l):So(e,l),fromBytes(t,n=!0){if(o){if(!o.includes(t.length)||t.length>l)throw Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);const e=new Uint8Array(l);e.set(t,r?0:e.length-t.length),t=e}if(t.length!==l)throw Error("Field.fromBytes: expected "+l+" bytes, got "+t.length);let s=r?Eo(t):vo(t);if(a&&(s=zo(s,e)),!n&&!h.isValid(s))throw Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>Zo(h,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(h)}function ea(e){if("bigint"!=typeof e)throw Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function ta(e){const t=ea(e);return t+Math.ceil(t/2)}const ra=BigInt(0),na=BigInt(1);function sa(e,t){const r=t.negate();return e?r:t}function ia(e,t){const r=Zo(e.Fp,t.map((e=>e.Z)));return t.map(((t,n)=>e.fromAffine(t.toAffine(r[n]))))}function oa(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function aa(e,t){oa(e,t);const r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:To(e),maxNumber:r,shiftBy:BigInt(e)}}function ca(e,t,r){const{windowSize:n,mask:s,maxNumber:i,shiftBy:o}=r;let a=Number(e&s),c=e>>o;a>n&&(a-=i,c+=na);const l=t*n;return{nextN:c,offset:l+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:l}}const la=new WeakMap,ua=new WeakMap;function ha(e){return ua.get(e)||1}function da(e){if(e!==ra)throw Error("invalid wNAF")}class pa{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let n=e;for(;t>ra;)t&na&&(r=r.add(n)),n=n.double(),t>>=na;return r}precomputeWindow(e,t){const{windows:r,windowSize:n}=aa(t,this.bits),s=[];let i=e,o=i;for(let e=0;e<r;e++){o=i,s.push(o);for(let e=1;e<n;e++)o=o.add(i),s.push(o);i=o.double()}return s}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let n=this.ZERO,s=this.BASE;const i=aa(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:o,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:h}=ca(r,e,i);r=o,c?s=s.add(sa(u,t[h])):n=n.add(sa(l,t[a]))}return da(r),{p:n,f:s}}wNAFUnsafe(e,t,r,n=this.ZERO){const s=aa(e,this.bits);for(let e=0;e<s.windows&&r!==ra;e++){const{nextN:i,offset:o,isZero:a,isNeg:c}=ca(r,e,s);if(r=i,!a){const e=t[o];n=n.add(c?e.negate():e)}}return da(r),n}getPrecomputes(e,t,r){let n=la.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&("function"==typeof r&&(n=r(n)),la.set(t,n))),n}cached(e,t,r){const n=ha(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){const s=ha(e);return 1===s?this._unsafeLadder(e,t,n):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),t,n)}createCache(e,t){oa(t,this.bits),ua.set(e,t),la.delete(e)}hasCache(e){return 1!==ha(e)}}function fa(e,t,r,n){!function(e,t){if(!Array.isArray(e))throw Error("array expected");e.forEach(((e,r)=>{if(!(e instanceof t))throw Error("invalid point at index "+r)}))}(r,e),function(e,t){if(!Array.isArray(e))throw Error("array of scalars expected");e.forEach(((e,r)=>{if(!t.isValid(e))throw Error("invalid scalar at index "+r)}))}(n,t);const s=r.length,i=n.length;if(s!==i)throw Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=ko(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=To(c),u=Array(Number(l)+1).fill(o);let h=o;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){u.fill(o);for(let t=0;t<i;t++){const s=n[t],i=Number(s>>BigInt(e)&l);u[i]=u[i].add(r[t])}let t=o;for(let e=u.length-1,r=o;e>0;e--)r=r.add(u[e]),t=t.add(r);if(h=h.add(t),0!==e)for(let e=0;e<c;e++)h=h.double()}return h}function ga(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){const t=Xo.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"});Po(e,t)}(t),t}return Jo(e,{isLE:r})}function ma(e,t,r={},n){if(void 0===n&&(n="edwards"===e),!t||"object"!=typeof t)throw Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const r=t[e];if(!("bigint"==typeof r&&r>ra))throw Error(`CURVE.${e} must be positive bigint`)}const s=ga(t.p,r.Fp,n),i=ga(t.n,r.Fn,n),o=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of o)if(!s.isValid(t[e]))throw Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:s,Fn:i}}const ya=BigInt(0),ba=BigInt(1),wa=BigInt(2),va=BigInt(8);const Ea=BigInt(0),Sa=BigInt(1),Aa=BigInt(2),Ia=BigInt(1),_a=BigInt(2),Ca=BigInt(3),xa=BigInt(5),ka=BigInt(8),Ta=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Pa={p:Ta,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ka,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ra(e){const t=BigInt(10),r=BigInt(20),n=BigInt(40),s=BigInt(80),i=Ta,o=e*e%i*e%i,a=jo(o,_a,i)*o%i,c=jo(a,Ia,i)*e%i,l=jo(c,xa,i)*c%i,u=jo(l,t,i)*l%i,h=jo(u,r,i)*u%i,d=jo(h,n,i)*h%i,p=jo(d,s,i)*d%i,f=jo(p,s,i)*d%i,g=jo(f,t,i)*l%i;return{pow_p_5_8:jo(g,_a,i)*e%i,b2:o}}function La(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Da=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");const Ma=Jo(Pa.p,{isLE:!0}),Na=function(e){const{CURVE:t,curveOpts:r,hash:n,eddsaOpts:s}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r={Fp:e.Fp,Fn:Jo(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},n={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:r,hash:e.hash,eddsaOpts:n}}(e),i=function(e,t={}){const r=ma("edwards",e,t,t.FpFnLE),{Fp:n,Fn:s}=r;let i=r.CURVE;const{h:o}=i;Po(t,{},{uvRatio:"function"});const a=wa<<BigInt(8*s.BYTES)-ba,c=e=>n.create(e),l=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:n.sqrt(n.div(e,t))}}catch(e){return{isValid:!1,value:ya}}});if(!((e,t,r,n)=>{const s=e.sqr(r),i=e.sqr(n),o=e.add(e.mul(t.a,s),i),a=e.add(e.ONE,e.mul(t.d,e.mul(s,i)));return e.eql(o,a)})(n,i,i.Gx,i.Gy))throw Error("bad curve params: generator point");function u(e,t,r=!1){return xo("coordinate "+e,t,r?ba:ya,a),t}function h(e){if(!(e instanceof f))throw Error("ExtendedPoint expected")}const d=Ro(((e,t)=>{const{X:r,Y:s,Z:i}=e,o=e.is0();null==t&&(t=o?va:n.inv(i));const a=c(r*t),l=c(s*t),u=n.mul(i,t);if(o)return{x:ya,y:ba};if(u!==ba)throw Error("invZ was invalid");return{x:a,y:l}})),p=Ro((e=>{const{a:t,d:r}=i;if(e.is0())throw Error("bad point: ZERO");const{X:n,Y:s,Z:o,T:a}=e,l=c(n*n),u=c(s*s),h=c(o*o),d=c(h*h),p=c(l*t);if(c(h*c(p+u))!==c(d+c(r*c(l*u))))throw Error("bad point: equation left != right (1)");if(c(n*s)!==c(o*a))throw Error("bad point: equation left != right (2)");return!0}));class f{constructor(e,t,r,n){this.X=u("x",e),this.Y=u("y",t),this.Z=u("z",r,!0),this.T=u("t",n),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){if(e instanceof f)throw Error("extended point not allowed");const{x:t,y:r}=e||{};return u("x",t),u("y",r),new f(t,r,ba,c(t*r))}static fromBytes(e,t=!1){const r=n.BYTES,{a:s,d:o}=i;e=_o(yo(e,r,"point")),mo(t,"zip215");const u=_o(e),h=e[r-1];u[r-1]=-129&h;const d=Eo(u),p=t?a:n.ORDER;xo("point.y",d,ya,p);const g=c(d*d),m=c(g-ba),y=c(o*g-s);let{isValid:b,value:w}=l(m,y);if(!b)throw Error("bad point: invalid y coordinate");const v=(w&ba)===ba,E=!!(128&h);if(!t&&w===ya&&E)throw Error("bad point: x=0 and x_0=1");return E!==v&&(w=c(-w)),f.fromAffine({x:w,y:d})}static fromHex(e,t=!1){return f.fromBytes(Io("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return g.createCache(this,e),t||this.multiply(wa),this}assertValidity(){p(this)}equals(e){h(e);const{X:t,Y:r,Z:n}=this,{X:s,Y:i,Z:o}=e,a=c(t*o),l=c(s*n),u=c(r*o),d=c(i*n);return a===l&&u===d}is0(){return this.equals(f.ZERO)}negate(){return new f(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=i,{X:t,Y:r,Z:n}=this,s=c(t*t),o=c(r*r),a=c(wa*c(n*n)),l=c(e*s),u=t+r,h=c(c(u*u)-s-o),d=l+o,p=d-a,g=l-o,m=c(h*p),y=c(d*g),b=c(h*g),w=c(p*d);return new f(m,y,w,b)}add(e){h(e);const{a:t,d:r}=i,{X:n,Y:s,Z:o,T:a}=this,{X:l,Y:u,Z:d,T:p}=e,g=c(n*l),m=c(s*u),y=c(a*r*p),b=c(o*d),w=c((n+s)*(l+u)-g-m),v=b-y,E=b+y,S=c(m-t*g),A=c(w*v),I=c(E*S),_=c(w*S),C=c(v*E);return new f(A,I,C,_)}subtract(e){return this.add(e.negate())}multiply(e){if(!s.isValidNot0(e))throw Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:r}=g.cached(this,e,(e=>ia(f,e)));return ia(f,[t,r])[0]}multiplyUnsafe(e,t=f.ZERO){if(!s.isValid(e))throw Error("invalid scalar: expected 0 <= sc < curve.n");return e===ya?f.ZERO:this.is0()||e===ba?this:g.unsafe(this,e,(e=>ia(f,e)),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return g.unsafe(this,i.n).is0()}toAffine(e){return d(this,e)}clearCofactor(){return o===ba?this:this.multiplyUnsafe(o)}toBytes(){const{x:e,y:t}=this.toAffine(),r=n.toBytes(t);return r[r.length-1]|=e&ba?128:0,r}toHex(){return lr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return ia(f,e)}static msm(e,t){return fa(f,s,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}f.BASE=new f(i.Gx,i.Gy,ba,c(i.Gx*i.Gy)),f.ZERO=new f(ya,ba,ba,ya),f.Fp=n,f.Fn=s;const g=new pa(f,s.BITS);return f.BASE.precompute(8),f}(t,r);return function(e,t){const r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}(e,function(e,t,r={}){if("function"!=typeof t)throw Error('"hash" function param is required');Po(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:s,Fp:i,Fn:o}=e,a=r.randomBytes||Sr,c=r.adjustScalarBytes||(e=>e),l=r.domain||((e,t,r)=>{if(mo(r,"phflag"),t.length||r)throw Error("Contexts/pre-hash are not supported");return e});function u(e){return o.create(Eo(e))}function h(e){const{head:r,prefix:n,scalar:i}=function(e){const r=m.secretKey;e=Io("private key",e,r);const n=Io("hashed private key",t(e),2*r),s=c(n.slice(0,r));return{head:s,prefix:n.slice(r,2*r),scalar:u(s)}}(e),o=s.multiply(i),a=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:a}}function d(e){return h(e).pointBytes}function p(e=Uint8Array.of(),...r){const s=wr(...r);return u(t(l(s,Io("context",e),!!n)))}const f={zip215:!0},g=i.BYTES,m={secretKey:g,publicKey:g,signature:2*g,seed:g};function y(e=a(m.seed)){return yo(e,m.seed,"seed")}const b={getExtendedPublicKey:h,randomSecretKey:y,isValidSecretKey:e=>Jt(e)&&e.length===o.BYTES,isValidPublicKey(t,r){try{return!!e.fromBytes(t,r)}catch(e){return!1}},toMontgomery(t){const{y:r}=e.fromBytes(t),n=m.publicKey,s=32===n;if(!s&&57!==n)throw Error("only defined for 25519 and 448");const o=s?i.div(ba+r,ba-r):i.div(r-ba,r+ba);return i.toBytes(o)},toMontgomerySecret(e){const r=m.secretKey;yo(e,r);const n=t(e.subarray(0,r));return c(n).subarray(0,r)},randomPrivateKey:y,precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({keygen(e){const t=b.randomSecretKey(e);return{secretKey:t,publicKey:d(t)}},getPublicKey:d,sign(e,t,r={}){e=Io("message",e),n&&(e=n(e));const{prefix:i,scalar:a,pointBytes:c}=h(t),l=p(r.context,i,e),u=s.multiply(l).toBytes(),d=p(r.context,u,c,e),f=o.create(l+d*a);if(!o.isValid(f))throw Error("sign failed: invalid s");return yo(wr(u,o.toBytes(f)),m.signature,"result")},verify(t,r,i,o=f){const{context:a,zip215:c}=o,l=m.signature;t=Io("signature",t,l),r=Io("message",r),i=Io("publicKey",i,m.publicKey),void 0!==c&&mo(c,"zip215"),n&&(r=n(r));const u=l/2,h=t.subarray(0,u),d=Eo(t.subarray(u,l));let g,y,b;try{g=e.fromBytes(i,c),y=e.fromBytes(h,c),b=s.multiplyUnsafe(d)}catch(e){return!1}if(!c&&g.isSmallOrder())return!1;const w=p(a,y.toBytes(),g.toBytes(),r);return y.add(g.multiplyUnsafe(w)).subtract(b).clearCofactor().is0()},utils:b,Point:e,lengths:m})}(i,n,s))}({...Pa,Fp:Ma,hash:Jr,adjustScalarBytes:La,uvRatio:function(e,t){const r=Ta,n=zo(t*t*t,r),s=zo(n*n*t,r);let i=zo(e*n*Ra(e*s).pow_p_5_8,r);const o=zo(t*i*i,r),a=i,c=zo(i*Da,r),l=o===e,u=o===zo(-e,r),h=o===zo(-e*Da,r);return l&&(i=a),(u||h)&&(i=c),(zo(i,r)&Do)===Do&&(i=zo(-i,r)),{isValid:l||u,value:i}}}),Oa=(()=>{const e=Ma.ORDER;return function(e){const t=(Po(r=e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r}));var r;const{P:n,type:s,adjustScalarBytes:i,powPminus2:o,randomBytes:a}=t,c="x25519"===s;if(!c&&"x448"!==s)throw Error("invalid type");const l=a||Sr,u=c?255:448,h=c?32:56,d=c?BigInt(9):BigInt(5),p=c?BigInt(121665):BigInt(39081),f=c?Aa**BigInt(254):Aa**BigInt(447),g=c?BigInt(8)*Aa**BigInt(251)-Sa:BigInt(4)*Aa**BigInt(445)-Sa,m=f+g+Sa,y=e=>zo(e,n),b=w(d);function w(e){return Ao(y(e),h)}function v(e,t){const r=function(e,t){xo("u",e,Ea,n),xo("scalar",t,f,m);const r=t,s=e;let i=Sa,a=Ea,c=e,l=Sa,h=Ea;for(let e=BigInt(u-1);e>=Ea;e--){const t=r>>e&Sa;h^=t,({x_2:i,x_3:c}=S(h,i,c)),({x_2:a,x_3:l}=S(h,a,l)),h=t;const n=i+a,o=y(n*n),u=i-a,d=y(u*u),f=o-d,g=c+l,m=y((c-l)*n),b=y(g*u),w=m+b,v=m-b;c=y(w*w),l=y(s*y(v*v)),i=y(o*d),a=y(f*(o+y(p*f)))}({x_2:i,x_3:c}=S(h,i,c)),({x_2:a,x_3:l}=S(h,a,l));const d=o(a);return y(i*d)}(function(e){const t=Io("u coordinate",e,h);return c&&(t[31]&=127),y(Eo(t))}(t),function(e){return Eo(i(Io("scalar",e,h)))}(e));if(r===Ea)throw Error("invalid private or public key received");return w(r)}function E(e){return v(e,b)}function S(e,t,r){const n=y(e*(t-r));return{x_2:t=y(t-n),x_3:r=y(r+n)}}const A={secretKey:h,publicKey:h,seed:h},I=(e=l(h))=>(tr(e,A.seed),e);return{keygen(e){const t=I(e);return{secretKey:t,publicKey:E(t)}},getSharedSecret:(e,t)=>v(e,t),getPublicKey:e=>E(e),scalarMult:v,scalarMultBase:E,utils:{randomSecretKey:I,randomPrivateKey:I},GuBytes:b.slice(),lengths:A}}({P:e,type:"x25519",powPminus2(t){const{pow_p_5_8:r,b2:n}=Ra(t);return zo(jo(r,Ca,e)*n,e)},adjustScalarBytes:La})})();let Ua=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Fa=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ba={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new Fa("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};let $a;const qa=(async()=>{try{return await Ba.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function za(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}let ja=class{type="Ed25519";raw;constructor(e){this.raw=Ha(e,32)}toMultihash(){return Ne.digest(Ac(this))}toCID(){return qe.createV1(114,this.toMultihash())}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();const n=async function(e,t,r){return null==$a&&($a=await qa),$a?async function(e,t,r){if(e.buffer instanceof ArrayBuffer){const n=await Ba.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Ba.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(e,t,r):function(e,t,r){return Na.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(e,t,r)}(this.raw,t,e);return za(n)?n.then((e=>(r?.signal?.throwIfAborted(),e))):n}};class Ka{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Ha(e,64),this.publicKey=new ja(t)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();const r=async function(e,t){return null==$a&&($a=await qa),$a?async function(e,t){let r;r=64===e.length?e.subarray(0,32):e;const n={crv:"Ed25519",kty:"OKP",x:tn(e.subarray(32),"base64url"),d:tn(r,"base64url"),ext:!0,key_ops:["sign"]},s=await Ba.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),i=await Ba.get().subtle.sign({name:"Ed25519"},s,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(i,0,i.byteLength)}(e,t):function(e,t){const r=e.subarray(0,32);return Na.sign(t instanceof Uint8Array?t:t.subarray(),r)}(e,t)}(this.raw,e);return za(r)?r.then((e=>(t?.signal?.throwIfAborted(),e))):(t?.signal?.throwIfAborted(),r)}}function Va(e){return e=Ha(e,32),new ja(e)}function Ha(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Pn(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var Ga,Wa,Xa,Za;function Ya(e){if(isNaN(e)||e<=0)throw new Pn("random bytes length must be a Number bigger than 0");return Sr(e)}(e=>{e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(Ga||(Ga={})),(e=>{e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(Wa||(Wa={})),(Ga||(Ga={})).codec=()=>Gt(Wa),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Ga.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=Ga.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Xa||(Xa={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Ga.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=Ga.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Za||(Za={}));let Qa=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return null==this._raw&&(this._raw=function(e){if(null==e.n||null==e.e)throw new Pn("JWK was missing components");return eo([Ja,Ji(eo([Qi(Ye(e.n,"base64url")),Qi(Ye(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return qe.createV1(114,this._multihash)}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}verify(e,t,r){return async function(e,t,r,n){const s=await Ba.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();const i=await Ba.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}};const Ja=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);class ec extends vr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,rr(e);const r=br(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,s=new Uint8Array(n);s.set(r.length>n?e.create().update(r).digest():r);for(let e=0;e<s.length;e++)s[e]^=54;this.iHash.update(s),this.oHash=e.create();for(let e=0;e<s.length;e++)s[e]^=106;this.oHash.update(s),sr(s)}update(e){return nr(this),this.iHash.update(e),this}digestInto(e){nr(this),tr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:n,destroyed:s,blockLen:i,outputLen:o}=this;return e.finished=n,e.destroyed=s,e.blockLen=i,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const tc=(e,t,r)=>new ec(e,t).update(r).digest();tc.create=(e,t)=>new ec(e,t);const rc=(e,t)=>(e+(e>=0?t:-t)/cc)/t;function nc(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function sc(e,t){const r={};for(let n of Object.keys(t))r[n]=void 0===e[n]?t[n]:e[n];return mo(r.lowS,"lowS"),mo(r.prehash,"prehash"),void 0!==r.format&&nc(r.format),r}const ic={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode(e,t){const{Err:r}=ic;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const n=t.length/2,s=bo(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const i=n>127?bo(s.length/2|128):"";return bo(e)+i+s+t},decode(e,t){const{Err:r}=ic;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const s=t[n++];let i=0;if(128&s){const e=127&s;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const o=t.subarray(n,n+e);if(o.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===o[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of o)i=i<<8|e;if(n+=e,i<128)throw new r("tlv.decode(long): not minimal encoding")}else i=s;const o=t.subarray(n,n+i);if(o.length!==i)throw new r("tlv.decode: wrong value length");return{v:o,l:t.subarray(n+i)}}},_int:{encode(e){const{Err:t}=ic;if(e<oc)throw new t("integer: negative integers are not allowed");let r=bo(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=ic;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return vo(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=ic,s=Io("signature",e),{v:i,l:o}=n.decode(48,s);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){const{_tlv:t,_int:r}=ic,n=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,n)}},oc=BigInt(0),ac=BigInt(1),cc=BigInt(2),lc=BigInt(3),uc=BigInt(4);function hc(e,t){const{BYTES:r}=e;let n;if("bigint"==typeof t)n=t;else{let s=Io("private key",t);try{n=e.fromBytes(s)}catch(e){throw Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw Error("invalid private key: out of range [1..N-1]");return n}function dc(e){return Uint8Array.of(e?2:3)}function pc(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function fc(e){const{CURVE:t,curveOpts:r,hash:n,ecdsaOpts:s}=function(e){const{CURVE:t,curveOpts:r}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp;let n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map((e=>Math.ceil(e/2))))):void 0;return{CURVE:t,curveOpts:{Fp:r,Fn:Jo(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,hash:e.hash,ecdsaOpts:n}}(e);return function(e,t){const r=t.Point;return Object.assign({},t,{ProjectivePoint:r,CURVE:Object.assign({},e,Qo(r.Fn.ORDER,r.Fn.BITS))})}(e,function(e,t,r={}){rr(t),Po(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||Sr,s=r.hmac||((e,...r)=>tc(t,e,wr(...r))),{Fp:i,Fn:o}=e,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:p}=function(e,t={}){const{Fn:r}=e,n=t.randomBytes||Sr,s=Object.assign(pc(e.Fp,r),{seed:ta(r.ORDER)});function i(e){try{return!!hc(r,e)}catch(e){return!1}}function o(e=n(s.seed)){return function(e,t,r=!1){const n=e.length,s=ea(t),i=ta(t);if(n<16||n<i||n>1024)throw Error("expected "+i+"-1024 bytes of input, got "+n);const o=zo(r?Eo(e):vo(e),t-Do)+Do;return r?Ao(o,s):So(o,s)}(yo(e,s.seed,"seed"),r.ORDER)}function a(t,n=!0){return e.BASE.multiply(hc(r,t)).toBytes(n)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:n,publicKey:i,publicKeyUncompressed:o}=s;if(r.allowedLengths||n===i)return;const a=Io("key",t).length;return a===i||a===o}const l={isValidSecretKey:i,isValidPublicKey(t,r){const{publicKey:n,publicKeyUncompressed:i}=s;try{const s=t.length;return!(!0===r&&s!==n||!1===r&&s!==i||!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:o,isValidPrivateKey:i,randomPrivateKey:o,normPrivateKeyToScalar:e=>hc(r,e),precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret(t,n,s=!0){if(!0===c(t))throw Error("first arg must be private key");if(!1===c(n))throw Error("second arg must be public key");const i=hc(r,t);return e.fromHex(n).multiply(i).toBytes(s)},keygen(e){const t=o(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:l,lengths:s})}(e,r),f={prehash:!1,lowS:"boolean"==typeof r.lowS&&r.lowS,format:void 0,extraEntropy:!1},g="compact";function m(e){return e>a>>ac}function y(e,t){if(!o.isValidNot0(t))throw Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class b{constructor(e,t,r){this.r=y("r",e),this.s=y("s",t),null!=r&&(this.recovery=r),Object.freeze(this)}static fromBytes(e,t=g){let r;if(function(e,t){nc(t);const r=p.signature;yo(e,"compact"===t?r:"recovered"===t?r+1:void 0,t+" signature")}(e,t),"der"===t){const{r:t,s:r}=ic.toSig(yo(e));return new b(t,r)}"recovered"===t&&(r=e[0],t="compact",e=e.subarray(1));const n=o.BYTES,s=e.subarray(0,n),i=e.subarray(n,2*n);return new b(o.fromBytes(s),o.fromBytes(i),r)}static fromHex(e,t){return this.fromBytes(yr(e),t)}addRecoveryBit(e){return new b(this.r,this.s,e)}recoverPublicKey(t){const r=i.ORDER,{r:n,s:s,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw Error("recovery id invalid");if(a*cc<r&&c>1)throw Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?n+a:n;if(!i.isValid(l))throw Error("recovery id 2 or 3 invalid");const u=i.toBytes(l),h=e.fromBytes(wr(dc(!(1&c)),u)),d=o.inv(l),p=v(Io("msgHash",t)),f=o.create(-p*d),g=o.create(s*d),m=e.BASE.multiplyUnsafe(f).add(h.multiplyUnsafe(g));if(m.is0())throw Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(e=g){if(nc(e),"der"===e)return yr(ic.hexFromSig(this));const t=o.toBytes(this.r),r=o.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw Error("recovery bit must be present");return wr(Uint8Array.of(this.recovery),t,r)}return wr(t,r)}toHex(e){return lr(this.toBytes(e))}assertValidity(){}static fromCompact(e){return b.fromBytes(Io("sig",e),"compact")}static fromDER(e){return b.fromBytes(Io("sig",e),"der")}normalizeS(){return this.hasHighS()?new b(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return lr(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return lr(this.toBytes("compact"))}}const w=r.bits2int||function(e){if(e.length>8192)throw Error("input is too large");const t=vo(e),r=8*e.length-c;return r>0?t>>BigInt(r):t},v=r.bits2int_modN||function(e){return o.create(w(e))},E=To(c);function S(e){return xo("num < 2^"+c,e,oc,E),o.toBytes(e)}function A(e,r){return yo(e,void 0,"message"),r?yo(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:p,Point:e,sign(r,i,a={}){r=Io("message",r);const{seed:c,k2sig:l}=function(t,r,s){if(["recovered","canonical"].some((e=>e in s)))throw Error("sign() legacy options not supported");const{lowS:i,prehash:a,extraEntropy:c}=sc(s,f);t=A(t,a);const l=v(t),u=hc(o,r),h=[S(u),S(l)];if(null!=c&&!1!==c){const e=!0===c?n(p.secretKey):c;h.push(Io("extraEntropy",e))}const d=wr(...h),g=l;return{seed:d,k2sig(t){const r=w(t);if(!o.isValidNot0(r))return;const n=o.inv(r),s=e.BASE.multiply(r).toAffine(),a=o.create(s.x);if(a===oc)return;const c=o.create(n*o.create(g+a*u));if(c===oc)return;let l=(s.x===a?0:2)|Number(s.y&ac),h=c;return i&&m(c)&&(h=o.neg(c),l^=1),new b(a,h,l)}}}(r,i,a),u=function(e,t,r){if("number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");if("function"!=typeof r)throw Error("hmacFn must be a function");const n=e=>new Uint8Array(e),s=e=>Uint8Array.of(e);let i=n(e),o=n(e),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...e)=>r(o,i,...e),u=(e=n(0))=>{o=l(s(0),e),i=l(),0!==e.length&&(o=l(s(1),e),i=l())},h=()=>{if(a++>=1e3)throw Error("drbg: tried 1000 values");let e=0;const r=[];for(;e<t;){i=l();const t=i.slice();r.push(t),e+=i.length}return wr(...r)};return(e,t)=>{let r;for(c(),u(e);!(r=t(h()));)u();return c(),r}}(t.outputLen,o.BYTES,s);return u(c,l)},verify(t,r,n,s={}){const{lowS:i,prehash:a,format:c}=sc(s,f);if(n=Io("publicKey",n),r=A(Io("message",r),a),"strict"in s)throw Error("options.strict was renamed to lowS");const l=void 0===c?function(e){let t;const r="string"==typeof e||Jt(e),n=!r&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!r&&!n)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(n)t=new b(e.r,e.s);else if(r){try{t=b.fromBytes(Io("sig",e),"der")}catch(e){if(!(e instanceof ic.Err))throw e}if(!t)try{t=b.fromBytes(Io("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):b.fromBytes(Io("sig",t),c);if(!1===l)return!1;try{const t=e.fromBytes(n);if(i&&l.hasHighS())return!1;const{r:s,s:a}=l,c=v(r),u=o.inv(a),h=o.create(c*u),d=o.create(s*u),p=e.BASE.multiplyUnsafe(h).add(t.multiplyUnsafe(d));return!p.is0()&&o.create(p.x)===s}catch(e){return!1}},recoverPublicKey(e,t,r={}){const{prehash:n}=sc(r,f);return t=A(t,n),b.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:b,hash:t})}(function(e,t={}){const r=ma("weierstrass",e,t),{Fp:n,Fn:s}=r;let i=r.CURVE;const{h:o,n:a}=i;Po(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!n.is0(i.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw Error('invalid endo: expected "beta": bigint and "basises": array');const l=pc(n,s);function u(){if(!n.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}const h=t.toBytes||function(e,t,r){const{x:s,y:i}=t.toAffine(),o=n.toBytes(s);return mo(r,"isCompressed"),r?(u(),wr(dc(!n.isOdd(i)),o)):wr(Uint8Array.of(4),o,n.toBytes(i))},d=t.fromBytes||function(e){yo(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:r}=l,s=e.length,i=e[0],o=e.subarray(1);if(s!==t||2!==i&&3!==i){if(s===r&&4===i){const e=n.BYTES,t=n.fromBytes(o.subarray(0,e)),r=n.fromBytes(o.subarray(e,2*e));if(!f(t,r))throw Error("bad point: is not on curve");return{x:t,y:r}}throw Error(`bad point: got length ${s}, expected compressed=${t} or uncompressed=${r}`)}{const t=n.fromBytes(o);if(!n.isValid(t))throw Error("bad point: is not on curve, wrong x");const r=p(t);let s;try{s=n.sqrt(r)}catch(e){const t=e instanceof Error?": "+e.message:"";throw Error("bad point: is not on curve, sqrt error"+t)}return u(),!(1&~i)!==n.isOdd(s)&&(s=n.neg(s)),{x:t,y:s}}};function p(e){const t=n.sqr(e),r=n.mul(t,e);return n.add(n.add(r,n.mul(e,i.a)),i.b)}function f(e,t){const r=n.sqr(t),s=p(e);return n.eql(r,s)}if(!f(i.Gx,i.Gy))throw Error("bad curve params: generator point");const g=n.mul(n.pow(i.a,lc),uc),m=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(g,m)))throw Error("bad curve params: a or b");function y(e,t,r=!1){if(!n.isValid(t)||r&&n.is0(t))throw Error("bad point coordinate "+e);return t}function b(e){if(!(e instanceof A))throw Error("ProjectivePoint expected")}function w(e){if(!c||!c.basises)throw Error("no endo");return function(e,t,r){const[[n,s],[i,o]]=t,a=rc(o*e,r),c=rc(-s*e,r);let l=e-a*n-c*i,u=-a*s-c*o;const h=l<oc,d=u<oc;h&&(l=-l),d&&(u=-u);const p=To(Math.ceil(ko(r)/2))+ac;if(l<oc||l>=p||u<oc||u>=p)throw Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}(e,c.basises,s.ORDER)}const v=Ro(((e,t)=>{const{X:r,Y:s,Z:i}=e;if(n.eql(i,n.ONE))return{x:r,y:s};const o=e.is0();null==t&&(t=o?n.ONE:n.inv(i));const a=n.mul(r,t),c=n.mul(s,t),l=n.mul(i,t);if(o)return{x:n.ZERO,y:n.ZERO};if(!n.eql(l,n.ONE))throw Error("invZ was invalid");return{x:a,y:c}})),E=Ro((e=>{if(e.is0()){if(t.allowInfinityPoint&&!n.is0(e.Y))return;throw Error("bad point: ZERO")}const{x:r,y:s}=e.toAffine();if(!n.isValid(r)||!n.isValid(s))throw Error("bad point: x or y not field elements");if(!f(r,s))throw Error("bad point: equation left != right");if(!e.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0}));function S(e,t,r,s,i){return r=new A(n.mul(r.X,e),r.Y,r.Z),t=sa(s,t),r=sa(i,r),t.add(r)}class A{constructor(e,t,r){this.X=y("x",e),this.Y=y("y",t,!0),this.Z=y("z",r),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){const{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw Error("invalid affine point");if(e instanceof A)throw Error("projective point not allowed");return n.is0(t)&&n.is0(r)?A.ZERO:new A(t,r,n.ONE)}static fromBytes(e){const t=A.fromAffine(d(yo(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return A.fromBytes(Io("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return _.createCache(this,e),t||this.multiply(lc),this}assertValidity(){E(this)}hasEvenY(){const{y:e}=this.toAffine();if(!n.isOdd)throw Error("Field doesn't support isOdd");return!n.isOdd(e)}equals(e){b(e);const{X:t,Y:r,Z:s}=this,{X:i,Y:o,Z:a}=e,c=n.eql(n.mul(t,a),n.mul(i,s)),l=n.eql(n.mul(r,a),n.mul(o,s));return c&&l}negate(){return new A(this.X,n.neg(this.Y),this.Z)}double(){const{a:e,b:t}=i,r=n.mul(t,lc),{X:s,Y:o,Z:a}=this;let c=n.ZERO,l=n.ZERO,u=n.ZERO,h=n.mul(s,s),d=n.mul(o,o),p=n.mul(a,a),f=n.mul(s,o);return f=n.add(f,f),u=n.mul(s,a),u=n.add(u,u),c=n.mul(e,u),l=n.mul(r,p),l=n.add(c,l),c=n.sub(d,l),l=n.add(d,l),l=n.mul(c,l),c=n.mul(f,c),u=n.mul(r,u),p=n.mul(e,p),f=n.sub(h,p),f=n.mul(e,f),f=n.add(f,u),u=n.add(h,h),h=n.add(u,h),h=n.add(h,p),h=n.mul(h,f),l=n.add(l,h),p=n.mul(o,a),p=n.add(p,p),h=n.mul(p,f),c=n.sub(c,h),u=n.mul(p,d),u=n.add(u,u),u=n.add(u,u),new A(c,l,u)}add(e){b(e);const{X:t,Y:r,Z:s}=this,{X:o,Y:a,Z:c}=e;let l=n.ZERO,u=n.ZERO,h=n.ZERO;const d=i.a,p=n.mul(i.b,lc);let f=n.mul(t,o),g=n.mul(r,a),m=n.mul(s,c),y=n.add(t,r),w=n.add(o,a);y=n.mul(y,w),w=n.add(f,g),y=n.sub(y,w),w=n.add(t,s);let v=n.add(o,c);return w=n.mul(w,v),v=n.add(f,m),w=n.sub(w,v),v=n.add(r,s),l=n.add(a,c),v=n.mul(v,l),l=n.add(g,m),v=n.sub(v,l),h=n.mul(d,w),l=n.mul(p,m),h=n.add(l,h),l=n.sub(g,h),h=n.add(g,h),u=n.mul(l,h),g=n.add(f,f),g=n.add(g,f),m=n.mul(d,m),w=n.mul(p,w),g=n.add(g,m),m=n.sub(f,m),m=n.mul(d,m),w=n.add(w,m),f=n.mul(g,w),u=n.add(u,f),f=n.mul(v,w),l=n.mul(y,l),l=n.sub(l,f),f=n.mul(y,g),h=n.mul(v,h),h=n.add(h,f),new A(l,u,h)}subtract(e){return this.add(e.negate())}is0(){return this.equals(A.ZERO)}multiply(e){const{endo:r}=t;if(!s.isValidNot0(e))throw Error("invalid scalar: out of range");let n,i;const o=e=>_.cached(this,e,(e=>ia(A,e)));if(r){const{k1neg:t,k1:s,k2neg:a,k2:c}=w(e),{p:l,f:u}=o(s),{p:h,f:d}=o(c);i=u.add(d),n=S(r.beta,l,h,t,a)}else{const{p:t,f:r}=o(e);n=t,i=r}return ia(A,[n,i])[0]}multiplyUnsafe(e){const{endo:r}=t,n=this;if(!s.isValid(e))throw Error("invalid scalar: out of range");if(e===oc||n.is0())return A.ZERO;if(e===ac)return n;if(_.hasCache(this))return this.multiply(e);if(r){const{k1neg:t,k1:s,k2neg:i,k2:o}=w(e),{p1:a,p2:c}=function(e,t,r,n){let s=t,i=e.ZERO,o=e.ZERO;for(;r>ra||n>ra;)r&na&&(i=i.add(s)),n&na&&(o=o.add(s)),s=s.double(),r>>=na,n>>=na;return{p1:i,p2:o}}(A,n,s,o);return S(r.beta,a,c,t,i)}return _.unsafe(n,e)}multiplyAndAddUnsafe(e,t,r){const n=this.multiplyUnsafe(t).add(e.multiplyUnsafe(r));return n.is0()?void 0:n}toAffine(e){return v(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return o===ac||(e?e(A,this):_.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return o===ac?this:e?e(A,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return mo(e,"isCompressed"),this.assertValidity(),h(A,this,e)}toHex(e=!0){return lr(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return ia(A,e)}static msm(e,t){return fa(A,s,e,t)}static fromPrivateKey(e){return A.BASE.multiply(hc(s,e))}}A.BASE=new A(i.Gx,i.Gy,n.ONE),A.ZERO=new A(n.ZERO,n.ONE,n.ZERO),A.Fp=n,A.Fn=s;const I=s.BITS,_=new pa(A,t.endo?Math.ceil(I/2):I);return A.BASE.precompute(8),A}(t,r),n,s))}const gc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},mc={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},yc=BigInt(2),bc=Jo(gc.p,{sqrt(e){const t=gc.p,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,h=jo(u,r,t)*u%t,d=jo(h,r,t)*u%t,p=jo(d,yc,t)*l%t,f=jo(p,s,t)*p%t,g=jo(f,i,t)*f%t,m=jo(g,a,t)*g%t,y=jo(m,c,t)*m%t,b=jo(y,a,t)*g%t,w=jo(b,r,t)*u%t,v=jo(w,o,t)*f%t,E=jo(v,n,t)*l%t,S=jo(E,yc,t);if(!bc.eql(bc.sqr(S),e))throw Error("Cannot find square root");return S}}),wc=function(e,t){const r=t=>fc({...e,hash:t});return{...r(t),create:r}}({...gc,Fp:bc,lowS:!0,endo:mc},Qr);let vc=class{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return wc.ProjectivePoint.fromHex(e),e}catch(e){throw new Rn(e+"")}}(e),this.raw=function(e){return wc.ProjectivePoint.fromHex(e).toRawBytes(!0)}(this._key)}toMultihash(){return Ne.digest(Ac(this))}toCID(){return qe.createV1(114,this.toMultihash())}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}verify(e,t,r){return function(e,t,r,n){const s=Ue.digest(r instanceof Uint8Array?r:r.subarray());if(za(s))return s.then((({digest:r})=>(n?.signal?.throwIfAborted(),wc.verify(t,r,e)))).catch((e=>{if("AbortError"===e.name)throw e;throw new Ua(e+"")}));try{return n?.signal?.throwIfAborted(),wc.verify(t,s.digest,e)}catch(e){throw new Ua(e+"")}}(this._key,t,e,r)}};function Ec(e){return new vc(e)}function Sc(e,t){const{Type:r,Data:n}=Xa.decode(e),s=n??new Uint8Array;switch(r){case Ga.RSA:return function(e,t){if(e.byteLength>=1062)throw new Rn("Key size is too large");return function(e,t,r){const n=function(e){const t=Wi(e[1],{offset:0});return{kty:"RSA",n:tn(t[0],"base64url"),e:tn(t[1],"base64url")}}(e);return null==r&&(r=Re(18,en(Xa.encode({Type:Ga.RSA,Data:t})))),new Qa(n,r)}(Wi(e,{offset:0}),e,t)}(s,t);case Ga.Ed25519:return Va(s);case Ga.secp256k1:return Ec(s);case Ga.ECDSA:return uo(s);default:throw new Qn}}function Ac(e){return Xa.encode({Type:Ga[e.type],Data:e.raw})}const Ic=Symbol.for("nodejs.util.inspect.custom");let _c=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[En]=!0;toString(){return null==this.string&&(this.string=fe.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return qe.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Ds(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return Ds(this.multihash.bytes,e.toMultihash().bytes);throw Error("not valid Id")}[Ic](){return`PeerId(${this.toString()})`}},Cc=class extends _c{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},xc=class extends _c{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},kc=class extends _c{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}};class Tc{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ne.digest(Ye(this.url))}[Ic](){return`PeerId(${this.url})`}[En]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return qe.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=tn(e)),e.toString()===this.toString())}}function Pc(e){let t;if("1"!==e.charAt(0)&&"Q"!==e.charAt(0)){if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return Dc(qe.parse(e));throw new Pn('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return t=Le(fe.decode("z"+e)),Lc(t)}function Rc(e){if("Ed25519"===e.type)return new xc({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new kc({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Cc({multihash:e.toCID().multihash,publicKey:e});throw new Qn}function Lc(e){if(function(e){return e.code===Ue.code}(e))return new Cc({multihash:e});if(function(e){return e.code===Ne.code}(e))try{const t=function(e){const{Type:t,Data:r}=Xa.decode(e.digest),n=r??new Uint8Array;switch(t){case Ga.Ed25519:return Va(n);case Ga.secp256k1:return Ec(n);case Ga.ECDSA:return uo(n);default:throw new Qn}}(e);if("Ed25519"===t.type)return new xc({multihash:e,publicKey:t});if("secp256k1"===t.type)return new kc({multihash:e,publicKey:t})}catch(t){const r=tn(e.digest);return new Tc(new URL(r))}throw new zn("Supplied PeerID Multihash is invalid")}function Dc(e){if(null==e?.multihash||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new qn("Supplied PeerID CID is invalid");if(2336===e.code){const t=tn(e.multihash.digest);return new Tc(new URL(t))}return Lc(e.multihash)}class Mc extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"}class Nc extends Error{static name="ValidationError";name="ValidationError"}class Oc extends Error{static name="InvalidParametersError";name="InvalidParametersError"}class Uc extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"}const Fc=new class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){const t=this.index,r=e();return void 0===r&&(this.index=t),r}parseWith(e){const t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically((()=>{const t=this.readChar();if(t===e)return t}))}readSeparator(e,t,r){return this.readAtomically((()=>{if(!(t>0&&void 0===this.readGivenChar(e)))return r()}))}readNumber(e,t,r,n){return this.readAtomically((()=>{let s=0,i=0;const o=this.peekChar();if(void 0===o)return;const a="0"===o,c=2**(8*n)-1;for(;;){const r=this.readAtomically((()=>{const t=this.readChar();if(void 0===t)return;const r=Number.parseInt(t,e);return Number.isNaN(r)?void 0:r}));if(void 0===r)break;if(s*=e,s+=r,s>c)return;if(i+=1,void 0!==t&&i>t)return}return 0===i||!r&&a&&i>1?void 0:s}))}readIPv4Addr(){return this.readAtomically((()=>{const e=new Uint8Array(4);for(let t=0;t<e.length;t++){const r=this.readSeparator(".",t,(()=>this.readNumber(10,3,!1,1)));if(void 0===r)return;e[t]=r}return e}))}readIPv6Addr(){const e=e=>{for(let t=0;t<e.length/2;t++){const r=2*t;if(t<e.length-3){const n=this.readSeparator(":",t,(()=>this.readIPv4Addr()));if(void 0!==n)return e[r]=n[0],e[r+1]=n[1],e[r+2]=n[2],e[r+3]=n[3],[r+4,!0]}const n=this.readSeparator(":",t,(()=>this.readNumber(16,4,!0,2)));if(void 0===n)return[r,!1];e[r]=n>>8,e[r+1]=255&n}return[e.length,!1]};return this.readAtomically((()=>{const t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(n)return;if(void 0===this.readGivenChar(":"))return;if(void 0===this.readGivenChar(":"))return;const s=new Uint8Array(14),i=16-(r+2),[o]=e(s.subarray(0,i));return t.set(s.subarray(0,o),16-o),t}))}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function Bc(e){if(!(e.length>15))return Fc.new(e).parseWith((()=>Fc.readIPv4Addr()))}function $c(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Fc.new(e).parseWith((()=>Fc.readIPv6Addr()))}function qc(e,t=!1){if(e.includes("%")&&(e=e.split("%")[0]),e.length>45)return;const r=Fc.new(e).parseWith((()=>Fc.readIPAddr()));return r?t&&4===r.length?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,r[0],r[1],r[2],r[3]]):r:void 0}function zc(e){return!!Bc(e)}function jc(e){return!!$c(e)}const Kc=41,Vc=42;function Hc(e){return t=>tn(t,e)}function Gc(e){return t=>Ye(t,e)}function Wc(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function Xc(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function Zc(e){const t=e.subarray(0,e.length-2),r=e.subarray(e.length-2);return`${tn(t,"base32")}:${Wc(r)}`}const Yc=e=>{e=e.toString().trim();const t=new Uint8Array(4);return e.split(/\./g).forEach(((e,r)=>{const n=parseInt(e,10);if(isNaN(n)||n<0||n>255)throw new Mc("Invalid byte value in IP address");t[r]=n})),t},Qc=Object.values(He).map((e=>e.decoder)),Jc=(()=>{let e=Qc[0].or(Qc[1]);return Qc.slice(2).forEach((t=>e=e.or(t))),e})(),el=function(...e){return t=>{for(const r of e)r(t)}}((function(e){if(parseInt(e).toString()!==e)throw new Nc("Value must be an integer")}),(function(e){if(e<0)throw new Nc("Value must be a positive integer, or zero")}),(e=>{if(e>65535)throw new Nc("Value must be smaller than or equal to 65535")})),tl=-1,rl=new class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(t="string"==typeof e?this.protocolsByName.get(e):this.protocolsByCode.get(e),null==t)throw new Uc(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach((t=>{this.protocolsByName.set(t,e)}))}removeProtocol(e){const t=this.protocolsByCode.get(e);null!=t&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach((e=>{this.protocolsByName.delete(e)})))}},nl=[{code:4,name:"ip4",size:32,valueToBytes:Yc,bytesToValue(e){if(4!==e.byteLength)throw new Mc("IPv4 address was incorrect length");const t=[];for(let r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},validate(e){if(!zc(e))throw new Nc(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Xc,bytesToValue:Wc,validate:el},{code:273,name:"udp",size:16,valueToBytes:Xc,bytesToValue:Wc,validate:el},{code:33,name:"dccp",size:16,valueToBytes:Xc,bytesToValue:Wc,validate:el},{code:Kc,name:"ip6",size:128,valueToBytes(e){let t=0;const r=(e=e.toString().trim()).split(":",8);let n;for(n=0;n<r.length;n++){let e;zc(r[n])&&(e=Yc(r[n]),r[n]=tn(e.subarray(0,2),"base16")),null!=e&&++n<8&&r.splice(n,0,tn(e.subarray(2,4),"base16"))}if(""===r[0])for(;r.length<8;)r.unshift("0");else if(""===r[r.length-1])for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&""!==r[n];n++);const e=[n,1];for(n=9-r.length;n>0;n--)e.push("0");r.splice.apply(r,e)}const s=new Uint8Array(t+16);for(n=0;n<r.length;n++){""===r[n]&&(r[n]="0");const e=parseInt(r[n],16);if(isNaN(e)||e<0||e>65535)throw new Mc("Invalid byte value in IP address");s[t++]=e>>8&255,s[t++]=255&e}return s},bytesToValue(e){if(16!==e.byteLength)throw new Mc("IPv6 address was incorrect length");const t=[];for(let r=0;r<e.byteLength;r+=2){const n=e[r],s=e[r+1],i=`${n.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}const r=t.join(":");try{const e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Mc(`Invalid IPv6 address "${r}"`)}},stringToValue(e){try{const t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new Mc(`Invalid IPv6 address "${e}"`)}},validate(e){if(!jc(e))throw new Nc(`Invalid IPv6 address "${e}"`)}},{code:Vc,name:"ip6zone",size:tl},{code:43,name:"ipcidr",size:8,bytesToValue:Hc("base10"),valueToBytes:Gc("base10")},{code:53,name:"dns",size:tl,resolvable:!0},{code:54,name:"dns4",size:tl,resolvable:!0},{code:55,name:"dns6",size:tl,resolvable:!0},{code:56,name:"dnsaddr",size:tl,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Xc,bytesToValue:Wc,validate:el},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:tl,path:!0,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:tl,bytesToValue:Hc("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?Gc("base58btc")(e):qe.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Zc,valueToBytes(e){const t=e.split(":");if(2!==t.length)throw Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(16!==t[0].length)throw Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);const r=Ye(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw Error("Port number is not in range(1, 65536)");const s=Xc(n);return Ls([r,s],r.length+s.length)}},{code:445,name:"onion3",size:296,bytesToValue:Zc,valueToBytes(e){const t=e.split(":");if(2!==t.length)throw Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(56!==t[0].length)throw Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);const r=te.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw Error("Port number is not in range(1, 65536)");const s=Xc(n);return Ls([r,s],r.length+s.length)}},{code:446,name:"garlic64",size:tl},{code:447,name:"garlic32",size:tl},{code:448,name:"tls"},{code:449,name:"sni",size:tl},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:tl,bytesToValue:function(e){return t=>e.encoder.encode(t)}(we),valueToBytes:e=>Jc.decode(e)},{code:480,name:"http"},{code:481,name:"http-path",size:tl,stringToValue:e=>"/"+decodeURIComponent(e),valueToString:e=>encodeURIComponent(e.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:tl}];function sl(e,t,r){return null==e.size||0===e.size?0:e.size>0?e.size/8:b(t,r)}nl.forEach((e=>{rl.addProtocol(e)}));const il=Symbol.for("nodejs.util.inspect.custom"),ol=Symbol.for("@multiformats/multiaddr"),al=[53,54,55,56];class cl extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}}class ll{[ol]=!0;#t;#r;#n;constructor(e="/",t={}){this.#t=function(e){if(null==e&&(e="/"),yl(e))return e.getComponents();if(e instanceof Uint8Array)return function(e){const t=[];let r=0;for(;r<e.length;){const n=b(e,r),s=rl.getProtocol(n),i=f(n),o=sl(s,e,r+i);let a=0;o>0&&s.size===tl&&(a=f(o));const c=i+a+o,l={code:n,name:s.name,bytes:e.subarray(r,r+c)};if(o>0){const t=r+i+a,n=e.subarray(t,t+o);l.value=s.bytesToValue?.(n)??tn(n)}t.push(l),r+=c}return t}(e);if("string"==typeof e)return""===(e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""))&&(e="/"),function(e){if("/"!==e.charAt(0))throw new Mc('String multiaddr must start with "/"');const t=[];let r="protocol",n="",s="";for(let i=1;i<e.length;i++){const o=e.charAt(i);"/"!==o&&("protocol"===r?s+=e.charAt(i):n+=e.charAt(i));const a=i===e.length-1;if("/"===o||a){const e=rl.getProtocol(s);if("protocol"===r){if(null==e.size||0===e.size){t.push({code:e.code,name:e.name}),n="",s="",r="protocol";continue}if(a)throw new Mc(`Component ${s} was missing value`);r="value"}else if("value"===r){const i={code:e.code,name:e.name};if(null!=e.size&&0!==e.size){if(""===n)throw new Mc(`Component ${s} was missing value`);i.value=e.stringToValue?.(n)??n}t.push(i),n="",s="",r="protocol"}}}if(""!==s&&""!==n)throw new Mc("Incomplete multiaddr");return t}(e);if(Array.isArray(e))return e;throw new Mc("Must be a string, Uint8Array, Component[], or another Multiaddr")}(e),!1!==t.validate&&function(e){e.getComponents().forEach((e=>{const t=rl.getProtocol(e.code);null!=e.value&&t.validate?.(e.value)}))}(this)}get bytes(){return null==this.#n&&(this.#n=function(e){let t=0;const r=[];for(const n of e){if(null==n.bytes){const e=rl.getProtocol(n.code),t=f(n.code);let r,s=0,i=0;null!=n.value&&(r=e.valueToBytes?.(n.value)??Ye(n.value),s=r.byteLength,e.size===tl&&(i=f(s)));const o=new Uint8Array(t+i+s);let a=0;g(n.code,o,a),a+=t,null!=r&&(e.size===tl&&(g(s,o,a),a+=i),o.set(r,a)),n.bytes=o}r.push(n.bytes),t+=n.bytes.byteLength}return Ls(r,t)}(this.#t)),this.#n}toString(){return null==this.#r&&(this.#r="/"+this.#t.flatMap((e=>{if(null==e.value)return e.name;const t=rl.getProtocol(e.code);if(null==t)throw new Mc("Unknown protocol code "+e.code);return[e.name,t.valueToString?.(e.value)??e.value]})).join("/")),this.#r}toJSON(){return this.toString()}toOptions(){let e,t,r,n,s="";for(const{code:i,name:o,value:a}of this.#t)i===Vc&&(s="%"+(a??"")),al.includes(i)&&(t="tcp",n=443,r=`${a??""}${s}`,e=55===i?6:4),6!==i&&273!==i||(t="tcp"===o?"tcp":"udp",n=parseInt(a??"")),4!==i&&i!==Kc||(t="tcp",r=`${a??""}${s}`,e=i===Kc?6:4);if(null==e||null==t||null==r||null==n)throw Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:r,transport:t,port:n}}getComponents(){return[...this.#t]}protos(){return this.#t.map((({code:e,value:t})=>{const r=rl.getProtocol(e);return{code:e,size:r.size??0,name:r.name,resolvable:!!r.resolvable,path:!!r.path}}))}protoCodes(){return this.#t.map((({code:e})=>e))}protoNames(){return this.#t.map((({name:e})=>e))}tuples(){return this.#t.map((({code:e,value:t})=>{if(null==t)return[e];const r=rl.getProtocol(e),n=[e];return null!=t&&n.push(r.valueToBytes?.(t)??Ye(t)),n}))}stringTuples(){return this.#t.map((({code:e,value:t})=>null==t?[e]:[e,t]))}encapsulate(e){const t=new ll(e);return new ll([...this.#t,...t.getComponents()],{validate:!1})}decapsulate(e){const t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw new Oc(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new ll(r.slice(0,n),{validate:!1})}decapsulateCode(e){let t;for(let r=this.#t.length-1;r>-1;r--)if(this.#t[r].code===e){t=r;break}return new ll(this.#t.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#t.forEach((({code:t,value:r})=>{421===t&&e.push([t,r]),290===t&&(e=[])}));const t=e.pop();if(null!=t?.[1]){const e=t[1];return"Q"===e[0]||"1"===e[0]?tn(fe.decode("z"+e),"base58btc"):tn(qe.parse(e).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){for(const e of this.#t)if(rl.getProtocol(e.code).path)return e.value??null;return null}equals(e){return Ds(this.bytes,e.bytes)}async resolve(e){const t=this.protos().find((e=>e.resolvable));if(null==t)return[this];const r=ml.get(t.name);if(null==r)throw new cl("no available resolver for "+t.name);return(await r(this,e)).map((e=>bl(e)))}nodeAddress(){const e=this.toOptions();if("tcp"!==e.transport&&"udp"!==e.transport)throw Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return!(2!==this.#t.length||4!==this.#t[0].code&&this.#t[0].code!==Kc||6!==this.#t[1].code&&273!==this.#t[1].code)}[il](){return`Multiaddr(${this.toString()})`}}const ul=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function hl(e,t){16===t.length&&4===e.length&&function(e,t,r){let n=0;for(const t of e)if(!(n<0)){if(n>11)break;if(255!==t)return!1;n++}return!0}(t)&&(t=t.slice(12)),4===t.length&&16===e.length&&function(e,t,r,n){let s=0;for(const r of e)if(!(s<0)){if(s>11)break;if(r!==t[s])return!1;s++}return!0}(e,ul)&&(e=e.slice(12));const r=e.length;if(r!=t.length)throw Error("Failed to mask ip");const n=new Uint8Array(r);for(let s=0;s<r;s++)n[s]=e[s]&t[s];return n}function dl(e,t){if(32!==t&&128!==t)throw Error("Invalid CIDR mask");if(e<0||e>t)throw Error("Invalid CIDR mask");const r=t/8,n=new Uint8Array(r);for(let t=0;t<r;t++)e>=8?(n[t]=255,e-=8):(n[t]=255-(255>>e),e=0);return n}class pl{constructor(e,t){if(null==t)({network:this.network,mask:this.mask}=function(e){const[t,r]=e.split("/");if(!t||!r)throw Error("Failed to parse given CIDR: "+e);let n=4,s=Bc(t);if(null==s&&(n=16,s=$c(t),null==s))throw Error("Failed to parse given CIDR: "+e);const i=parseInt(r,10);if(Number.isNaN(i)||(i+"").length!==r.length||i<0||i>8*n)throw Error("Failed to parse given CIDR: "+e);const o=dl(i,8*n);return{network:hl(s,o),mask:o}}(e));else{const r=qc(e);if(null==r)throw Error("Failed to parse network");const n=parseInt(t+="",10);if(Number.isNaN(n)||(n+"").length!==t.length||n<0||n>8*r.length){const e=qc(t);if(null==e)throw Error("Failed to parse mask");this.mask=e}else this.mask=dl(n,8*r.length);this.network=hl(r,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=qc(t)),null==t)throw Error("Invalid ip");if(t.length!==e.network.length)return!1;for(let r=0;r<t.length;r++)if((e.network[r]&e.mask[r])!=(t[r]&e.mask[r]))return!1;return!0}({network:this.network,mask:this.mask},e)}toString(){const e=function(e){let t=0;for(let[r,n]of e.entries()){if(255!==n){for(;128&n;)t++,n<<=1;if(128&n)return-1;for(let t=r+1;t<e.length;t++)if(0!=e[t])return-1;break}t+=8}return t}(this.mask),t=-1!==e?e+"":function(e){let t="0x";for(const r of e)t+=(r>>4).toString(16)+(15&r).toString(16);return t}(this.mask);return function(e){switch(e.length){case 4:return e.join(".");case 16:{const t=[];for(let r=0;r<e.length;r++)r%2==0&&t.push(e[r].toString(16).padStart(2,"0")+e[r+1].toString(16).padStart(2,"0"));return t.join(":")}default:throw Error("Invalid ip length")}}(this.network)+"/"+t}}function fl(e,t){return rl.getProtocol(e).bytesToValue?.(t)??tn(t,"base16")}function gl(e,t){return rl.getProtocol(e).valueToBytes?.(t)??Ye(t,"base16")}const ml=new Map;function yl(e){return!!e?.[ol]}function bl(e){return new ll(e)}function wl(e){const t=rl.getProtocol(e);return{code:t.code,size:t.size??0,name:t.name,resolvable:!!t.resolvable,path:!!t.path}}const vl=e=>{if(!e)return-1;try{const t=e.metadata.get("ping");return t?Number(on(t)):-1}catch(e){return-1}},El=new fs("connection-limiter");class Sl{libp2p;events;networkMonitor;dialer;connectionMonitorInterval=null;options;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.networkMonitor=e.networkMonitor,this.dialer=e.dialer,this.options=e.options,this.onWakuConnectionEvent=this.onWakuConnectionEvent.bind(this),this.onDisconnectedEvent=this.onDisconnectedEvent.bind(this)}start(){this.dialPeersFromStore(),this.options.enableAutoRecovery&&null===this.connectionMonitorInterval&&(this.connectionMonitorInterval=setInterval((()=>{this.maintainConnections()}),5e3)),this.events.addEventListener(Cs.Connection,this.onWakuConnectionEvent),this.libp2p.addEventListener("peer:disconnect",this.onDisconnectedEvent)}stop(){this.events.removeEventListener(Cs.Connection,this.onWakuConnectionEvent),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnectedEvent),this.connectionMonitorInterval&&(clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=null)}onWakuConnectionEvent(){this.options.enableAutoRecovery?this.networkMonitor.isBrowserConnected()&&this.dialPeersFromStore():El.info("Auto recovery is disabled, skipping")}async maintainConnections(){await this.maintainConnectionsCount(),await this.maintainBootstrapConnections(),await this.maintainTTLConnectedPeers()}async onDisconnectedEvent(){0===this.libp2p.getConnections().length&&(El.info("No connections, dialing peers from store"),await this.dialPeersFromStore())}async maintainConnectionsCount(){El.info("Maintaining connections count");const e=this.libp2p.getConnections();if(e.length<=this.options.maxConnections){El.info(`Node has less than max connections ${this.options.maxConnections}, trying to dial more peers`);const t=await this.getPrioritizedPeers();if(0===t.length)return El.info("No peers to dial, skipping"),void await this.triggerBootstrap();const r=t.slice(0,this.options.maxConnections-e.length).map((e=>this.dialer.dial(e.id)));await Promise.all(r)}else{El.info(`Node has more than max connections ${this.options.maxConnections}, dropping connections`);try{const t=e.filter((e=>!e.tags.includes(ks))).slice(this.options.maxConnections);if(0===t.length)return void El.info("No connections to drop, skipping");const r=t.map((e=>this.libp2p.hangUp(e.remotePeer)));await Promise.all(r),El.info(`Dropped ${t.length} connections`)}catch(e){El.error("Unexpected error while maintaining connections",e)}}}async maintainBootstrapConnections(){El.info("Maintaining bootstrap connections");const e=await this.getBootstrapPeers();if(!(e.length<=this.options.maxBootstrapPeers))try{const t=e.slice(this.options.maxBootstrapPeers);El.info(`Dropping ${t.length} bootstrap connections because node has more than max bootstrap connections ${this.options.maxBootstrapPeers}`);const r=t.map((e=>this.libp2p.hangUp(e.id)));await Promise.all(r),El.info(`Dropped ${t.length} bootstrap connections`)}catch(e){El.error("Unexpected error while maintaining bootstrap connections",e)}}async maintainTTLConnectedPeers(){El.info("Maintaining TTL connected peers");const e=this.libp2p.getConnections().map((async e=>{try{await this.libp2p.peerStore.merge(e.remotePeer,{metadata:{ttl:nn(Date.now())}}),El.info("TTL updated for connected peer "+e.remotePeer.toString())}catch(e){El.error("Unexpected error while maintaining TTL connected peer",e)}}));await Promise.all(e)}async dialPeersFromStore(){El.info("Dialing peers from store");try{const e=await this.getPrioritizedPeers();if(0===e.length)return El.info("No peers to dial, skipping"),void await this.triggerBootstrap();const t=e.map((e=>this.dialer.dial(e.id)));El.info(`Dialing ${e.length} peers from store`),await Promise.all(t),El.info(`Dialed ${t.length} peers from store`)}catch(e){El.error("Unexpected error while dialing peer store peers",e)}}async getPrioritizedPeers(){const e=await this.libp2p.peerStore.all(),t=this.libp2p.getConnections();El.info(`Found ${e.length} peers in store, and found ${t.length} connections`);const r=e.filter((e=>!t.some((t=>t.remotePeer.equals(e.id)))&&((e,t)=>{const r=e?.components?.transportManager?.getTransports()||[];return 0!==r.length&&r.map((e=>e.dialFilter(t))).some((e=>e.length>0))})(this.libp2p,e.addresses.map((e=>e.multiaddr)))));return[...r.filter((e=>e.tags.has(xs.BOOTSTRAP))),...r.filter((e=>e.tags.has(xs.PEER_EXCHANGE))),...r.filter((e=>e.tags.has(xs.PEER_CACHE))),...r.filter((e=>!e.tags.has(xs.BOOTSTRAP)&&!e.tags.has(xs.PEER_EXCHANGE)&&!e.tags.has(xs.PEER_CACHE)))]}async getBootstrapPeers(){return(await Promise.all(this.libp2p.getConnections().map((e=>e.remotePeer)).map((e=>this.getPeer(e))))).filter((e=>e&&e.tags.has(xs.BOOTSTRAP)))}async getPeer(e){try{return await this.libp2p.peerStore.get(e)}catch(t){return El.error(`Failed to get peer ${e}, error: ${t}`),null}}async triggerBootstrap(){El.info("Triggering bootstrap discovery");const e=Object.values(this.libp2p.components.components).filter((e=>!!e)).filter((e=>["@waku/"+xs.BOOTSTRAP,"@waku/"+xs.PEER_CACHE].includes(e?.[Symbol.toStringTag])));if(0===e.length)return void El.warn("No bootstrap components found to trigger");El.info(`Found ${e.length} bootstrap components, starting them`);const t=e.map((async e=>{try{await(e?.stop?.()),await(e?.start?.()),El.info("Successfully started bootstrap component")}catch(e){El.error("Failed to start bootstrap component",e)}}));await Promise.all(t)}}const Al=new fs("dialer");class Il{libp2p;shardReader;options;dialingQueue=[];dialHistory=new Map;failedDials=new Map;dialingInterval=null;isProcessing=!1;isImmediateDialing=!1;constructor(e){this.libp2p=e.libp2p,this.shardReader=e.shardReader,this.options=e.options}start(){Al.info("Starting dialer"),this.dialingInterval||(this.dialingInterval=setInterval((()=>{this.processQueue()}),500)),this.dialHistory.clear(),this.failedDials.clear()}stop(){Al.info("Stopping dialer"),this.dialingInterval&&(clearInterval(this.dialingInterval),this.dialingInterval=null),this.dialHistory.clear(),this.failedDials.clear()}async dial(e){if(await this.shouldSkipPeer(e))return void Al.info("Skipping peer: "+e);const t=0===this.dialingQueue.length,r=!this.isProcessing&&!this.isImmediateDialing;t&&r?(this.isImmediateDialing=!0,Al.info("Dialed peer immediately"),await this.dialPeer(e),this.isImmediateDialing=!1,Al.info("Released immediate dial lock")):(this.dialingQueue.push(e),Al.info("Added peer to dialing queue, queue size: "+this.dialingQueue.length))}async processQueue(){if(0!==this.dialingQueue.length&&!this.isProcessing){this.isProcessing=!0;try{const e=this.dialingQueue.slice(0,this.options.maxDialingPeers);this.dialingQueue=this.dialingQueue.slice(e.length),Al.info(`Processing dial queue: dialing ${e.length} peers, ${this.dialingQueue.length} remaining in queue`),await Promise.all(e.map((e=>this.dialPeer(e))))}finally{this.isProcessing=!1}}}async dialPeer(e){try{Al.info("Dialing peer from queue: "+e),await this.libp2p.dial(e),this.dialHistory.set(e.toString(),Date.now()),this.failedDials.delete(e.toString()),Al.info("Successfully dialed peer from queue: "+e)}catch(t){Al.error("Error dialing peer "+e,t),this.failedDials.set(e.toString(),Date.now())}}async shouldSkipPeer(e){if(this.libp2p.getPeers().some((t=>t.equals(e))))return Al.info(`Skipping peer ${e} - already connected`),!0;if(this.isRecentlyDialed(e))return Al.info(`Skipping peer ${e} - already dialed in the last 10 seconds`),!0;if(this.isRecentlyFailed(e))return Al.info(`Skipping peer ${e} - recently failed to dial`),!0;try{return await this.shardReader.hasShardInfo(e)?!await this.shardReader.isPeerOnCluster(e)&&(Al.info(`Skipping peer ${e} - not on same cluster`),!0):(Al.info(`Skipping peer ${e} - no shard info`),!1)}catch(t){return Al.error("Error checking shard info for peer "+e,t),!0}}isRecentlyDialed(e){const t=this.dialHistory.get(e.toString());return!!(t&&Date.now()-t<1e3*this.options.dialCooldown)}isRecentlyFailed(e){const t=this.failedDials.get(e.toString());return!!(t&&Date.now()-t<1e3*this.options.failedDialCooldown)}}const _l=new fs("discovery-dialer");class Cl{libp2p;dialer;constructor(e){this.libp2p=e.libp2p,this.dialer=e.dialer,this.onPeerDiscovery=this.onPeerDiscovery.bind(this)}start(){this.libp2p.addEventListener("peer:discovery",this.onPeerDiscovery)}stop(){this.libp2p.removeEventListener("peer:discovery",this.onPeerDiscovery)}async onPeerDiscovery(e){const t=e.detail.id;_l.info("Discovered new peer: "+t);try{await this.updatePeerStore(t,e.detail.multiaddrs),await this.dialer.dial(t)}catch(e){_l.error("Error dialing peer "+t,e)}}async updatePeerStore(e,t){try{_l.info("Updating peer store for "+e);const r=await this.getPeer(e);if(!r)return _l.info(`Peer ${e} not found in store, saving`),void await this.libp2p.peerStore.save(e,{multiaddrs:t});if(t.every((e=>r.addresses.some((t=>t.multiaddr.equals(e))))))return void _l.info(`Peer ${e} has same addresses in peer store, skipping`);_l.info(`Merging peer ${e} addresses in peer store`),await this.libp2p.peerStore.merge(e,{multiaddrs:t})}catch(t){_l.error("Error updating peer store for "+e,t)}}async getPeer(e){try{return await this.libp2p.peerStore.get(e)}catch(t){return void _l.error("Error getting peer info for "+e,t)}}}const xl="/relay-ping/1/ping/null",kl=new fs("keep-alive");class Tl{relay;networkConfig;libp2p;options;pingKeepAliveTimers=new Map;relayKeepAliveTimers=new Map;constructor({options:e,relay:t,networkConfig:r,libp2p:n}){this.options=e,this.relay=t,this.networkConfig=r,this.libp2p=n,this.onPeerConnect=this.onPeerConnect.bind(this),this.onPeerDisconnect=this.onPeerDisconnect.bind(this)}start(){this.libp2p.addEventListener("peer:connect",this.onPeerConnect),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnect)}stop(){this.libp2p.removeEventListener("peer:connect",this.onPeerConnect),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnect);for(const e of this.pingKeepAliveTimers.values())clearInterval(e);for(const e of this.relayKeepAliveTimers.values())for(const t of e)clearInterval(t);this.pingKeepAliveTimers.clear(),this.relayKeepAliveTimers.clear()}onPeerConnect(e){const t=e.detail;this.startPingForPeer(t)}onPeerDisconnect(e){const t=e.detail;this.stopPingForPeer(t)}startPingForPeer(e){this.stopPingForPeer(e),this.startLibp2pPing(e),this.startRelayPing(e)}stopPingForPeer(e){this.stopLibp2pPing(e),this.stopRelayPing(e)}startLibp2pPing(e){if(0===this.options.pingKeepAlive)return void kl.warn(`Ping keep alive is disabled pingKeepAlive:${this.options.pingKeepAlive}, skipping start for libp2p ping`);const t=e.toString();if(this.pingKeepAliveTimers.has(t))return void kl.warn(`Ping already started for peer: ${t}, skipping start for libp2p ping`);const r=setInterval((()=>{this.pingLibp2p(e)}),1e3*this.options.pingKeepAlive);this.pingKeepAliveTimers.set(t,r)}stopLibp2pPing(e){const t=e.toString();this.pingKeepAliveTimers.has(t)?(clearInterval(this.pingKeepAliveTimers.get(t)),this.pingKeepAliveTimers.delete(t)):kl.warn(`Ping not started for peer: ${t}, skipping stop for ping`)}startRelayPing(e){if(!this.relay)return;if(0===this.options.relayKeepAlive)return void kl.warn(`Relay keep alive is disabled relayKeepAlive:${this.options.relayKeepAlive}, skipping start for relay ping`);if(this.relayKeepAliveTimers.has(e.toString()))return void kl.warn(`Relay ping already started for peer: ${e.toString()}, skipping start for relay ping`);const t=[];for(const r of this.relay.pubsubTopics){if(!this.relay.getMeshPeers(r).includes(e.toString())){kl.warn(`Peer: ${e.toString()} is not in the mesh for topic: ${r}, skipping start for relay ping`);continue}const n=vs({routingInfo:gn(this.networkConfig,{contentTopic:xl,pubsubTopic:r}),contentTopic:xl,ephemeral:!0}),s=setInterval((()=>{this.pingRelay(n)}),1e3*this.options.relayKeepAlive);t.push(s)}this.relayKeepAliveTimers.set(e.toString(),t)}stopRelayPing(e){if(!this.relay)return;const t=e.toString();this.relayKeepAliveTimers.has(t)?(this.relayKeepAliveTimers.get(t)?.map(clearInterval),this.relayKeepAliveTimers.delete(t)):kl.warn(`Relay ping not started for peer: ${t}, skipping stop for relay ping`)}async pingRelay(e){try{kl.info("Sending Waku Relay ping message"),await this.relay.send(e,{payload:new Uint8Array([1])})}catch(e){kl.error("Failed to send relay ping",e)}}async pingLibp2p(e){try{kl.info(`Pinging libp2p peer (${e.toString()})`);const t=await this.libp2p.services.ping.ping(e);kl.info(`Ping succeeded (${e.toString()})`,t),await this.libp2p.peerStore.merge(e,{metadata:{ping:an(t.toString())}}),kl.info(`Ping updated for peer (${e.toString()})`)}catch(t){kl.error(`Ping failed for peer (${e.toString()})`,t)}}}class Pl{libp2p;events;isNetworkConnected=!1;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.onConnectedEvent=this.onConnectedEvent.bind(this),this.onDisconnectedEvent=this.onDisconnectedEvent.bind(this),this.dispatchNetworkEvent=this.dispatchNetworkEvent.bind(this)}start(){this.libp2p.addEventListener("peer:connect",this.onConnectedEvent),this.libp2p.addEventListener("peer:disconnect",this.onDisconnectedEvent);try{globalThis.addEventListener("online",this.dispatchNetworkEvent),globalThis.addEventListener("offline",this.dispatchNetworkEvent)}catch(e){}}stop(){this.libp2p.removeEventListener("peer:connect",this.onConnectedEvent),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnectedEvent);try{globalThis.removeEventListener("online",this.dispatchNetworkEvent),globalThis.removeEventListener("offline",this.dispatchNetworkEvent)}catch(e){}}isConnected(){return!!this.isBrowserConnected()&&this.isP2PConnected()}isP2PConnected(){return this.isNetworkConnected}isBrowserConnected(){try{if(globalThis?.navigator&&!globalThis?.navigator?.onLine)return!1}catch(e){}return!0}onConnectedEvent(){this.isNetworkConnected||(this.isNetworkConnected=!0,this.dispatchNetworkEvent())}onDisconnectedEvent(){this.isNetworkConnected&&0===this.libp2p.getConnections().length&&(this.isNetworkConnected=!1,this.dispatchNetworkEvent())}dispatchNetworkEvent(){this.events.dispatchEvent(new CustomEvent(Cs.Connection,{detail:this.isConnected()}))}}const Rl=new fs("shard-reader");class Ll{libp2p;clusterId;constructor(e){this.libp2p=e.libp2p,this.clusterId=e.networkConfig.clusterId}async isPeerOnCluster(e){const t=await this.getRelayShards(e);return!!t&&t.clusterId===this.clusterId}async hasShardInfo(e){return!!await this.getRelayShards(e)}async isPeerOnTopic(e,t){try{const{clusterId:r,shard:n}=un(t);return r===this.clusterId&&await this.isPeerOnShard(e,n)}catch(r){return Rl.error(`Error comparing pubsub topic ${t} with shard info for ${e}`,r),!1}}async isPeerOnShard(e,t){const r=await this.getRelayShards(e);return Rl.info(`Checking if peer on same shard: this { clusterId: ${this.clusterId}, shardId: ${t} },${e} { clusterId: ${r?.clusterId}, shards: ${r?.shards} }`),!!r&&r.clusterId===this.clusterId&&r.shards.includes(t)}async getRelayShards(e){try{const t=(await this.libp2p.peerStore.get(e)).metadata.get("shardInfo");if(!t)return;return mn(t)}catch(t){return void Rl.error("Error getting shard info for "+e,t)}}}const Dl=new fs("connection-manager");class Ml{keepAliveManager;discoveryDialer;dialer;shardReader;networkMonitor;connectionLimiter;options;libp2p;constructor(e){this.libp2p=e.libp2p,this.options={maxBootstrapPeers:3,maxConnections:10,pingKeepAlive:300,relayKeepAlive:300,enableAutoRecovery:!0,maxDialingPeers:3,failedDialCooldown:60,dialCooldown:10,...e.config},this.keepAliveManager=new Tl({relay:e.relay,libp2p:e.libp2p,networkConfig:e.networkConfig,options:{pingKeepAlive:this.options.pingKeepAlive,relayKeepAlive:this.options.relayKeepAlive}}),this.shardReader=new Ll({libp2p:e.libp2p,networkConfig:e.networkConfig}),this.dialer=new Il({libp2p:e.libp2p,shardReader:this.shardReader,options:this.options}),this.discoveryDialer=new Cl({libp2p:e.libp2p,dialer:this.dialer}),this.networkMonitor=new Pl({libp2p:e.libp2p,events:e.events}),this.connectionLimiter=new Sl({libp2p:e.libp2p,events:e.events,networkMonitor:this.networkMonitor,dialer:this.dialer,options:this.options})}start(){this.dialer.start(),this.networkMonitor.start(),this.discoveryDialer.start(),this.keepAliveManager.start(),this.connectionLimiter.start()}stop(){this.dialer.stop(),this.networkMonitor.stop(),this.discoveryDialer.stop(),this.keepAliveManager.stop(),this.connectionLimiter.stop()}isConnected(){return this.networkMonitor.isConnected()}async dial(e,t){const r=Sn(n=e)?n:bl(n);var n;Dl.info(`Dialing peer ${r.toString()} with protocols ${t}`);const s=await this.libp2p.dialProtocol(r,t);return Dl.info(`Dialed peer ${r.toString()} with protocols ${t}`),s}async hangUp(e){const t=Sn(r=e)?r:Pc(bl(r).getPeerId());var r;try{return Dl.info("Dropping connection with peer "+t.toString()),await this.libp2p.hangUp(t),Dl.info("Dropped connection with peer "+t.toString()),!0}catch(e){return Dl.error(`Error dropping connection with peer ${t.toString()} - ${e}`),!1}}async getConnectedPeers(e){const t=this.libp2p.getPeers();if(Dl.info("Getting connected peers for codec "+e),0===t.length)return Dl.info("No connected peers"),[];const r=(await Promise.all(t.map((async e=>{try{return await this.libp2p.peerStore.get(e)}catch(e){return null}})))).filter((e=>!!e)).filter((t=>!e||t.protocols.includes(e))).sort(((e,t)=>vl(e)-vl(t)));return Dl.info(`Found ${r.length} connected peers for codec ${e}`),r}async hasShardInfo(e){return this.shardReader.hasShardInfo(e)}async isPeerOnTopic(e,t){return this.shardReader.isPeerOnTopic(e,t)}async isPeerOnShard(e,t){return this.shardReader.isPeerOnShard(e,t)}}const Nl=new fs("metadata"),Ol="/vac/waku/metadata/1.0.0";class Ul{clusterId;streamManager;libp2pComponents;handshakesConfirmed=new Map;multicodec=Ol;constructor(e,t){this.clusterId=e,this.streamManager=new di(Ol,t),this.libp2pComponents=t,t.registrar.handle(Ol,(e=>{this.onRequest(e)}))}async query(e){const t=zt.encode({clusterId:this.clusterId,shards:[]});if(!await this.libp2pComponents.peerStore.get(e))return{shardInfo:null,error:_s.NO_PEER_AVAILABLE};const r=await this.streamManager.getStream(e);if(!r)return Nl.error("Failed to get a stream for remote peer:"+e.toString()),{shardInfo:null,error:_s.NO_STREAM_AVAILABLE};const n=await si([t],$s,r,Gs,(async e=>await Rs(e))),{error:s,shardInfo:i}=this.decodeMetadataResponse(n);return s?{shardInfo:null,error:s}:(await this.savePeerShardInfo(e,i),{shardInfo:i,error:null})}async confirmOrAttemptHandshake(e){const t=this.handshakesConfirmed.get(e.toString());return t?{shardInfo:t,error:null}:await this.query(e)}async onRequest(e){try{const{stream:t,connection:r}=e,n=jt.encode({clusterId:this.clusterId,shards:[]}),s=await si([n],$s,t,Gs,(async e=>await Rs(e))),{error:i,shardInfo:o}=this.decodeMetadataResponse(s);if(i)return;await this.savePeerShardInfo(r.remotePeer,o)}catch(e){Nl.error("Error handling metadata request",e)}}decodeMetadataResponse(e){const t=new Us;e.forEach((e=>{t.append(e)}));const r=jt.decode(t);return r?{shardInfo:r,error:null}:(Nl.error("Error decoding metadata response"),{shardInfo:null,error:_s.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:yn(t)}}),this.handshakesConfirmed.set(e.toString(),t)}}function Fl(e){return t=>new Ul(e,t)}const Bl=new fs("peer-manager");var $l;(e=>{e.FilterConnect="filter:connect",e.FilterDisconnect="filter:disconnect",e.StoreConnect="store:connect"})($l||($l={}));class ql{events=new Jn;numPeersToUse;libp2p;connectionManager;lockedPeers=new Set;unlockedPeers=new Map;constructor(e){this.onConnected=this.onConnected.bind(this),this.onDisconnected=this.onDisconnected.bind(this),this.numPeersToUse=e?.config?.numPeersToUse||2,this.libp2p=e.libp2p,this.connectionManager=e.connectionManager}start(){this.libp2p.addEventListener("peer:identify",this.onConnected),this.libp2p.addEventListener("peer:disconnect",this.onDisconnected)}stop(){this.libp2p.removeEventListener("peer:identify",this.onConnected),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnected)}async getPeers(e){Bl.info(`Getting peers for protocol: ${e.protocol}, pubsubTopic: ${e.pubsubTopic}`);const t=await this.connectionManager.getConnectedPeers();Bl.info(`Found ${t.length} connected peers`);let r=[];for(const n of t){const t=this.hasPeerProtocol(n,e.protocol),s=await this.isPeerOnPubsub(n.id,e.pubsubTopic),i=this.isPeerAvailableForUse(n.id);t&&s&&i&&(r.push(n),Bl.info(`Peer ${n.id} qualifies for protocol ${e.protocol}`))}const n=r.filter((e=>this.isPeerLocked(e.id)));if(Bl.info(`Found ${n.length} locked peers out of ${r.length} qualifying peers`),n.length>=this.numPeersToUse){const e=n.slice(0,this.numPeersToUse).map((e=>e.id));return Bl.info(`Using ${e.length} locked peers: ${e.map((e=>e.toString()))}`),e}const s=r.filter((e=>!this.isPeerLocked(e.id)));Bl.info(`Found ${s.length} unlocked peers, need ${this.numPeersToUse-n.length} more`),r=[...n,...s].slice(0,this.numPeersToUse).map((e=>(this.lockPeer(e.id),e)));const i=r.map((e=>e.id));return Bl.info(`Selected ${i.length} peers: ${i.map((e=>e.toString()))}`),i}async renewPeer(e,t){Bl.info(`Renewing peer ${e} for protocol: ${t.protocol}, pubsubTopic: ${t.pubsubTopic}`);const r=(await this.connectionManager.getConnectedPeers()).find((t=>t.id.equals(e)));r?(Bl.info(`Found peer ${e} in connected peers, unlocking and getting new peers`),this.unlockPeer(r.id),await this.getPeers(t)):Bl.warn(`Cannot renew peer:${e}, no connection to the peer.`)}async isPeerOnPubsub(e,t){return!await this.connectionManager.hasShardInfo(e)||this.connectionManager.isPeerOnTopic(e,t)}async onConnected(e){const t=e.detail,r=t.protocols.includes(this.getProtocolCodecs(Ss.Filter)),n=t.protocols.includes(this.getProtocolCodecs(Ss.Store));r&&this.dispatchFilterPeerConnect(t.peerId),n&&this.dispatchStorePeerConnect(t.peerId)}async onDisconnected(e){const t=e.detail;try{const e=await this.libp2p.peerStore.get(t);this.hasPeerProtocol(e,Ss.Filter)&&this.dispatchFilterPeerDisconnect(e.id)}catch(e){Bl.error("Failed to dispatch Filter disconnect event:"+e)}}hasPeerProtocol(e,t){return e.protocols.includes(this.getProtocolCodecs(t))}lockPeer(e){Bl.info("Locking peer "+e),this.lockedPeers.add(e.toString()),this.libp2p.getConnections().filter((t=>t.remotePeer.equals(e))).forEach((e=>e.tags.push(ks))),this.unlockedPeers.delete(e.toString())}isPeerLocked(e){return this.lockedPeers.has(e.toString())}unlockPeer(e){Bl.info("Unlocking peer "+e),this.lockedPeers.delete(e.toString()),this.libp2p.getConnections().filter((t=>t.remotePeer.equals(e))).forEach((e=>{e.tags=e.tags.filter((e=>e!==ks))})),this.unlockedPeers.set(e.toString(),Date.now())}isPeerAvailableForUse(e){const t=this.unlockedPeers.get(e.toString());if(!t)return!0;const r=new Date(t).getTime();return Date.now()-r>=1e4}dispatchFilterPeerConnect(e){this.events.dispatchEvent(new CustomEvent($l.FilterConnect,{detail:e}))}dispatchStorePeerConnect(e){this.events.dispatchEvent(new CustomEvent($l.StoreConnect,{detail:e}))}dispatchFilterPeerDisconnect(e){this.events.dispatchEvent(new CustomEvent($l.FilterDisconnect,{detail:e}))}getProtocolCodecs(e){if(e===Ss.Relay)throw Error("Relay protocol is not supported");return{[Ss.Filter]:Ai,[Ss.LightPush]:Ti,[Ss.Store]:zi,"light-push-v2":ki}[e]}}class zl{ttlMs;cleanupIntervalId=null;entryTimestamps=new Map;constructor(e,t=5e3){this.ttlMs=e,this.startCleanupInterval(t)}dispose(){null!==this.cleanupIntervalId&&(clearInterval(this.cleanupIntervalId),this.cleanupIntervalId=null),this.entryTimestamps.clear()}add(e){return this.entryTimestamps.set(e,Date.now()),this}has(e){return this.entryTimestamps.has(e)}startCleanupInterval(e){this.cleanupIntervalId=setInterval((()=>{this.removeExpiredEntries()}),e)}removeExpiredEntries(){const e=Date.now();for(const[t,r]of this.entryTimestamps.entries())e-r>this.ttlMs&&this.entryTimestamps.delete(t)}}const jl=new fs("sdk:filter-subscription");class Kl{pubsubTopic;protocol;peerManager;config;isStarted=!1;inProgress=!1;peers=new Map;peerFailures=new Map;receivedMessages=new zl(6e4);callbacks=new Map;messageEmitter=new Jn;toSubscribeContentTopics=new Set;toUnsubscribeContentTopics=new Set;subscribeIntervalId=null;keepAliveIntervalId=null;get contentTopics(){const e=Array.from(this.callbacks.keys()).map((e=>e.contentTopic)),t=new Set(e).values();return Array.from(t)}constructor(e){this.config=e.config,this.pubsubTopic=e.pubsubTopic,this.protocol=e.protocol,this.peerManager=e.peerManager,this.onPeerConnected=this.onPeerConnected.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this)}start(){jl.info("Starting subscription for pubsubTopic: "+this.pubsubTopic),this.isStarted||this.inProgress?jl.info("Subscription already started or in progress, skipping start"):(this.inProgress=!0,this.attemptSubscribe({useNewContentTopics:!1}),this.setupSubscriptionInterval(),this.setupKeepAliveInterval(),this.setupEventListeners(),this.isStarted=!0,this.inProgress=!1,jl.info("Subscription started for pubsubTopic: "+this.pubsubTopic))}stop(){jl.info("Stopping subscription for pubsubTopic: "+this.pubsubTopic),this.isStarted&&!this.inProgress?(this.inProgress=!0,this.disposeEventListeners(),this.disposeIntervals(),this.disposePeers(),this.disposeHandlers(),this.receivedMessages.dispose(),this.inProgress=!1,this.isStarted=!1,jl.info("Subscription stopped for pubsubTopic: "+this.pubsubTopic)):jl.info("Subscription not started or stop in progress, skipping stop")}isEmpty(){return 0===this.callbacks.size}async add(e,t){const r=Array.isArray(e)?e:[e];for(const e of r)this.addSingle(e,t);return!(this.toSubscribeContentTopics.size>0)||await this.attemptSubscribe({useNewContentTopics:!0})}async remove(e){const t=Array.isArray(e)?e:[e];for(const e of t)this.removeSingle(e);return!(this.toUnsubscribeContentTopics.size>0)||await this.attemptUnsubscribe({useNewContentTopics:!0})}invoke(e,t){this.isMessageReceived(e)?jl.info(`Skipping invoking callbacks for already received message: pubsubTopic:${this.pubsubTopic}, peerId:${t.toString()}, contentTopic:${e.contentTopic}`):(jl.info("Invoking message for contentTopic: "+e.contentTopic),this.messageEmitter.dispatchEvent(new CustomEvent(e.contentTopic,{detail:e})))}addSingle(e,t){jl.info("Adding subscription for contentTopic: "+e.contentTopic);const r=!this.contentTopics.includes(e.contentTopic);if(r&&this.toSubscribeContentTopics.add(e.contentTopic),this.callbacks.has(e)){jl.warn(`Replacing callback associated associated with decoder with pubsubTopic:${e.pubsubTopic} and contentTopic:${e.contentTopic}`);const t=this.callbacks.get(e);this.callbacks.delete(e),this.messageEmitter.removeEventListener(e.contentTopic,t)}const n=r=>{(async()=>{try{const n=await e.fromProtoObj(e.pubsubTopic,r.detail);t(n)}catch(e){jl.error("Error decoding message",e)}})()};this.callbacks.set(e,n),this.messageEmitter.addEventListener(e.contentTopic,n),jl.info(`Subscription added for contentTopic: ${e.contentTopic}, isNewContentTopic: ${r}`)}removeSingle(e){jl.info("Removing subscription for contentTopic: "+e.contentTopic);const t=this.callbacks.get(e);t||jl.warn(`No callback associated with decoder with pubsubTopic:${e.pubsubTopic} and contentTopic:${e.contentTopic}`),this.callbacks.delete(e),this.messageEmitter.removeEventListener(e.contentTopic,t);const r=!this.contentTopics.includes(e.contentTopic);r&&this.toUnsubscribeContentTopics.add(e.contentTopic),jl.info(`Subscription removed for contentTopic: ${e.contentTopic}, isCompletelyRemoved: ${r}`)}isMessageReceived(e){try{const t=function(e,t){const r=gs(e,t);return sn(r)}(this.pubsubTopic,e);if(this.receivedMessages.has(t))return!0;this.receivedMessages.add(t)}catch(e){}return!1}setupSubscriptionInterval(){jl.info("Setting up subscription interval with period 1000ms"),this.subscribeIntervalId=setInterval((()=>{(async()=>{this.toSubscribeContentTopics.size>0&&(jl.info(`Subscription interval: ${this.toSubscribeContentTopics.size} topics to subscribe`),await this.attemptSubscribe({useNewContentTopics:!0})),this.toUnsubscribeContentTopics.size>0&&(jl.info(`Subscription interval: ${this.toUnsubscribeContentTopics.size} topics to unsubscribe`),await this.attemptUnsubscribe({useNewContentTopics:!0}))})()}),1e3)}setupKeepAliveInterval(){jl.info(`Setting up keep-alive interval with period ${this.config.keepAliveIntervalMs}ms`),this.keepAliveIntervalId=setInterval((()=>{(async()=>{jl.info(`Keep-alive interval running for ${this.peers.size} peers`);let e=await Promise.all(Array.from(this.peers.values()).map((async e=>{if((await this.protocol.ping(e)).success)return jl.info("Ping successful for peer: "+e.toString()),void this.peerFailures.set(e.toString(),0);let t=this.peerFailures.get(e.toString())||0;return t+=1,this.peerFailures.set(e.toString(),t),jl.warn(`Ping failed for peer: ${e.toString()}, failures: ${t}/${this.config.pingsBeforePeerRenewed}`),t<this.config.pingsBeforePeerRenewed?void 0:(jl.info(`Peer ${e.toString()} exceeded max failures (${this.config.pingsBeforePeerRenewed}), will be replaced`),e)})));e=e.filter((e=>!!e)),await Promise.all(e.map((e=>(this.peers.delete(e?.toString()),this.peerFailures.delete(e?.toString()),this.requestUnsubscribe(e,this.contentTopics))))),e.length>0&&(jl.info(`Replacing ${e.length} failed peers`),await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0}))})()}),this.config.keepAliveIntervalMs)}setupEventListeners(){this.peerManager.events.addEventListener($l.FilterConnect,this.onPeerConnected),this.peerManager.events.addEventListener($l.FilterDisconnect,this.onPeerDisconnected)}disposeIntervals(){this.subscribeIntervalId&&clearInterval(this.subscribeIntervalId),this.keepAliveIntervalId&&clearInterval(this.keepAliveIntervalId)}disposeHandlers(){for(const[e,t]of this.callbacks.entries())this.messageEmitter.removeEventListener(e.contentTopic,t);this.callbacks.clear()}async disposePeers(){await this.attemptUnsubscribe({useNewContentTopics:!1}),this.peers.clear(),this.peerFailures=new Map}disposeEventListeners(){this.peerManager.events.removeEventListener($l.FilterConnect,this.onPeerConnected),this.peerManager.events.removeEventListener($l.FilterDisconnect,this.onPeerDisconnected)}async onPeerConnected(e){const t=e.detail?.toString();jl.info("Peer connected: "+t),await this.peerManager.isPeerOnPubsub(e.detail,this.pubsubTopic)?this.peers.has(t)?jl.info(`Peer ${t} already subscribed, skipping`):await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0}):jl.info(`Peer ${t} doesn't support pubsubTopic:${this.pubsubTopic}`)}async onPeerDisconnected(e){const t=e.detail?.toString();jl.info("Peer disconnected: "+t),await this.peerManager.isPeerOnPubsub(e.detail,this.pubsubTopic)?this.peers.has(t)?(jl.info(`Active peer ${t} disconnected, removing from peers list`),this.peers.delete(t),this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0})):jl.info(`Disconnected peer ${t} not in use, ignoring`):jl.info(`Peer ${t} doesn't support pubsubTopic:${this.pubsubTopic}`)}async attemptSubscribe(e){const{useNewContentTopics:t,useOnlyNewPeers:r=!1}=e,n=t?Array.from(this.toSubscribeContentTopics):this.contentTopics;if(jl.info(`Attempting to subscribe: useNewContentTopics=${t}, useOnlyNewPeers=${r}, contentTopics=${n.length}`),!n.length)return jl.warn("Requested content topics is an empty array, skipping"),!1;const s=new Set(this.peers.keys()),i=await this.peerManager.getPeers({protocol:Ss.Filter,pubsubTopic:this.pubsubTopic});for(const e of i){if(this.peers.size>=this.config.numPeersToUse)break;this.peers.set(e.toString(),e)}const o=r?Array.from(this.peers.values()).filter((e=>!s.has(e.toString()))):Array.from(this.peers.values());if(jl.info(`Subscribing with ${o.length} peers for ${n.length} content topics`),r&&0===o.length)return jl.warn("Requested to use only new peers, but no peers found, skipping"),!1;const a=await Promise.all(o.map((e=>this.requestSubscribe(e,n)))),c=a.filter((e=>e)).length;return jl.info(`Subscribe attempts completed: ${c}/${a.length} successful`),t&&(this.toSubscribeContentTopics=new Set),a.some((e=>e))}async requestSubscribe(e,t){if(jl.info(`requestSubscribe: pubsubTopic:${this.pubsubTopic}\tcontentTopics:${t.join(",")}`),!t.length||!this.pubsubTopic)return jl.warn("requestSubscribe: no contentTopics or pubsubTopic provided, not sending subscribe request"),!1;const r=await this.protocol.subscribe(this.pubsubTopic,e,t);return r.failure?(jl.warn(`requestSubscribe: Failed to subscribe ${this.pubsubTopic} to ${e.toString()} with error:${r.failure.error} for contentTopics:${t}`),!1):(jl.info(`requestSubscribe: Subscribed ${this.pubsubTopic} to ${e.toString()} for contentTopics:${t}`),!0)}async attemptUnsubscribe(e){const{useNewContentTopics:t}=e,r=t?Array.from(this.toUnsubscribeContentTopics):this.contentTopics;if(jl.info(`Attempting to unsubscribe: useNewContentTopics=${t}, contentTopics=${r.length}`),!r.length)return jl.warn("Requested content topics is an empty array, skipping"),!1;const n=Array.from(this.peers.values()),s=await Promise.all(n.map((e=>this.requestUnsubscribe(e,t?r:void 0)))),i=s.filter((e=>e)).length;return jl.info(`Unsubscribe attempts completed: ${i}/${s.length} successful`),t&&(this.toUnsubscribeContentTopics=new Set),s.some((e=>e))}async requestUnsubscribe(e,t){const r=t?await this.protocol.unsubscribe(this.pubsubTopic,e,t):await this.protocol.unsubscribeAll(this.pubsubTopic,e);return r.failure?(jl.warn(`requestUnsubscribe: Failed to unsubscribe for pubsubTopic:${this.pubsubTopic} from peerId:${e.toString()} with error:${r.failure?.error} for contentTopics:${t}`),!1):(jl.info(`requestUnsubscribe: Unsubscribed pubsubTopic:${this.pubsubTopic} from peerId:${e.toString()} for contentTopics:${t}`),!0)}}const Vl=new fs("sdk:filter");class Hl{protocol;peerManager;config;subscriptions=new Map;constructor(e){this.config={numPeersToUse:2,pingsBeforePeerRenewed:3,keepAliveIntervalMs:6e4,...e.options},this.peerManager=e.peerManager,this.protocol=new _i(this.onIncomingMessage.bind(this),e.libp2p)}get multicodec(){return this.protocol.multicodec}async start(){await this.protocol.start()}async stop(){await this.protocol.stop()}unsubscribeAll(){for(const e of this.subscriptions.values())e.stop();this.subscriptions.clear()}async subscribe(e,t){const r=Array.isArray(e)?e:[e];if(0===r.length)throw Error("Cannot subscribe with 0 decoders.");const n=r.map((e=>e.pubsubTopic)),s=n[0],i=r.map((e=>e.contentTopic));Vl.info(`Subscribing to contentTopics: ${i}, pubsubTopic: ${s}`),this.throwIfTopicNotSame(n);let o=this.subscriptions.get(s);o||(o=new Kl({pubsubTopic:s,protocol:this.protocol,config:this.config,peerManager:this.peerManager}),o.start());const a=await o.add(r,t);return this.subscriptions.set(s,o),Vl.info(`Subscription ${a?"successful":"failed"} for content topic: ${i}`),a}async unsubscribe(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw Error("Cannot unsubscribe with 0 decoders.");const r=t.map((e=>e.pubsubTopic)),n=r[0],s=t.map((e=>e.contentTopic));Vl.info(`Unsubscribing from contentTopics: ${s}, pubsubTopic: ${n}`),this.throwIfTopicNotSame(r);const i=this.subscriptions.get(n);if(!i)return Vl.warn("No subscriptions associated with the decoder."),!1;const o=await i.remove(t);return i.isEmpty()&&(Vl.warn("Subscription has no decoders anymore, terminating it."),i.stop(),this.subscriptions.delete(n)),Vl.info(`Unsubscribing ${o?"successful":"failed"} for content topic: ${s}`),o}async onIncomingMessage(e,t,r){Vl.info(`Received message for pubsubTopic:${e}, contentTopic:${t.contentTopic}, peerId:${r.toString()}`);const n=this.subscriptions.get(e);n?n.invoke(t,r):Vl.error("No subscription locally registered for topic "+e)}throwIfTopicNotSame(e){const t=e[0];if(!e.every((e=>e===t)))throw Error("Cannot subscribe to more than one pubsub topic at the same time, got pubsubTopics:"+e)}}var Gl,Wl,Xl=function(){if(Wl)return Gl;Wl=1;var e=/^\s+|\s+$/g,t=/^[-+]0x[0-9a-f]+$/i,r=/^0b[01]+$/i,n=/^0o[0-7]+$/i,s=parseInt,i="object"==typeof ns&&ns&&ns.Object===Object&&ns,o="object"==typeof self&&self&&self.Object===Object&&self,a=i||o||Function("return this")(),c=Object.prototype.toString,l=Math.max,u=Math.min,h=()=>a.Date.now();function d(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function p(i){if("number"==typeof i)return i;if(function(e){return"symbol"==typeof e||(e=>!!e&&"object"==typeof e)(e)&&"[object Symbol]"==c.call(e)}(i))return NaN;if(d(i)){var o="function"==typeof i.valueOf?i.valueOf():i;i=d(o)?o+"":o}if("string"!=typeof i)return 0===i?i:+i;i=i.replace(e,"");var a=r.test(i);return a||n.test(i)?s(i.slice(2),a?2:8):t.test(i)?NaN:+i}return Gl=function(e,t,r){var n,s,i,o,a,c,f=0,g=!1,m=!1,y=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function b(t){var r=n,i=s;return n=s=void 0,f=t,o=e.apply(i,r)}function w(e){var r=e-c;return void 0===c||r>=t||r<0||m&&e-f>=i}function v(){var e=h();if(w(e))return E(e);a=setTimeout(v,function(e){var r=t-(e-c);return m?u(r,i-(e-f)):r}(e))}function E(e){return a=void 0,y&&n?b(e):(n=s=void 0,o)}function S(){var e=h(),r=w(e);if(n=arguments,s=this,c=e,r){if(void 0===a)return function(e){return f=e,a=setTimeout(v,t),g?b(e):o}(c);if(m)return a=setTimeout(v,t),b(c)}return void 0===a&&(a=setTimeout(v,t)),o}return t=p(t)||0,d(r)&&(g=!!r.leading,i=(m="maxWait"in r)?l(p(r.maxWait)||0,t):i,y="trailing"in r?!!r.trailing:y),S.cancel=function(){void 0!==a&&clearTimeout(a),f=0,n=c=s=a=void 0},S.flush=function(){return void 0===a?o:E(h())},S},Gl}(),Zl=ss(Xl);const Yl=new fs("health-indicator");class Ql{isStarted=!1;libp2p;events;value=Ps.Unhealthy;debouncedAssessHealth;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.onPeerIdentify=this.onPeerIdentify.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this),this.debouncedAssessHealth=Zl((()=>{this.assessHealth()}),100)}start(){this.isStarted||(this.isStarted=!0,Yl.info("start: adding listeners to libp2p"),this.libp2p.addEventListener("peer:identify",this.onPeerIdentify),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnected),this.debouncedAssessHealth())}stop(){this.isStarted&&(this.isStarted=!1,Yl.info("stop: removing listeners to libp2p"),this.libp2p.removeEventListener("peer:identify",this.onPeerIdentify),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnected),this.debouncedAssessHealth.cancel())}toValue(){return this.value}onPeerDisconnected(e){Yl.info("onPeerDisconnected: received libp2p event"),this.debouncedAssessHealth()}onPeerIdentify(e){Yl.info("onPeerIdentify: received libp2p event"),this.debouncedAssessHealth()}async assessHealth(){const e=this.libp2p.getConnections();if(0===e.length)return Yl.info("assessHealth: no connections, setting to Unhealthy"),void this.updateAndDispatchHealthEvent(Ps.Unhealthy);const t=await Promise.all(e.map((async e=>{try{return await this.libp2p.peerStore.get(e.remotePeer)}catch(t){return Yl.warn(`assessHealth: failed to get peer ${e.remotePeer}, skipping`),null}}))),r=t.filter((e=>e?.protocols.includes(Ai))).length,n=t.filter((e=>e?.protocols.includes(Ti))).length;let s;0===r||0===n?s=Ps.Unhealthy:r>=2&&n>=2?s=Ps.SufficientlyHealthy:1===r&&1===n?s=Ps.MinimallyHealthy:(Yl.error(`assessHealth: unexpected state, cannot identify health status of the node: Filter:${r}; LightPush:${n}`),s=this.value),Yl.info(`assessHealth: node identified as ${s} Filter:${r}; LightPush:${n}`),this.updateAndDispatchHealthEvent(s)}updateAndDispatchHealthEvent(e){this.value!==e&&(this.value=e,this.events.dispatchEvent(new CustomEvent(Cs.Health,{detail:this.value})))}}const Jl=e=>new Promise(((t,r)=>setTimeout((()=>r(Error("Task timeout"))),e))),eu=new fs("sdk:retry-manager");class tu{intervalID=null;retryIntervalMs;inProgress=0;queue=[];peerManager;constructor(e){this.peerManager=e.peerManager,this.retryIntervalMs=e.retryIntervalMs||1e3}start(){this.intervalID=setInterval((()=>{this.processQueue()}),this.retryIntervalMs)}stop(){this.intervalID&&(clearInterval(this.intervalID),this.intervalID=null)}push(e,t,r){this.queue.push({maxAttempts:t,callback:e,routingInfo:r})}processQueue(){if(0!==this.queue.length)for(;this.queue.length&&this.inProgress<5;){const e=this.queue.shift();e&&this.scheduleTask(e)}}scheduleTask(e){setTimeout((async()=>this.taskExecutor(e)),100)}async taskExecutor(e){if(e.maxAttempts<=0)return void eu.warn("scheduleTask: max attempts has reached, removing from queue");const t=(await this.peerManager.getPeers({protocol:Ss.LightPush,pubsubTopic:e.routingInfo.pubsubTopic}))[0];if(!t)return eu.warn("scheduleTask: no peers, putting back to queue"),void this.queue.push({...e,maxAttempts:e.maxAttempts-1});try{this.inProgress+=1;const r=await Promise.race([Jl(1e4),e.callback(t)]);if(void 0===r)throw Error("Task timeout");if(r.failure)throw Error(r.failure.error);if(eu.info("scheduleTask: executed successfully"),0===e.maxAttempts)return void eu.warn("scheduleTask: discarded a task due to limit of max attempts");this.queue.push({...e,maxAttempts:e.maxAttempts-1})}catch(n){const s=n;if(eu.error("scheduleTask: task execution failed with error:",s),((r=s.message)===As.REMOTE_PEER_REJECTED||r===As.NO_RESPONSE||r===As.RLN_PROOF_GENERATION||r===As.NO_PEER_AVAILABLE)&&await this.peerManager.renewPeer(t,{protocol:Ss.LightPush,pubsubTopic:e.routingInfo.pubsubTopic}),0===e.maxAttempts)return void eu.warn("scheduleTask: discarded a task due to limit of max attempts");this.queue.push({...e,maxAttempts:e.maxAttempts-1})}finally{this.inProgress-=1}var r}}const ru=new fs("sdk:light-push"),nu={autoRetry:!0,retryIntervalMs:1e3,maxAttempts:3,numPeersToUse:1};class su{config;retryManager;peerManager;protocol;constructor(e){this.config={...nu,...e.options||{}},this.peerManager=e.peerManager,this.protocol=new Ni(e.libp2p),this.retryManager=new tu({peerManager:e.peerManager,retryIntervalMs:this.config.retryIntervalMs})}get multicodec(){return this.protocol.multicodec}start(){this.retryManager.start()}stop(){this.retryManager.stop()}async send(e,t,r={}){r={useLegacy:!1,...this.config,...r};const{pubsubTopic:n}=e;ru.info("send: attempting to send a message to pubsubTopic:",n);const s=await this.peerManager.getPeers({protocol:r.useLegacy?"light-push-v2":Ss.LightPush,pubsubTopic:e.pubsubTopic}),i=s?.length>0?await Promise.all(s.map((n=>this.protocol.send(e,t,n,r.useLegacy).catch((()=>({success:null,failure:{error:As.GENERIC_FAIL}})))))):[],o=i.length?{successes:i.filter((e=>e.success)).map((e=>e.success)),failures:i.filter((e=>e.failure)).map((e=>e.failure))}:{successes:[],failures:[{error:As.NO_PEER_AVAILABLE}]};if(r.autoRetry&&0===o.successes.length){const n=n=>this.protocol.send(e,t,n,r.useLegacy);this.retryManager.push(n.bind(this),r.maxAttempts||3,e.routingInfo)}return o}}const iu=new fs("store-sdk");class ou{options;libp2p;peerManager;protocol;constructor(e){this.options=e.options||{},this.peerManager=e.peerManager,this.libp2p=e.libp2p,this.protocol=new ji(e.libp2p)}get multicodec(){return this.protocol.multicodec}async*queryGenerator(e,t){const{decodersAsMap:r,queryOptions:n}=this.buildQueryParams(e,t);for(const e of n){const n=t?.peerId??await this.getPeerToUse(e.pubsubTopic);if(!n)throw iu.error("No peers available to query"),Error("No peers available to query");iu.info("Querying store with options: "+JSON.stringify(e));const s=this.protocol.queryPerPage(e,r,n);for await(const e of s)yield e}}async queryWithOrderedCallback(e,t,r){iu.info("Querying store with ordered callback");for await(const n of this.queryGenerator(e,r))if(await this.processMessages(n,t))break}async queryWithPromiseCallback(e,t,r){iu.info("Querying store with promise callback");let n=!1;for await(const s of this.queryGenerator(e,r)){const e=s.map((async e=>{n||(n=!!await t(e))}));if(await Promise.all(e),n)break}}async processMessages(e,t){let r=!1;const n=(await Promise.all(e)).filter(Yt);return await Promise.all(n.map((async e=>{e&&!r&&(r=!!await t(e))}))),r}createCursor(e){return gs(e.pubsubTopic,e)}validateDecodersAndPubsubTopic(e){if(0===e.length)throw iu.error("No decoders provided"),Error("No decoders provided");const t=Array.from(new Set(e.map((e=>e.pubsubTopic))));if(t.length>1)throw iu.error("API does not support querying multiple pubsub topics at once"),Error("API does not support querying multiple pubsub topics at once");const r=t[0],n=new Map;e.forEach((e=>{if(n.has(e.contentTopic))throw iu.error("API does not support different decoder per content topic"),Error("API does not support different decoder per content topic");n.set(e.contentTopic,e)}));const s=e.filter((e=>e.pubsubTopic===r)).map((e=>e.contentTopic));if(0===s.length)throw iu.error("No decoders found for topic "+r),Error("No decoders found for topic "+r);return{pubsubTopic:r,contentTopics:s,decodersAsMap:n}}async getPeerToUse(e){const t=await this.peerManager.getPeers({protocol:Ss.Store,pubsubTopic:e});return this.options.peers?await this.getPeerFromConfigurationOrFirst(t,this.options.peers):t[0]}async getPeerFromConfigurationOrFirst(e,t){const r=t.map(bl),n=[];for(const t of r){const r=e.find((e=>e.toString()===t.getPeerId()?.toString()));if(r)return r;n.push(t)}for(;n.length;){const e=n.pop();if(!e)return;try{if(await this.libp2p.dial(e))return Pc(e.getPeerId())}catch(t){iu.warn(`Failed to dial peer from options.peers list for Store protocol. Peer:${e.getPeerId()}, error:${t}`)}}return iu.warn(`Passed node to use for Store not found: ${t.toString()}. Attempting to use first available peers.`),e[0]}buildQueryParams(e,t){let r,n,s;if(t?.messageHashes&&t.messageHashes.length>0)r=t.pubsubTopic||e[0]?.pubsubTopic||"",n=[],s=new Map,e.forEach((e=>{s.set(e.contentTopic,e)}));else{const t=this.validateDecodersAndPubsubTopic(e);r=t.pubsubTopic,n=t.contentTopics,s=t.decodersAsMap}const i=[];if(t?.timeStart&&t?.timeEnd){let e=t.timeStart;const r=t.timeEnd;for(;r.getTime()-e.getTime()>this.protocol.maxTimeLimit;){const t=new Date(e.getTime()+this.protocol.maxTimeLimit);i.push([e,t]),e=t}0===i.length&&(iu.info("Using single time range"),i.push([e,r]))}return 0===i.length?(iu.info("No sub time ranges"),{decodersAsMap:s,queryOptions:[{pubsubTopic:r,contentTopics:n,includeData:!0,paginationForward:!0,...t}]}):(iu.info(`Building ${i.length} sub time ranges`),{decodersAsMap:s,queryOptions:i.map((([e,s])=>({pubsubTopic:r,contentTopics:n,includeData:!0,paginationForward:!0,...t,timeStart:e,timeEnd:s})))})}}const au=new fs("wait-for-remote-peer");function cu(e,t){return e.map((e=>async function(e,t){au.info(`Waiting for ${e} peer.`),await new Promise((r=>{const n=async s=>{if(s.detail?.protocols?.includes(e)){const e=t.services.metadata;if(!e)return t.removeEventListener("peer:identify",n),void r();try{await e.confirmOrAttemptHandshake(s.detail.peerId),t.removeEventListener("peer:identify",n),r()}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&au.error("Connection closed. Some peers can be on different shard."),au.error("Error waiting for metadata: "+e)}}};t.addEventListener("peer:identify",n)}))}(e,t)))}async function lu(e,t){const r=[];if(e.relay&&t.includes(Ss.Relay)&&r.push(e.relay.waitForPeers()),e.store&&t.includes(Ss.Store)&&r.push(...cu([zi],e.libp2p)),e.lightPush&&t.includes(Ss.LightPush)){const t=cu([Ti,ki],e.libp2p);r.push(Promise.any(t))}return e.filter&&t.includes(Ss.Filter)&&r.push(...cu([Ai],e.libp2p)),Promise.all(r)}const uu=(e,t)=>new Promise(((r,n)=>setTimeout((()=>n(Error(t))),e))),hu=new fs("sdk:waku");class du{libp2p;relay;store;filter;lightPush;events=new Jn;networkConfig;_nodeStateLock=!1;_nodeStarted=!1;connectionManager;peerManager;healthIndicator;constructor(e,t,r,n){this.relay=n,this.libp2p=t,this.networkConfig=e.networkConfig||Ts,r={filter:!1,lightpush:!1,store:!1,...r};const s=this.libp2p.peerId.toString();this.connectionManager=new Ml({libp2p:t,relay:this.relay,events:this.events,networkConfig:this.networkConfig,config:e?.connectionManager}),this.peerManager=new ql({libp2p:t,config:{numPeersToUse:e.numPeersToUse},connectionManager:this.connectionManager}),this.healthIndicator=new Ql({libp2p:t,events:this.events}),r.store&&(this.store=new ou({libp2p:t,peerManager:this.peerManager,options:e?.store})),r.lightpush&&(this.lightPush=new su({libp2p:t,peerManager:this.peerManager,options:e?.lightPush})),r.filter&&(this.filter=new Hl({libp2p:t,peerManager:this.peerManager,options:e.filter})),hu.info("Waku node created",s,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}get peerId(){return this.libp2p.peerId}get protocols(){return this.libp2p.getProtocols()}get health(){return this.healthIndicator.toValue()}async dial(e,t){const r=t??[];void 0===t&&(this.relay&&r.push(Ss.Relay),this.store&&r.push(Ss.Store),this.filter&&r.push(Ss.Filter),this.lightPush&&r.push(Ss.LightPush));const n=[];return r.includes(Ss.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach((e=>n.push(e))):hu.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(Ss.Store)&&(this.store?n.push(this.store.multicodec):hu.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(Ss.LightPush)&&(this.lightPush?n.push(...this.lightPush.multicodec):hu.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(Ss.Filter)&&(this.filter?n.push(this.filter.multicodec):hu.error("Filter codec not included in dial codec: protocol not mounted locally")),hu.info(`Dialing to ${e?.toString()} with protocols ${r}`),await this.connectionManager.dial(e,n)}async hangUp(e){return hu.info(`Hanging up peer:${e?.toString()}.`),this.connectionManager.hangUp(e)}async start(){this._nodeStateLock||this.isStarted()||(this._nodeStateLock=!0,await this.libp2p.start(),await(this.filter?.start()),this.connectionManager.start(),this.peerManager.start(),this.healthIndicator.start(),this.lightPush?.start(),this._nodeStateLock=!1,this._nodeStarted=!0)}async stop(){!this._nodeStateLock&&this.isStarted()&&(this._nodeStateLock=!0,this.lightPush?.stop(),await(this.filter?.stop()),this.healthIndicator.stop(),this.peerManager.stop(),this.connectionManager.stop(),await this.libp2p.stop(),this._nodeStateLock=!1,this._nodeStarted=!1)}async getConnectedPeers(){return this.connectionManager.getConnectedPeers()}async waitForPeers(e,t){return async function(e,t,r){t=t?.length?t:function(e){const t=[];return e.relay&&t.push(Ss.Relay),e.filter&&t.push(Ss.Filter),e.store&&t.push(Ss.Store),e.lightPush&&t.push(Ss.LightPush),t}(e);const n=e.libp2p.getConnections();if(!e.isStarted())throw Error("Waku node is not started");for(const r of t)switch(r){case Ss.Relay:if(!e.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");break;case Ss.LightPush:if(!e.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");break;case Ss.Store:if(!e.store)throw Error("Cannot wait for Store peer: protocol not mounted");break;case Ss.Filter:if(!e.filter)throw Error("Cannot wait for Filter peer: protocol not mounted")}const s=[lu(e,t)];n.length>0&&!t.includes(Ss.Relay)&&s.push(async function(e,t){const r=e.libp2p.getPeers(),n=e.libp2p.services.metadata,s=function(e){const t=new Map,r={[Ss.Filter]:[Ai],[Ss.LightPush]:[Ti,ki],[Ss.Store]:[zi]};for(const n of e)r[n]&&r[n].forEach((e=>{t.set(e,!1)}));return t}(t);if(r.length&&n)for(const t of r)try{const r=await e.libp2p.peerStore.get(t);if(r.protocols.some((e=>s.has(e)))&&!(await n.confirmOrAttemptHandshake(t)).error&&(r.protocols.forEach((e=>{s.has(e)&&s.set(e,!0)})),Array.from(s.values()).every((e=>e))))return}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&au.error("Connection closed. Some peers can be on different shard."),au.error("Error while iterating through peers: "+e);continue}else au.info(`Skipping waitForMetadata due to missing connections:${r.length} or metadataService:${!!n}`)}(e,t)),r?await async function(e,t,r){await Promise.race([e,uu(t,"Timed out waiting for a remote peer.")])}(Promise.any(s),r):await Promise.any(s)}(this,e,t)}isStarted(){return this._nodeStarted&&"started"===this.libp2p.status}isConnected(){return this.connectionManager.isConnected()}createDecoder(e){const t=this.createRoutingInfo(e.contentTopic,e.shardId);return function(e,t){return new class{contentTopic;routingInfo;constructor(e,t){if(this.contentTopic=e,this.routingInfo=t,!e||""===e)throw Error("Content topic must be specified")}get pubsubTopic(){return this.routingInfo.pubsubTopic}fromWireToProtoObj(e){const t=ft.decode(e);return Promise.resolve({payload:t.payload,contentTopic:t.contentTopic,version:t.version??void 0,timestamp:t.timestamp??void 0,meta:t.meta??void 0,rateLimitProof:t.rateLimitProof??void 0,ephemeral:t.ephemeral??!1})}async fromProtoObj(e,t){return t.version?(ms.error("Failed to decode due to incorrect version, expected:",0,", actual:",t.version),Promise.resolve(void 0)):new bs(e,t)}}(e,t)}(e.contentTopic,t)}createEncoder(e){const t=this.createRoutingInfo(e.contentTopic,e.shardId);return vs({contentTopic:e.contentTopic,ephemeral:e.ephemeral,routingInfo:t})}createRoutingInfo(e,t){return gn(this.networkConfig,{contentTopic:e,shardId:t})}}const pu=4194304;let fu=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},gu=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},mu=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},yu=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function bu(e){return null!=e[Symbol.asyncIterator]}function wu(e,t){if(e.byteLength>t)throw new gu("Message length too long")}const vu=e=>{const t=f(e),r=a(t);return y(e,r),vu.bytes=t,r};function Eu(e,t){const r=(t=t??{}).lengthEncoder??vu,n=t?.maxDataLength??pu;function*s(e){wu(e,n);const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return bu(e)?async function*(){for await(const t of e)yield*s(t)}():function*(){for(const t of e)yield*s(t)}()}var Su;vu.bytes=0,Eu.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??vu;return wu(e,t?.maxDataLength??pu),new Us(r(e.byteLength),e)},(e=>{e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(Su||(Su={}));const Au=e=>{const t=b(e);return Au.bytes=f(t),t};function Iu(e,t){const r=new Us;let n=Su.LENGTH,s=-1;const i=t?.lengthDecoder??Au,o=t?.maxLengthLength??8,a=t?.maxDataLength??pu;function*c(){for(;r.byteLength>0;){if(n===Su.LENGTH)try{if(s=i(r),s<0)throw new fu("Invalid message length");if(s>a)throw new gu("Message length too long");const e=i.bytes;r.consume(e),null!=t?.onLength&&t.onLength(s),n=Su.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>o)throw new mu("Message length length too long");break}throw e}if(n===Su.DATA){if(r.byteLength<s)break;const e=r.sublist(0,s);r.consume(s),null!=t?.onData&&t.onData(e),yield e,n=Su.LENGTH}}}return bu(e)?async function*(){for await(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new yu("Unexpected end of input")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new yu("Unexpected end of input")}()}Au.bytes=0,Iu.fromReader=(e,t)=>{let r=1;return Iu(async function*(){for(;;)try{const{done:t,value:n}=await e.next(r);if(!0===t)return;null!=n&&(yield n)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{r=1}}(),{...t??{},onLength(e){r=e}})};class _u extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}function Cu(e,t){const r=ri();e.sink(r).catch((async e=>{await r.end(e)})),e.sink=async e=>{for await(const t of e)await r.push(t);await r.end()};let n=e.source;null!=e.source[Symbol.iterator]?n=e.source[Symbol.iterator]():null!=e.source[Symbol.asyncIterator]&&(n=e.source[Symbol.asyncIterator]());const s=new Us;return{async read(e){if(e?.signal?.throwIfAborted(),null==e?.bytes){const{done:t,value:r}=await ei(n.next(),e?.signal);return!0===t?null:r}for(;s.byteLength<e.bytes;){const{value:t,done:r}=await ei(n.next(),e?.signal);if(!0===r)throw new _u("unexpected end of input");s.append(t)}const t=s.sublist(0,e.bytes);return s.consume(e.bytes),t},async write(e,t){t?.signal?.throwIfAborted(),e instanceof Uint8Array?await r.push(e,t):await r.push(e.subarray(),t)},unwrap(){if(s.byteLength>0){const r=e.source;e.source=async function*(){!1===t?.yieldBytes?yield s:yield*s,yield*r}()}return e}}}class xu extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class ku extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class Tu extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function Pu(e,t={}){const r=Cu(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=f(t.maxDataLength));const n=t?.lengthDecoder??b,s=t?.lengthEncoder??y;return{async read(e){let s=-1;const i=new Us;for(;;){i.append(await r.read({...e,bytes:1}));try{s=n(i)}catch(e){if(e instanceof RangeError)continue;throw e}if(s<0)throw new xu("Invalid message length");if(null!=t?.maxLengthLength&&i.byteLength>t.maxLengthLength)throw new Tu("message length length too long");if(s>-1)break}if(null!=t?.maxDataLength&&s>t.maxDataLength)throw new ku("message length too long");return r.read({...e,bytes:s})},async write(e,t){await r.write(new Us(s(e.byteLength),e),t)},async writeV(e,t){const n=new Us(...e.flatMap((e=>[s(e.byteLength),e])));await r.write(n,t)},unwrap:()=>r.unwrap()}}function Ru(){const e=Ws();let t=!1;return{async sink(r){if(t)throw Error("already piped");t=!0,e.resolve(r)},source:async function*(){const t=await e.promise;yield*t}()}}const Lu=65535,Du=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function Mu(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Nu(e){if("boolean"!=typeof e)throw Error("boolean expected, not "+e)}function Ou(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function Uu(e,...t){if(!Mu(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function Fu(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Bu(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function $u(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const qu=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];function zu(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!Mu(e))throw Error("Uint8Array expected, got "+typeof e);e=Vu(e)}return e}function ju(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw Error("invalid output length, expected "+e+", got: "+t.length);if(r&&t.byteOffset%4!=0)throw Error("invalid output, must be aligned");return t}function Ku(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i);e.setUint32(t+4,o,n),e.setUint32(t+0,a,n)}function Vu(e){return Uint8Array.from(e)}const Hu=e=>Uint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),Gu=Hu("expand 16-byte k"),Wu=Hu("expand 32-byte k"),Xu=Bu(Gu),Zu=Bu(Wu);function Yu(e,t){return e<<t|e>>>32-t}function Qu(e){return e.byteOffset%4==0}const Ju=2**32-1,eh=new Uint32Array,th=(e,t)=>255&e[t++]|(255&e[t++])<<8;class rh{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,Uu(e=zu(e),32);const t=th(e,0),r=th(e,2),n=th(e,4),s=th(e,6),i=th(e,8),o=th(e,10),a=th(e,12),c=th(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|r<<3),this.r[2]=7939&(r>>>10|n<<6),this.r[3]=8191&(n>>>7|s<<9),this.r[4]=255&(s>>>4|i<<12),this.r[5]=i>>>1&8190,this.r[6]=8191&(i>>>14|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=th(e,16+2*t)}process(e,t,r=!1){const n=r?0:2048,{h:s,r:i}=this,o=i[0],a=i[1],c=i[2],l=i[3],u=i[4],h=i[5],d=i[6],p=i[7],f=i[8],g=i[9],m=th(e,t+0),y=th(e,t+2),b=th(e,t+4),w=th(e,t+6),v=th(e,t+8),E=th(e,t+10),S=th(e,t+12),A=th(e,t+14);let I=s[0]+(8191&m),_=s[1]+(8191&(m>>>13|y<<3)),C=s[2]+(8191&(y>>>10|b<<6)),x=s[3]+(8191&(b>>>7|w<<9)),k=s[4]+(8191&(w>>>4|v<<12)),T=s[5]+(v>>>1&8191),P=s[6]+(8191&(v>>>14|E<<2)),R=s[7]+(8191&(E>>>11|S<<5)),L=s[8]+(8191&(S>>>8|A<<8)),D=s[9]+(A>>>5|n),M=0,N=M+I*o+_*(5*g)+C*(5*f)+x*(5*p)+k*(5*d);M=N>>>13,N&=8191,N+=T*(5*h)+P*(5*u)+R*(5*l)+L*(5*c)+D*(5*a),M+=N>>>13,N&=8191;let O=M+I*a+_*o+C*(5*g)+x*(5*f)+k*(5*p);M=O>>>13,O&=8191,O+=T*(5*d)+P*(5*h)+R*(5*u)+L*(5*l)+D*(5*c),M+=O>>>13,O&=8191;let U=M+I*c+_*a+C*o+x*(5*g)+k*(5*f);M=U>>>13,U&=8191,U+=T*(5*p)+P*(5*d)+R*(5*h)+L*(5*u)+D*(5*l),M+=U>>>13,U&=8191;let F=M+I*l+_*c+C*a+x*o+k*(5*g);M=F>>>13,F&=8191,F+=T*(5*f)+P*(5*p)+R*(5*d)+L*(5*h)+D*(5*u),M+=F>>>13,F&=8191;let B=M+I*u+_*l+C*c+x*a+k*o;M=B>>>13,B&=8191,B+=T*(5*g)+P*(5*f)+R*(5*p)+L*(5*d)+D*(5*h),M+=B>>>13,B&=8191;let $=M+I*h+_*u+C*l+x*c+k*a;M=$>>>13,$&=8191,$+=T*o+P*(5*g)+R*(5*f)+L*(5*p)+D*(5*d),M+=$>>>13,$&=8191;let q=M+I*d+_*h+C*u+x*l+k*c;M=q>>>13,q&=8191,q+=T*a+P*o+R*(5*g)+L*(5*f)+D*(5*p),M+=q>>>13,q&=8191;let z=M+I*p+_*d+C*h+x*u+k*l;M=z>>>13,z&=8191,z+=T*c+P*a+R*o+L*(5*g)+D*(5*f),M+=z>>>13,z&=8191;let j=M+I*f+_*p+C*d+x*h+k*u;M=j>>>13,j&=8191,j+=T*l+P*c+R*a+L*o+D*(5*g),M+=j>>>13,j&=8191;let K=M+I*g+_*f+C*p+x*d+k*h;M=K>>>13,K&=8191,K+=T*u+P*l+R*c+L*a+D*o,M+=K>>>13,K&=8191,M=(M<<2)+M|0,M=M+N|0,N=8191&M,M>>>=13,O+=M,s[0]=N,s[1]=O,s[2]=U,s[3]=F,s[4]=B,s[5]=$,s[6]=q,s[7]=z,s[8]=j,s[9]=K}finalize(){const{h:e,pad:t}=this,r=new Uint16Array(10);let n=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=n,n=e[t]>>>13,e[t]&=8191;e[0]+=5*n,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+n,n=r[t]>>>13,r[t]&=8191;r[9]-=8192;let s=(1^n)-1;for(let e=0;e<10;e++)r[e]&=s;s=~s;for(let t=0;t<10;t++)e[t]=e[t]&s|r[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let i=e[0]+t[0];e[0]=65535&i;for(let r=1;r<8;r++)i=(e[r]+t[r]|0)+(i>>>16)|0,e[r]=65535&i;$u(r)}update(e){Fu(this),Uu(e=zu(e));const{buffer:t,blockLen:r}=this,n=e.length;for(let s=0;s<n;){const i=Math.min(r-this.pos,n-s);if(i!==r)t.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(t,0,!1),this.pos=0);else for(;r<=n-s;s+=r)this.process(e,s)}return this}destroy(){$u(this.h,this.r,this.buffer,this.pad)}digestInto(e){Fu(this),function(e,t){Uu(e);const r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,h:r}=this;let{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let t=0;t<8;t++)e[s++]=r[t]>>>0,e[s++]=r[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}}const nh=function(e){const t=(t,r)=>e(r).update(zu(t)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}((e=>new rh(e))),sh=function(e,t){const{allowShortKeys:r,extendNonceFn:n,counterLength:s,counterRight:i,rounds:o}=function(e,t){if(null==t||"object"!=typeof t)throw Error("options must be defined");return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t)}(0,{counterRight:!1,counterLength:4,allowShortKeys:!1});return Ou(s),Ou(o),Nu(i),Nu(r),(t,a,c,l,u=0)=>{Uu(t),Uu(a),Uu(c);const h=c.length;if(void 0===l&&(l=new Uint8Array(h)),Uu(l),Ou(u),u<0||u>=Ju)throw Error("arx: counter overflow");if(l.length<h)throw Error(`arx: output (${l.length}) is shorter than data (${h})`);const d=[];let p,f,g=t.length;if(32===g)d.push(p=Vu(t)),f=Zu;else{if(16!==g||!r)throw Error("arx: invalid 32-byte key, got length="+g);p=new Uint8Array(32),p.set(t),p.set(t,16),f=Xu,d.push(p)}Qu(a)||d.push(a=Vu(a));const m=Bu(p);if(n){if(24!==a.length)throw Error("arx: extended nonce must be 24 bytes");n(f,m,Bu(a.subarray(0,16)),m),a=a.subarray(16)}const y=16-s;if(y!==a.length)throw Error(`arx: nonce must be ${y} or 16 bytes`);if(12!==y){const e=new Uint8Array(12);e.set(a,i?0:12-a.length),a=e,d.push(a)}const b=Bu(a);return function(e,t,r,n,s,i,o,a){const c=s.length,l=new Uint8Array(64),u=Bu(l),h=Qu(s)&&Qu(i),d=h?Bu(s):eh,p=h?Bu(i):eh;for(let f=0;f<c;o++){if(e(t,r,n,u,o,a),o>=Ju)throw Error("arx: counter overflow");const g=Math.min(64,c-f);if(h&&64===g){const e=f/4;if(f%4!=0)throw Error("arx: invalid block position");for(let t,r=0;r<16;r++)t=e+r,p[t]=d[t]^u[r];f+=64}else{for(let e,t=0;t<g;t++)e=f+t,i[e]=s[e]^l[t];f+=g}}}(e,f,m,b,c,l,u,o),$u(...d),l}}((function(e,t,r,n,s,i=20){let o=e[0],a=e[1],c=e[2],l=e[3],u=t[0],h=t[1],d=t[2],p=t[3],f=t[4],g=t[5],m=t[6],y=t[7],b=s,w=r[0],v=r[1],E=r[2],S=o,A=a,I=c,_=l,C=u,x=h,k=d,T=p,P=f,R=g,L=m,D=y,M=b,N=w,O=v,U=E;for(let e=0;e<i;e+=2)S=S+C|0,M=Yu(M^S,16),P=P+M|0,C=Yu(C^P,12),S=S+C|0,M=Yu(M^S,8),P=P+M|0,C=Yu(C^P,7),A=A+x|0,N=Yu(N^A,16),R=R+N|0,x=Yu(x^R,12),A=A+x|0,N=Yu(N^A,8),R=R+N|0,x=Yu(x^R,7),I=I+k|0,O=Yu(O^I,16),L=L+O|0,k=Yu(k^L,12),I=I+k|0,O=Yu(O^I,8),L=L+O|0,k=Yu(k^L,7),_=_+T|0,U=Yu(U^_,16),D=D+U|0,T=Yu(T^D,12),_=_+T|0,U=Yu(U^_,8),D=D+U|0,T=Yu(T^D,7),S=S+x|0,U=Yu(U^S,16),L=L+U|0,x=Yu(x^L,12),S=S+x|0,U=Yu(U^S,8),L=L+U|0,x=Yu(x^L,7),A=A+k|0,M=Yu(M^A,16),D=D+M|0,k=Yu(k^D,12),A=A+k|0,M=Yu(M^A,8),D=D+M|0,k=Yu(k^D,7),I=I+T|0,N=Yu(N^I,16),P=P+N|0,T=Yu(T^P,12),I=I+T|0,N=Yu(N^I,8),P=P+N|0,T=Yu(T^P,7),_=_+C|0,O=Yu(O^_,16),R=R+O|0,C=Yu(C^R,12),_=_+C|0,O=Yu(O^_,8),R=R+O|0,C=Yu(C^R,7);let F=0;n[F++]=o+S|0,n[F++]=a+A|0,n[F++]=c+I|0,n[F++]=l+_|0,n[F++]=u+C|0,n[F++]=h+x|0,n[F++]=d+k|0,n[F++]=p+T|0,n[F++]=f+P|0,n[F++]=g+R|0,n[F++]=m+L|0,n[F++]=y+D|0,n[F++]=b+M|0,n[F++]=w+N|0,n[F++]=v+O|0,n[F++]=E+U|0})),ih=new Uint8Array(16),oh=(e,t)=>{e.update(t);const r=t.length%16;r&&e.update(ih.subarray(r))},ah=new Uint8Array(32);function ch(e,t,r,n,s){const i=e(t,r,ah),o=nh.create(i);s&&oh(o,s),oh(o,n);const a=function(e,t,r){Nu(r);const n=new Uint8Array(16),s=(i=n,new DataView(i.buffer,i.byteOffset,i.byteLength));var i;return Ku(s,0,BigInt(t),r),Ku(s,8,BigInt(e),r),n}(n.length,s?s.length:0,!0);o.update(a);const c=o.digest();return $u(i,a),c}const lh=((e,t)=>{function r(r,...n){if(Uu(r),!qu)throw Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){const t=n[0];if(!t)throw Error("nonce / iv required");e.varSizeNonce?Uu(t):Uu(t,e.nonceLength)}const s=e.tagLength;s&&void 0!==n[1]&&Uu(n[1]);const i=t(r,...n),o=(e,t)=>{if(void 0!==t){if(2!==e)throw Error("cipher output not supported");Uu(t)}};let a=!1;return{encrypt(e,t){if(a)throw Error("cannot encrypt() twice with same key + nonce");return a=!0,Uu(e),o(i.encrypt.length,t),i.encrypt(e,t)},decrypt(e,t){if(Uu(e),s&&e.length<s)throw Error("invalid ciphertext length: smaller than tagLength="+s);return o(i.decrypt.length,t),i.decrypt(e,t)}}}return Object.assign(r,e),r})({blockSize:64,nonceLength:12,tagLength:16},(uh=sh,(e,t,r)=>({encrypt(n,s){const i=n.length;(s=ju(i+16,s,!1)).set(n);const o=s.subarray(0,-16);uh(e,t,o,o,1);const a=ch(uh,e,t,o,r);return s.set(a,i),$u(a),s},decrypt(n,s){s=ju(n.length-16,s,!1);const i=n.subarray(0,-16),o=n.subarray(-16),a=ch(uh,e,t,i,r);if(!((e,t)=>{if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r})(o,a))throw Error("invalid tag");return s.set(n.subarray(0,-16)),uh(e,t,s,s,1),$u(a),s}})));var uh;const hh=Uint8Array.from([0]),dh=Uint8Array.of(),ph={hashSHA256:e=>en(e.subarray()),getHKDF(e,t){const r=function(e,t,r){return rr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),tc(e,br(r),br(t))}(en,t,e),n=function(e,t,r,n=32){rr(e),er(n);const s=e.outputLen;if(n>255*s)throw Error("Length should be <= 255*HashLen");const i=Math.ceil(n/s);void 0===r&&(r=dh);const o=new Uint8Array(i*s),a=tc.create(e,t),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let e=0;e<i;e++)hh[0]=e+1,c.update(0===e?dh:l).update(r).update(hh).digestInto(l),o.set(l,s*e),a._cloneInto(c);return a.destroy(),c.destroy(),sr(l,hh),o.slice(0,n)}(en,r,void 0,96),s=n;return[s.subarray(0,32),s.subarray(32,64),s.subarray(64,96)]},generateX25519KeyPair(){const e=Oa.utils.randomPrivateKey();return{publicKey:Oa.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:Oa.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>Oa.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>lh(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,s)=>lh(n,t,r).decrypt(e.subarray(),s)},fh=ph,gh=e=>{const t=a(2);return t[0]=e>>8,t[1]=e,t};gh.bytes=2;const mh=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};function yh(e,t){t.enabled&&Du&&(e?(t("LOCAL_STATIC_PUBLIC_KEY "+tn(e.publicKey,"hex")),t("LOCAL_STATIC_PRIVATE_KEY "+tn(e.privateKey,"hex"))):t("Missing local static keys."))}function bh(e,t){t.enabled&&Du&&(e?(t("LOCAL_PUBLIC_EPHEMERAL_KEY "+tn(e.publicKey,"hex")),t("LOCAL_PRIVATE_EPHEMERAL_KEY "+tn(e.privateKey,"hex"))):t("Missing local ephemeral keys."))}function wh(e,t){t.enabled&&Du&&t(e?"REMOTE_EPHEMERAL_PUBLIC_KEY "+tn(e.subarray(),"hex"):"Missing remote ephemeral keys.")}function vh(e,t,r){r.enabled&&Du&&(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&tn(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&tn(t.k,"hex")}`))}mh.bytes=2;class Eh extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=Eh.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}class Sh{n;bytes;view;constructor(e=0){this.n=e,this.bytes=o(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw Error("Cipherstate has reached maximum n, a new handshake must be performed")}}const Ah=o(0);class Ih{k;n;crypto;constructor(e,t,r=0){this.crypto=e,this.k=t,this.n=new Sh(r)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();const r=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,t,r){if(!this.hasKey())return t;this.n.assertValue();const n=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,r);return this.n.increment(),n}}class _h{cs;ck;h;crypto;constructor(e,t){this.crypto=e;const r=Ye(t,"utf-8");this.h=function(e,t){if(t.length<=32){const e=o(32);return e.set(t),e}return e.hash(t)}(e,r),this.ck=this.h,this.cs=new Ih(e)}mixKey(e){const[t,r]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new Ih(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new Us(this.h,e))}encryptAndHash(e){const t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){const t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){const[e,t]=this.crypto.hkdf(this.ck,Ah);return[new Ih(this.crypto,e),new Ih(this.crypto,t)]}}class Ch{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:t,protocolName:r,prologue:n,initiator:s,s:i,e:o,rs:a,re:c}=e;this.crypto=t,this.ss=new _h(t,r),this.ss.mixHash(n),this.initiator=s,this.s=i,this.e=o,this.rs=a,this.re=c}writeE(){if(this.e)throw Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw Error("ephemeral keypair is not set");if(!this.re)throw Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw Error("ephemeral keypair is not set");if(!this.rs)throw Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw Error("static keypair is not set");if(!this.re)throw Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw Error("static keypair is not set");if(!this.re)throw Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw Error("ephemeral keypair is not set");if(!this.rs)throw Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw Error("remote static public key is already set");const r=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+r)throw Error("message is not long enough");const n=e.sublist(t,t+r);return this.rs=this.ss.decryptAndHash(n),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class xh extends Ch{writeMessageA(e){return new Us(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const t=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new Us(t,r,this.ss.encryptAndHash(e))}writeMessageC(e){const t=this.writeS();return this.writeSE(),new Us(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new Eh("handshake stage 0 validation fail: "+e.message)}}readMessageB(e){try{this.readE(e),this.readEE();const t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(e){throw new Eh("handshake stage 1 validation fail: "+e.message)}}readMessageC(e){try{const t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(e){throw new Eh("handshake stage 2 validation fail: "+e.message)}}}var kh,Th;async function Ph(e,t,r){const n=await e.sign(Lh(t));return Th.encode({identityKey:Ac(e.publicKey),identitySig:n,extensions:r})}async function Rh(e,t,r){try{const n=Th.decode(e),s=Sc(n.identityKey);if(!1===r?.equals(s))throw Error(`Payload identity key ${s} does not match expected remote identity key ${r}`);if(!t)throw Error("Remote static does not exist");const i=Lh(t);if(!await s.verify(i,n.identitySig))throw Error("Invalid payload signature");return n}catch(e){throw new kn(e.message)}}function Lh(e){const t=Ye("noise-libp2p-static-key:");return e instanceof Uint8Array?Ls([t,e],t.length+e.length):(e.prepend(t),e)}(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(const r of e.webtransportCerthashes)t.uint32(10),t.bytes(r);if(null!=e.streamMuxers)for(const r of e.streamMuxers)t.uint32(18),t.string(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={webtransportCerthashes:[],streamMuxers:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:if(null!=r.limits?.webtransportCerthashes&&n.webtransportCerthashes.length===r.limits.webtransportCerthashes)throw new Xt('Decode error - map field "webtransportCerthashes" had too many elements');n.webtransportCerthashes.push(e.bytes());break;case 2:if(null!=r.limits?.streamMuxers&&n.streamMuxers.length===r.limits.streamMuxers)throw new Xt('Decode error - map field "streamMuxers" had too many elements');n.streamMuxers.push(e.string());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(kh||(kh={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.identityKey&&e.identityKey.byteLength>0&&(t.uint32(10),t.bytes(e.identityKey)),null!=e.identitySig&&e.identitySig.byteLength>0&&(t.uint32(18),t.bytes(e.identitySig)),null!=e.extensions&&(t.uint32(34),kh.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={identityKey:o(0),identitySig:o(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.identityKey=e.bytes();break;case 2:n.identitySig=e.bytes();break;case 4:n.extensions=kh.codec().decode(e,e.uint32(),{limits:r.limits?.extensions});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Th||(Th={}));class Dh{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(e,t={}){const{staticNoiseKey:r,extensions:n,crypto:s,prologueBytes:i}=t,{metrics:a}=e;this.components=e;const c=s??fh;this.crypto=function(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}(c),this.extensions={webtransportCerthashes:[],...n},this.metrics=a?function(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(a):void 0,this.staticKey=r?c.generateX25519KeyPairFromSeed(r):c.generateX25519KeyPair(),this.prologue=i??o(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[ts]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){const r=Pu(e,{lengthEncoder:gh,lengthDecoder:mh,maxDataLength:Lu}),n=await this.performHandshakeInitiator(r,this.components.privateKey,t?.remotePeer?.publicKey,t),s=await this.createSecureConnection(r,n);e.source=s.source,e.sink=s.sink;const i=Sc(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:Rc(i),streamMuxer:!0===t?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(n.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(null==e||0===e.length)return;const t=this.components.upgrader.getStreamMuxers();if(null!=t)for(const r of e){const e=t.get(r);if(null!=e)return e}if(e.length)throw new Tn("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){const r=Pu(e,{lengthEncoder:gh,lengthDecoder:mh,maxDataLength:Lu}),n=await this.performHandshakeResponder(r,this.components.privateKey,t?.remotePeer?.publicKey,t),s=await this.createSecureConnection(r,n);e.source=s.source,e.sink=s.sink;const i=Sc(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:Rc(i),streamMuxer:!0===t?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(n.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,r,n){let s;const i=!0===n?.skipStreamMuxerNegotiation?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await async function(e,t){const{log:r,connection:n,crypto:s,privateKey:i,prologue:o,s:a,remoteIdentityKey:c,extensions:l}=e,u=await Ph(i,a.publicKey,l),h=new xh({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:o,s:a});yh(h.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(Ah),t),r.trace("Stage 0 - Initiator finished sending first message."),bh(h.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");const d=h.readMessageB(await n.read(t));var p,f;r.trace("Stage 1 - Initiator received the message."),wh(h.re,r),p=h.rs,(f=r).enabled&&Du&&f(p?"REMOTE_STATIC_PUBLIC_KEY "+tn(p.subarray(),"hex"):"Missing remote static public key."),r.trace("Initiator going to check remote's signature...");const g=await Rh(d,h.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(h.writeMessageC(u),t),r.trace("Stage 2 - Initiator sent message with signed payload.");const[m,y]=h.ss.split();return vh(m,y,r),{payload:g,encrypt:e=>m.encryptWithAd(Ah,e),decrypt:(e,t)=>y.decryptWithAd(Ah,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:i,webtransportCerthashes:[],...this.extensions}},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}async performHandshakeResponder(e,t,r,n){let s;const i=!0===n?.skipStreamMuxerNegotiation?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await async function(e,t){const{log:r,connection:n,crypto:s,privateKey:i,prologue:o,s:a,remoteIdentityKey:c,extensions:l}=e,u=await Ph(i,a.publicKey,l),h=new xh({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:o,s:a});yh(h.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),wh(h.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(h.writeMessageB(u),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),bh(h.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");const d=h.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");const p=await Rh(d,h.rs,c),[f,g]=h.ss.split();return vh(f,g,r),{payload:p,encrypt:e=>g.encryptWithAd(Ah,e),decrypt:(e,t)=>f.decryptWithAd(Ah,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:i,webtransportCerthashes:[],...this.extensions}},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}async createSecureConnection(e,t){const[r,n]=function(){const e=Ru(),t=Ru();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}(),s=e.unwrap();return await si(r,function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=65519){let s,i=r+65519;i>n.length&&(i=n.length),s=n instanceof Uint8Array?e.encrypt(n.subarray(r,i)):e.encrypt(n.sublist(r,i)),t?.encryptedPackets.increment(),yield new Us(gh(s.byteLength),s)}}}(t,this.metrics),s,(e=>Iu(e,{lengthDecoder:mh})),function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=Lu){let s=r+Lu;if(s>n.length&&(s=n.length),s-16<r)throw Error("Invalid chunk");const i=n.sublist(r,s),o=n.subarray(r,s-16);try{const r=e.decrypt(i,o);t?.decryptedPackets.increment(),yield r}catch(e){throw t?.decryptErrors.increment(),e}}}}(t,this.metrics),r),n}}function Mh(e={}){return t=>new Dh(t,e)}const Nh=dd("dns4"),Oh=dd("dns6"),Uh=dd("dnsaddr"),Fh=hd(dd("dns"),Uh,Nh,Oh),Bh=hd(dd("ip4"),dd("ip6")),$h=hd(ud(Bh,dd("tcp")),ud(Fh,dd("tcp"))),qh=ud(Bh,dd("udp")),zh=ud(qh,dd("utp")),jh=ud(qh,dd("quic")),Kh=ud(qh,dd("quic-v1")),Vh=hd(ud($h,dd("ws")),ud(Fh,dd("ws"))),Hh=hd(ud(Vh,dd("p2p")),Vh),Gh=hd(ud($h,dd("wss")),ud(Fh,dd("wss")),ud($h,dd("tls"),dd("ws")),ud(Fh,dd("tls"),dd("ws"))),Wh=hd(ud(Gh,dd("p2p")),Gh),Xh=hd(ud($h,dd("http")),ud(Bh,dd("http")),ud(Fh,dd("http"))),Zh=hd(ud($h,dd("https")),ud(Bh,dd("https")),ud(Fh,dd("https"))),Yh=ud(qh,dd("webrtc-direct"),dd("certhash")),Qh=hd(ud(Yh,dd("p2p")),Yh),Jh=ud(Kh,dd("webtransport"),dd("certhash"),dd("certhash")),ed=hd(ud(Jh,dd("p2p")),Jh),td=hd(ud(Hh,dd("p2p-webrtc-star"),dd("p2p")),ud(Wh,dd("p2p-webrtc-star"),dd("p2p")),ud(Hh,dd("p2p-webrtc-star")),ud(Wh,dd("p2p-webrtc-star")));hd(ud(Hh,dd("p2p-websocket-star"),dd("p2p")),ud(Wh,dd("p2p-websocket-star"),dd("p2p")),ud(Hh,dd("p2p-websocket-star")),ud(Wh,dd("p2p-websocket-star")));const rd=hd(ud(Xh,dd("p2p-webrtc-direct"),dd("p2p")),ud(Zh,dd("p2p-webrtc-direct"),dd("p2p")),ud(Xh,dd("p2p-webrtc-direct")),ud(Zh,dd("p2p-webrtc-direct"))),nd=hd(Vh,Gh,Xh,Zh,td,rd,$h,zh,jh,Fh,Qh,ed);hd(ud(nd,dd("p2p-stardust"),dd("p2p")),ud(nd,dd("p2p-stardust")));const sd=hd(ud(nd,dd("p2p")),td,rd,Qh,ed,dd("p2p")),id=hd(ud(sd,dd("p2p-circuit"),sd),ud(sd,dd("p2p-circuit")),ud(dd("p2p-circuit"),sd),ud(nd,dd("p2p-circuit")),ud(dd("p2p-circuit"),nd),dd("p2p-circuit")),od=()=>hd(ud(id,od),id),ad=od(),cd=hd(ud(ad,sd,ad),ud(sd,ad),ud(ad,sd),ad,sd);function ld(e){return function(t){let r;try{r=bl(t)}catch(e){return!1}const n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function ud(...e){function t(t){if(t.length<e.length)return null;let r=t;return e.some((e=>(r="function"==typeof e?e().partialMatch(t):e.partialMatch(t),Array.isArray(r)&&(t=r),null===r))),r}return{toString:()=>"{ "+e.join(" ")+" }",input:e,matches:ld(t),partialMatch:t}}function hd(...e){function t(t){let r=null;return e.some((e=>{const n="function"==typeof e?e().partialMatch(t):e.partialMatch(t);return null!=n&&(r=n,!0)})),r}return{toString:()=>"{ "+e.join(" ")+" }",input:e,matches:ld(t),partialMatch:t}}function dd(e){const t=e;return{toString:()=>t,matches(e){let r;try{r=bl(e)}catch(e){return!1}const n=r.protoNames();return 1===n.length&&n[0]===t},partialMatch:e=>0===e.length?null:e[0]===t?e.slice(1):null}}hd(ud(ad,dd("webrtc"),dd("p2p")),ud(ad,dd("webrtc")),ud(nd,dd("webrtc"),dd("p2p")),ud(nd,dd("webrtc")),dd("webrtc"));class pd extends Jn{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(null==t.list||0===t.list.length)throw Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??1e3,this.list=[];for(const e of t.list){if(!cd.matches(e)){this.log.error("Invalid multiaddr");continue}const t=bl(e),r=t.getPeerId();if(null==r){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const n={id:Pc(r),multiaddrs:[t]};this.list.push(n)}this._init=t}[vn]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[ts]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout((()=>{this._discoverBootstrapPeers().catch((e=>{this.log.error(e)}))}),this.timeout))}async _discoverBootstrapPeers(){if(null!=this.timer)for(const e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??"bootstrap"]:{value:this._init.tagValue??50,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),null==this.timer)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch((t=>{this.log.error("could not dial bootstrap peer %p",e.id,t)}))}}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}var fd;(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(26),t.bytes(e.payload)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={publicKey:o(0),payloadType:o(0),payload:o(0),signature:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.publicKey=e.bytes();break;case 2:r.payloadType=e.bytes();break;case 3:r.payload=e.bytes();break;case 5:r.signature=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(fd||(fd={}));class gd extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}}class md{static createFromProtobuf=e=>{const t=fd.decode(e),r=Sc(t.publicKey);return new md({publicKey:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,r)=>{if(null==t)throw Error("Missing private key");const n=e.domain,s=e.codec,i=e.marshal(),o=yd(n,s,i),a=await t.sign(o.subarray(),r);return new md({publicKey:t.publicKey,payloadType:s,payload:i,signature:a})};static openAndCertify=async(e,t,r)=>{const n=md.createFromProtobuf(e);if(!await n.validate(t,r))throw new gd("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){const{publicKey:t,payloadType:r,payload:n,signature:s}=e;this.publicKey=t,this.payloadType=r,this.payload=n,this.signature=s}marshal(){return null==this.marshaled&&(this.marshaled=fd.encode({publicKey:Ac(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return null!=e&&Ds(this.marshal(),e.marshal())}async validate(e,t){const r=yd(e,this.payloadType,this.payload);return this.publicKey.verify(r.subarray(),this.signature,t)}}const yd=(e,t,r)=>{const n=Ye(e),s=y(n.byteLength),i=y(t.length),o=y(r.length);return new Us(s,n,i,t,o,r)},bd=Uint8Array.from([3,1]);var wd;(e=>{let t;(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={multiaddr:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.multiaddr=e.bytes():e.skipType(7&t)}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==t&&(t=Wt(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.peerId&&t.peerId.byteLength>0&&(r.uint32(10),r.bytes(t.peerId)),null!=t.seq&&0n!==t.seq&&(r.uint32(16),r.uint64(t.seq)),null!=t.addresses)for(const n of t.addresses)r.uint32(26),e.AddressInfo.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={peerId:o(0),seq:0n,addresses:[]},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:s.peerId=t.bytes();break;case 2:s.seq=t.uint64();break;case 3:if(null!=n.limits?.addresses&&s.addresses.length===n.limits.addresses)throw new Xt('Decode error - map field "addresses" had too many elements');s.addresses.push(e.AddressInfo.codec().decode(t,t.uint32(),{limits:n.limits?.addresses$}));break;default:t.skipType(7&r)}}return s}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(wd||(wd={}));class vd{static createFromProtobuf=e=>{const t=wd.decode(e),r=Lc(Le(t.peerId)),n=(t.addresses??[]).map((e=>bl(e.multiaddr))),s=t.seq;return new vd({peerId:r,multiaddrs:n,seqNumber:s})};static DOMAIN="libp2p-peer-record";static CODEC=bd;peerId;multiaddrs;seqNumber;domain=vd.DOMAIN;codec=vd.CODEC;marshaled;constructor(e){const{peerId:t,multiaddrs:r,seqNumber:n}=e;this.peerId=t,this.multiaddrs=r??[],this.seqNumber=n??BigInt(Date.now())}marshal(){return null==this.marshaled&&(this.marshaled=wd.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map((e=>({multiaddr:e.bytes})))})),this.marshaled}equals(e){return e instanceof vd&&!!this.peerId.equals(e.peerId)&&this.seqNumber===e.seqNumber&&!!function(e,t){const r=(e,t)=>e.toString().localeCompare(t.toString());return e.length===t.length&&(t.sort(r),e.sort(r).every(((e,r)=>t[r].equals(e))))}(this.multiaddrs,e.multiaddrs)}}function Ed(e,t){let r;const n=()=>{clearTimeout(r),r=setTimeout((()=>{r=void 0,e()}),t)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}function Sd(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);}const Ad=globalThis.CustomEvent??Event;function Id(e,t){const r=Pu(e,t),n={async read(e,t){const n=await r.read(t);return e.decode(n)},async write(e,t,n){await r.write(t.encode(e),n)},async writeV(e,t,n){await r.writeV(e.map((e=>t.encode(e))),n)},pb:e=>({read:async t=>n.read(e,t),write:async(t,r)=>n.write(t,e,r),writeV:async(t,r)=>n.writeV(t,e,r),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var _d;(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.protocolVersion&&(t.uint32(42),t.string(e.protocolVersion)),null!=e.agentVersion&&(t.uint32(50),t.string(e.agentVersion)),null!=e.publicKey&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.listenAddrs)for(const r of e.listenAddrs)t.uint32(18),t.bytes(r);if(null!=e.observedAddr&&(t.uint32(34),t.bytes(e.observedAddr)),null!=e.protocols)for(const r of e.protocols)t.uint32(26),t.string(r);null!=e.signedPeerRecord&&(t.uint32(66),t.bytes(e.signedPeerRecord)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={listenAddrs:[],protocols:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 5:n.protocolVersion=e.string();break;case 6:n.agentVersion=e.string();break;case 1:n.publicKey=e.bytes();break;case 2:if(null!=r.limits?.listenAddrs&&n.listenAddrs.length===r.limits.listenAddrs)throw new Xt('Decode error - map field "listenAddrs" had too many elements');n.listenAddrs.push(e.bytes());break;case 4:n.observedAddr=e.bytes();break;case 3:if(null!=r.limits?.protocols&&n.protocols.length===r.limits.protocols)throw new Xt('Decode error - map field "protocols" had too many elements');n.protocols.push(e.string());break;case 8:n.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(_d||(_d={}));const Cd="ipfs";class xd{host;protocol;started;timeout;peerId;privateKey;peerStore;registrar;addressManager;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;events;runOnLimitedConnection;log;constructor(e,t){var r,n;this.protocol=t.protocol,this.started=!1,this.peerId=e.peerId,this.privateKey=e.privateKey,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.events=e.events,this.log=t.log,this.timeout=t.timeout??5e3,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.maxMessageSize=t.maxMessageSize??8192,this.maxObservedAddresses=t.maxObservedAddresses??10,this.runOnLimitedConnection=t.runOnLimitedConnection??true,this.host={protocolVersion:(t.protocolPrefix??Cd)+"/0.1.0",agentVersion:(r=e.nodeInfo,n=t.agentVersion,null!=n?n:r.userAgent)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:Ye(this.host.agentVersion),ProtocolVersion:Ye(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,(e=>{this.handleProtocol(e).catch((e=>{this.log.error(e)}))}),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}}var kd,Td={},Pd=(kd||(kd=1,function(){var e,t,r,n,s,i,o,a;a=e=>[(-16777216&e)>>>24,(16711680&e)>>>16,(65280&e)>>>8,255&e].join("."),o=e=>{var r,n,s,i,o,a;for(r=[],s=i=0;i<=3&&0!==e.length;s=++i){if(s>0){if("."!==e[0])throw Error("Invalid IP");e=e.substring(1)}o=(a=t(e))[0],n=a[1],e=e.substring(n),r.push(o)}if(0!==e.length)throw Error("Invalid IP");switch(r.length){case 1:if(r[0]>4294967295)throw Error("Invalid IP");return r[0]>>>0;case 2:if(r[0]>255||r[1]>16777215)throw Error("Invalid IP");return(r[0]<<24|r[1])>>>0;case 3:if(r[0]>255||r[1]>255||r[2]>65535)throw Error("Invalid IP");return(r[0]<<24|r[1]<<16|r[2])>>>0;case 4:if(r[0]>255||r[1]>255||r[2]>255||r[3]>255)throw Error("Invalid IP");return(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0;default:throw Error("Invalid IP")}},n=(r=e=>e.charCodeAt(0))("0"),i=r("a"),s=r("A"),t=e=>{var t,o,a,c,l;for(c=0,t=10,o="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,o="7")),l=a;a<e.length;){if("0"<=e[a]&&e[a]<=o)c=c*t+(r(e[a])-n)>>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")c=c*t+(10+r(e[a])-i)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+r(e[a])-s)>>>0}}if(c>4294967295)throw Error("too large");a++}if(a===l)throw Error("empty octet");return[c,a]},e=function(){function e(e,t){var r,n,s;if("string"!=typeof e)throw Error("Missing `net' parameter");if(t||(s=e.split("/",2),e=s[0],t=s[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=o(t)}catch(e){throw Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else{if(!t&&0!==t)throw Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(o(e)&this.maskLong)>>>0}catch(t){throw Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"==typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(o(t)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(a(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=o(this.first),r=o(this.last),t=0;n<=r;)e(a(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),Td.ip2long=o,Td.long2ip=a,Td.Netmask=e}()),Td);const Rd=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"].map((e=>new Pd.Netmask(e)));function Ld(e){for(const t of Rd)if(t.contains(e))return!0;return!1}function Dd(e){return zc(e)?Ld(e):/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(e)?function(e){const t=e.split(":");if(t.length<2)return!1;const r=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0");return Ld(`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(r.substring(0,2),16)}.${parseInt(r.substring(2),16)}`)}(e):function(e){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)}(e)?function(e){const t=e.split(":");return Ld(t[t.length-1])}(e):jc(e)?function(e){return/^::$/.test(e)||/^::1$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e)}(e):void 0}function Md(e){try{for(const{code:t}of e.getComponents())if(t!==Vc)return 4===t||t===Kc}catch{}return!1}function Nd(e){try{if(!Md(e))return!1;const[[,t]]=e.stringTuples();return null!=t&&(Dd(t)??!1)}catch{}return!0}const Od=e=>({match:t=>!(t.length<1)&&!!e(t[0])&&t.slice(1),pattern:"fn"}),Ud=e=>({match:t=>Od((t=>t===e)).match(t),pattern:e}),Fd=()=>({match:e=>Od((e=>"string"==typeof e)).match(e),pattern:"{string}"}),Bd=()=>({match:e=>Od((e=>!isNaN(parseInt(e)))).match(e),pattern:"{number}"}),$d=()=>({match(e){if(e.length<2)return!1;if("p2p"!==e[0]&&"ipfs"!==e[0])return!1;if(!e[1].startsWith("Q")&&!e[1].startsWith("1"))return!1;try{fe.decode("z"+e[1])}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),qd=()=>({match(e){if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{we.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),zd=e=>({match(t){const r=e.match(t);return!1===r?t:r},pattern:`optional(${e.pattern})`}),jd=(...e)=>({match(t){let r;for(const n of e){const e=n.match(t);!1!==e&&(null==r||e.length<r.length)&&(r=e)}return null!=r&&r},pattern:`or(${e.map((e=>e.pattern)).join(", ")})`}),Kd=(...e)=>({match(t){for(const r of e){const e=r.match(t);if(!1===e)return!1;t=e}return t},pattern:`and(${e.map((e=>e.pattern)).join(", ")})`});function Vd(...e){function t(t){let r=(e=>e.toString().split("/").slice(1))(t);for(const t of e){const e=t.match(r);if(!1===e)return!1;r=e}return r}return{matchers:e,matches:e=>!1!==t(e),exactMatch(e){const r=t(e);return!1!==r&&0===r.length}}}const Hd=Vd($d()),Gd=Kd(Ud("dns4"),Fd()),Wd=Kd(Ud("dns6"),Fd()),Xd=Kd(Ud("dnsaddr"),Fd()),Zd=Kd(Ud("dns"),Fd());Vd(Gd,zd($d())),Vd(Wd,zd($d())),Vd(Xd,zd($d())),Vd(jd(Zd,Xd,Gd,Wd),zd($d()));const Yd=Kd(Ud("ip4"),Od(zc)),Qd=Kd(Ud("ip6"),Od(jc)),Jd=jd(Yd,Qd),ep=jd(Jd,Zd,Gd,Wd,Xd),tp=Vd(jd(Jd,Kd(jd(Zd,Xd,Gd,Wd),zd($d())))),rp=Vd(Yd),np=Vd(Qd);Vd(Jd);const sp=Kd(ep,Ud("tcp"),Bd()),ip=Kd(ep,Ud("udp"),Bd()),op=Vd(Kd(sp,zd($d())));Vd(ip);const ap=Kd(ip,Ud("quic"),zd($d())),cp=Kd(ip,Ud("quic-v1"),zd($d())),lp=jd(ap,cp);Vd(ap);const up=Vd(cp),hp=jd(ep,sp,ip,ap,cp),dp=jd(Kd(hp,Ud("ws"),zd($d()))),pp=Vd(dp),fp=jd(Kd(hp,Ud("wss"),zd($d())),Kd(hp,Ud("tls"),zd(Kd(Ud("sni"),Fd())),Ud("ws"),zd($d()))),gp=Vd(fp),mp=Kd(ip,Ud("webrtc-direct"),zd(qd()),zd(qd()),zd($d())),yp=Vd(mp),bp=Kd(cp,Ud("webtransport"),zd(qd()),zd(qd()),zd($d())),wp=Vd(bp),vp=jd(dp,fp,Kd(sp,zd($d())),Kd(lp,zd($d())),Kd(ep,zd($d())),mp,bp,$d());Vd(vp);const Ep=Vd(Kd(vp,Ud("p2p-circuit"),$d())),Sp=Vd(jd(Kd(vp,Ud("p2p-circuit"),Ud("webrtc"),zd($d())),Kd(vp,Ud("webrtc"),zd($d())),Kd(Ud("webrtc"),zd($d()))));Vd(jd(Kd(ep,Ud("tcp"),Bd(),Ud("http"),zd($d())),Kd(ep,Ud("http"),zd($d())))),Vd(jd(Kd(ep,Ud("tcp"),jd(Kd(Ud("443"),Ud("http")),Kd(Bd(),Ud("https")),Kd(Bd(),Ud("tls"),Ud("http"))),zd($d())),Kd(ep,Ud("tls"),Ud("http"),zd($d())),Kd(ep,Ud("https"),zd($d())))),Vd(jd(Kd(Ud("memory"),Fd(),zd($d()))));class Ap extends xd{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??Cd}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??true)&&e.events.addEventListener("connection:open",(e=>{const t=e.detail;this.identify(t).catch((e=>{e.name!==jn.name&&this.log.error("error during identify trigged by connection:open",e)}))}))}[ts]=["@libp2p/identify"];async _identify(e,t={}){let r;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{r=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});const n=Id(r,{maxDataLength:this.maxMessageSize}).pb(_d),s=await n.read(t);return await r.close(t),s}catch(e){throw r?.abort(e),e}}async identify(e,t={}){const r=await this._identify(e,t),{publicKey:n,protocols:s,observedAddr:i}=r;if(null==n)throw new Kn("public key was missing from identify message");const o=Dc(Sc(n).toCID());if(!e.remotePeer.equals(o))throw new Kn("identified peer does not match the expected peer");if(this.peerId.equals(o))throw new Kn("identified peer is our own peer id?");return this.maybeAddObservedAddress(i),this.log("identify completed for peer %p and protocols %o",o,s),async function(e,t,r,n,s){if(r("received identify from %p",n.remotePeer),null==s)throw new Kn("message was null or undefined");const i={};if(s.listenAddrs.length>0&&(i.addresses=s.listenAddrs.map((e=>({isCertified:!1,multiaddr:bl(e)})))),s.protocols.length>0&&(i.protocols=s.protocols),null!=s.publicKey){const e=Sc(s.publicKey);if(!Rc(e).equals(n.remotePeer))throw new Kn("public key did not match remote PeerId");i.publicKey=e}let o;if(null!=s.signedPeerRecord){r.trace("received signedPeerRecord from %p",n.remotePeer);let t=s.signedPeerRecord;const a=await md.openAndCertify(t,vd.DOMAIN);let c=vd.createFromProtobuf(a.payload);const l=Dc(a.publicKey.toCID());if(!c.peerId.equals(l))throw new Kn("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(c.peerId))throw new Kn("signing key does not match remote PeerId");let u;try{u=await e.get(c.peerId)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=u&&(i.metadata=u.metadata,null!=u.peerRecordEnvelope)){const e=md.createFromProtobuf(u.peerRecordEnvelope),n=vd.createFromProtobuf(e.payload);n.seqNumber>=c.seqNumber&&(r("sequence number was lower or equal to existing sequence number - stored: %d received: %d",n.seqNumber,c.seqNumber),c=n,t=u.peerRecordEnvelope)}i.peerRecordEnvelope=t,i.addresses=c.multiaddrs.map((e=>({isCertified:!0,multiaddr:e}))),o={seq:c.seqNumber,addresses:c.multiaddrs}}else r("%p did not send a signed peer record",n.remotePeer);if(r.trace("patching %p with",n.remotePeer,i),await e.patch(n.remotePeer,i),null!=s.agentVersion||null!=s.protocolVersion){const t={};null!=s.agentVersion&&(t.AgentVersion=Ye(s.agentVersion)),null!=s.protocolVersion&&(t.ProtocolVersion=Ye(s.protocolVersion)),r.trace("merging %p metadata",n.remotePeer,t),await e.merge(n.remotePeer,{metadata:t})}const a={peerId:n.remotePeer,protocolVersion:s.protocolVersion,agentVersion:s.agentVersion,publicKey:s.publicKey,listenAddrs:s.listenAddrs.map((e=>bl(e))),observedAddr:null==s.observedAddr?void 0:bl(s.observedAddr),protocols:s.protocols,signedPeerRecord:o,connection:n};return t.safeDispatchEvent("peer:identify",{detail:a}),a}(this.peerStore,this.events,this.log,e,r)}maybeAddObservedAddress(e){const t=function(e){if(null!=e&&e.length>0)try{return bl(e)}catch{}}(e);if(null==t)return;if(this.log.trace("our observed address was %a",t),Nd(t))return void this.log.trace("our observed address was private");const r=t.getComponents();r[0].code!==Kc&&(r[0].code!==Vc||r[1].code!==Kc)||function(e){try{for(const{code:r,value:n}of e.getComponents())if(null!=n&&r===Kc)return t=n,new pl("2000::/3").contains(t)}catch{}var t;return!1}(t)?op.exactMatch(t)||(this.log.trace("storing the observed address"),this.addressManager.addObservedAddr(t)):this.log.trace("our observed address was IPv6 but not a global unicast address")}async handleProtocol(e){const{connection:t,stream:r}=e,n=AbortSignal.timeout(this.timeout);try{const e=await this.peerStore.get(this.peerId),s=this.addressManager.getAddresses().map((e=>e.decapsulateCode(wl("p2p").code)));let i=e.peerRecordEnvelope;if(s.length>0&&null==i){const e=new vd({peerId:this.peerId,multiaddrs:s});i=(await md.seal(e,this.privateKey)).marshal().subarray()}let o=t.remoteAddr.bytes;tp.matches(t.remoteAddr)||(o=void 0);const a=Id(r).pb(_d);await a.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Ac(this.privateKey.publicKey),listenAddrs:s.map((e=>e.bytes)),signedPeerRecord:i,observedAddr:o,protocols:e.protocols},{signal:n}),await r.close({signal:n})}catch(e){this.log.error("could not respond to identify request",e),r.abort(e)}}}function Ip(e={}){return t=>new Ap(t,e)}function _p(e,t){const r=function(e){if(null!=e){if("function"==typeof e[Symbol.iterator])return e[Symbol.iterator]();if("function"==typeof e[Symbol.asyncIterator])return e[Symbol.asyncIterator]();if("function"==typeof e.next)return e}throw Error("argument is not an iterator or iterable")}(e).return?.();var n;null!=(n=r)&&"function"==typeof n.then&&"function"==typeof n.catch&&"function"==typeof n.finally&&r.catch((e=>{t.error("could not cause iterator to return",e)}))}const Cp=()=>{const e=Error("Delay aborted");return e.name="AbortError",e},xp=new WeakMap,kp=function({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(Cp());let i,o,a;const c=e??clearTimeout,l=()=>{c(i),a(Cp())},u=new Promise(((e,c)=>{o=()=>{s&&s.removeEventListener("abort",l),e(n)},a=c,i=(t??setTimeout)(o,r)}));return s&&s.addEventListener("abort",l,{once:!0}),xp.set(u,(()=>{c(i),i=null,o()})),u}}();class Tp extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}}let Pp=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};class Rp{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??1e3*this.duration/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Lp}async consume(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r);let i=this.memoryStorage.incrby(n,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(n,i.consumedPoints,this.blockDuration)),new Tp("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let e=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));e<this.execEvenlyMinDelayMs&&(e=i.consumedPoints*this.execEvenlyMinDelayMs),await kp(e)}return i}penalty(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r),i=this.memoryStorage.incrby(n,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r),i=this.memoryStorage.incrby(n,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){const r=1e3*t,n=this.points+1;return this.memoryStorage.set(this.getKey(e),n,t),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:n,isFirstInDuration:!1}}set(e,t,r=0){const n=1e3*(r>=0?r:this.duration);return this.memoryStorage.set(this.getKey(e),t,r),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){const t=this.memoryStorage.get(this.getKey(e));return null!=t&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return null!=e?.customDuration&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}}class Lp{storage;constructor(){this.storage=new Map}incrby(e,t,r){const n=this.storage.get(e);if(null!=n){const s=null!=n.expiresAt?n.expiresAt.getTime()-(new Date).getTime():-1;return null==n.expiresAt||s>0?(n.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){const n=1e3*r,s=this.storage.get(e);null!=s&&clearTimeout(s.timeoutId);const i={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,i),n>0&&(i.timeoutId=setTimeout((()=>{this.storage.delete(e)}),n),null!=i.timeoutId.unref&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:i.value,isFirstInDuration:!0}}get(e){const t=this.storage.get(e);if(null!=t)return{remainingPoints:0,msBeforeNext:null!=t.expiresAt?t.expiresAt.getTime()-(new Date).getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){const t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}var Dp;(e=>{e[e.NEW_STREAM=0]="NEW_STREAM",e[e.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",e[e.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",e[e.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",e[e.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",e[e.RESET_RECEIVER=5]="RESET_RECEIVER",e[e.RESET_INITIATOR=6]="RESET_INITIATOR"})(Dp||(Dp={}));const Mp=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),Np=Object.freeze({NEW_STREAM:Dp.NEW_STREAM,MESSAGE:Dp.MESSAGE_INITIATOR,CLOSE:Dp.CLOSE_INITIATOR,RESET:Dp.RESET_INITIATOR}),Op=Object.freeze({MESSAGE:Dp.MESSAGE_RECEIVER,CLOSE:Dp.CLOSE_RECEIVER,RESET:Dp.RESET_RECEIVER}),Up=1048576;class Fp{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=Up,t=4194304){this._buffer=new Us,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(null==e||0===e.length)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new Kn("Unprocessed message queue size too large!");const t=[];for(;0!==this._buffer.length;){if(null==this._headerInfo)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(e){if("InvalidMessageError"===e.name)throw e;break}const{id:r,type:n,length:s,offset:i}=this._headerInfo;if(this._buffer.length-i<s)break;const o={id:r,type:n};n!==Dp.NEW_STREAM&&n!==Dp.MESSAGE_INITIATOR&&n!==Dp.MESSAGE_RECEIVER||(o.data=this._buffer.sublist(i,i+s)),t.push(o),this._buffer.consume(i+s),this._headerInfo=null}return t}_decodeHeader(e){const{value:t,offset:r}=qp(e),{value:n,offset:s}=qp(e,r),i=7&t;if(null==Mp[i])throw Error("Invalid type received: "+i);if(n>this._maxMessageSize)throw new Kn("Message size too large");return{id:t>>3,type:i,offset:r+s,length:n}}}const Bp=128,$p=127;function qp(e,t=0){let r,n=0,s=0,i=t;const o=e.length;do{if(i>=o||s>49)throw t=0,new RangeError("Could not decode varint");r=e.get(i++),n+=s<28?(r&$p)<<s:(r&$p)*Math.pow(2,s),s+=7}while(r>=Bp);return{value:n,offset:t=i-t}}const zp=10240,jp=new class{_pool;_poolOffset;constructor(){this._pool=a(zp),this._poolOffset=0}write(e,t){const r=this._pool;let n=this._poolOffset;y(e.id<<3|e.type,r,n),n+=f(e.id<<3|e.type),e.type!==Dp.NEW_STREAM&&e.type!==Dp.MESSAGE_INITIATOR&&e.type!==Dp.MESSAGE_RECEIVER||null==e.data?(y(0,r,n),n+=f(0)):(y(e.data.length,r,n),n+=f(e.data.length));const s=r.subarray(this._poolOffset,n);zp-n<100?(this._pool=a(zp),this._poolOffset=0):this._poolOffset=n,t.append(s),e.type!==Dp.NEW_STREAM&&e.type!==Dp.MESSAGE_INITIATOR&&e.type!==Dp.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}};class Kp extends Error{constructor(e="Stream input buffer error"){super(e),this.name="StreamInputBufferError"}}function Vp(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class Hp{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=Ws(),this.closed=Ws(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??5e3,this.onEnd=e.onEnd,this.onCloseRead=e.onCloseRead,this.onCloseWrite=e.onCloseWrite,this.onReset=e.onReset,this.onAbort=e.onAbort,this.source=this.streamSource=Qs({onEnd:e=>{null!=e?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(e){if("ready"!==this.writeStatus)throw new Un(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";const t={signal:this.sinkController.signal};if("outbound"===this.direction){const e=this.sendNewStream(t);Vp(e)&&await e}const r=()=>{_p(e,this.log)};try{this.sinkController.signal.addEventListener("abort",r),this.log.trace("sink reading from source");for await(let r of e){r=r instanceof Uint8Array?new Us(r):r;const e=this.sendData(r,t);Vp(e)&&(this.sendingData=Ws(),await e,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",r)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),"writing"===this.writeStatus&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){null==this.timeline.closeRead&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseRead?.(),null!=this.timeline.closeWrite?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){null==this.timeline.closeWrite&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseWrite?.(),null!=this.timeline.closeRead?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){"open"===this.status&&(this.log.trace("closing gracefully"),this.status="closing",await ei(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(e={}){if("closing"===this.readStatus||"closed"===this.readStatus)return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);const t=this.readStatus;this.readStatus="closing","reset"!==this.status&&"aborted"!==this.status&&null==this.timeline.closeRead&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),"ready"===t&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){"closing"!==this.writeStatus&&"closed"!==this.writeStatus&&(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),"ready"===this.writeStatus&&(this.log.trace("sink was never sunk, sink an empty array"),await ei(this.sink([]),e.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await ei(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await ei(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;this.log("abort with error",e),this.log("try to send reset to remote");const t=this.sendReset();Vp(t)&&t.catch((e=>{this.log.error("error sending reset message",e)})),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;const e=new On("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){"writing"===this.writeStatus&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){"closing"!==this.readStatus&&"closed"!==this.readStatus&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){"closing"!==this.readStatus&&"closed"!==this.readStatus?(this.log.trace("remote close write"),this._closeSource()):this.log("received remote close write but local source is already closed")}remoteCloseRead(){"closing"!==this.writeStatus&&"closed"!==this.writeStatus?(this.log.trace("remote close read"),this._closeSink()):this.log("received remote close read but local sink is already closed")}destroy(){"closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status?(this.log.trace("stream destroyed"),this._closeSinkAndSource()):this.log("received destroy but we are already closed")}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}}class Gp extends Hp{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types="outbound"===e.direction?Np:Op,this.send=e.send,this.name=e.name,this.streamId=e.streamId,this.maxDataSize=e.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:Np.NEW_STREAM,data:new Us(Ye(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){const t=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,t)}),e.consume(t)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}}function Wp(e){const t={...e,type:`${Mp[e.type]} (${e.type})`};return e.type===Dp.NEW_STREAM&&(t.data=tn(e.data instanceof Uint8Array?e.data:e.data.subarray())),e.type!==Dp.MESSAGE_INITIATOR&&e.type!==Dp.MESSAGE_RECEIVER||(t.data=tn(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class Xp{protocol="/mplex/6.7.0";sink;source;log;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;logger;constructor(e,t){t=t??{},this.log=e.logger.forComponent("libp2p:mplex"),this.logger=e.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=t,this.closeTimeout=t.closeTimeout??500,this.sink=this._createSink(),this._source=Qs({objectMode:!0,onEnd:()=>{for(const e of this._streams.initiators.values())e.destroy();for(const e of this._streams.receivers.values())e.destroy()}}),this.source=si(this._source,(e=>async function*(e){for await(const t of e){const e=new Us;jp.write(t,e),yield e}}(e))),this.closeController=new AbortController,this.rateLimiter=new Rp({points:t.disconnectThreshold??5,duration:1})}get streams(){const e=[];for(const t of this._streams.initiators.values())e.push(t);for(const t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new Nn("Muxer already closed");const t=this._streamId++;e=null==e?t.toString():e.toString();const r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}async close(e){if(this.closeController.signal.aborted)return;const t=e?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map((async e=>e.close({signal:t})))),this._source.end(),await this._source.onEmpty({signal:t}),this.closeController.abort()}catch(e){this.abort(e)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach((t=>{t.abort(e)})),this.closeController.abort(e))}_newReceiverStream(e){const{id:t,name:r}=e,n=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:n})}_newStream(e){const{id:t,name:r,type:n,registry:s}=e;if(this.log("new %s stream %s",n,t),"initiator"===n&&this._streams.initiators.size===(this._init.maxOutboundStreams??1024))throw new Yn("Too many outbound streams open");if(s.has(t))throw Error(`${n} stream ${t} already exists!`);const i=function(e){const{id:t,name:r,send:n,onEnd:s,type:i="initiator",maxMsgSize:o=Up}=e;return new Gp({id:"initiator"===i?"i"+t:"r"+t,streamId:t,name:""+(r??t),direction:"initiator"===i?"outbound":"inbound",maxDataSize:o,onEnd:s,send:n,log:e.logger.forComponent(`libp2p:mplex:stream:${i}:${t}`)})}({id:t,name:r,send:async e=>{this.log.enabled&&this.log.trace("%s stream %s send",n,t,Wp(e)),this._source.push(e)},type:n,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",n,t,i.protocol),s.delete(t),null!=this._init.onStreamEnd&&this._init.onStreamEnd(i)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return s.set(t,i),i}_createSink(){return async e=>{this.closeController.signal.addEventListener("abort",(()=>{_p(e,this.log)}));try{const t=new Fp(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const r of e)for(const e of t.write(r))await this._handleIncoming(e);this._source.end()}catch(e){this.log("error in sink",e),this._source.end(e)}finally{this.closeController.signal.removeEventListener("abort",t)}}}async _handleIncoming(e){const{id:t,type:r}=e;if(this.log.enabled&&this.log.trace("incoming message",Wp(e)),e.type===Dp.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024)){this.log("too many inbound streams open"),this._source.push({id:t,type:Dp.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{return this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),void this.abort(Error("Too many open streams"))}return}const r=this._newReceiverStream({id:t,name:tn(e.data instanceof Uint8Array?e.data:e.data.subarray())});return void(null!=this._init.onIncomingStream&&this._init.onIncomingStream(r))}const n=(1&~r?this._streams.receivers:this._streams.initiators).get(t);if(null==n){this.log("missing stream %s for message type %s",t,Mp[r]);try{await this.rateLimiter.consume("missing-stream",1)}catch{return this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),void this.abort(Error("Too many messages for missing streams"))}return}const s=this._init.maxStreamBufferSize??4194304;try{switch(r){case Dp.MESSAGE_INITIATOR:case Dp.MESSAGE_RECEIVER:if(n.sourceReadableLength()>s)throw this._source.push({id:e.id,type:r===Dp.MESSAGE_INITIATOR?Dp.RESET_RECEIVER:Dp.RESET_INITIATOR}),new Kp("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");n.sourcePush(e.data);break;case Dp.CLOSE_INITIATOR:case Dp.CLOSE_RECEIVER:n.remoteCloseWrite();break;case Dp.RESET_INITIATOR:case Dp.RESET_RECEIVER:n.reset();break;default:this.log("unknown message type %s",r)}}catch(e){this.log.error("error while processing message",e),n.abort(e)}}}class Zp{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}[Symbol.toStringTag]="@libp2p/mplex";[ts]=["@libp2p/stream-multiplexing"];createStreamMuxer(e={}){return new Xp(this.components,{...e,...this._init})}}function Yp(e={}){return t=>new Zp(t,e)}class Qp{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;log;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[ts]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(e){this.log("incoming ping from %p",e.connection.remotePeer);const{stream:t}=e,r=Date.now(),n=Cu(t);let s=!1;Promise.resolve().then((async()=>{for(;;){const e=AbortSignal.timeout(this.timeout);e.addEventListener("abort",(()=>{t?.abort(new Hn("ping timeout"))}));const r=await n.read({bytes:32,signal:e});await n.write(r,{signal:e}),s=!0}})).catch((r=>{s&&"UnexpectedEOFError"===r.name&&"ready"!==t.readStatus||(this.log.error("incoming ping from %p failed with error - %e",e.connection.remotePeer,r),t?.abort(r))})).finally((()=>{const n=Date.now()-r;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,n);const s=AbortSignal.timeout(this.timeout);t.close({signal:s}).catch((r=>{this.log.error("error closing ping stream from %p - %e",e.connection.remotePeer,r),t?.abort(r)}))}))}async ping(e,t={}){this.log("pinging %p",e);const r=Date.now(),n=Ya(32),s=await this.components.connectionManager.openConnection(e,t);let i;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{i=await s.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});const e=Cu(i),[,o]=await Promise.all([e.write(n,t),e.read({...t,bytes:32})]),a=Date.now()-r;if(!Ds(n,o.subarray()))throw new Vn(`Received wrong ping ack after ${a}ms`);return this.log("ping %p complete in %dms",s.remotePeer,a),a}catch(e){throw this.log.error("error while pinging %p",s.remotePeer,e),i?.abort(e),e}finally{null!=i&&await i.close(t)}}}function Jp(e={}){return t=>new Qp(t,e)}const ef=[6,53,56,54,55];function tf(e){return nf("sni",e)?.value}function rf(e){const t=nf("tcp",e)?.value;return null==t?"":":"+t}function nf(e,t){return t.find((t=>t.name===e))}function sf(e){return e.some((({code:e})=>448===e))}function of(e,t){const r=af[e.name];if(null==r)throw Error("Can't interpret protocol "+e.name);const n=r(e,t);return e.code===Kc?`[${n}]`:n}const af={ip4:e=>e.value,ip6:(e,t)=>0===t.length?e.value:`[${e.value}]`,tcp(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return`tcp://${of(r,t)}:${e.value}`},udp(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return`udp://${of(r,t)}:${e.value}`},dnsaddr:e=>e.value,dns4:e=>e.value,dns6:e=>e.value,dns:e=>e.value,ipfs(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return""+of(r,t)},p2p(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return""+of(r,t)},http(e,t){const r=sf(t),n=tf(t),s=rf(t);if(r&&null!=n)return`https://${n}${s}`;const i=r?"https://":"http://",o=t.pop();if(null==o)throw Error("Unexpected end of multiaddr");let a=of(o,t);return a=a?.replace("tcp://",""),`${i}${a}`},"http-path"(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return`${of(r,t)}${decodeURIComponent(e.value??"")}`},tls(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return of(r,t)},sni(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return of(r,t)},https(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");let n=of(r,t);return n=n?.replace("tcp://",""),"https://"+n},ws(e,t){const r=sf(t),n=tf(t),s=rf(t);if(r&&null!=n)return`wss://${n}${s}`;const i=r?"wss://":"ws://",o=t.pop();if(null==o)throw Error("Unexpected end of multiaddr");let a=of(o,t);return a=a?.replace("tcp://",""),`${i}${a}`},wss(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");let n=of(r,t);return n=n?.replace("tcp://",""),"wss://"+n}};var cf,lf,uf=async e=>{if(e.readyState>=2)throw Error("socket closed");1!==e.readyState&&await new Promise(((t,r)=>{function n(){e.removeEventListener("open",s),e.removeEventListener("error",i)}function s(){n(),t()}function i(t){n(),r(t.error??Error("connect ECONNREFUSED "+e.url))}e.addEventListener("open",s),e.addEventListener("error",i)}))},hf=(e,t)=>((t=t??{}).closeOnEnd=!1!==t.closeOnEnd,async r=>{for await(const t of r){try{await uf(e)}catch(e){if("socket closed"===e.message)break;throw e}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(t)}null!=t.closeOnEnd&&e.readyState<=1&&await new Promise(((t,r)=>{e.addEventListener("close",(e=>{if(e.wasClean||1006===e.code)t();else{const t=Object.assign(Error("ws error"),{event:e});r(t)}})),setTimeout((()=>{e.close()}))}))}),df={},pf={},ff=function(){if(lf)return df;lf=1,Object.defineProperty(df,"__esModule",{value:!0});const e=function(){if(cf)return pf;cf=1,Object.defineProperty(pf,"__esModule",{value:!0});class e{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;const t={value:e,done:!1};if(this.pullQueue.length){const e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch((()=>{})),this.pushQueue.push(t)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:()=>{const e=this.pushQueue.shift();return e?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),e):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise(((e,t)=>{this.pullQueue.push({resolve:e,reject:t})}))},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class t{constructor(t,{highWaterMark:r=100,lowWaterMark:n=1}={}){const s=new e;s.highWaterMark=r,s.lowWaterMark=n,s.removeCallback=t({push:e=>s.push(e),stop:()=>s.stop(),fail:e=>s.fail(e),on(e,t){s.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>s[Symbol.asyncIterator](),Object.freeze(this)}}return pf.EventIterator=t,pf.default=t,pf}();return df.EventIterator=e.EventIterator,df.subscribe=function(t,r,n){return new e.EventIterator((({push:e})=>(this.addEventListener(t,e,r),()=>this.removeEventListener(t,e,r))),n)},df.default=e.EventIterator,df}();function gf(e){return e instanceof ArrayBuffer||"ArrayBuffer"===e?.constructor?.name&&"number"==typeof e?.byteLength}var mf=WebSocket;const yf={"http:":"ws:","https:":"wss:"};class bf extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}}function wf(e){return e.filter((e=>gp.exactMatch(e)||pp.exactMatch(e)))}function vf(e){return e.filter((e=>gp.exactMatch(e)))}class Ef{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,null!=e.metrics&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[_n]=!0;[Symbol.toStringTag]="@libp2p/websockets";[ts]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};const r=function(e,t,r){const n=r.logger.forComponent("libp2p:websockets:maconn"),s=r.metrics,i=r.metricPrefix??"",o={log:n,async sink(t){try{await e.sink(async function*(){for await(const e of t)e instanceof Uint8Array?yield e:yield e.subarray()}())}catch(e){"aborted"!==e.type&&n.error(e)}},source:e.source,remoteAddr:t,timeline:{open:Date.now()},async close(t={}){const r=Date.now();if(null==t.signal){const e=AbortSignal.timeout(500);t={...t,signal:e}}const s=()=>{const{host:e,port:t}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-r),this.abort(new xn("Socket close timeout"))};t.signal?.addEventListener("abort",s);try{await e.close()}catch(e){n.error("error closing WebSocket gracefully",e),this.abort(e)}finally{t.signal?.removeEventListener("abort",s),o.timeline.close=Date.now()}},abort(t){const{host:r,port:a}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",r,a,t),e.destroy(),o.timeline.close=Date.now(),s?.increment({[i+"error"]:!0})}};return e.socket.addEventListener("close",(()=>{s?.increment({[i+"close"]:!0}),null==o.timeline.close&&(o.timeline.close=Date.now())}),{once:!0}),o}(await this._connect(e,t),e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",r.remoteAddr);const n=await t.upgrader.upgradeOutbound(r,t);return this.log("outbound connection %s upgraded",r.remoteAddr),n}async _connect(e,t){t?.signal?.throwIfAborted();const r=e.toOptions();this.log("dialing %s:%s",r.host,r.port);const n=Ws(),s=function(e,t){t=t??{};const r=((e,t)=>{if(e.startsWith("//")&&(e=`${t?.protocol??"ws:"}${e}`),e.startsWith("/")&&null!=t){const r=t.protocol??"ws:",n=t.host,s=null!=t.port&&!0!==n?.endsWith(":"+t.port)?":"+t.port:"";e=`${r}//${n}${s}${e}`}const r=new URL(e);for(const[e,t]of Object.entries(yf))r.protocol===e&&(r.protocol=t);return r})(e,"undefined"==typeof window?void 0:window.location);return((e,t)=>{t=t??{};const r=(e=>{e.binaryType="arraybuffer";const t=async()=>{await new Promise(((t,r)=>{if(s)return void t();if(null!=n)return void r(n);const i=t=>{e.removeEventListener("open",o),e.removeEventListener("error",a),t()},o=()=>{i(t)},a=t=>{i((()=>{r(t.error??Error("connect ECONNREFUSED "+e.url))}))};e.addEventListener("open",o),e.addEventListener("error",a)}))},r=async function*(){const r=new ff.EventIterator((({push:t,stop:r,fail:n})=>{const s=e=>{let r=null;"string"==typeof e.data&&(r=Ye(e.data)),gf(e.data)&&(r=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(r=e.data),null!=r&&t(r)},i=e=>{n(e.error??Error("Socket error"))};return e.addEventListener("message",s),e.addEventListener("error",i),e.addEventListener("close",r),()=>{e.removeEventListener("message",s),e.removeEventListener("error",i),e.removeEventListener("close",r)}}),{highWaterMark:1/0});await t();for await(const e of r)yield gf(e)?new Uint8Array(e):e}();let n,s=1===e.readyState;return e.addEventListener("open",(()=>{s=!0,n=null})),e.addEventListener("close",(()=>{s=!1,n=null})),e.addEventListener("error",(t=>{s||(n=t.error??Error("connect ECONNREFUSED "+e.url))})),Object.assign(r,{connected:t})})(e);let n=t.remoteAddress,s=t.remotePort;if(null!=e.url)try{const t=new URL(e.url);n=t.hostname,s=parseInt(t.port,10)}catch{}if(null==n||null==s)throw Error("Remote connection did not have address and/or port");return{sink:hf(e,t),source:r,async connected(){await r.connected()},async close(){e.readyState!==e.CONNECTING&&e.readyState!==e.OPEN||await new Promise((t=>{e.addEventListener("close",(()=>{t()})),e.close()}))},destroy(){null!=e.terminate?e.terminate():e.close()},remoteAddress:n,remotePort:s,socket:e}})(new mf(r.toString(),t.websocket),t)}(function(e){const t=bl(e).getComponents(),r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");const n=af[r.name];if(null==n)throw Error("No interpreter found for "+r.name);let s=n(r,t)??"";return ef.includes(r.code)&&(s=s.replace(/^.*:\/\//,""),s="443"===r.value?"https://"+s:"http://"+s),(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("ws://")||s.startsWith("wss://"))&&(s=new URL(s).toString(),s.endsWith("/")&&(s=s.substring(0,s.length-1))),s}(e),this.init);s.socket.addEventListener("error",(()=>{const t=new Mn("Could not connect to "+e.toString());this.log.error("connection error:",t),this.metrics?.dialerEvents.increment({error:!0}),n.reject(t)}));try{t.onProgress?.(new bf("websockets:open-connection")),await ei(Promise.race([s.connected(),n.promise]),t.signal)}catch(e){throw t.signal?.aborted&&this.metrics?.dialerEvents.increment({abort:!0}),s.close().catch((e=>{this.log.error("error closing raw socket",e)})),e}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),s}createListener(e){return function(){throw Error("WebSocket Servers can not be created in the browser!")}((this.logger,this.components.events,this.components.metrics),this.init)}listenFilter(e){return e=Array.isArray(e)?e:[e],null!=this.init?.filter?this.init?.filter(e):wf(e)}dialFilter(e){return this.listenFilter(e)}}function Sf(e={}){return t=>new Ef(t,e)}function Af(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)}const{hasOwnProperty:If}=Object.prototype,{propertyIsEnumerable:_f}=Object,Cf=(e,t,r)=>{Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})},xf={concatArrays:!1,ignoreUndefined:!1},kf=e=>{const t=[];for(const r in e)If.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)_f.call(e,n)&&t.push(n)}return t};function Tf(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return kf(e).forEach((r=>{Cf(t,r,Tf(e[r]))})),t}(e):Af(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return kf(e).forEach((r=>{Cf(t,r,Tf(e[r]))})),t}(e):e}const Pf=(e,t,r,n)=>(r.forEach((r=>{void 0===t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?Cf(e,r,Lf(e[r],t[r],n)):Cf(e,r,Tf(t[r])))})),e),Rf=(e,t,r)=>{let n=e.slice(0,0),s=0;return[e,t].forEach((t=>{const i=[];for(let r=0;r<t.length;r++)If.call(t,r)&&(i.push(r+""),Cf(n,s++,t===e?t[r]:Tf(t[r])));n=Pf(n,t,kf(t).filter((e=>!i.includes(e))),r)})),n};function Lf(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?Rf(e,t,r):Af(t)&&Af(e)?Pf(e,t,kf(t),r):Tf(t)}function Df(...e){const t=Lf(Tf(xf),void 0!==this&&this||{},xf);let r={_:{}};for(const n of e)if(void 0!==n){if(!Af(n))throw new TypeError("`"+n+"` is not an Option Object");r=Lf(r,{_:n},t)}return r._}var Mf,Nf={exports:{}},Of=(Mf||(Mf=1,function(e){var t={}.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function i(e,t,n,i,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,o=Array(i);s<i;s++)o[s]=n[s].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,s,i,o){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,u=this._events[a],h=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),h){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,s),!0;case 5:return u.fn.call(u.context,t,n,s,i),!0;case 6:return u.fn.call(u.context,t,n,s,i,o),!0}for(l=1,c=Array(h-1);l<h;l++)c[l-1]=arguments[l];u.fn.apply(u.context,c)}else{var d,p=u.length;for(l=0;l<p;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),h){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,t);break;case 3:u[l].fn.call(u[l].context,t,n);break;case 4:u[l].fn.call(u[l].context,t,n,s);break;default:if(!c)for(d=1,c=Array(h-1);d<h;d++)c[d-1]=arguments[d];u[l].fn.apply(u[l].context,c)}}return!0},a.prototype.on=function(e,t,r){return i(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return i(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,s){var i=r?r+e:e;if(!this._events[i])return this;if(!t)return o(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||s&&!a.once||n&&a.context!==n||o(this,i);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||s&&!a[c].once||n&&a[c].context!==n)&&l.push(a[c]);l.length?this._events[i]=1===l.length?l[0]:l:o(this,i)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}(Nf)),Nf.exports),Uf=ss(Of);class Ff extends Error{constructor(e){super(e),this.name="TimeoutError"}}let Bf=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}};const $f=e=>void 0===globalThis.DOMException?new Bf(e):new DOMException(e),qf=e=>{const t=void 0===e.reason?$f("This operation was aborted."):e.reason;return t instanceof Error?t:$f(t)};let zf=class{#s=[];enqueue(e,t){const r={priority:(t={priority:0,...t}).priority,id:t.id,run:e};if(0===this.size||this.#s[this.size-1].priority>=t.priority)return void this.#s.push(r);const n=function(e,t,r){let n=0,s=e.length;for(;s>0;){const i=Math.trunc(s/2);let o=n+i;r(e[o],t)<=0?(n=++o,s-=i+1):s=i}return n}(this.#s,r,((e,t)=>t.priority-e.priority));this.#s.splice(n,0,r)}setPriority(e,t){const r=this.#s.findIndex((t=>t.id===e));if(-1===r)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);const[n]=this.#s.splice(r,1);this.enqueue(n.run,{priority:t,id:e})}dequeue(){return this.#s.shift()?.run}filter(e){return this.#s.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this.#s.length}};class jf extends Uf{#i;#o;#a=0;#c;#l;#u=0;#h;#d;#s;#p;#f=0;#g;#m;#y;#b=1n;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:zf,...e}).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#i=e.carryoverConcurrencyCount,this.#o=e.intervalCap===1/0||0===e.interval,this.#c=e.intervalCap,this.#l=e.interval,this.#s=new e.queueClass,this.#p=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#y=!0===e.throwOnTimeout,this.#m=!1===e.autoStart}get#w(){return this.#o||this.#a<this.#c}get#v(){return this.#f<this.#g}#E(){this.#f--,this.#S(),this.emit("next")}#A(){this.#I(),this.#_(),this.#d=void 0}get#C(){const e=Date.now();if(void 0===this.#h){const t=this.#u-e;if(!(t<0))return void 0===this.#d&&(this.#d=setTimeout((()=>{this.#A()}),t)),!0;this.#a=this.#i?this.#f:0}return!1}#S(){if(0===this.#s.size)return this.#h&&clearInterval(this.#h),this.#h=void 0,this.emit("empty"),0===this.#f&&this.emit("idle"),!1;if(!this.#m){const e=!this.#C;if(this.#w&&this.#v){const t=this.#s.dequeue();return!!t&&(this.emit("active"),t(),e&&this.#_(),!0)}}return!1}#_(){this.#o||void 0!==this.#h||(this.#h=setInterval((()=>{this.#I()}),this.#l),this.#u=Date.now()+this.#l)}#I(){0===this.#a&&0===this.#f&&this.#h&&(clearInterval(this.#h),this.#h=void 0),this.#a=this.#i?this.#f:0,this.#x()}#x(){for(;this.#S(););}get concurrency(){return this.#g}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#g=e,this.#x()}async#k(e){return new Promise(((t,r)=>{e.addEventListener("abort",(()=>{r(e.reason)}),{once:!0})}))}setPriority(e,t){this.#s.setPriority(e,t)}async add(e,t={}){return t.id??=""+this.#b++,t={timeout:this.timeout,throwOnTimeout:this.#y,...t},new Promise(((r,n)=>{this.#s.enqueue((async()=>{this.#f++,this.#a++;try{t.signal?.throwIfAborted();let n=e({signal:t.signal});t.timeout&&(n=function(e,t){const{milliseconds:r,fallback:n,message:s,customTimers:i={setTimeout:setTimeout,clearTimeout:clearTimeout}}=t;let o,a;const c=new Promise(((c,l)=>{if("number"!=typeof r||1!==Math.sign(r))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){const{signal:e}=t;e.aborted&&l(qf(e)),a=()=>{l(qf(e))},e.addEventListener("abort",a,{once:!0})}if(r===1/0)return void e.then(c,l);const u=new Ff;o=i.setTimeout.call(void 0,(()=>{if(n)try{c(n())}catch(e){l(e)}else"function"==typeof e.cancel&&e.cancel(),!1===s?c():s instanceof Error?l(s):(u.message=s??`Promise timed out after ${r} milliseconds`,l(u))}),r),(async()=>{try{c(await e)}catch(e){l(e)}})()})).finally((()=>{c.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)}));return c.clear=()=>{i.clearTimeout.call(void 0,o),o=void 0},c}(Promise.resolve(n),{milliseconds:t.timeout})),t.signal&&(n=Promise.race([n,this.#k(t.signal)]));const s=await n;r(s),this.emit("completed",s)}catch(e){if(e instanceof Ff&&!t.throwOnTimeout)return void r();n(e),this.emit("error",e)}finally{this.#E()}}),t),this.emit("add"),this.#S()}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this.#m?(this.#m=!1,this.#x(),this):this}pause(){this.#m=!0}clear(){this.#s=new this.#p}async onEmpty(){0!==this.#s.size&&await this.#T("empty")}async onSizeLessThan(e){this.#s.size<e||await this.#T("next",(()=>this.#s.size<e))}async onIdle(){0===this.#f&&0===this.#s.size||await this.#T("idle")}async#T(e,t){return new Promise((r=>{const n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)}))}get size(){return this.#s.size}sizeBy(e){return this.#s.filter(e).length}get pending(){return this.#f}get isPaused(){return this.#m}}function Kf(e){const t=[Xf.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function Vf(e){return{Status:e.Status??0,TC:e.TC??e.flag_tc??!1,RD:e.RD??e.flag_rd??!1,RA:e.RA??e.flag_ra??!1,AD:e.AD??e.flag_ad??!1,CD:e.CD??e.flag_cd??!1,Question:(e.Question??e.questions??[]).map((e=>({name:e.name,type:Xf[e.type]}))),Answer:(e.Answer??e.answers??[]).map((e=>({name:e.name,type:Xf[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?tn(e.data):e.data})))}}function Hf(e,t={}){const r=new jf({concurrency:t.queryConcurrency??4});return async(t,n={})=>{const s=new URLSearchParams;s.set("name",t),Kf(n.types).forEach((e=>{s.append("type",Xf[e])})),n.onProgress?.(new bf("dns:query",{detail:t}));const i=await r.add((async()=>{const t=await fetch(`${e}?${s}`,{headers:{accept:"application/dns-json"},signal:n?.signal});if(200!==t.status)throw Error(`Unexpected HTTP status: ${t.status} - ${t.statusText}`);const r=Vf(await t.json());return n.onProgress?.(new bf("dns:response",{detail:r})),r}),{signal:n.signal});if(null==i)throw Error("No DNS response received");return i}}var Gf,Wf,Xf,Zf=(Wf||(Wf=1,Gf=e=>{if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,r=Object.create(null),n=Object.create(null);function s(s,i){r[s]=i,++t>=e&&(t=0,n=r,r=Object.create(null))}return{has:e=>void 0!==r[e]||void 0!==n[e],remove(e){void 0!==r[e]&&(r[e]=void 0),void 0!==n[e]&&(n[e]=void 0)},get(e){var t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(s(e,t),t):void 0},set(e,t){void 0!==r[e]?r[e]=t:s(e,t)},clear(){r=Object.create(null),n=Object.create(null)}}}),Gf),Yf=ss(Zf);class Qf{lru;constructor(e){this.lru=Yf(e)}get(e,t){let r=!0;const n=[];for(const s of t){const t=this.getAnswers(e,s);if(0===t.length){r=!1;break}n.push(...t)}if(r)return Vf({answers:n})}getAnswers(e,t){const r=`${e.toLowerCase()}-${t}`,n=this.lru.get(r);if(null!=n){const e=n.filter((e=>e.expires>Date.now())).map((({expires:e,value:t})=>({...t,TTL:Math.round((e-Date.now())/1e3),type:Xf[t.type]})));return 0===e.length&&this.lru.remove(r),e}return[]}add(e,t){const r=`${e.toLowerCase()}-${t.type}`,n=this.lru.get(r)??[];n.push({expires:Date.now()+1e3*(t.TTL??60),value:t}),this.lru.set(r,n)}remove(e,t){const r=`${e.toLowerCase()}-${t}`;this.lru.remove(r)}clear(){this.lru.clear()}}class Jf{resolvers;cache;constructor(e){var t;this.resolvers={},this.cache=(t=e.cacheSize??1e3,new Qf(t)),Object.entries(e.resolvers??{}).forEach((([e,t])=>{Array.isArray(t)||(t=[t]),e.endsWith(".")||(e+="."),this.resolvers[e]=t})),null==this.resolvers["."]&&(this.resolvers["."]=[Hf("https://cloudflare-dns.com/dns-query"),Hf("https://dns.google/resolve")])}async query(e,t={}){const r=Kf(t.types),n=!1!==t.cached?this.cache.get(e,r):void 0;if(null!=n)return t.onProgress?.(new bf("dns:cache",{detail:n})),n;const s=e.split(".").pop()+".",i=(this.resolvers[s]??this.resolvers["."]).sort((()=>Math.random()>.5?-1:1)),o=[];for(const n of i){if(!0===t.signal?.aborted)break;try{const s=await n(e,{...t,types:r});for(const t of s.Answer)this.cache.add(e,t);return s}catch(e){o.push(e),t.onProgress?.(new bf("dns:error",{detail:e}))}}if(1===o.length)throw o[0];throw new AggregateError(o,`DNS lookup of ${e} ${r} failed`)}}(e=>{e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"})(Xf||(Xf={}));const eg=-1,tg={},rg={};[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,eg,"ip6zone"],[43,8,"ipcidr"],[53,eg,"dns",!0],[54,eg,"dns4",!0],[55,eg,"dns6",!0],[56,eg,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,eg,"unix",!1,!0],[421,eg,"ipfs"],[421,eg,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,eg,"garlic64"],[448,0,"tls"],[449,eg,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,eg,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,eg,"http-path"],[777,eg,"memory"]].forEach((e=>{const t=function(e,t,r,n,s){return{code:e,size:t,name:r,resolvable:!!n,path:!!s}}(...e);rg[t.code]=t,tg[t.name]=t}));const{code:ng}=function(e){if(null!=tg[e])return tg[e];throw Error("no protocol with name: "+e)}("dnsaddr");class sg extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}const ig=async function(e,t={}){const r=t.maxRecursiveDepth??32;if(0===r)throw new sg("Max recursive depth reached");const[,n]=e.stringTuples().find((([e])=>e===ng))??[],s=t?.dns??function(e={}){return new Jf(e)}(),i=await s.query("_dnsaddr."+n,{signal:t?.signal,types:[Xf.TXT]}),o=e.getPeerId(),a=[];for(const e of i.Answer){const n=e.data.replace(/["']/g,"").trim().split("=")[1];if(null==n)continue;if(null!=o&&!n.includes(o))continue;const s=bl(n);if(n.startsWith("/dnsaddr")){const e=await s.resolve({...t,maxRecursiveDepth:r-1});a.push(...e.map((e=>e.toString())))}else a.push(s.toString())}return a},og={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:ig}},transportManager:{faultTolerance:Cn.FATAL_ALL}};async function ag(e){const t=Df(og,e);if(null===t.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new Pn("Private network is enforced, but no protector was provided");return t}const cg=1e3,lg=6e4,ug=60*lg,hg=24*ug,dg=7*hg;function pg(e,t){try{if("string"==typeof e&&e.length>0)return function(e){if((e+="").length>100)throw Error("Value exceeds the maximum length of 100 characters.");const t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return NaN;const r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return r*dg;case"days":case"day":case"d":return r*hg;case"hours":case"hour":case"hrs":case"hr":case"h":return r*ug;case"minutes":case"minute":case"mins":case"min":case"m":return r*lg;case"seconds":case"second":case"secs":case"sec":case"s":return r*cg;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:throw Error(`The unit ${n} was matched, but no matching case exists.`)}}(e);if("number"==typeof e&&isFinite(e))return t?.long?function(e){const t=Math.abs(e);return t>=hg?fg(e,t,hg,"day"):t>=ug?fg(e,t,ug,"hour"):t>=lg?fg(e,t,lg,"minute"):t>=cg?fg(e,t,cg,"second"):e+" ms"}(e):function(e){const t=Math.abs(e);return t>=hg?Math.round(e/hg)+"d":t>=ug?Math.round(e/ug)+"h":t>=lg?Math.round(e/lg)+"m":t>=cg?Math.round(e/cg)+"s":e+"ms"}(e);throw Error("Value is not a string or number.")}catch(t){const r=function(e){return"object"==typeof e&&null!==e&&"message"in e}(t)?`${t.message}. value=${JSON.stringify(e)}`:"An unknown error has occured.";throw Error(r)}}function fg(e,t,r,n){const s=t>=1.5*r;return`${Math.round(e/r)} ${n}${s?"s":""}`}const gg=function(){try{return localStorage}catch(e){}}(),mg=console.debug??console.log??(()=>{});var yg=function(e){function t(e){let n,s,i,o=null;function a(...e){if(!a.enabled)return;const r=a,s=Number(new Date),i=s-(n||s);r.diff=i,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];n=i.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set(e){o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack??e.message:e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r<s;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(RegExp("^"+e.substr(1)+"$")):t.names.push(RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=pg,t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.setupFormatters(t.formatters),t.enable(t.load()),t}({formatArgs(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+pg(this.diff),!this.useColors)return;const t="color: "+this.color;e.splice(1,0,t,"color: inherit");let r=0,n=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(n=r))})),e.splice(n,0,t)},save(e){try{e?gg?.setItem("debug",e):gg?.removeItem("debug")}catch(e){}},load(){let e;try{e=gg?.getItem("debug")}catch(e){}return!e&&void 0!==globalThis.process&&"env"in globalThis.process&&(e=globalThis.process.env.DEBUG),e},useColors:()=>!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||null==navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement?.style?.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&null!=navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)),setupFormatters(e){e.j=e=>{try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},colors:["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],storage:gg,log:mg});function bg(){return{forComponent:e=>wg(e)}}function wg(e){let t=function(e){const t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}(e+":trace");return yg.enabled(e+":trace")&&null!=yg.names.map((e=>e.toString())).find((e=>e.includes(":trace")))&&(t=yg(e+":trace")),Object.assign(yg(e),{error:yg(e+":error"),trace:t,newScope:t=>wg(`${e}:${t}`)})}function vg(e){if(null!=e&&0!==(e=e.trim()).length)return e}function Eg(e,t){const r={[Symbol.iterator]:()=>r,next(){const r=e.next(),n=r.value;return!0===r.done||null==n?{done:!0,value:void 0}:{done:!1,value:t(n)}}};return r}function Sg(e){return Lc(Le(fe.decode("z"+e)))}yg.formatters.b=e=>null==e?"undefined":fe.baseEncode(e),yg.formatters.t=e=>null==e?"undefined":te.baseEncode(e),yg.formatters.m=e=>null==e?"undefined":ye.baseEncode(e),yg.formatters.p=e=>null==e?"undefined":e.toString(),yg.formatters.c=e=>null==e?"undefined":e.toString(),yg.formatters.k=e=>null==e?"undefined":e.toString(),yg.formatters.a=e=>null==e?"undefined":e.toString(),yg.formatters.e=e=>null==e?"undefined":vg(e.stack)??vg(e.message)??e.toString();class Ag{map;constructor(e){if(this.map=new Map,null!=e)for(const[t,r]of e.entries())this.map.set(t.toString(),{key:t,value:r})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Eg(this.map.entries(),(e=>[e[1].key,e[1].value]))}forEach(e){this.map.forEach((t=>{e(t.value,t.key,this)}))}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Eg(this.map.values(),(e=>e.key))}values(){return Eg(this.map.values(),(e=>e.value))}get size(){return this.map.size}}class Ig{set;constructor(e){if(this.set=new Set,null!=e)for(const t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Eg(this.set.entries(),(e=>{const t=Sg(e[0]);return[t,t]}))}forEach(e){this.set.forEach((t=>{const r=Sg(t);e(r,r,this)}))}has(e){return this.set.has(e.toString())}values(){return Eg(this.set.values(),(e=>Sg(e)))}intersection(e){const t=new Ig;for(const r of e)this.has(r)&&t.add(r);return t}difference(e){const t=new Ig;for(const r of this)e.has(r)||t.add(r);return t}union(e){const t=new Ig;for(const r of e)t.add(r);for(const e of this)t.add(e);return t}}const _g={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Cg={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},xg=new globalThis.TextEncoder,kg={hash:e=>Number(function(e,{size:t=32,utf8Buffer:r}={}){if(!_g[t])throw Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if("string"==typeof e){if(r)return function(e,t,r){if(0===r.length)throw Error("The `utf8Buffer` option must have a length greater than zero");const n=_g[t];let s=Cg[t],i=e;for(;i.length>0;){const e=xg.encodeInto(i,r);i=i.slice(e.read);for(let i=0;i<e.written;i++)s^=BigInt(r[i]),s=BigInt.asUintN(t,s*n)}return s}(e,t,r);e=xg.encode(e)}return function(e,t){const r=_g[t];let n=Cg[t];for(let s=0;s<e.length;s++)n^=BigInt(e[s]),n=BigInt.asUintN(t,n*r);return n}(e,t)}(e,{size:32})),hashV:(e,t)=>function(e){let t=e.toString(16);return t.length%2==1&&(t="0"+t),Ye(t,"base16")}(kg.hash(e,t))};class Tg{fp;h;seed;constructor(e,t,r,n=2){if(n>64)throw new TypeError("Invalid Fingerprint Size");const s=t.hashV(e,r),i=o(n);for(let e=0;e<i.length;e++)i[e]=s[e];0===i.length&&(i[0]=7),this.fp=i,this.h=t,this.seed=r}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array&&Ds(this.fp,e.fp)}}function Pg(e,t){return Math.floor(Math.random()*(t-e))+e}class Rg{contents;constructor(e){this.contents=Array(e).fill(null)}has(e){if(!(e instanceof Tg))throw new TypeError("Invalid Fingerprint");return this.contents.some((t=>e.equals(t)))}add(e){if(!(e instanceof Tg))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(null==this.contents[t])return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Tg))throw new TypeError("Invalid Fingerprint");const t=Pg(0,this.contents.length-1),r=this.contents[t];return this.contents[t]=e,r}remove(e){if(!(e instanceof Tg))throw new TypeError("Invalid Fingerprint");const t=this.contents.findIndex((t=>e.equals(t)));return t>-1&&(this.contents[t]=null,!0)}}class Lg{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??kg,this.seed=e.seed??Pg(0,1024)}add(e){"string"==typeof e&&(e=Ye(e));const t=new Tg(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=(r^t.hash())%this.filterSize;if(null==this.buckets[r]&&(this.buckets[r]=new Rg(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new Rg(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;const s=[r,n];let i=s[Pg(0,s.length-1)];null==this.buckets[i]&&(this.buckets[i]=new Rg(this.bucketSize));for(let e=0;e<500;e++){const e=this.buckets[i].swap(t);if(null!=e&&(i=(i^e.hash())%this.filterSize,null==this.buckets[i]&&(this.buckets[i]=new Rg(this.bucketSize)),this.buckets[i].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=Ye(e));const t=new Tg(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.has(t)??!1;if(n)return n;const s=(r^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){"string"==typeof e&&(e=Ye(e));const t=new Tg(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.remove(t)??!1;if(n)return this.count--,n;const s=(r^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}}const Dg={1:.5,2:.84,4:.95,8:.98};function Mg(e,t=.001){const r=function(e=.001){return e>.002?2:e>1e-5?4:8}(t);return{filterSize:Math.round(e/Dg[r]),bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*r)),64)}}class Ng{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??262144/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??kg,this.seed=e.seed??Pg(0,1024),this.filterSeries=[new Lg({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=Ye(e)),this.has(e))return!0;let t=this.filterSeries.find((e=>e.reliable));if(null==t){const e=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Lg({filterSize:e,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){"string"==typeof e&&(e=Ye(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){"string"==typeof e&&(e=Ye(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce(((e,t)=>e+t.count),0)}}function Og(e,t=.001){return new Ng({...Mg(e,t)})}class Ug extends Ag{metric;constructor(e){super();const{name:t,metrics:r}=e;this.metric=r.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}let Fg=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Bg(e,t,r,n){const s=new Fg(n?.errorMessage);null!=n?.errorCode&&(s.code=n.errorCode);const i=n?.errorEvent??"error";return!0===r?.aborted?Promise.reject(s):new Promise(((o,a)=>{function c(){qg(r,"abort",h),qg(e,t,l),qg(e,i,u)}const l=e=>{try{if(!1===n?.filter?.(e))return}catch(e){return c(),void a(e)}c(),o(e)},u=e=>{c(),a(e instanceof Error?e:e.detail??n?.error??Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},h=()=>{c(),a(s)};$g(r,"abort",h),$g(e,t,l),$g(e,i,u)}))}function $g(e,t,r){null!=e&&(zg(e)?e.addEventListener(t,r):e.addListener(t,r))}function qg(e,t,r){null!=e&&(zg(e)?e.removeEventListener(t,r):e.removeListener(t,r))}function zg(e){return"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener}class jg extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}function Kg(e,t){let r;const n=()=>{clearTimeout(r),r=setTimeout((()=>{r=void 0,e()}),t)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}let Vg=class extends Jn{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??1/0,this.maxSize=e.maxSize??1/0,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=Kg(this.emitEmpty.bind(this),1),this.emitIdle=Kg(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally((()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()})),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}start(){!1===this.autoStart&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new jg;const r=new class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(1e9*Math.random()+"",10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce(((e,t)=>e&&!0===t.signal?.aborted),!0)&&(this.controller.abort(new Fg),this.cleanup())}async join(e={}){const t=new class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Fg)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await ei(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach((t=>{t.deferred.resolve(e)})),this.status="complete"}catch(e){this.recipients.forEach((t=>{t.deferred.reject(e)})),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach((e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}))}}(e,t);return this.enqueue(r),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),r.join(t).then((e=>(this.safeDispatchEvent("success",{detail:{job:r,result:e}}),e))).catch((e=>{if("queued"===r.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===r){this.queue.splice(e,1);break}throw this.safeDispatchEvent("failure",{detail:{job:r,error:e}}),e}))}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new Fg)})),this.clear()}async onEmpty(e){0!==this.size&&await Bg(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Bg(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await Bg(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();const t=Qs({objectMode:!0}),r=e=>{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail.result)},s=e=>{r(e.detail.error)},i=()=>{r()},o=()=>{r(new Fg("Queue aborted"))};this.addEventListener("success",n),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("success",n),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",o),r()}}};const Hg="lock:worker:request-read",Gg="lock:worker:abort-read-request",Wg="lock:worker:release-read",Xg="lock:master:grant-read",Zg="lock:master:error-read",Yg="lock:worker:request-write",Qg="lock:worker:abort-write-request",Jg="lock:worker:release-write",em="lock:master:grant-write",tm="lock:master:error-write",rm="lock:worker:finalize",nm="mortice",sm={singleProcess:!1},im=(e,t,r,n,s,i,o,a,c)=>l=>{if(null==l.data)return;const u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===s&&e.safeDispatchEvent(r,{detail:{name:u.name,identifier:u.identifier,async handler(){t.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise((e=>{const r=n=>{if(null==n?.data)return;const s=n.data.type,i=(n.data.name,n.data.identifier);s===a&&i===u.identifier&&(t.removeEventListener("message",r),e())};t.addEventListener("message",r)}))},onError(e){t.postMessage({type:o,name:u.name,identifier:u.identifier,error:{message:e.message,name:e.name,stack:e.stack}})}}}),u.type===i&&e.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===rm&&e.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};class om{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(nm)}readLock(e){return this.sendRequest(Hg,Gg,Xg,Zg,Wg,e)}writeLock(e){return this.sendRequest(Yg,Qg,em,tm,Jg,e)}finalize(){this.channel.postMessage({type:rm,name:this.name}),this.channel.close()}async sendRequest(e,t,r,n,s,i){i?.signal?.throwIfAborted();const o=((e=10)=>Math.random().toString().substring(2,e+2))();return this.channel.postMessage({type:e,identifier:o,name:this.name}),new Promise(((e,a)=>{const c=()=>{this.channel.postMessage({type:t,identifier:o,name:this.name})};i?.signal?.addEventListener("abort",c,{once:!0});const l=t=>{if(t.data?.identifier===o&&(t.data?.type===r&&(this.channel.removeEventListener("message",l),i?.signal?.removeEventListener("abort",c),e((()=>{this.channel.postMessage({type:s,identifier:o,name:this.name})}))),t.data.type===n)){this.channel.removeEventListener("message",l),i?.signal?.removeEventListener("abort",c);const e=Error();null!=t.data.error&&(e.message=t.data.error.message,e.name=t.data.error.name,e.stack=t.data.error.stack),a(e)}};this.channel.addEventListener("message",l)}))}}const am=new Map;let cm;function lm(e){return"function"==typeof e?.readLock&&"function"==typeof e?.writeLock}async function um(e,t){let r,n;const s=new Promise(((e,t)=>{r=e,n=t})),i=()=>{n(new Fg)};return t?.signal?.addEventListener("abort",i,{once:!0}),e.add((async()=>{await new Promise((e=>{r((()=>{t?.signal?.removeEventListener("abort",i),e()}))}))}),{signal:t?.signal}).catch((e=>{n(e)})),s}const hm={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function dm(e){const t=Object.assign({},hm,e);return((e,t)=>{let r=am.get(e);if(null!=r)return r;const n=function(e){if(null==cm&&(cm=(e=>{if(e=Object.assign({},sm,e),globalThis.document||e.singleProcess){const e=new BroadcastChannel(nm),t=new Jn;return e.addEventListener("message",im(t,e,"requestReadLock","abortReadLockRequest",Hg,Gg,Zg,Wg,Xg)),e.addEventListener("message",im(t,e,"requestWriteLock","abortWriteLockRequest",Yg,Qg,tm,Jg,em)),t}return new om(e.name)})(e),!lm(cm))){const e=cm;e.addEventListener("requestReadLock",(t=>{const r=t.detail.name,n=t.detail.identifier,s=am.get(r);if(null==s)return;const i=new AbortController,o=e=>{e.detail.name===r&&e.detail.identifier===n&&i.abort()};e.addEventListener("abortReadLockRequest",o),s.readLock({signal:i.signal}).then((async e=>{await t.detail.handler().finally((()=>{e()}))})).catch((e=>{t.detail.onError(e)})).finally((()=>{e.removeEventListener("abortReadLockRequest",o)}))})),e.addEventListener("requestWriteLock",(t=>{const r=t.detail.name,n=t.detail.identifier,s=am.get(r);if(null==s)return;const i=new AbortController,o=e=>{e.detail.name===r&&e.detail.identifier===n&&i.abort()};e.addEventListener("abortWriteLockRequest",o),s.writeLock({signal:i.signal}).then((async e=>{await t.detail.handler().finally((()=>{e()}))})).catch((e=>{t.detail.onError(e)})).finally((()=>{e.removeEventListener("abortWriteLockRequest",o)}))})),e.addEventListener("finalizeRequest",(e=>{const t=e.detail.name,r=am.get(t);null!=r&&r.finalize()}))}return cm}(t);if(lm(n))return r=n,am.set(e,r),r;const s=new Vg({concurrency:1});let i;return r={async readLock(e){if(null!=i)return um(i,e);i=new Vg({concurrency:t.concurrency,autoStart:!1});const r=i,n=um(i,e);return s.add((async()=>{r.start(),await r.onIdle().then((()=>{i===r&&(i=null)}))})),n},writeLock:async e=>(i=null,um(s,e)),finalize(){am.delete(e)},queue:s},am.set(e,r),!0===t.autoFinalize&&s.addEventListener("idle",(()=>{r.finalize()}),{once:!0}),r})(t.name,t)}var pm,fm,gm;function mm(e,t){if(null!=e.publicKey||null==t.publicKey)return e;let r;return"RSA"===e.type&&(r=e.toMultihash()),Rc(Sc(t.publicKey,r))}function ym(e,t,r){const n=new Map,s=BigInt(Date.now());for(const[e,r]of t.tags.entries())null!=r.expiry&&r.expiry<s||n.set(e,r);return{...t,id:mm(e,t),addresses:t.addresses.filter((({observed:e})=>null!=e&&e>Date.now()-r)).map((({multiaddr:e,isCertified:t})=>({multiaddr:bl(e),isCertified:t??!1}))),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}function bm(e,t){return vm(e.addresses,t.addresses,((e,t)=>e.isCertified===t.isCertified&&!!Ds(e.multiaddr,t.multiaddr)))&&vm(e.protocols,t.protocols,((e,t)=>e===t))&&wm(e.publicKey,t.publicKey)&&wm(e.peerRecordEnvelope,t.peerRecordEnvelope)&&Em(e.metadata,t.metadata,((e,t)=>Ds(e,t)))&&function(e,t){return Em(e,t,((e,t)=>e.value===t.value&&e.expiry===t.expiry))}(e.tags,t.tags)}function wm(e,t){return null==e&&null==t||null!=e&&null!=t&&Ds(e,t)}function vm(e,t,r){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!r(e[n],t[n]))return!1;return!0}function Em(e,t,r){if(e.size!==t.size)return!1;for(const[n,s]of e.entries()){const e=t.get(n);if(null==e)return!1;if(!r(s,e))return!1}return!0}(e=>{let t;(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={key:"",value:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&(t.uint32(18),gm.codec().encode(e.value,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={key:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.key=e.string();break;case 2:n.value=gm.codec().decode(e,e.uint32(),{limits:r.limits?.value});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==t&&(t=Wt(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.addresses)for(const e of t.addresses)r.uint32(10),fm.codec().encode(e,r);if(null!=t.protocols)for(const e of t.protocols)r.uint32(18),r.string(e);if(null!=t.publicKey&&(r.uint32(34),r.bytes(t.publicKey)),null!=t.peerRecordEnvelope&&(r.uint32(42),r.bytes(t.peerRecordEnvelope)),null!=t.metadata&&0!==t.metadata.size)for(const[n,s]of t.metadata.entries())r.uint32(50),e.Peer$metadataEntry.codec().encode({key:n,value:s},r);if(null!=t.tags&&0!==t.tags.size)for(const[n,s]of t.tags.entries())r.uint32(58),e.Peer$tagsEntry.codec().encode({key:n,value:s},r);null!=t.updated&&(r.uint32(64),r.uint64Number(t.updated)),!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={addresses:[],protocols:[],metadata:new Map,tags:new Map},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:if(null!=n.limits?.addresses&&s.addresses.length===n.limits.addresses)throw new Xt('Decode error - map field "addresses" had too many elements');s.addresses.push(fm.codec().decode(t,t.uint32(),{limits:n.limits?.addresses$}));break;case 2:if(null!=n.limits?.protocols&&s.protocols.length===n.limits.protocols)throw new Xt('Decode error - map field "protocols" had too many elements');s.protocols.push(t.string());break;case 4:s.publicKey=t.bytes();break;case 5:s.peerRecordEnvelope=t.bytes();break;case 6:{if(null!=n.limits?.metadata&&s.metadata.size===n.limits.metadata)throw new Zt('Decode error - map field "metadata" had too many elements');const r=e.Peer$metadataEntry.codec().decode(t,t.uint32());s.metadata.set(r.key,r.value);break}case 7:{if(null!=n.limits?.tags&&s.tags.size===n.limits.tags)throw new Zt('Decode error - map field "tags" had too many elements');const r=e.Peer$tagsEntry.codec().decode(t,t.uint32(),{limits:{value:n.limits?.tags$value}});s.tags.set(r.key,r.value);break}case 8:s.updated=t.uint64Number();break;default:t.skipType(7&r)}}return s}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(pm||(pm={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),null!=e.isCertified&&(t.uint32(16),t.bool(e.isCertified)),null!=e.observed&&(t.uint32(24),t.uint64Number(e.observed)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={multiaddr:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.multiaddr=e.bytes();break;case 2:r.isCertified=e.bool();break;case 3:r.observed=e.uint64Number();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(fm||(fm={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.value&&0!==e.value&&(t.uint32(8),t.uint32(e.value)),null!=e.expiry&&(t.uint32(16),t.uint64(e.expiry)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={value:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.value=e.uint32();break;case 2:r.expiry=e.uint64();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(gm||(gm={}));const Sm="/",Am=(new TextEncoder).encode(Sm),Im=Am[0];class _m{_buf;constructor(e,t){if("string"==typeof e)this._buf=Ye(e);else{if(!(e instanceof Uint8Array))throw Error("Invalid key, should be String of Uint8Array");this._buf=e}if(null==t&&(t=!0),t&&this.clean(),0===this._buf.byteLength||this._buf[0]!==Im)throw Error("Invalid key")}toString(e="utf8"){return tn(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new _m(e.join(Sm))}static random(){return new _m(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new _m(e):"function"==typeof e.uint8Array?new _m(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Am),this._buf[0]!==Im){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Im,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Im;)this._buf=this._buf.subarray(0,-1)}less(e){const t=this.list(),r=e.list();for(let e=0;e<t.length;e++){if(r.length<e+1)return!1;const n=t[e],s=r[e];if(n<s)return!0;if(n>s)return!1}return t.length<r.length}reverse(){return _m.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Sm).slice(1)}type(){return function(e){const t=e.split(":");return t.length<2?"":t.slice(0,-1).join(":")}(this.baseNamespace())}name(){return function(e){const t=e.split(":");return t[t.length-1]}(this.baseNamespace())}instance(e){return new _m(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Sm)||(e+=Sm),e+=this.type(),new _m(e)}parent(){const e=this.list();return 1===e.length?new _m(Sm):new _m(e.slice(0,-1).join(Sm))}child(e){return this.toString()===Sm?e:e.toString()===Sm?this:new _m(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()!==this.toString()&&e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()!==this.toString()&&this.toString().startsWith(e.toString())}isTopLevel(){return 1===this.list().length}concat(...e){var t;return _m.withNamespaces([...this.namespaces(),...(t=e.map((e=>e.namespaces())),[].concat(...t))])}}const Cm="/peers/";function xm(e){if(!Sn(e)||null==e.type)throw new Pn("Invalid PeerId");const t=e.toCID().toString();return new _m(`${Cm}${t}`)}async function km(e,t,r,n,s){const i=new Map;for(const n of r){if(null==n)continue;if(n.multiaddr instanceof Uint8Array&&(n.multiaddr=bl(n.multiaddr)),!yl(n.multiaddr))throw new Pn("Multiaddr was invalid");if(!await t(e,n.multiaddr,s))continue;const r=n.isCertified??!1,o=n.multiaddr.toString(),a=i.get(o);null!=a?n.isCertified=a.isCertified||r:i.set(o,{multiaddr:n.multiaddr,isCertified:r})}return[...i.values()].sort(((e,t)=>e.multiaddr.toString().localeCompare(t.multiaddr.toString()))).map((({isCertified:t,multiaddr:r})=>{const n=r.getPeerId();return e.equals(n)&&(r=r.decapsulate(bl("/p2p/"+e))),{isCertified:t,multiaddr:r.bytes}}))}async function Tm(e,t,r,n){if(null==t)throw new Pn("Invalid PeerData");if(null!=t.publicKey&&null!=e.publicKey&&!t.publicKey.equals(e.publicKey))throw new Pn("publicKey bytes do not match peer id publicKey bytes");const s=n.existingPeer?.peer;if(null!=s&&!e.equals(s.id))throw new Pn("peer id did not match existing peer id");let i,o=s?.addresses??[],a=new Set(s?.protocols??[]),c=s?.metadata??new Map,l=s?.tags??new Map,u=s?.peerRecordEnvelope;if("patch"===r&&(null==t.multiaddrs&&null==t.addresses||(o=[],null!=t.multiaddrs&&o.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&o.push(...t.addresses)),null!=t.protocols&&(a=new Set(t.protocols)),null!=t.metadata&&(c=Pm(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:Rm})),null!=t.tags&&(l=Pm(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:Lm,map:Dm})),null!=t.peerRecordEnvelope&&(u=t.peerRecordEnvelope)),"merge"===r){if(null!=t.multiaddrs&&o.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&o.push(...t.addresses),null!=t.protocols&&(a=new Set([...a,...t.protocols])),null!=t.metadata){const e=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(const[t,r]of e)null==r?c.delete(t):c.set(t,r);c=Pm([...c.entries()],{validate:Rm})}if(null!=t.tags){const e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),r=new Map(l);for(const[t,n]of e)null==n?r.delete(t):r.set(t,n);l=Pm([...r.entries()],{validate:Lm,map:Dm})}null!=t.peerRecordEnvelope&&(u=t.peerRecordEnvelope)}null!=s?.id.publicKey?i=Ac(s.id.publicKey):null!=t.publicKey?i=Ac(t.publicKey):null!=e.publicKey&&(i=Ac(e.publicKey));const h={addresses:await km(e,n.addressFilter??(async()=>!0),o,n.existingPeer?.peerPB.addresses,n),protocols:[...a.values()].sort(((e,t)=>e.localeCompare(t))),metadata:c,tags:l,publicKey:i,peerRecordEnvelope:u};return h.addresses.forEach((e=>{e.observed=n.existingPeer?.peerPB.addresses?.find((e=>Ds(e.multiaddr,e.multiaddr)))?.observed??Date.now()})),"RSA"!==e.type&&delete h.publicKey,h}function Pm(e,t){const r=new Map;for(const[r,n]of e)null!=n&&t.validate(r,n);for(const[n,s]of e.sort((([e],[t])=>e.localeCompare(t))))null!=s&&r.set(n,t.map?.(n,s)??s);return r}function Rm(e,t){if("string"!=typeof e)throw new Pn("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new Pn("Metadata value must be a Uint8Array")}function Lm(e,t){if("string"!=typeof e)throw new Pn("Tag name must be a string");if(null!=t.value){if(parseInt(""+t.value,10)!==t.value)throw new Pn("Tag value must be an integer");if(t.value<0||t.value>100)throw new Pn("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt(""+t.ttl,10)!==t.ttl)throw new Pn("Tag ttl must be an integer");if(t.ttl<0)throw new Pn("Tag ttl must be between greater than 0")}}function Dm(e,t){let r;null!=t.expiry&&(r=t.expiry),null!=t.ttl&&(r=BigInt(Date.now()+Number(t.ttl)));const n={value:t.value??0};return null!=r&&(n.expiry=r),n}function Mm(e){const t=e.toString().split("/")[2];return Dc(qe.parse(t,te))}function Nm(e,t,r){return function(e,t,r){return ym(e,pm.decode(t),r)}(Mm(e),t,r)}class Om{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=function(e){const{name:t,metrics:r}=e;let n;return n=null!=r?new Ug({name:t,metrics:r}):new Ag,n}({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return null==t&&(t={refs:0,lock:dm({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,0===t.refs&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){const r=this.getLock(e);try{const n=await r.lock.readLock(t);return()=>{n(),this.maybeRemoveLock(e,r)}}catch(t){throw this.maybeRemoveLock(e,r),t}}async getWriteLock(e,t){const r=this.getLock(e);try{const n=await r.lock.writeLock(t);return()=>{n(),this.maybeRemoveLock(e,r)}}catch(t){throw this.maybeRemoveLock(e,r),t}}async has(e,t){try{return await this.load(e,t),!0}catch(e){if("NotFoundError"!==e.name)throw e}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(xm(e),t)}async load(e,t){const r=xm(e),n=await this.datastore.get(r,t),s=pm.decode(n);if(this.#P(e,s))throw await this.datastore.delete(r,t),new Fn;return ym(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,r){const n=await this.#R(e,r),s=await Tm(e,t,"patch",{...r,addressFilter:this.addressFilter});return this.#L(e,s,n)}async patch(e,t,r){const n=await this.#R(e,r),s=await Tm(e,t,"patch",{...r,addressFilter:this.addressFilter,existingPeer:n});return this.#L(e,s,n)}async merge(e,t,r){const n=await this.#R(e,r),s=await Tm(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#L(e,s,n)}async*all(e){for await(const{key:t,value:r}of this.datastore.query(function(e,t){return{prefix:Cm,filters:(e.filters??[]).map((e=>({key:r,value:n})=>e(Nm(r,n,t)))),orders:(e.orders??[]).map((e=>(r,n)=>e(Nm(r.key,r.value,t),Nm(n.key,n.value,t))))}}(e??{},this.maxAddressAge),e)){const n=Mm(t);if(n.equals(this.peerId))continue;const s=pm.decode(r);this.#P(n,s)?await this.datastore.delete(t,e):yield ym(n,s,this.peerId.equals(n)?1/0:this.maxAddressAge)}}async#R(e,t){try{const r=xm(e),n=await this.datastore.get(r,t),s=pm.decode(n);if(this.#P(e,s))throw await this.datastore.delete(r,t),new Fn;return{peerPB:s,peer:ym(e,s,this.maxAddressAge)}}catch(e){"NotFoundError"!==e.name&&this.log.error("invalid peer data found in peer store - %e",e)}}async#L(e,t,r,n){t.updated=Date.now();const s=pm.encode(t);return await this.datastore.put(xm(e),s,n),{peer:ym(e,t,this.maxAddressAge),previous:r?.peer,updated:null==r||!bm(t,r.peerPB)}}#P(e,t){if(null==t.updated)return!0;if(this.peerId.equals(e))return!1;const r=t.updated<Date.now()-this.maxPeerAge,n=Date.now()-this.maxAddressAge,s=t.addresses.filter((e=>null!=e.observed&&e.observed>n));return r&&0===s.length}}class Um{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Om(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(const r of this.store.all(t))e(r)}async all(e){return Rs(this.store.all(e))}async delete(e,t){const r=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{r()}}async has(e,t){const r=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),r?.()}}async get(e,t){const r=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{r?.()}}async getInfo(e,t){const r=await this.get(e,t);return{id:r.id,multiaddrs:r.addresses.map((({multiaddr:e})=>e))}}async save(e,t,r){await this.store.getWriteLock(e,r);try{const n=await this.store.save(e,t,r);return this.#D(e,n),n.peer}finally{n?.()}}async patch(e,t,r){await this.store.getWriteLock(e,r);try{const n=await this.store.patch(e,t,r);return this.#D(e,n),n.peer}finally{n?.()}}async merge(e,t,r){await this.store.getWriteLock(e,r);try{const n=await this.store.merge(e,t,r);return this.#D(e,n),n.peer}finally{n?.()}}async consumePeerRecord(e,t,r){const n=Sn(t)?t:Sn(t?.expectedPeer)?t.expectedPeer:void 0,s=Sn(t)||void 0===t?r:t,i=await md.openAndCertify(e,vd.DOMAIN,s),o=Dc(i.publicKey.toCID());if(!1===n?.equals(o))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",n,o),!1;const a=vd.createFromProtobuf(i.payload);let c;try{c=await this.get(o,s)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=c?.peerRecordEnvelope){const e=md.createFromProtobuf(c.peerRecordEnvelope),t=vd.createFromProtobuf(e.payload);if(t.seqNumber>=a.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,a.seqNumber),!1}return await this.patch(a.peerId,{peerRecordEnvelope:e,addresses:a.multiaddrs.map((e=>({isCertified:!0,multiaddr:e})))},s),!0}#D(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}}class Fm extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=Fm.name;code=Fm.code;constructor(e="Not Found"){super(e)}}function Bm(e,t){let r=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(const n of e)await t(n,r++)&&(yield n)}();const n=function(e){const[t,r]=null!=e[Symbol.asyncIterator]?[e[Symbol.asyncIterator](),Symbol.asyncIterator]:[e[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push(e){n.push(e)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[r](){return this}}}(e),{value:s,done:i}=n.next();if(!0===i)return function*(){}();const o=t(s,r++);if("function"==typeof o.then)return async function*(){await o&&(yield s);for await(const e of n)await t(e,r++)&&(yield e)}();const a=t;return function*(){!0===o&&(yield s);for(const e of n)a(e,r++)&&(yield e)}()}function $m(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const r=await Rs(e);yield*r.sort(t)}():function*(){const r=Rs(e);yield*r.sort(t)}()}function qm(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let r=0;if(!(t<1))for await(const n of e)if(yield n,r++,r===t)return}():function*(){let r=0;if(!(t<1))for(const n of e)if(yield n,r++,r===t)return}()}class zm{put(e,t,r){return Promise.reject(Error(".put is not implemented"))}get(e,t){return Promise.reject(Error(".get is not implemented"))}has(e,t){return Promise.reject(Error(".has is not implemented"))}delete(e,t){return Promise.reject(Error(".delete is not implemented"))}async*putMany(e,t={}){for await(const{key:r,value:n}of e)await this.put(r,n,t),yield r}async*getMany(e,t={}){for await(const r of e)yield{key:r,value:await this.get(r,t)}}async*deleteMany(e,t={}){for await(const r of e)await this.delete(r,t),yield r}batch(){let e=[],t=[];return{put(t,r){e.push({key:t,value:r})},delete(e){t.push(e)},commit:async r=>{await Sd(this.putMany(e,r)),e=[],await Sd(this.deleteMany(t,r)),t=[]}}}async*_all(e,t){throw Error("._all is not implemented")}async*_allKeys(e,t){throw Error("._allKeys is not implemented")}query(e,t){let r=this._all(e,t);if(null!=e.prefix){const t=e.prefix;r=Bm(r,(e=>e.key.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>Bm(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>$m(e,t)),r)),null!=e.offset){let t=0;const n=e.offset;r=Bm(r,(()=>t++>=n))}return null!=e.limit&&(r=qm(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;r=Bm(r,(e=>e.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>Bm(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>$m(e,t)),r)),null!=e.offset){const t=e.offset;let n=0;r=Bm(r,(()=>n++>=t))}return null!=e.limit&&(r=qm(r,e.limit)),r}}class jm extends zm{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){const t=this.data.get(e.toString());if(null==t)throw new Fm;return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(const[e,t]of this.data.entries())yield{key:new _m(e),value:t}}*_allKeys(){for(const e of this.data.keys())yield new _m(e)}}class Km extends Map{metric;constructor(e){super();const{name:t,metrics:r}=e;this.metric=r.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function Vm(e){const{name:t,metrics:r}=e;let n;return n=null!=r?new Km({name:t,metrics:r}):new Map,n}const Hm=864e13;class Gm{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Vm({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){const t=this.findHost(e);for(const e of this.mappings.values())if(e.domain===t)return!0;return!1}add(e,t){t.forEach((t=>{this.log("add DNS mapping %s to %s",t,e);const r=!0===Dd(t);this.mappings.set(t,{domain:e,verified:r,expires:r?Hm-Date.now():0,lastVerified:r?Hm-Date.now():void 0})}))}remove(e){const t=this.findHost(e);let r=!1;for(const[e,n]of this.mappings.entries())n.domain===t&&(this.log("removing %s to %s DNS mapping %e",e,n.domain,Error("where")),this.mappings.delete(e),r=r||n.verified);return r}getAll(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r].multiaddr.stringTuples(),s=n[0][1];if(null!=s)for(const[i,o]of this.mappings.entries())s===i&&this.maybeAddSNITuple(n,o.domain)&&(e.splice(r,1),r--,t.push({multiaddr:bl("/"+n.map((e=>[wl(e[0]).name,e[1]].join("/"))).join("/")),verified:o.verified,type:"dns-mapping",expires:o.expires,lastVerified:o.lastVerified}))}return t}maybeAddSNITuple(e,t){for(let r=0;r<e.length;r++)if(448===e[r][0]&&449!==e[r+1]?.[0])return e.splice(r+1,0,[449,t]),!0;return!1}confirm(e,t){const r=this.findHost(e);let n=!1;for(const[e,s]of this.mappings.entries())s.domain===r&&(this.log("marking %s to %s DNS mapping as verified",e,s.domain),n=s.verified,s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now());return n}unconfirm(e,t){const r=this.findHost(e);let n=!1;for(const[e,s]of this.mappings.entries())s.domain===r&&(this.log("removing verification of %s to %s DNS mapping",e,s.domain),n=n||s.verified,s.verified=!1,s.expires=Date.now()+t);return n}findHost(e){for(const t of e.stringTuples()){if(449===t[0])return t[1];if(53===t[0]||54===t[0]||55===t[0]||56===t[0])return t[1]}}}class Wm{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Vm({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){const t=e.stringTuples();for(const e of this.mappings.values())for(const r of e)if(r.externalIp===t[0][1])return!0;return!1}add(e,t,r,n=t,s="tcp"){const i=`${e}-${t}-${s}`,o=this.mappings.get(i)??[],a={internalIp:e,internalPort:t,externalIp:r,externalPort:n,externalFamily:zc(r)?4:6,protocol:s,verified:!1,expires:0};o.push(a),this.mappings.set(i,o)}remove(e){const t=e.stringTuples(),r=t[0][1]??"",n=6===t[1][0]?"tcp":"udp",s=parseInt(t[1][1]??"0");let i=!1;for(const[e,t]of this.mappings.entries()){for(let e=0;e<t.length;e++){const o=t[e];o.externalIp===r&&o.externalPort===s&&o.protocol===n&&(this.log("removing %s:%s to %s:%s %s IP mapping",o.externalIp,o.externalPort,r,s,n),i=i||o.verified,t.splice(e,1),e--)}0===t.length&&this.mappings.delete(e)}return i}getAll(e){const t=[];for(const{multiaddr:r}of e){const e=r.stringTuples();let n;if(4!==e[0][0]&&41!==e[0][0]||6!==e[1][0]?4!==e[0][0]&&41!==e[0][0]||273!==e[1][0]||(n=`${e[0][1]}-${e[1][1]}-udp`):n=`${e[0][1]}-${e[1][1]}-tcp`,null==n)continue;const s=this.mappings.get(n);if(null!=s)for(const r of s)e[0][0]=4===r.externalFamily?4:41,e[0][1]=r.externalIp,e[1][1]=""+r.externalPort,t.push({multiaddr:bl("/"+e.map((e=>[wl(e[0]).name,e[1]].join("/"))).join("/")),verified:r.verified,type:"ip-mapping",expires:r.expires,lastVerified:r.lastVerified})}return t}confirm(e,t){const r=e.stringTuples()[0][1];let n=!1;for(const e of this.mappings.values())for(const s of e)s.externalIp===r&&(this.log("marking %s to %s IP mapping as verified",s.internalIp,s.externalIp),n=s.verified,s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now());return n}unconfirm(e,t){const r=e.stringTuples(),n=r[0][1]??"",s=6===r[1][0]?"tcp":"udp",i=parseInt(r[1][1]??"0");let o=!1;for(const e of this.mappings.values())for(let r=0;r<e.length;r++){const a=e[r];a.externalIp===n&&a.externalPort===i&&a.protocol===s&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n,i,s),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}}class Xm{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Vm({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(const t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Nd(e)||function(e){try{for(const{code:t,value:r}of e.getComponents())if(t!==Vc&&null!=r){if(4===t)return r.startsWith("169.254.");if(t===Kc)return r.toLowerCase().startsWith("fe80")}}catch{}return!1}(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map((([e,t])=>({multiaddr:bl(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified})))}remove(e){const t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){const r=e.toString(),n=this.addresses.get(r)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=n.verified;return n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now(),this.log("marking observed address %a as verified",r),this.addresses.set(r,n),s}}const Zm=[4,Kc,53,54,55,56];function Ym(e){try{for(const{code:t}of e.getComponents())if(t!==Vc)return Zm.includes(t)}catch{}return!1}class Qm{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Vm({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}get(e,t){if(Nd(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};const r=this.toKey(e);let n=this.addresses.get(r);return null==n&&(n={verified:!Ym(e),expires:0},this.addresses.set(r,n)),{multiaddr:e,verified:n.verified,type:"transport",expires:n.expires,lastVerified:n.lastVerified}}has(e){const t=this.toKey(e);return this.addresses.has(t)}remove(e){const t=this.toKey(e),r=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),r}confirm(e,t){const r=this.toKey(e),n=this.addresses.get(r)??{verified:!1,expires:0,lastVerified:0},s=n.verified;return n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now(),this.addresses.set(r,n),s}unconfirm(e,t){const r=this.toKey(e),n=this.addresses.get(r)??{verified:!1,expires:0},s=n.verified;return n.verified=!1,n.expires=Date.now()+t,this.addresses.set(r,n),s}toKey(e){if(Ym(e)){const t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}return e.toString()}}const Jm=e=>e;function ey(e,t){const r=e.getPeerId();return null!=r&&Pc(r).equals(t)&&(e=e.decapsulate(bl("/p2p/"+t.toString()))),e}class ty{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){const{listen:r=[],announce:n=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=r.map((e=>e.toString())),this.announce=new Set(n.map((e=>e.toString()))),this.appendAnnounce=new Set(s.map((e=>e.toString()))),this.observed=new Xm(e,t),this.dnsMappings=new Gm(e,t),this.ipMappings=new Wm(e,t),this.transportAddresses=new Qm(e,t),this.announceFilter=t.announceFilter??Jm,this.observedAddressFilter=Og(1024),this.addressVerificationTTL=t.addressVerificationTTL??6e5,this.addressVerificationRetry=t.addressVerificationRetry??3e5,this._updatePeerStoreAddresses=Ed(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",(()=>{this._updatePeerStoreAddresses()})),e.events.addEventListener("transport:close",(()=>{this._updatePeerStoreAddresses()}))}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){const e=this.getAddresses().map((e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate("/p2p/"+this.components.peerId.toString()):e));this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch((e=>{this.log.error("error updating addresses",e)}))}getListenAddrs(){return Array.from(this.listen).map((e=>bl(e)))}getAnnounceAddrs(){return Array.from(this.announce).map((e=>bl(e)))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map((e=>bl(e)))}getObservedAddrs(){return this.observed.getAll().map((e=>e.multiaddr))}addObservedAddr(e){const t=e.stringTuples(),r=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(r)||(this.observedAddressFilter.add(r),e=ey(e,this.components.peerId),this.ipMappings.has(e)||this.dnsMappings.has(e)||this.observed.add(e))}confirmObservedAddr(e,t){e=ey(e,this.components.peerId);let r=!0;("transport"===t?.type||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1),("dns-mapping"===t?.type||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1),("ip-mapping"===t?.type||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1),("observed"===t?.type||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),r=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1)),r||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=ey(e,this.components.peerId),this.observed.has(e)&&this.observed.remove(e),this.transportAddresses.has(e)&&this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry),this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry),this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)}getAddresses(){const e=new Set,t=this.getAddressesWithMetadata().filter((t=>{if(!t.verified)return!1;const r=t.multiaddr.toString();return!e.has(r)&&(e.add(r),!0)})).map((e=>e.multiaddr));return this.announceFilter(t.map((e=>{const t=bl(e);return t.getComponents().pop()?.value===this.components.peerId.toString()?t:t.encapsulate("/p2p/"+this.components.peerId.toString())})))}getAddressesWithMetadata(){const e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach((t=>{t.updateAnnounceAddrs(e)})),e.map((e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})));let t=[];t=t.concat(this.components.transportManager.getAddrs().map((e=>this.transportAddresses.get(e,this.addressVerificationTTL))));const r=this.getAppendAnnounceAddrs();return r.length>0&&(this.components.transportManager.getListeners().forEach((e=>{e.updateAnnounceAddrs(r)})),t=t.concat(r.map((e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}))))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(bl("/dns/"+e))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,r,n=t,s="tcp"){this.ipMappings.add(e,t,r,n,s),this.observed.removePrefixed(`/ip${zc(r)?4:6}/${r}/${s}/${n}`)}removePublicAddressMapping(e,t,r,n=t,s="tcp"){this.ipMappings.remove(bl(`/ip${zc(r)?4:6}/${r}/${s}/${n}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;const t=e.toOptions();if(6===t.family||"127.0.0.1"===t.host||!0===Dd(t.host))return!1;const r=this.components.transportManager.getListeners(),n=[e=>pp.exactMatch(e)||gp.exactMatch(e),e=>op.exactMatch(e),e=>up.exactMatch(e)];for(const s of n){if(!s(e))continue;const n=r.filter((e=>e.getAddrs().filter((e=>4===e.toOptions().family&&s(e))).length>0));if(1!==n.length)continue;const i=n[0].getAddrs().filter((e=>"127.0.0.1"!==e.toOptions().host)).pop();if(null==i)continue;const o=i.toOptions();return this.observed.remove(e),this.ipMappings.add(o.host,o.port,t.host,t.port,t.transport),!0}return!1}}var ry;(e=>{e.NOT_STARTED_YET="The libp2p node is not started yet",e.NOT_FOUND="Not found"})(ry||(ry={}));class ny extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}}class sy extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}}class iy extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}}class oy extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}}class ay extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}}class cy extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}}class ly extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}}class uy extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}}class hy extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}}class dy extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}}class py extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}}class fy extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}}class gy extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}}class my extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}}class yy extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}}class by extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}}class wy{components={};_started=!1;constructor(e={}){this.components={};for(const[t,r]of Object.entries(e))this.components[t]=r;null==this.components.logger&&(this.components.logger=bg())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter((e=>es(e))).map((async t=>{await(t[e]?.())})))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}}const vy=["metrics","connectionProtector","dns"],Ey=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Sy(e){return Array.isArray(e?.[ts])?e[ts]:[]}function Ay(e){return Array.isArray(e?.[rs])?e[rs]:[]}function Iy(e){return e?.[Symbol.toStringTag]??e?.toString()??"unknown"}function _y(e={}){return{denyDialPeer:async()=>!1,async denyDialMultiaddr(e){if(pp.matches(e))return!1;const t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&!!Dd(""+t[0][1])},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...e}}function Cy(e){if(Sn(e))return{peerId:e,multiaddrs:[]};let t,r=Array.isArray(e)?e:[e];if(r.length>0){const e=r[0].getPeerId();t=null==e?void 0:Pc(e),r.forEach((e=>{if(!yl(e))throw new $n("Invalid multiaddr");const r=e.getPeerId();if(null==r){if(null!=t)throw new Pn("Multiaddrs must all have the same peer id or have no peer id")}else{const e=Pc(r);if(!0!==t?.equals(e))throw new Pn("Multiaddrs must all have the same peer id or have no peer id")}}))}return r=r.filter((e=>!Hd.exactMatch(e))),{peerId:t,multiaddrs:r}}const xy=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function ky(e){try{let t;if(t="string"==typeof e?bl(e):e,!t.protoNames().includes("ipcidr")){const e=t.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(e)}return function(e){let t,r;if(e.getComponents().forEach((e=>{"ip4"!==e.name&&"ip6"!==e.name||(r=e.value),"ipcidr"===e.name&&(t=e.value)})),null==t||null==r)throw Error("Invalid multiaddr");return new pl(r,t)}(t)}catch(t){throw Error("Can't convert to IpNet, Invalid multiaddr format: "+e)}}class Ty{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map((e=>ky(e))),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch((e=>{this.log.error("error while pruning connections %e",e)}))}async _maybePruneConnections(){const e=this.connectionManager.getConnections(),t=e.length,r=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,r),t<=r)return;const n=new Ag;for(const t of e){const r=t.remotePeer;if(!n.has(r)){n.set(r,0);try{const e=await this.peerStore.get(r);n.set(r,[...e.tags.values()].reduce(((e,t)=>e+t.value),0))}catch(e){"NotFoundError"!==e.name&&this.log.error("error loading peer tags",e)}}}const s=this.sortConnections(e,n),i=Math.max(t-r,0),o=[];for(const e of s)if(this.log("too many connections open - closing a connection to %p",e.remotePeer),this.allow.some((t=>t.contains(e.remoteAddr.nodeAddress().address)))||o.push(e),o.length===i)break;await Promise.all(o.map((async e=>{await async function(e,t){const r=e?.streams?.map((e=>e.protocol))??[],n=t?.closableProtocols??xy;if(!(r.filter((e=>null!=e&&!n.includes(e))).length>0))try{await(e?.close(t))}catch(t){e?.abort(t)}}(e,{signal:AbortSignal.timeout(1e3)})}))),this.events.safeDispatchEvent("connection:prune",{detail:o})}sortConnections(e,t){return e.sort(((e,t)=>{const r=e.timeline.open,n=t.timeline.open;return r<n?1:r>n?-1:0})).sort(((e,t)=>"outbound"===e.direction&&"inbound"===t.direction?1:"inbound"===e.direction&&"outbound"===t.direction?-1:0)).sort(((e,t)=>e.streams.length>t.streams.length?1:e.streams.length<t.streams.length?-1:0)).sort(((e,r)=>{const n=t.get(e.remotePeer)??0,s=t.get(r.remotePeer)??0;return n>s?1:n<s?-1:0}))}}class Py{deferred;signal;constructor(e){this.signal=e,this.deferred=Ws(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new xn)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Ry{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(1e9*Math.random()+"",10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce(((e,t)=>e&&!0===t.signal?.aborted),!0)&&(this.controller.abort(new xn),this.cleanup())}async join(e={}){const t=new Py(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await ei(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach((t=>{t.deferred.resolve(e)})),this.status="complete"}catch(e){this.recipients.forEach((t=>{t.deferred.reject(e)})),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach((e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}))}}class Ly extends Jn{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??1/0,this.maxSize=e.maxSize??1/0,this.pending=0,null!=e.metricName&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Ed(this.emitEmpty.bind(this),1),this.emitIdle=Ed(this.emitIdle.bind(this),1)}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally((()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")})),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Pp;const r=new Ry(e,t);return this.enqueue(r),this.safeDispatchEvent("add"),this.tryToStartAnother(),r.join(t).then((e=>(this.safeDispatchEvent("completed",{detail:e}),this.safeDispatchEvent("success",{detail:{job:r,result:e}}),e))).catch((e=>{if("queued"===r.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===r){this.queue.splice(e,1);break}throw this.safeDispatchEvent("failure",{detail:{job:r,error:e}}),e}))}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new xn)})),this.clear()}async onEmpty(e){0!==this.size&&await Bg(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Bg(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await Bg(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();const t=Qs({objectMode:!0}),r=e=>{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail)},s=e=>{r(e.detail.error)},i=()=>{r()},o=()=>{r(new xn("Queue aborted"))};this.addEventListener("completed",n),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",o),r()}}}class Dy extends Ly{constructor(e={}){super({...e,sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0})}}function My(e){const t=new globalThis.AbortController;function r(){t.abort();for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",r)}for(const t of e){if(!0===t?.aborted){r();break}null!=t?.addEventListener&&t.addEventListener("abort",r)}const n=t.signal;return n.clear=function(){for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",r)},n}function Ny(e){if(!Md(e))return!1;const{address:t}=e.nodeAddress();var r;return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r=t)||/^::1$/.test(r)}function Oy(e,t){const r=op.exactMatch(e.multiaddr),n=op.exactMatch(t.multiaddr);if(r&&!n)return-1;if(!r&&n)return 1;const s=gp.exactMatch(e.multiaddr),i=gp.exactMatch(t.multiaddr);if(s&&!i)return-1;if(!s&&i)return 1;const o=pp.exactMatch(e.multiaddr),a=pp.exactMatch(t.multiaddr);if(o&&!a)return-1;if(!o&&a)return 1;const c=Sp.exactMatch(e.multiaddr),l=Sp.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;const u=yp.exactMatch(e.multiaddr),h=yp.exactMatch(t.multiaddr);if(u&&!h)return-1;if(!u&&h)return 1;const d=wp.exactMatch(e.multiaddr),p=wp.exactMatch(t.multiaddr);return d&&!p?-1:!d&&p?1:0}function Uy(e,t){const r=Ny(e.multiaddr),n=Ny(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function Fy(e,t){const r=Nd(e.multiaddr),n=Nd(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function By(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function $y(e,t){const r=Ep.exactMatch(e.multiaddr),n=Ep.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}class qy{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??25,this.maxDialQueueLength=t.maxDialQueueLength??500,this.dialTimeout=t.dialTimeout??1e4,this.connections=t.connections??new Ag,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,this.shutDownController.signal;for(const[e,r]of Object.entries(t.resolvers??{}))ml.set(e,r);this.queue=new Dy({concurrency:t.maxParallelDials??50,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",(e=>{e.detail?.name!==xn.name&&this.log.error("error in dial queue - %e",e.detail)}))}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){const{peerId:r,multiaddrs:n}=Cy(e),s=Array.from(this.connections.values()).flat().find((e=>!0!==t.force&&(!!e.remotePeer.equals(r)||n.find((t=>t.equals(e.remoteAddr))))));if("open"===s?.status)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new bf("dial-queue:already-connected")),s;const i=this.queue.queue.find((e=>{if(!0===r?.equals(e.options.peerId))return!0;const t=e.options.multiaddrs;if(null==t)return!1;for(const e of n)if(t.has(e.toString()))return!0;return!1}));if(null!=i){this.log("joining existing dial target for %p",r);for(const e of n)i.options.multiaddrs.add(e.toString());return t.onProgress?.(new bf("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Wn("Dial queue is full");return this.log("creating dial target for %p",r,n.map((e=>e.toString()))),t.onProgress?.(new bf("dial-queue:add-to-dial-queue")),this.queue.add((async e=>{e.onProgress?.(new bf("dial-queue:start-dial"));const t=My([this.shutDownController.signal,e.signal]);try{return await this.dialPeer(e,t)}finally{t.clear()}}),{peerId:r,priority:t.priority??rb,multiaddrs:new Set(n.map((e=>e.toString()))),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){const r=e.peerId,n=e.multiaddrs,s=new Set;let i=0===e.multiaddrs.size,o=0,a=0;const c=[];for(this.log("starting dial to %p",r);i||n.size>0;){a++,i=!1;const l=[],u=new Set(e.multiaddrs);n.clear(),this.log("calculating addrs to dial %p from %s",r,[...u]);const h=await this.calculateMultiaddrs(r,u,{...e,signal:t});for(const e of h)s.has(e.multiaddr.toString())?this.log.trace("skipping previously failed multiaddr %a while dialing %p",e.multiaddr,r):l.push(e);this.log("%s dial to %p with %s",1===a?"starting":"continuing",r,l.map((e=>e.multiaddr.toString()))),e?.onProgress?.(new bf("dial-queue:calculated-addresses",l));for(const n of l){if(o===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",o,e.peerId),new Wn("Peer had more than maxPeerAddrsToDial");o++;try{const s=await this.components.transportManager.dial(n.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",n.multiaddr);try{await this.components.peerStore.merge(s.remotePeer,{multiaddrs:[s.remoteAddr],metadata:{"last-dial-success":Ye(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}return s}catch(e){if(this.log.error("dial failed to %a",n.multiaddr,e),s.add(n.multiaddr.toString()),null!=r)try{await this.components.peerStore.merge(r,{metadata:{"last-dial-failure":Ye(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}if(t.aborted)throw new Hn(e.message);c.push(e)}}}if(1===c.length)throw c[0];throw new AggregateError(c,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,r={}){const n=[...t].map((e=>({multiaddr:bl(e),isCertified:!1})));if(null!=e){if(this.components.peerId.equals(e))throw new Wn("Tried to dial self");if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new uy("The dial request is blocked by gater.allowDialPeer");if(0===n.length){this.log("loading multiaddrs for %p",e);try{const t=await this.components.peerStore.get(e);n.push(...t.addresses),this.log("loaded multiaddrs for %p",e,n.map((({multiaddr:e})=>e.toString())))}catch(e){if("NotFoundError"!==e.name)throw e}}if(0===n.length){this.log("looking up multiaddrs for %p in the peer routing",e);try{const t=await this.components.peerRouting.findPeer(e,r);this.log("found multiaddrs for %p in the peer routing",e,n.map((({multiaddr:e})=>e.toString()))),n.push(...t.multiaddrs.map((e=>({multiaddr:e,isCertified:!1}))))}catch(t){"NoPeerRoutersError"===t.name?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,t)}}}let s=(await Promise.all(n.map((async e=>{const t=await async function(e,t){let r=!1;for(const t of ml.keys())if(r=e.protoNames().includes(t),r)break;if(!r)return[e];const n=await e.resolve(t);return t.log("resolved %s to",e,n.map((e=>e.toString()))),n}(e.multiaddr,{dns:this.components.dns,...r,log:this.log});return 1===t.length&&t[0].equals(e.multiaddr)?e:t.map((e=>({multiaddr:e,isCertified:!1})))})))).flat();if(null!=e){const t="/p2p/"+e.toString();s=s.map((e=>"p2p"!==e.multiaddr.getComponents().pop()?.name?{multiaddr:e.multiaddr.encapsulate(t),isCertified:e.isCertified}:e))}const i=s.filter((t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;const r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)})),o=new Map;for(const e of i){const t=e.multiaddr.toString(),r=o.get(t);null==r?o.set(t,e):r.isCertified=r.isCertified||e.isCertified||!1}const a=[...o.values()];if(0===a.length)throw new py("The dial request has no valid addresses");const c=[];for(const e of a)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||c.push(e);const l=null==this.addressSorter?c.sort(Oy).sort(By).sort($y).sort(Fy).sort(Uy):c.sort(this.addressSorter);if(0===l.length)throw new uy("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map((({multiaddr:e})=>e.toString()))),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map((({multiaddr:e})=>e.toString()))),l}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{const r=await this.calculateMultiaddrs(void 0,new Set(e.map((e=>e.toString()))),t);return!1!==t.runOnLimitedConnection||null!=r.find((e=>!Ep.matches(e.multiaddr)))}catch(e){this.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}}class zy extends Ly{has(e){return null!=this.find(e)}find(e){return this.queue.find((t=>e.equals(t.options.peerId)))}}var jy,Ky,Vy,Hy,Gy,Wy={},Xy=ss(Gy?Hy:(Gy=1,Hy=function(){var e,t;return Vy||(Vy=1,e=Wy,t=function(){if(Ky)return jy;function e(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return Ky=1,jy=e,e.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},e.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},e.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((()=>{n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((()=>{n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),r),this._options.unref&&this._timer.unref(),!0},e.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout((()=>{r._operationTimeoutCb()}),r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},e.prototype.try=function(e){this.attempt(e)},e.prototype.start=function(e){this.attempt(e)},e.prototype.start=e.prototype.try,e.prototype.errors=function(){return this._errors},e.prototype.attempts=function(){return this._attempts},e.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var s=this._errors[n],i=s.message,o=(e[i]||0)+1;e[i]=o,o>=r&&(t=s,r=o)}return t},jy}(),e.operation=r=>{var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw Error("minTimeout is greater than maxTimeout");for(var n=[],s=0;s<t.retries;s++)n.push(this.createTimeout(s,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(s,t)),n.sort(((e,t)=>e-t)),n},e.createTimeout=(e,t)=>{var r=t.randomize?Math.random()+1:1,n=Math.round(r*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return Math.min(n,t.maxTimeout)},e.wrap=function(t,r,n){if(r instanceof Array&&(n=r,r=null),!n)for(var s in n=[],t)"function"==typeof t[s]&&n.push(s);for(var i=0;i<n.length;i++){var o=n[i],a=t[o];t[o]=function(n){var s=e.operation(r),i=[].slice.call(arguments,1),o=i.pop();i.push((function(e){s.retry(e)||(e&&(arguments[0]=s.mainError()),o.apply(this,arguments))})),s.attempt((()=>{n.apply(t,i)}))}.bind(t,a),t[o].options=r}}),Wy}()));const Zy={}.toString,Yy=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);class Qy extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const Jy=(e,t,r)=>{const n=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=n,e};class eb{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new zy({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",(e=>{this.maybeReconnect(e.detail).catch((t=>{this.log.error("failed to maybe reconnect to %p - %e",e.detail,t)}))}))}async maybeReconnect(e){if(!this.started)return;const t=await this.peerStore.get(e);tb(t)&&(this.queue.has(e)||this.queue.add((async t=>{await async function(e,t){return new Promise(((r,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;const s=Xy.operation(t),i=()=>{s.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",i,{once:!0});const o=()=>{t.signal?.removeEventListener("abort",i),s.stop()};s.attempt((async i=>{try{const t=await e(i);o(),r(t)}catch(e){try{if(!(e instanceof Error))throw new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(e instanceof Qy)throw e.originalError;if(e instanceof TypeError&&!function(e){var t;return!(!e||(t=e,"[object Error]"!==Zy.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)&&("Load failed"===e.message?void 0===e.stack:Yy.has(e.message))}(e))throw e;if(Jy(e,i,t),await t.shouldRetry(e)||(s.stop(),n(e)),await t.onFailedAttempt(e),!s.retry(e))throw s.mainError()}catch(e){Jy(e,i,t),o(),n(e)}}}))}))}((async r=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:t?.signal})}catch(t){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,r,this.retries,t),t}}),{signal:t?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})}),{peerId:e}).catch((async r=>{this.log.error("failed to reconnect to %p - %e",e,r);const n={};[...t.tags.keys()].forEach((e=>{e.startsWith(In)&&(n[e]=void 0)})),await this.peerStore.merge(e,{tags:n}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})})).catch((async t=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,t)})))}start(){this.started=!0}async afterStart(){Promise.resolve().then((async()=>{const e=await this.peerStore.all({filters:[e=>tb(e)]});await Promise.all(e.map((async e=>{await this.connectionManager.openConnection(e.id).catch((e=>{this.log.error(e)}))})))})).catch((e=>{this.log.error(e)}))}stop(){this.started=!1,this.queue.abort()}}function tb(e){for(const t of e.tags.keys())if(t.startsWith(In))return!0;return!1}const rb=50;class nb{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??100,this.maxConnections<1)throw new Pn("Connection Manager maxConnections must be greater than 0");this.connections=new Ag,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map((e=>ky(e))),this.deny=(t.deny??[]).map((e=>ky(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??10,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Rp({points:t.inboundConnectionThreshold??5,duration:1}),this.connectionPruner=new Ty({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map((e=>bl(e)))}),this.dialQueue=new qy(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:ig},connections:this.connections}),this.reconnectQueue=new eb({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(const t of this.connections.values())for(const r of t)e[r.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t)for(const t of r.streams){const r=`${t.direction} ${t.protocol??"unnegotiated"}`;e[r]=(e[r]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t){const t={};for(const e of r.streams){const r=`${e.direction} ${e.protocol??"unnegotiated"}`;t[r]=(t[r]??0)+1}for(const[r,n]of Object.entries(t))e[r]=e[r]??[],e[r].push(n)}const t={};for(let[r,n]of Object.entries(e)){n=n.sort(((e,t)=>e-t));const e=Math.floor(.9*n.length);t[r]=n[e]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await async function(...e){const t=[];for(const r of e)es(r)&&t.push(r);await Promise.all(t.map((async e=>{null!=e.beforeStart&&await e.beforeStart()}))),await Promise.all(t.map((async e=>{await e.start()}))),await Promise.all(t.map((async e=>{null!=e.afterStart&&await e.afterStart()})))}(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await async function(...e){const t=[];for(const r of e)es(r)&&t.push(r);await Promise.all(t.map((async e=>{null!=e.beforeStop&&await e.beforeStop()}))),await Promise.all(t.map((async e=>{await e.stop()}))),await Promise.all(t.map((async e=>{null!=e.afterStop&&await e.afterStop()})))}(this.reconnectQueue,this.dialQueue,this.connectionPruner);const e=[];for(const t of this.connections.values())for(const r of t)e.push((async()=>{try{await r.close()}catch(e){this.log.error(e)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new Pn("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch((e=>{this.log.error(e)}))}async _onConnect(e){const{detail:t}=e;if(!this.started)return void await t.close();if("open"!==t.status)return;const r=t.remotePeer,n=!this.connections.has(r),s=this.connections.get(r)??[];s.push(t),this.connections.set(r,s),null!=r.publicKey&&"RSA"===r.type&&await this.peerStore.patch(r,{publicKey:r.publicKey}),n&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){const{detail:t}=e,r=t.remotePeer,n=(this.connections.get(r)??[]).filter((e=>e.id!==t.id));this.connections.set(r,n),0===n.length&&(this.log("onDisconnect remove all connections for peer %p",r),this.connections.delete(r),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(null!=e)return this.connections.get(e)??[];let t=[];for(const e of this.connections.values())t=t.concat(e);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Gn("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();const{peerId:r}=Cy(e);if(this.peerId.equals(r))throw new Bn("Can not dial self");if(null!=r&&!0!==t.force){this.log("dial %p",r);const e=this.getConnections(r).find((e=>null==e.limits));if(null!=e)return this.log("had an existing non-limited connection to %p",r),t.onProgress?.(new bf("dial-queue:already-connected")),e}const n=await this.dialQueue.dial(e,{...t,priority:t.priority??rb});if("open"!==n.status)throw new Dn("Remote closed connection during opening");let s=this.connections.get(n.remotePeer);null==s&&(s=[],this.connections.set(n.remotePeer,s));let i=!1;for(const e of s)if(e.id===n.id&&(i=!0),!0!==t.force&&e.id!==n.id&&e.remoteAddr.equals(n.remoteAddr))return n.abort(new $n("Duplicate multiaddr connection")),e;return i||s.push(n),n}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){const r=this.connections.get(e)??[];await Promise.all(r.map((async e=>{try{await e.close(t)}catch(t){e.abort(t)}})))}async acceptIncomingConnection(e){if(this.deny.some((t=>t.contains(e.remoteAddr.nodeAddress().address))))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some((t=>t.contains(e.remoteAddr.nodeAddress().address))))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){const t=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(t,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,t),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){const e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map((t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map((e=>bl(e)))})))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class sb{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(null!=this.previousTime){const r=this.alpha(t,this.previousTime),n=e-this.movingAverage,s=r*n;this.movingAverage=r*e+(1-r)*this.movingAverage,this.variance=(1-r)*(this.variance+n*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+r*n}else this.movingAverage=e;this.previousTime=t}}class ib{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){const t=e.interval??5e3;this.success=new sb(t),this.failure=new sb(t),this.next=new sb(t),this.failureMultiplier=e.failureMultiplier??2,this.timeoutMultiplier=e.timeoutMultiplier??1.2,this.minTimeout=e.minTimeout??5e3,this.maxTimeout=e.maxTimeout??6e4,null!=e.metricName&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);const r=AbortSignal.timeout(t),n=My([e.signal,r]);return n.start=Date.now(),n.timeout=t,n}cleanUp(e){const t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}}class ob{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??1e4,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??!0,this.timeout=new ib({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[ts]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval((()=>{this.components.connectionManager.getConnections().forEach((e=>{Promise.resolve().then((async()=>{let t=Date.now();try{const r=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),n=Cu(await e.newStream(this.protocol,{signal:r,runOnLimitedConnection:!0}));t=Date.now(),await Promise.all([n.write(Ya(32),{signal:r}),n.read({bytes:32,signal:r})]),e.rtt=Date.now()-t,await n.unwrap().close({signal:r})}catch(r){if("UnsupportedProtocolError"!==r.name)throw r;e.rtt=(Date.now()-t)/2}})).catch((t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")}))}))}),this.pingIntervalMs)}stop(){this.abortController?.abort(),null!=this.heartbeatInterval&&clearInterval(this.heartbeatInterval)}}class ab{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()}),getAttributesFromYieldedValue:(e,t)=>({...t,providers:[...Array.isArray(t.providers)?t.providers:[],e.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([e])=>({key:tn(e,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([e])=>({key:tn(e,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(0===this.routers.length)throw new iy("No content routers available");const r=this,n=new Ig;for await(const s of ni(...r.routers.filter((e=>e.findProviders instanceof Function)).map((r=>r.findProviders(e,t)))))null!=s&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),n.has(s.id)||(n.add(s.id),yield s))}async provide(e,t={}){if(0===this.routers.length)throw new iy("No content routers available");await Promise.all(this.routers.filter((e=>e.provide instanceof Function)).map((async r=>{await r.provide(e,t)})))}async cancelReprovide(e,t={}){if(0===this.routers.length)throw new iy("No content routers available");await Promise.all(this.routers.filter((e=>e.cancelReprovide instanceof Function)).map((async r=>{await r.cancelReprovide(e,t)})))}async put(e,t,r){if(!this.isStarted())throw new Gn;await Promise.all(this.routers.filter((e=>e.put instanceof Function)).map((async n=>{await n.put(e,t,r)})))}async get(e,t){if(!this.isStarted())throw new Gn;return Promise.any(this.routers.filter((e=>e.get instanceof Function)).map((async r=>r.get(e,t))))}}class cb{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,peer:e.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,key:tn(e,"base36")}),getAttributesFromYieldedValue:(e,t)=>({...t,peers:[...Array.isArray(t.peers)?t.peers:[],e.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(0===this.routers.length)throw new oy("No peer routers available");if(e.toString()===this.peerId.toString())throw new ay("Should not try to find self");const r=this,n=ni(...this.routers.filter((e=>e.findPeer instanceof Function)).map((n=>async function*(){try{yield await n.findPeer(e,t)}catch(e){r.log.error(e)}}())));for await(const e of n)if(null!=e)return e.multiaddrs.length>0&&await this.peerStore.merge(e.id,{multiaddrs:e.multiaddrs},t),e;throw new Fn}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new oy("No peer routers available");const r=this,n=Og(1024);for await(const s of async function*(e,t={}){let r=t.concurrency??1/0;r<1&&(r=1/0);const n=t.ordered??!1,s=new EventTarget,i=[];let o,a=Ws(),c=Ws(),l=!1,u=!1;function h(){return n?i[0]?.done:!!i.find((e=>e.done))}function*d(){for(;i.length>0&&i[0].done;){const e=i[0];if(i.shift(),!e.ok)throw u=!0,a.resolve(),e.err;yield e.value,a.resolve()}}function*p(){for(;h();)for(let e=0;e<i.length;e++)if(i[e].done){const t=i[e];if(i.splice(e,1),e--,!t.ok)throw u=!0,a.resolve(),t.err;yield t.value,a.resolve()}}for(s.addEventListener("task-complete",(()=>{c.resolve()})),Promise.resolve().then((async()=>{try{for await(const t of e){if(i.length===r&&(a=Ws(),await a.promise),u)break;const e={done:!1};i.push(e),t().then((t=>{e.done=!0,e.ok=!0,e.value=t,s.dispatchEvent(new Ad("task-complete"))}),(t=>{e.done=!0,e.err=t,s.dispatchEvent(new Ad("task-complete"))}))}l=!0,s.dispatchEvent(new Ad("task-complete"))}catch(e){o=e,s.dispatchEvent(new Ad("task-complete"))}}));;){if(h()||(c=Ws(),await c.promise),null!=o)throw o;if(n?yield*d():yield*p(),null!=o)throw o;if(l&&0===i.length)break}}(async function*(){const n=ni(...r.routers.filter((e=>e.getClosestPeers instanceof Function)).map((r=>r.getClosestPeers(e,t))));for await(let e of n)yield async()=>{if(0===e.multiaddrs.length)try{e=await r.findPeer(e.id,{...t,useCache:!1})}catch(e){return void r.log.error("could not find peer multiaddrs",e)}return e}}()))null!=s&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),n.has(s.id.toMultihash().bytes)||(n.add(s.id.toMultihash().bytes),yield s))}}class lb extends Jn{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;const t=My([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=Ws();const e=await Bg(this,"walk:peer",t,{errorEvent:"walk:error"});yield e.detail}}finally{t.clear(),this.walkers--,0===this.walkers&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;const e=My([this.walkController.signal,this.shutdownController.signal]),t=Date.now();let r=0;Promise.resolve().then((async()=>{for(this.log("start walk");this.walkers>0;)try{const t=Ya(32);let n=Date.now();for await(const s of this.peerRouting.getClosestPeers(t,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-n,this.walkers),r++,this.safeDispatchEvent("walk:peer",{detail:s}),1===this.walkers&&null!=this.needNext&&(this.log("wait for need next"),await ei(this.needNext.promise,e)),n=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",t,this.walkers,r)}catch(e){this.log.error("random walk errored",e),this.safeDispatchEvent("walk:error",{detail:e})}this.log("no walkers left, ended walk")})).catch((e=>{this.log.error("random walk errored",e)})).finally((()=>{this.log("finished walk, found %d peers after %dms",r,Date.now()-t),this.walking=!1}))}}class ub{log;topologies;handlers;components;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{const e={};for(const[t,r]of this.topologies)e[t]=r.size;return e}}),this.handlers=Vm({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){const t=this.handlers.get(e);if(null==t)throw new cy("No handler registered for protocol "+e);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,r){if(this.handlers.has(e)&&!0!==r?.force)throw new ly("Handler already registered for protocol "+e);const n=Df.bind({ignoreUndefined:!0})({maxInboundStreams:32,maxOutboundStreams:64},r);this.handlers.set(e,{handler:t,options:n}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},r)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach((e=>{this.handlers.delete(e)})),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(null==t)throw new Pn("invalid topology");const r=`${(1e9*Math.random()).toString(36)}${Date.now()}`;let n=this.topologies.get(e);return null==n&&(n=new Map,this.topologies.set(e,n)),n.set(r,t),r}unregister(e){for(const[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){const t=e.detail,r={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(t,r).then((e=>{for(const r of e.protocols){const e=this.topologies.get(r);if(null!=e)for(const r of e.values())!1!==r.filter?.has(t)&&(r.filter?.remove(t),r.onDisconnect?.(t))}})).catch((e=>{"NotFoundError"!==e.name&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)}))}_onPeerUpdate(e){const{peer:t,previous:r}=e.detail,n=(r?.protocols??[]).filter((e=>!t.protocols.includes(e)));for(const e of n){const r=this.topologies.get(e);if(null!=r)for(const e of r.values())!1!==e.filter?.has(t.id)&&(e.filter?.remove(t.id),e.onDisconnect?.(t.id))}}_onPeerIdentify(e){const t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(const e of t){const t=this.topologies.get(e);if(null!=t)for(const e of t.values())null!=r.limits&&!0!==e.notifyOnLimitedConnection||!0!==e.filter?.has(n)&&(e.filter?.add(n),e.onConnect?.(n,r))}}}class hb{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Vm({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Vm({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Cn.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){const t=e[Symbol.toStringTag];if(null==t)throw new Pn("Transport must have a valid tag");if(this.transports.has(t))throw new Pn("There is already a transport with the tag "+t);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){const e=[];for(const[t,r]of this.listeners)for(this.log("closing listeners for %s",t);r.length>0;){const t=r.pop();null!=t&&e.push(t.close())}await Promise.all(e),this.log("all listeners closed");for(const e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(e,t){const r=this.dialTransportForMultiaddr(e);if(null==r)throw new by("No transport available for address "+e);return t?.onProgress?.(new bf("transport-manager:selected-transport",r[Symbol.toStringTag])),r.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(const t of this.listeners.values())for(const r of t)e=[...e,...r.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(const t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(const t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Gn("Not started");if(null==e||0===e.length)return void this.log("no addresses were provided for listening, this node is dial only");const t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach((e=>{t.errors.set(e.toString(),new hy)}));const r=[];for(const[n,s]of this.transports.entries()){const i=s.listenFilter(e);for(const e of i){this.log("creating listener for %s on %a",n,e);const i=s.createListener({upgrader:this.components.upgrader});let o=this.listeners.get(n)??[];null==o&&(o=[],this.listeners.set(n,o)),o.push(i),i.addEventListener("listening",(()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:i})})),i.addEventListener("close",(()=>{const e=o.findIndex((e=>e===i));o.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:i})})),rp.matches(e)?t.ipv4.attempts++:np.matches(e)&&t.ipv6.attempts++,r.push(i.listen(e).then((()=>{t.errors.delete(e.toString()),rp.matches(e)&&t.ipv4.success++,np.matches(e)&&t.ipv6.success++}),(r=>{throw this.log.error("transport %s could not listen on address %a - %e",n,e,r),t.errors.set(e.toString(),r),r})))}}const n=await Promise.allSettled(r);if(!(n.length>0&&n.every((e=>"fulfilled"===e.status))))if(this.ipv6Unsupported(t))this.log("all IPv4 addresses succeed but all IPv6 failed");else{if(this.faultTolerance!==Cn.NO_FATAL)throw new dy("Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set `transportManager.faultTolerance` to NO_FATAL:\n"+[...t.errors.entries()].map((([e,t])=>`\n ${e}: ${(""+(t.stack??t)).split("\n").join("\n ")}\n`)).join(""));this.log("failed to listen on any address but fault tolerance allows this")}}ipv6Unsupported(e){if(0===e.ipv4.attempts||0===e.ipv6.attempts)return!1;const t=e.ipv4.attempts===e.ipv4.success,r=0===e.ipv6.success;return t&&r}async remove(e){const t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);const r=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){const e=t.pop();null!=e&&r.push(e.close())}await Promise.all(r),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){const e=[];for(const t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}}const db="/multistream/1.0.0",pb=1024,fb=Ye("\n");async function gb(e,t,r){await e.write(t,r)}async function mb(e,t){const r=await async function(e,t){const r=await e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==fb[0])throw t.log.error("Invalid mss message - missing newline",r),new Kn("Missing newline");return r.sublist(0,-1)}(e,t);return tn(r.subarray())}async function yb(e,t,r){if(1===(t=Array.isArray(t)?[...t]:[t]).length&&!1===r.negotiateFully)return function(e,t,r){const n=e.sink.bind(e),s=e.source;let i=!1,o=!1;const a=Ws();let c=!1,l=!1;const u=Ws();let h=!1,d=!1;const p=Ws(),f=Pu({sink:n,source:s},{...r,maxDataLength:pb});async function g(){if(o)return r.log.trace("optimistic: already negotiating %s stream",t),void await a.promise;o=!0;try{c||(r.log.trace("optimistic: doing send protocol for %s stream",t),await async function(){if(l)await u.promise;else{l=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',db,t),await f.writeV([Ye(db+"\n"),Ye(t+"\n")]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',db,t)}finally{c=!0,l=!1,u.resolve()}}}()),h||(r.log.trace("optimistic: doing read protocol for %s stream",t),await async function(){if(d)await p.promise;else{d=!0;try{r.log.trace("optimistic: reading multistream select header");let e=await mb(f,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===db&&(e=await mb(f,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new jn("protocol selection failed")}finally{h=!0,d=!1,p.resolve()}}}())}finally{o=!1,i=!0,a.resolve()}}if(e.sink=async e=>{const{sink:n}=f.unwrap();await n(async function*(){let n=!1;for await(const s of e){if(l&&await u.promise,c)yield s;else{l=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',db,t,s.byteLength);const e=t+"\n";yield new Us(Uint8Array.from([19]),Ye(db+"\n"),y(e.length),Ye(e),s).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',db,t,s.byteLength),c=!0,l=!1,u.resolve(),g().catch((e=>{r.log.error("could not finish optimistic protocol negotiation of %s",t,e)}))}n=!0}n||await g()}())},e.source=async function*(){await g(),r.log.trace('optimistic: reading data from "%s" stream',t),yield*f.unwrap().source}(),null!=e.closeRead){const t=e.closeRead.bind(e);e.closeRead=async e=>{i||await g().catch((e=>{r.log.error("could not negotiate protocol before close read",e)})),await t(e)}}if(null!=e.closeWrite){const t=e.closeWrite.bind(e);e.closeWrite=async e=>{i||await g().catch((e=>{r.log.error("could not negotiate protocol before close write",e)})),await t(e)}}if(null!=e.close){const t=e.close.bind(e);e.close=async e=>{const r=[];l&&r.push(u.promise),d&&r.push(p.promise),r.length>0?await ei(Promise.all(r),e?.signal):(i=!0,o=!1,a.resolve()),await t(e)}}return{stream:e,protocol:t}}(e,t[0],r);const n=Pu(e,{...r,maxDataLength:pb}),s=t.shift();if(null==s)throw Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',db,s);const i=Ye(db+"\n"),o=Ye(s+"\n");await async function(e,t,r){await e.writeV(t,r)}(n,[i,o],r),r.log.trace("select: reading multistream-select header");let a=await mb(n,r);if(r.log.trace('select: read "%s"',a),a===db&&(r.log.trace("select: reading protocol response"),a=await mb(n,r),r.log.trace('select: read "%s"',a)),a===s)return{stream:n.unwrap(),protocol:s};for(const e of t){r.log.trace('select: write "%s"',e),await gb(n,Ye(e+"\n"),r),r.log.trace("select: reading protocol response");const t=await mb(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new jn("protocol selection failed")}async function bb(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);const n=Pu(e,{...r,maxDataLength:pb,maxLengthLength:2});for(;;){r.log.trace("handle: reading incoming string");const e=await mb(n,r);if(r.log.trace('handle: read "%s"',e),e!==db){if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await gb(n,Ye(e+"\n"),r),r.log.trace('handle: responded with "%s" for "%s"',e,e),{stream:n.unwrap(),protocol:e};if("ls"!==e)r.log.trace('handle: respond with "na" for "%s"',e),await gb(n,Ye("na\n"),r),r.log('handle: responded with "na" for "%s"',e);else{const s=new Us(...t.map((e=>Eu.single(Ye(e+"\n")))),Ye("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await gb(n,s,r),r.log.trace('handle: responded with "%s" for %s',t,e)}}else r.log.trace('handle: respond with "%s" for "%s"',db,e),await gb(n,Ye(db+"\n"),r),r.log.trace('handle: responded with "%s" for "%s"',db,e)}}class wb{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){const{remoteAddr:t,remotePeer:r,newStream:n,close:s,abort:i,getStreams:o}=e;this.id=`${parseInt(1e9*Math.random()+"").toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=r,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),null==this.remoteAddr.getPeerId()&&(this.remoteAddr=this.remoteAddr.encapsulate("/p2p/"+this.remotePeer)),this._newStream=n,this._close=s,this._abort=i,this._getStreams=o,this.tags=[]}[Symbol.toStringTag]="Connection";[bn]=!0;get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new Ln("the connection is being closed");if("closed"===this.status)throw new Dn("the connection is closed");if(Array.isArray(e)||(e=[e]),null!=this.limits&&!0!==t?.runOnLimitedConnection)throw new Xn("Cannot open protocol stream on limited connection");const r=await this._newStream(e,t);return r.direction="outbound",r}async close(e={}){if("closed"!==this.status&&"closing"!==this.status){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",null==e.signal){const t=AbortSignal.timeout(500);e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(e){"closed"!==this.status&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}}function vb(e,t,r){let n=0;return r.streams.forEach((r=>{r.direction===t&&r.protocol===e&&n++})),n}class Eb{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=Vm({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach((e=>{this.connectionEncrypters.set(e.protocol,e)})),this.streamMuxers=Vm({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach((e=>{this.streamMuxers.set(e.protocol,e)})),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){const r=this.components.connectionGater[e];if(null!=r&&!0===await r.apply(this.components.connectionGater,t))throw new fy("The multiaddr connection is blocked by gater."+e)}createInboundAbortSignal(e){return My([AbortSignal.timeout(this.inboundUpgradeTimeout),e])}async upgradeInbound(e,t){let r=!1;const n=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),r=await ei(this.components.connectionManager.acceptIncomingConnection(e),n),!r)throw new gy("Connection denied");await ei(this.shouldBlockConnection("denyInboundConnection",e),n),await this._performUpgrade(e,"inbound",{...t,signal:n})}catch(e){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[e.name??"Error"]:!0}),e}finally{n.clear(),r&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});const r=e.remoteAddr.getPeerId();let n;null!=r&&(n=Pc(r),await ei(this.shouldBlockConnection("denyOutboundConnection",n,e),t.signal));let s="outbound";return!1===t.initiator&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(e){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[e.name??"Error"]:!0}),e}}async _performUpgrade(e,t,r){let n,s,i,o,a;this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let c=e;if(!0!==r?.skipProtection){const n=this.components.connectionProtector;null!=n&&(e.log("protecting the %s connection",t),c=await n.protect(e,r))}try{if(n=c,!0!==r?.skipEncryption){r?.onProgress?.(new bf(`upgrader:encrypt-${t}-connection`)),({conn:n,remotePeer:s,protocol:a,streamMuxer:o}=await("inbound"===t?this._encryptInbound(c,r):this._encryptOutbound(c,r)));const e={...c,...n};await this.shouldBlockConnection("inbound"===t?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e)}else{const r=e.remoteAddr.getPeerId();if(null==r)throw new $n(t+" connection that skipped encryption must have a peer id");const n=Pc(r);a="native",s=n}if(s.equals(this.components.peerId)){const t=new Bn("Can not dial self");throw e.abort(t),t}if(i=n,null!=r?.muxerFactory)o=r.muxerFactory;else if(null==o&&this.streamMuxers.size>0){r?.onProgress?.(new bf(`upgrader:multiplex-${t}-connection`));const e=await("inbound"===t?this._multiplexInbound({...c,...n},this.streamMuxers,r):this._multiplexOutbound({...c,...n},this.streamMuxers,r));o=e.muxerFactory,i=e.stream}}catch(r){throw e.log.error("failed to upgrade inbound connection %s %a - %e","inbound"===t?"from":"to",e.remoteAddr,r),r}return await this.shouldBlockConnection("inbound"===t?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:a,direction:t,maConn:e,upgradedConn:i,muxerFactory:o,remotePeer:s,limits:r?.limits})}_createConnection(e){const{cryptoProtocol:t,direction:r,maConn:n,upgradedConn:s,remotePeer:i,muxerFactory:o,limits:a}=e;let c,l,u;null!=o&&(c=o.createStreamMuxer({direction:r,onIncomingStream:e=>{if(null==u)return;const t=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then((async()=>{const r=this.components.registrar.getProtocols(),{stream:n,protocol:s}=await bb(e,r,{signal:t,log:e.log,yieldBytes:!1});if(null==u)return;u.log("incoming stream opened on %s",s);const o=function(e,t){try{const{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return 32}(s,this.components.registrar);if(vb(s,"inbound",u)===o){const t=new Zn(`Too many inbound protocol streams for protocol "${s}" - limit ${o}`);throw e.abort(t),t}e.source=n.source,e.sink=n.sink,e.protocol=s,null!=n.closeWrite&&(e.closeWrite=n.closeWrite),null!=n.closeRead&&(e.closeRead=n.closeRead),null!=n.close&&(e.close=n.close),await this.components.peerStore.merge(i,{protocols:[s]},{signal:t}),this.components.metrics?.trackProtocolStream(e,u),this._onStream({connection:u,stream:e,protocol:s})})).catch((async r=>{u.log.error("error handling incoming stream id %s - %e",e.id,r),null==e.timeline.close&&await e.close({signal:t}).catch((t=>e.abort(t)))}))}}),l=async(t,n={})=>{if(null==c)throw new my("Connection is not multiplexed");u.log.trace("starting new stream for protocols %s",t);const s=await c.newStream();u.log.trace("started new stream %s for protocols %s",s.id,t);try{if(null==n.signal){s.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",t);const e=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);n={...n,signal:e}}s.log.trace("selecting protocol from protocols %s",t);const{stream:e,protocol:r}=await yb(s,t,{...n,log:s.log,yieldBytes:!0});s.log.trace("selected protocol %s",r);const o=function(e,t,r={}){try{const{options:r}=t.getHandler(e);if(null!=r.maxOutboundStreams)return r.maxOutboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return r.maxOutboundStreams??64}(r,this.components.registrar,n),a=vb(r,"outbound",u);if(a>=o){const e=new Yn(`Too many outbound protocol streams for protocol "${r}" - ${a}/${o}`);throw s.abort(e),e}return await this.components.peerStore.merge(i,{protocols:[r]}),s.source=e.source,s.sink=e.sink,s.protocol=r,null!=e.closeWrite&&(s.closeWrite=e.closeWrite),null!=e.closeRead&&(s.closeRead=e.closeRead),null!=e.close&&(s.close=e.close),this.components.metrics?.trackProtocolStream(s,u),s}catch(n){throw u.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e","inbound"===r?"from":"to",e.maConn.remoteAddr,t,n),null==s.timeline.close&&s.abort(n),n}},Promise.all([c.sink(s.source),s.sink(c.source)]).catch((e=>{u.log.error("error piping data through muxer - %e",e)})));const h=n.timeline;var d;return n.timeline=new Proxy(h,{set:(...e)=>("close"===e[1]&&null!=e[2]&&null==h.close&&(async()=>{try{"open"===u.status&&await u.close()}catch(e){u.log.error("error closing connection after timeline close %e",e)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch((e=>{u.log.error("error thrown while dispatching connection:close event %e",e)})),Reflect.set(...e))}),n.timeline.upgraded=Date.now(),d={remoteAddr:n.remoteAddr,remotePeer:i,status:"open",direction:r,timeline:n.timeline,multiplexer:c?.protocol,encryption:t,limits:a,logger:this.components.logger,newStream:l??(()=>{throw new my("Connection is not multiplexed")}),getStreams:()=>c?.streams??[],async close(e){await(c?.close(e)),await n.close(e)},abort(e){n.abort(e),c?.abort(e)}},u=new wb(d),this.events.safeDispatchEvent("connection:open",{detail:u}),u.__maConnTimeline=h,u}_onStream(e){const{connection:t,stream:r,protocol:n}=e,{handler:s,options:i}=this.components.registrar.getHandler(n);if(null!=t.limits&&!0!==i.runOnLimitedConnection)throw new Xn("Cannot open protocol stream on limited connection");s({connection:t,stream:r})}async _encryptInbound(e,t){const r=Array.from(this.connectionEncrypters.keys());try{const{stream:n,protocol:s}=await bb(e,r,{...t,log:e.log}),i=this.connectionEncrypters.get(s);if(null==i)throw new yy("no crypto module found for "+s);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,s),{...await i.secureInbound(n,t),protocol:s}}catch(t){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,t),new yy(t.message)}}async _encryptOutbound(e,t){const r=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",r);const{stream:n,protocol:s}=await yb(e,r,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(null==i)throw new yy("no crypto module found for "+s);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,s),{...await i.secureOutbound(n,t),protocol:s}}catch(t){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,t),new yy(t.message)}}async _multiplexOutbound(e,t,r){const n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);const{stream:s,protocol:i}=await yb(e,n,{...r,log:e.log,yieldBytes:!0});return e.log("selected %s as muxer protocol",i),{stream:s,muxerFactory:t.get(i)}}catch(t){throw e.log.error("error multiplexing outbound connection",t),new my(t+"")}}async _multiplexInbound(e,t,r){const n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{const{stream:s,protocol:i}=await bb(e,n,{...r,log:e.log});return{stream:s,muxerFactory:t.get(i)}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new my(t+"")}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}}const Sb="2.8.11",Ab="js-libp2p";function Ib(e,t){return`${e??Ab}/${t??Sb} browser/${globalThis.navigator.userAgent}`}class _b extends Jn{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new Jn,r=t.dispatchEvent.bind(t);t.dispatchEvent=e=>{const t=r(e),n=this.dispatchEvent(new CustomEvent(e.type,{detail:e.detail}));return t||n},this.peerId=e.peerId,this.logger=e.logger??bg(),this.log=this.logger.forComponent("libp2p"),this.services={};const n=e.nodeInfo?.name??Ab,s=e.nodeInfo?.version??Sb,i=this.components=function(e={}){const t=new wy(e);return new Proxy(t,{get(e,r,n){if("string"==typeof r&&!Ey.includes(r)){const e=t.components[r];if(null==e&&!vy.includes(r))throw new ny(r+" not set");return e}return Reflect.get(e,r,n)},set:(e,r,n)=>("string"==typeof r?t.components[r]=n:Reflect.set(e,r,n),!0)})}({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:n,version:s,userAgent:e.nodeInfo?.userAgent??Ib(n,s)},logger:this.logger,events:t,datastore:e.datastore??new jm,connectionGater:_y(e.connectionGater),dns:e.dns});null!=e.metrics&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",function(e,t={}){return new Um(e,t)}(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",(e=>{if(null==e.detail.previous){const t={id:e.detail.peer.id,multiaddrs:e.detail.peer.addresses.map((e=>e.multiaddr))};i.events.safeDispatchEvent("peer:discovery",{detail:t})}})),null!=e.connectionProtector&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Eb(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map(((e,t)=>this.configureComponent("connection-encryption-"+t,e(this.components)))),streamMuxers:(e.streamMuxers??[]).map(((e,t)=>this.configureComponent("stream-muxers-"+t,e(this.components)))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new hb(this.components,e.transportManager)),this.configureComponent("connectionManager",new nb(this.components,e.connectionManager)),!1!==e.connectionMonitor?.enabled&&this.configureComponent("connectionMonitor",new ob(this.components,e.connectionMonitor)),this.configureComponent("registrar",new ub(this.components)),this.configureComponent("addressManager",new ty(this.components,e.addresses));const o=(e.peerRouters??[]).map(((e,t)=>this.configureComponent("peer-router-"+t,e(this.components))));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new cb(this.components,{routers:o}));const a=(e.contentRouters??[]).map(((e,t)=>this.configureComponent("content-router-"+t,e(this.components))));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new ab(this.components,{routers:a})),this.configureComponent("randomWalk",new lb(this.components)),(e.peerDiscovery??[]).forEach(((e,t)=>{this.configureComponent("peer-discovery-"+t,e(this.components)).addEventListener("peer",(e=>{this.#M(e)}))})),e.transports?.forEach(((e,t)=>{this.components.transportManager.add(this.configureComponent("transport-"+t,e(this.components)))})),null!=e.services)for(const t of Object.keys(e.services)){const r=(0,e.services[t])(this.components);null!=r?(this.services[t]=r,this.configureComponent(t,r),null!=r[wn]&&(this.log("registering service %s for content routing",t),a.push(r[wn])),null!=r[An]&&(this.log("registering service %s for peer routing",t),o.push(r[An])),null!=r[vn]&&(this.log("registering service %s for peer discovery",t),r[vn].addEventListener?.("peer",(e=>{this.#M(e)})))):this.log.error("service factory %s returned null or undefined instance",t)}!function(e){const t={};for(const r of Object.values(e.components))for(const e of Sy(r))t[e]=!0;for(const r of Object.values(e.components))for(const e of Ay(r))if(!0!==t[e])throw new sy(`Service "${Iy(r)}" required capability "${e}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}(i)}configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if("stopped"===this.status){this.status="starting",this.log("libp2p is starting");try{await(this.components.beforeStart?.()),await this.components.start(),await(this.components.afterStart?.()),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){"started"===this.status&&(this.log("libp2p is stopping"),this.status="stopping",await(this.components.beforeStop?.()),await this.components.stop(),await(this.components.afterStop?.()),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const e=new Ig;for(const t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,r={}){if(null==t)throw new Pn("no protocols were provided to open a stream");if(0===(t=Array.isArray(t)?t:[t]).length)throw new Pn("no protocols were provided to open a stream");return(await this.dial(e,r)).newStream(t,r)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){yl(e)&&(e=Pc(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),null!=e.publicKey)return e.publicKey;try{const r=await this.peerStore.get(e,t);if(null!=r.id.publicKey)return r.id.publicKey}catch(e){if("NotFoundError"!==e.name)throw e}const r=Ls([Ye("/pk/"),e.toMultihash().bytes]),n=Sc(await this.contentRouting.get(r,t));return await this.peerStore.patch(e,{publicKey:n},t),n}async handle(e,t,r){Array.isArray(e)||(e=[e]),await Promise.all(e.map((async e=>{await this.components.registrar.handle(e,t,r)})))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map((async e=>{await this.components.registrar.unhandle(e,t)})))}async register(e,t,r){return this.components.registrar.register(e,t,r)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#M(e){const{detail:t}=e;t.id.toString()!==this.peerId.toString()?this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch((e=>{this.log.error(e)})):this.log.error("peer discovery mechanism discovered self")}}function Cb(){try{return!1}catch(e){return!1}}const xb="enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im",kb="enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im",Tb=xs.BOOTSTRAP,Pb="Invalid record id";var Rb=Object.freeze({__proto__:null,default:{}});const Lb=BigInt(0),Db=BigInt(1),Mb=BigInt(2),Nb=BigInt(3),Ob=BigInt(8),Ub=Object.freeze({a:Lb,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:Db,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),Fb=(e,t)=>(e+t/Mb)/t,Bb={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){const{n:t}=Ub,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Db*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,o=BigInt("0x100000000000000000000000000000000"),a=Fb(i*e,t),c=Fb(-n*e,t);let l=gw(e-a*r-c*s,t),u=gw(-a*n-c*i,t);const h=l>o,d=u>o;if(h&&(l=t-l),d&&(u=t-u),l>o||u>o)throw Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}},$b=32,qb=32;function zb(e){const{a:t,b:r}=Ub,n=gw(e*e),s=gw(n*e);return gw(s+t*e+r)}const jb=Ub.a===Lb;class Kb extends Error{constructor(e){super(e)}}function Vb(e){if(!(e instanceof Hb))throw new TypeError("JacobianPoint expected")}class Hb{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof Xb))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(Xb.ZERO)?Hb.ZERO:new Hb(e.x,e.y,Db)}static toAffineBatch(e){const t=function(e,t=Ub.P){const r=Array(e.length),n=yw(e.reduce(((e,n,s)=>n===Lb?e:(r[s]=e,gw(e*n,t))),Db),t);return e.reduceRight(((e,n,s)=>n===Lb?e:(r[s]=gw(e*r[s],t),gw(e*n,t))),n),r}(e.map((e=>e.z)));return e.map(((e,r)=>e.toAffine(t[r])))}static normalizeZ(e){return Hb.toAffineBatch(e).map(Hb.fromAffine)}equals(e){Vb(e);const{x:t,y:r,z:n}=this,{x:s,y:i,z:o}=e,a=gw(n*n),c=gw(o*o),l=gw(t*c),u=gw(s*a),h=gw(gw(r*o)*c),d=gw(gw(i*n)*a);return l===u&&h===d}negate(){return new Hb(this.x,gw(-this.y),this.z)}double(){const{x:e,y:t,z:r}=this,n=gw(e*e),s=gw(t*t),i=gw(s*s),o=e+s,a=gw(Mb*(gw(o*o)-n-i)),c=gw(Nb*n),l=gw(c*c),u=gw(l-Mb*a),h=gw(c*(a-u)-Ob*i),d=gw(Mb*t*r);return new Hb(u,h,d)}add(e){Vb(e);const{x:t,y:r,z:n}=this,{x:s,y:i,z:o}=e;if(s===Lb||i===Lb)return this;if(t===Lb||r===Lb)return e;const a=gw(n*n),c=gw(o*o),l=gw(t*c),u=gw(s*a),h=gw(gw(r*o)*c),d=gw(gw(i*n)*a),p=gw(u-l),f=gw(d-h);if(p===Lb)return f===Lb?this.double():Hb.ZERO;const g=gw(p*p),m=gw(p*g),y=gw(l*g),b=gw(f*f-m-Mb*y),w=gw(f*(y-b)-h*m),v=gw(n*o*p);return new Hb(b,w,v)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){const t=Hb.ZERO;if("bigint"==typeof e&&e===Lb)return t;let r=fw(e);if(r===Db)return this;if(!jb){let e=t,n=this;for(;r>Lb;)r&Db&&(e=e.add(n)),n=n.double(),r>>=Db;return e}let{k1neg:n,k1:s,k2neg:i,k2:o}=Bb.splitScalar(r),a=t,c=t,l=this;for(;s>Lb||o>Lb;)s&Db&&(a=a.add(l)),o&Db&&(c=c.add(l)),l=l.double(),s>>=Db,o>>=Db;return n&&(a=a.negate()),i&&(c=c.negate()),c=new Hb(gw(c.x*Bb.beta),c.y,c.z),a.add(c)}precomputeWindow(e){const t=jb?128/e+1:256/e+1,r=[];let n=this,s=n;for(let i=0;i<t;i++){s=n,r.push(s);for(let t=1;t<2**(e-1);t++)s=s.add(n),r.push(s);n=s.double()}return r}wNAF(e,t){!t&&this.equals(Hb.BASE)&&(t=Xb.BASE);const r=t&&t._WINDOW_SIZE||1;if(256%r)throw Error("Point#wNAF: Invalid precomputation window, must be power of 2");let n=t&&Wb.get(t);n||(n=this.precomputeWindow(r),t&&1!==r&&(n=Hb.normalizeZ(n),Wb.set(t,n)));let s=Hb.ZERO,i=Hb.BASE;const o=1+(jb?128/r:256/r),a=2**(r-1),c=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let t=0;t<o;t++){const r=t*a;let o=Number(e&c);e>>=u,o>a&&(o-=l,e+=Db);const h=r,d=r+Math.abs(o)-1,p=t%2!=0,f=o<0;0===o?i=i.add(Gb(p,n[h])):s=s.add(Gb(f,n[d]))}return{p:s,f:i}}multiply(e,t){let r,n,s=fw(e);if(jb){const{k1neg:e,k1:i,k2neg:o,k2:a}=Bb.splitScalar(s);let{p:c,f:l}=this.wNAF(i,t),{p:u,f:h}=this.wNAF(a,t);c=Gb(e,c),u=Gb(o,u),u=new Hb(gw(u.x*Bb.beta),u.y,u.z),r=c.add(u),n=l.add(h)}else{const{p:e,f:i}=this.wNAF(s,t);r=e,n=i}return Hb.normalizeZ([r,n])[0]}toAffine(e){const{x:t,y:r,z:n}=this,s=this.equals(Hb.ZERO);null==e&&(e=s?Ob:yw(n));const i=e,o=gw(i*i),a=gw(o*i),c=gw(t*o),l=gw(r*a),u=gw(n*i);if(s)return Xb.ZERO;if(u!==Db)throw Error("invZ was invalid");return new Xb(c,l)}}function Gb(e,t){const r=t.negate();return e?r:t}Hb.BASE=new Hb(Ub.Gx,Ub.Gy,Db),Hb.ZERO=new Hb(Lb,Db,Lb);const Wb=new WeakMap;class Xb{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,Wb.delete(this)}hasEvenY(){return this.y%Mb===Lb}static fromCompressedHex(e){const t=32===e.length,r=dw(t?e:e.subarray(1));if(!Aw(r))throw Error("Point is not on curve");let n=function(e){const{P:t}=Ub,r=BigInt(6),n=BigInt(11),s=BigInt(22),i=BigInt(23),o=BigInt(44),a=BigInt(88),c=e*e*e%t,l=c*c*e%t,u=mw(l,Nb)*l%t,h=mw(u,Nb)*l%t,d=mw(h,Mb)*c%t,p=mw(d,n)*d%t,f=mw(p,s)*p%t,g=mw(f,o)*f%t,m=mw(g,a)*g%t,y=mw(m,o)*f%t,b=mw(y,Nb)*l%t,w=mw(b,i)*p%t,v=mw(w,r)*c%t,E=mw(v,Mb);if(E*E%t!==e)throw Error("Cannot find square root");return E}(zb(r));const s=(n&Db)===Db;t?s&&(n=gw(-n)):!(1&~e[0])!==s&&(n=gw(-n));const i=new Xb(r,n);return i.assertValidity(),i}static fromUncompressedHex(e){const t=dw(e.subarray(1,33)),r=dw(e.subarray(33,65)),n=new Xb(t,r);return n.assertValidity(),n}static fromHex(e){const t=pw(e),r=t.length,n=t[0];if(r===$b)return this.fromCompressedHex(t);if(33===r&&(2===n||3===n))return this.fromCompressedHex(t);if(65===r&&4===n)return this.fromUncompressedHex(t);throw Error("Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not "+r)}static fromPrivateKey(e){return Xb.BASE.multiply(_w(e))}static fromSignature(e,t,r){const{r:n,s:s}=Cw(t);if(![0,1,2,3].includes(r))throw Error("Cannot recover: invalid recovery bit");const i=bw(pw(e)),{n:o}=Ub,a=2===r||3===r?n+o:n,c=yw(a,o),l=gw(-i*c,o),u=gw(s*c,o),h=1&r?"03":"02",d=Xb.fromHex(h+cw(a)),p=Xb.BASE.multiplyAndAddUnsafe(d,l,u);if(!p)throw Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return ow(this.toHex(e))}toHex(e=!1){const t=cw(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${cw(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const e="Point is not on elliptic curve",{x:t,y:r}=this;if(!Aw(t)||!Aw(r))throw Error(e);const n=gw(r*r);if(gw(n-zb(t))!==Lb)throw Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Xb(this.x,gw(-this.y))}double(){return Hb.fromAffine(this).double().toAffine()}add(e){return Hb.fromAffine(this).add(Hb.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Hb.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,r){const n=Hb.fromAffine(this),s=t===Lb||t===Db||this!==Xb.BASE?n.multiplyUnsafe(t):n.multiply(t),i=Hb.fromAffine(e).multiplyUnsafe(r),o=s.add(i);return o.equals(Hb.ZERO)?void 0:o.toAffine()}}function Zb(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function Yb(e){if(e.length<2||2!==e[0])throw Error("Invalid signature integer tag: "+nw(e));const t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw Error("Invalid signature integer: wrong length");if(0===r[0]&&r[1]<=127)throw Error("Invalid signature integer: trailing length");return{data:dw(r),left:e.subarray(t+2)}}Xb.BASE=new Xb(Ub.Gx,Ub.Gy),Xb.ZERO=new Xb(Lb,Lb);class Qb{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){const t=Jb(e),r="Signature.fromCompact";if("string"!=typeof e&&!t)throw new TypeError(r+": Expected string or Uint8Array");const n=t?nw(e):e;if(128!==n.length)throw Error(r+": Expected 64-byte hex");return new Qb(hw(n.slice(0,64)),hw(n.slice(64,128)))}static fromDER(e){const t=Jb(e);if("string"!=typeof e&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r:r,s:n}=function(e){if(e.length<2||48!=e[0])throw Error("Invalid signature tag: "+nw(e));if(e[1]!==e.length-2)throw Error("Invalid signature: incorrect length");const{data:t,left:r}=Yb(e.subarray(2)),{data:n,left:s}=Yb(r);if(s.length)throw Error("Invalid signature: left bytes after parsing: "+nw(s));return{r:t,s:n}}(t?e:ow(e));return new Qb(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){const{r:e,s:t}=this;if(!Sw(e))throw Error("Invalid Signature: r must be 0 < r < n");if(!Sw(t))throw Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const e=Ub.n>>Db;return this.s>e}normalizeS(){return this.hasHighS()?new Qb(this.r,gw(-this.s,Ub.n)):this}toDERRawBytes(){return ow(this.toDERHex())}toDERHex(){const e=Zb(uw(this.s)),t=Zb(uw(this.r)),r=e.length/2,n=t.length/2,s=uw(r),i=uw(n);return`30${uw(n+r+4)}02${i}${t}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return ow(this.toCompactHex())}toCompactHex(){return cw(this.r)+cw(this.s)}}function Jb(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ew(e){if(!Jb(e))throw Error("Uint8Array expected")}function tw(...e){if(e.every(ew),1===e.length)return e[0];const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}const rw=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function nw(e){ew(e);let t="";for(let r=0;r<e.length;r++)t+=rw[e[r]];return t}const sw={_0:48,_9:57,A:65,F:70,a:97,f:102};function iw(e){return e>=sw._0&&e<=sw._9?e-sw._0:e>=sw.A&&e<=sw.F?e-(sw.A-10):e>=sw.a&&e<=sw.f?e-(sw.a-10):void 0}function ow(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,s=0;t<r;t++,s+=2){const r=iw(e.charCodeAt(s)),i=iw(e.charCodeAt(s+1));if(void 0===r||void 0===i){const t=e[s]+e[s+1];throw Error('hex string expected, got non-hex character "'+t+'" at index '+s)}n[t]=16*r+i}return n}const aw=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function cw(e){if("bigint"!=typeof e)throw Error("Expected bigint");if(!(Lb<=e&&e<aw))throw Error("Expected number 0 <= n < 2^256");return e.toString(16).padStart(64,"0")}function lw(e){const t=ow(cw(e));if(32!==t.length)throw Error("Error: expected 32 bytes");return t}function uw(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function hw(e){if("string"!=typeof e)throw new TypeError("hexToNumber: expected string, got "+typeof e);return BigInt("0x"+e)}function dw(e){return hw(nw(e))}function pw(e){return Jb(e)?Uint8Array.from(e):ow(e)}function fw(e){if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if("bigint"==typeof e&&Sw(e))return e;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function gw(e,t=Ub.P){const r=e%t;return r>=Lb?r:t+r}function mw(e,t){const{P:r}=Ub;let n=e;for(;t-- >Lb;)n*=n,n%=r;return n}function yw(e,t=Ub.P){if(e===Lb||t<=Lb)throw Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=gw(e,t),n=t,s=Lb,i=Db;for(;r!==Lb;){const e=n%r,t=s-i*(n/r);n=r,r=e,s=i,i=t}if(n!==Db)throw Error("invert: does not exist");return gw(s,t)}function bw(e,t=!1){const r=function(e){const t=8*e.length-256,r=dw(e);return t>0?r>>BigInt(t):r}(e);if(t)return r;const{n:n}=Ub;return r>=n?r-n:r}let ww,vw;class Ew{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,"number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");this.v=new Uint8Array(e).fill(1),this.k=new Uint8Array(e).fill(0),this.counter=0}hmac(...e){return Dw.hmacSha256(this.k,...e)}hmacSync(...e){return vw(this.k,...e)}checkSync(){if("function"!=typeof vw)throw new Kb("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),0!==e.length&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),0!==e.length&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0;const t=[];for(;e<this.qByteLen;){this.v=await this.hmac(this.v);const r=this.v.slice();t.push(r),e+=this.v.length}return tw(...t)}generateSync(){this.checkSync(),this.incr();let e=0;const t=[];for(;e<this.qByteLen;){this.v=this.hmacSync(this.v);const r=this.v.slice();t.push(r),e+=this.v.length}return tw(...t)}}function Sw(e){return Lb<e&&e<Ub.n}function Aw(e){return Lb<e&&e<Ub.P}function Iw(e,t,r,n=!0){const{n:s}=Ub,i=bw(e,!0);if(!Sw(i))return;const o=yw(i,s),a=Xb.BASE.multiply(i),c=gw(a.x,s);if(c===Lb)return;const l=gw(o*gw(t+r*c,s),s);if(l===Lb)return;let u=new Qb(c,l),h=(a.x===u.r?0:2)|Number(a.y&Db);return n&&u.hasHighS()&&(u=u.normalizeS(),h^=1),{sig:u,recovery:h}}function _w(e){let t;if("bigint"==typeof e)t=e;else if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)t=BigInt(e);else if("string"==typeof e){if(64!==e.length)throw Error("Expected 32 bytes of private key");t=hw(e)}else{if(!Jb(e))throw new TypeError("Expected valid private key");if(e.length!==qb)throw Error("Expected 32 bytes of private key");t=dw(e)}if(!Sw(t))throw Error("Expected private key: 0 < key < n");return t}function Cw(e){if(e instanceof Qb)return e.assertValidity(),e;try{return Qb.fromDER(e)}catch(t){return Qb.fromCompact(e)}}function xw(e){return dw(e.length>$b?e.slice(0,$b):e)}function kw(e){const t=xw(e),r=gw(t,Ub.n);return Tw(r<Lb?t:r)}function Tw(e){return lw(e)}const Pw={strict:!0};Xb.BASE._setWindowSize(8);const Rw={node:Rb,web:"object"==typeof self&&"crypto"in self?self.crypto:void 0},Lw={},Dw={bytesToHex:nw,hexToBytes:ow,concatBytes:tw,mod:gw,invert:yw,isValidPrivateKey(e){try{return _w(e),!0}catch(e){return!1}},_bigintTo32Bytes:lw,_normalizePrivateKey:_w,hashToPrivateKey(e){if((e=pw(e)).length<40||e.length>1024)throw Error("Expected valid bytes of private key as per FIPS 186");return lw(gw(dw(e),Ub.n-Db)+Db)},randomBytes(e=32){if(Rw.web)return Rw.web.getRandomValues(new Uint8Array(e));if(Rw.node){const{randomBytes:t}=Rw.node;return Uint8Array.from(t(e))}throw Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Dw.hashToPrivateKey(Dw.randomBytes(40)),precompute(e=8,t=Xb.BASE){const r=t===Xb.BASE?t:new Xb(t.x,t.y);return r._setWindowSize(e),r.multiply(Nb),r},async sha256(...e){if(Rw.web){const t=await Rw.web.subtle.digest("SHA-256",tw(...e));return new Uint8Array(t)}if(Rw.node){const{createHash:t}=Rw.node,r=t("sha256");return e.forEach((e=>r.update(e))),Uint8Array.from(r.digest())}throw Error("The environment doesn't have sha256 function")},async hmacSha256(e,...t){if(Rw.web){const r=await Rw.web.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=tw(...t),s=await Rw.web.subtle.sign("HMAC",r,n);return new Uint8Array(s)}if(Rw.node){const{createHmac:r}=Rw.node,n=r("sha256",e);return t.forEach((e=>n.update(e))),Uint8Array.from(n.digest())}throw Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,async taggedHash(e,...t){let r=Lw[e];if(void 0===r){const t=await Dw.sha256(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=tw(t,t),Lw[e]=r}return Dw.sha256(r,...t)},taggedHashSync(e,...t){if("function"!=typeof ww)throw new Kb("sha256Sync is undefined, you need to set it");let r=Lw[e];if(void 0===r){const t=ww(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=tw(t,t),Lw[e]=r}return ww(r,...t)},_JacobianPoint:Hb};Object.defineProperties(Dw,{sha256Sync:{configurable:!1,get:()=>ww,set(e){ww||(ww=e)}},hmacSha256Sync:{configurable:!1,get:()=>vw,set(e){vw||(vw=e)}}});var Mw,Nw,Ow={exports:{}},Uw=(Mw||(Mw=1,Nw=Ow,function(){var e="input is invalid type",t="object"==typeof window,r=t?window:{};r.JS_SHA3_NO_WINDOW&&(t=!1);var n=!t&&"object"==typeof self;!r.JS_SHA3_NO_NODE_JS&&"object"==typeof s&&s.versions&&s.versions.node?r=ns:n&&(r=self);for(var i=!r.JS_SHA3_NO_COMMON_JS&&Nw.exports,o=!r.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,a="0123456789abcdef".split(""),c=[4,1024,262144,67108864],l=[0,8,16,24],u=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],h=[224,256,384,512],d=[128,256],p=["hex","buffer","arrayBuffer","array","digest"],f={128:168,256:136},g=r.JS_SHA3_NO_NODE_JS||!Array.isArray?e=>"[object Array]"==={}.toString.call(e):Array.isArray,m=!o||!r.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView?ArrayBuffer.isView:e=>"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer,y=t=>{var r=typeof t;if("string"===r)return[t,!0];if("object"!==r||null===t)throw Error(e);if(o&&t.constructor===ArrayBuffer)return[new Uint8Array(t),!1];if(!g(t)&&!m(t))throw Error(e);return[t,!1]},b=e=>0===y(e)[0].length,w=e=>{for(var t=[],r=0;r<e.length;++r)t[r]=e[r];return t},v=(e,t,r)=>n=>new N(e,t,e).update(n)[r](),E=(e,t,r)=>(n,s)=>new N(e,t,s).update(n)[r](),S=(e,t,r)=>(t,n,s,i)=>x["cshake"+e].update(t,n,s,i)[r](),A=(e,t,r)=>(t,n,s,i)=>x["kmac"+e].update(t,n,s,i)[r](),I=(e,t,r,n)=>{for(var s=0;s<p.length;++s){var i=p[s];e[i]=t(r,n,i)}return e},_=(e,t)=>{var r=v(e,t,"hex");return r.create=()=>new N(e,t,e),r.update=e=>r.create().update(e),I(r,v,e,t)},C=[{name:"keccak",padding:[1,256,65536,16777216],bits:h,createMethod:_},{name:"sha3",padding:[6,1536,393216,100663296],bits:h,createMethod:_},{name:"shake",padding:[31,7936,2031616,520093696],bits:d,createMethod(e,t){var r=E(e,t,"hex");return r.create=r=>new N(e,t,r),r.update=(e,t)=>r.create(t).update(e),I(r,E,e,t)}},{name:"cshake",padding:c,bits:d,createMethod(e,t){var r=f[e],n=S(e,0,"hex");return n.create=(n,s,i)=>b(s)&&b(i)?x["shake"+e].create(n):new N(e,t,n).bytepad([s,i],r),n.update=(e,t,r,s)=>n.create(t,r,s).update(e),I(n,S,e,t)}},{name:"kmac",padding:c,bits:d,createMethod(e,t){var r=f[e],n=A(e,0,"hex");return n.create=(n,s,i)=>new O(e,t,s).bytepad(["KMAC",i],r).bytepad([n],r),n.update=(e,t,r,s)=>n.create(e,r,s).update(t),I(n,A,e,t)}}],x={},k=[],T=0;T<C.length;++T)for(var P=C[T],R=P.bits,L=0;L<R.length;++L){var D=P.name+"_"+R[L];if(k.push(D),x[D]=P.createMethod(R[L],P.padding),"sha3"!==P.name){var M=P.name+R[L];k.push(M),x[M]=x[D]}}function N(e,t,r){this.blocks=[],this.s=[],this.padding=t,this.outputBits=r,this.reset=!0,this.finalized=!1,this.block=0,this.start=0,this.blockCount=1600-(e<<1)>>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function O(e,t,r){N.call(this,e,t,r)}N.prototype.update=function(e){if(this.finalized)throw Error("finalize already called");var t=y(e);e=t[0];for(var r,n,s=t[1],i=this.blocks,o=this.byteCount,a=e.length,c=this.blockCount,u=0,h=this.s;u<a;){if(this.reset)for(this.reset=!1,i[0]=this.block,r=1;r<c+1;++r)i[r]=0;if(s)for(r=this.start;u<a&&r<o;++u)(n=e.charCodeAt(u))<128?i[r>>2]|=n<<l[3&r++]:n<2048?(i[r>>2]|=(192|n>>6)<<l[3&r++],i[r>>2]|=(128|63&n)<<l[3&r++]):n<55296||n>=57344?(i[r>>2]|=(224|n>>12)<<l[3&r++],i[r>>2]|=(128|n>>6&63)<<l[3&r++],i[r>>2]|=(128|63&n)<<l[3&r++]):(n=65536+((1023&n)<<10|1023&e.charCodeAt(++u)),i[r>>2]|=(240|n>>18)<<l[3&r++],i[r>>2]|=(128|n>>12&63)<<l[3&r++],i[r>>2]|=(128|n>>6&63)<<l[3&r++],i[r>>2]|=(128|63&n)<<l[3&r++]);else for(r=this.start;u<a&&r<o;++u)i[r>>2]|=e[u]<<l[3&r++];if(this.lastByteIndex=r,r>=o){for(this.start=r-o,this.block=i[c],r=0;r<c;++r)h[r]^=i[r];U(h),this.reset=!0}else this.start=r}return this},N.prototype.encode=function(e,t){var r=255&e,n=1,s=[r];for(r=255&(e>>=8);r>0;)s.unshift(r),r=255&(e>>=8),++n;return t?s.push(n):s.unshift(n),this.update(s),s.length},N.prototype.encodeString=function(e){var t=y(e);e=t[0];var r=t[1],n=0,s=e.length;if(r)for(var i=0;i<e.length;++i){var o=e.charCodeAt(i);o<128?n+=1:o<2048?n+=2:o<55296||o>=57344?n+=3:(o=65536+((1023&o)<<10|1023&e.charCodeAt(++i)),n+=4)}else n=s;return n+=this.encode(8*n),this.update(e),n},N.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n<e.length;++n)r+=this.encodeString(e[n]);var s=(t-r%t)%t,i=[];return i.length=s,this.update(i),this},N.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex,r=this.blockCount,n=this.s;if(e[t>>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t<r+1;++t)e[t]=0;for(e[r-1]|=2147483648,t=0;t<r;++t)n[t]^=e[t];U(n)}},N.prototype.toString=N.prototype.hex=function(){this.finalize();for(var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,i=0,o=0,c="";o<n;){for(i=0;i<t&&o<n;++i,++o)e=r[i],c+=a[e>>4&15]+a[15&e]+a[e>>12&15]+a[e>>8&15]+a[e>>20&15]+a[e>>16&15]+a[e>>28&15]+a[e>>24&15];o%t==0&&(r=w(r),U(r),i=0)}return s&&(e=r[i],c+=a[e>>4&15]+a[15&e],s>1&&(c+=a[e>>12&15]+a[e>>8&15]),s>2&&(c+=a[e>>20&15]+a[e>>16&15])),c},N.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,i=0,o=0,a=this.outputBits>>3;e=s?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);o<n;){for(i=0;i<t&&o<n;++i,++o)c[o]=r[i];o%t==0&&(r=w(r),U(r))}return s&&(c[o]=r[i],e=e.slice(0,a)),e},N.prototype.buffer=N.prototype.arrayBuffer,N.prototype.digest=N.prototype.array=function(){this.finalize();for(var e,t,r=this.blockCount,n=this.s,s=this.outputBlocks,i=this.extraBytes,o=0,a=0,c=[];a<s;){for(o=0;o<r&&a<s;++o,++a)e=a<<2,t=n[o],c[e]=255&t,c[e+1]=t>>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r==0&&(n=w(n),U(n))}return i&&(e=a<<2,t=n[o],c[e]=255&t,i>1&&(c[e+1]=t>>8&255),i>2&&(c[e+2]=t>>16&255)),c},O.prototype=new N,O.prototype.finalize=function(){return this.encode(this.outputBits,!0),N.prototype.finalize.call(this)};var U=e=>{var t,r,n,s,i,o,a,c,l,h,d,p,f,g,m,y,b,w,v,E,S,A,I,_,C,x,k,T,P,R,L,D,M,N,O,U,F,B,$,q,z,j,K,V,H,G,W,X,Z,Y,Q,J,ee,te,re,ne,se,ie,oe,ae,ce,le,ue;for(n=0;n<48;n+=2)s=e[0]^e[10]^e[20]^e[30]^e[40],i=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],l=e[5]^e[15]^e[25]^e[35]^e[45],h=e[6]^e[16]^e[26]^e[36]^e[46],d=e[7]^e[17]^e[27]^e[37]^e[47],t=(p=e[8]^e[18]^e[28]^e[38]^e[48])^(o<<1|a>>>31),r=(f=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|o>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=s^(c<<1|l>>>31),r=i^(l<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=o^(h<<1|d>>>31),r=a^(d<<1|h>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(p<<1|f>>>31),r=l^(f<<1|p>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=h^(s<<1|i>>>31),r=d^(i<<1|s>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],m=e[1],G=e[11]<<4|e[10]>>>28,W=e[10]<<4|e[11]>>>28,T=e[20]<<3|e[21]>>>29,P=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,j=e[40]<<18|e[41]>>>14,K=e[41]<<18|e[40]>>>14,N=e[2]<<1|e[3]>>>31,O=e[3]<<1|e[2]>>>31,y=e[13]<<12|e[12]>>>20,b=e[12]<<12|e[13]>>>20,X=e[22]<<10|e[23]>>>22,Z=e[23]<<10|e[22]>>>22,R=e[33]<<13|e[32]>>>19,L=e[32]<<13|e[33]>>>19,le=e[42]<<2|e[43]>>>30,ue=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,U=e[14]<<6|e[15]>>>26,F=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,v=e[24]<<11|e[25]>>>21,Y=e[34]<<15|e[35]>>>17,Q=e[35]<<15|e[34]>>>17,D=e[45]<<29|e[44]>>>3,M=e[44]<<29|e[45]>>>3,_=e[6]<<28|e[7]>>>4,C=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,se=e[16]<<23|e[17]>>>9,B=e[26]<<25|e[27]>>>7,$=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,J=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,V=e[8]<<27|e[9]>>>5,H=e[9]<<27|e[8]>>>5,x=e[18]<<20|e[19]>>>12,k=e[19]<<20|e[18]>>>12,ie=e[29]<<7|e[28]>>>25,oe=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,z=e[39]<<8|e[38]>>>24,A=e[48]<<14|e[49]>>>18,I=e[49]<<14|e[48]>>>18,e[0]=g^~y&w,e[1]=m^~b&v,e[10]=_^~x&T,e[11]=C^~k&P,e[20]=N^~U&B,e[21]=O^~F&$,e[30]=V^~G&X,e[31]=H^~W&Z,e[40]=te^~ne&ie,e[41]=re^~se&oe,e[2]=y^~w&E,e[3]=b^~v&S,e[12]=x^~T&R,e[13]=k^~P&L,e[22]=U^~B&q,e[23]=F^~$&z,e[32]=G^~X&Y,e[33]=W^~Z&Q,e[42]=ne^~ie&ae,e[43]=se^~oe&ce,e[4]=w^~E&A,e[5]=v^~S&I,e[14]=T^~R&D,e[15]=P^~L&M,e[24]=B^~q&j,e[25]=$^~z&K,e[34]=X^~Y&J,e[35]=Z^~Q&ee,e[44]=ie^~ae&le,e[45]=oe^~ce&ue,e[6]=E^~A&g,e[7]=S^~I&m,e[16]=R^~D&_,e[17]=L^~M&C,e[26]=q^~j&N,e[27]=z^~K&O,e[36]=Y^~J&V,e[37]=Q^~ee&H,e[46]=ae^~le&te,e[47]=ce^~ue&re,e[8]=A^~g&y,e[9]=I^~m&b,e[18]=D^~_&x,e[19]=M^~C&k,e[28]=j^~N&U,e[29]=K^~O&F,e[38]=J^~V&G,e[39]=ee^~H&W,e[48]=le^~te&ne,e[49]=ue^~re&se,e[0]^=u[n],e[1]^=u[n+1]};if(i)Nw.exports=x;else for(T=0;T<k.length;++T)r[k[T]]=x[k[T]]}()),Ow.exports),Fw=ss(Uw);function Bw(e){return new Uint8Array(Fw.keccak256.arrayBuffer(e))}function $w(e,t,r){try{return function(e,t,r,n=Pw){let s;try{s=Cw(e),t=pw(t)}catch(e){return!1}const{r:i,s:o}=s;if(n.strict&&s.hasHighS())return!1;const a=bw(t);let c;try{c=function(e){return e instanceof Xb?(e.assertValidity(),e):Xb.fromHex(e)}(r)}catch(e){return!1}const{n:l}=Ub,u=yw(o,l),h=gw(a*u,l),d=gw(i*u,l),p=Xb.BASE.multiplyAndAddUnsafe(c,h,d);return!!p&&gw(p.x,l)===i}(Qb.fromCompact(e.slice(0,64)),t,r)}catch{return!1}}function qw(e,t){switch(t){case"udp":return qw(e,"udp4")||qw(e,"udp6");case"tcp":return qw(e,"tcp4")||qw(e,"tcp6")}const r=t.endsWith("6"),n=e.get(r?"ip6":"ip");if(!n)return;const s=t.slice(0,3);let i;switch(s){case"udp":i=r?e.get("udp6"):e.get("udp");break;case"tcp":i=r?e.get("tcp6"):e.get("tcp");break;default:return}return i?function(e,t,r,n){let s=bl("/"+e+"/"+fl(e,r));return s=s.encapsulate(bl("/"+t+"/"+fl(t,n))),s}(r?"ip6":"ip4",s,n,i):void 0}const zw=parseInt("11111",2),jw=parseInt("10000000",2),Kw=parseInt("01111111",2),Vw={0:Ww,1:Ww,2(e,t){const r=Gw(e,t),n=t.offset,s=t.offset+r,i=[];for(let t=n;t<s;t++)t===n&&0===e[t]||i.push(e[t]);return t.offset+=r,Uint8Array.from(i)},3(e,t){const r=Gw(e,t),n=e[t.offset];t.offset++;const s=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,0!==n)throw Error("Unused bits in bit string is unimplemented");return s},4(e,t){const r=Gw(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n},5:(e,t)=>(t.offset++,null),6(e,t){const r=Gw(e,t),n=t.offset+r,s=e[t.offset];t.offset++;let i=0,o=0;s<40?(i=0,o=s):s<80?(i=1,o=s-40):(i=2,o=s-80);let a=`${i}.${o}`,c=[];for(;t.offset<n;){const r=e[t.offset];if(t.offset++,c.push(127&r),r<128){c.reverse();let e=0;for(let t=0;t<c.length;t++)e+=c[t]<<7*t;a+="."+e,c=[]}}return a},16:Ww,22:Ww,48:Ww};function Hw(e,t={offset:0}){const r=e[t.offset]&zw;if(t.offset++,null!=Vw[r])return Vw[r](e,t);throw Error("No decoder for tag "+r)}function Gw(e,t){let r=0;if((e[t.offset]&jw)===jw){const n=e[t.offset]&Kw;let s="0x";t.offset++;for(let r=0;r<n;r++,t.offset++)s+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(s,16)}else r=e[t.offset],t.offset++;return r}function Ww(e,t){Gw(e,t);const r=[];for(;!(t.offset>=e.byteLength);){const n=Hw(e,t);if(null===n)break;r.push(n)}return r}function Xw(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);const t=function(e){let t=e.toString(16);t.length%2==1&&(t="0"+t);const r=new Us;for(let e=0;e<t.length;e+=2)r.append(Uint8Array.from([parseInt(`${t[e]}${t[e+1]}`,16)]));return r}(e.byteLength);return new Us(Uint8Array.from([t.byteLength|jw]),t)}function Zw(e){const t=new Us;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new Us(Uint8Array.from([2]),Xw(t),t)}function Yw(e){const t=Uint8Array.from([0]),r=new Us(t,e);return new Us(Uint8Array.from([3]),Xw(r),r)}function Qw(e,t=48){const r=new Us;for(const t of e)r.append(t);return new Us(Uint8Array.from([t]),Xw(r),r)}const Jw=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),ev=Uint8Array.from([6,5,43,129,4,0,34]),tv=Uint8Array.from([6,5,43,129,4,0,35]),rv={ext:!0,kty:"EC",crv:"P-256"},nv={ext:!0,kty:"EC",crv:"P-384"},sv={ext:!0,kty:"EC",crv:"P-521"};function iv(e){if("P-256"===e)return Jw;if("P-384"===e)return ev;if("P-521"===e)return tv;throw new Pn("Invalid curve "+e)}class ov{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){var e;return null==this._raw&&(this._raw=(e=this.jwk,Qw([Zw(Uint8Array.from([1])),Qw([iv(e.crv)],160),Qw([Yw(new Us(Uint8Array.from([4]),Ye(e.x??"","base64url"),Ye(e.y??"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return Ne.digest(Sv(this))}toCID(){return qe.createV1(114,this.toMultihash())}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}async verify(e,t,r){return async function(e,t,r,n){const s=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();const i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}}class av extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class cv extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}var lv={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new cv("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};let uv;const hv=(async()=>{try{return await lv.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function dv(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class pv{type="Ed25519";raw;constructor(e){this.raw=fv(e,32)}toMultihash(){return Ne.digest(Sv(this))}toCID(){return qe.createV1(114,this.toMultihash())}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();const n=async function(e,t,r){return null==uv&&(uv=await hv),uv?async function(e,t,r){if(e.buffer instanceof ArrayBuffer){const n=await lv.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await lv.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(e,t,r):function(e,t,r){return Na.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(e,t,r)}(this.raw,t,e);return dv(n)?n.then((e=>(r?.signal?.throwIfAborted(),e))):n}}function fv(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Pn(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var gv,mv,yv,bv;(e=>{e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(gv||(gv={})),(e=>{e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(mv||(mv={})),(e=>{e.codec=()=>Gt(mv)})(gv||(gv={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),gv.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=gv.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(yv||(yv={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),gv.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=gv.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(bv||(bv={}));class wv{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return null==this._raw&&(this._raw=function(e){if(null==e.n||null==e.e)throw new Pn("JWK was missing components");return Qw([vv,Yw(Qw([Zw(Ye(e.n,"base64url")),Zw(Ye(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return qe.createV1(114,this._multihash)}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}verify(e,t,r){return async function(e,t,r,n){const s=await lv.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();const i=await lv.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}}const vv=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);class Ev{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return wc.ProjectivePoint.fromHex(e),e}catch(e){throw new Rn(e+"")}}(e),this.raw=function(e){return wc.ProjectivePoint.fromHex(e).toRawBytes(!0)}(this._key)}toMultihash(){return Ne.digest(Sv(this))}toCID(){return qe.createV1(114,this.toMultihash())}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}verify(e,t,r){return function(e,t,r,n){const s=Ue.digest(r instanceof Uint8Array?r:r.subarray());if(dv(s))return s.then((({digest:r})=>(n?.signal?.throwIfAborted(),wc.verify(t,r,e)))).catch((e=>{if("AbortError"===e.name)throw e;throw new av(e+"")}));try{return n?.signal?.throwIfAborted(),wc.verify(t,s.digest,e)}catch(e){throw new av(e+"")}}(this._key,t,e,r)}}function Sv(e){return yv.encode({Type:gv[e.type],Data:e.raw})}const Av=Symbol.for("nodejs.util.inspect.custom");class Iv{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[En]=!0;toString(){return null==this.string&&(this.string=fe.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return qe.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Ds(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return Ds(this.multihash.bytes,e.toMultihash().bytes);throw Error("not valid Id")}[Av](){return`PeerId(${this.toString()})`}}class _v extends Iv{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class Cv extends Iv{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class xv extends Iv{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}function kv(e){const t=e.reduce(((e,t)=>e+2+t.bytes.length),0),r=new Uint8Array(t),n=new DataView(r.buffer);let s=0;return e.forEach((e=>{if(e.getPeerId())throw Error("`multiaddr` field MUST not contain peer id");n.setUint16(s,e.bytes.length),s+=2,r.set(e.bytes,s),s+=e.bytes.length})),r}function Tv(e){let t=0;return e.lightPush&&(t+=1),t<<=1,e.filter&&(t+=1),t<<=1,e.store&&(t+=1),t<<=1,e.relay&&(t+=1),t}class Pv extends Map{seq;signature;constructor(e={},t=BigInt(1),r){super(Object.entries(e)),this.seq=t,this.signature=r}set(e,t){return this.signature=void 0,this.seq++,super.set(e,t)}get id(){const e=this.get("id");if(!e)throw Error("id not found.");return on(e)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw Error(Pb)}get rs(){const e=this.get("rs");if(e)return mn(e)}get rsv(){const e=this.get("rsv");if(e)return mn(e)}get ip(){return Rv(this,"ip","ip4")}set ip(e){Dv(this,"ip","ip4",e)}get tcp(){return Lv(this,"tcp","tcp")}set tcp(e){Mv(this,"tcp","tcp",e)}get udp(){return Lv(this,"udp","udp")}set udp(e){Mv(this,"udp","udp",e)}get ip6(){return Rv(this,"ip6","ip6")}set ip6(e){Dv(this,"ip6","ip6",e)}get tcp6(){return Lv(this,"tcp6","tcp")}set tcp6(e){Mv(this,"tcp6","tcp",e)}get udp6(){return Lv(this,"udp6","udp")}set udp6(e){Mv(this,"udp6","udp",e)}get multiaddrs(){const e=this.get("multiaddrs");if(e)return function(e){const t=[];let r=0;for(;r<e.length;){const n=new DataView(e.buffer,r,2).getUint16(0);r+=2;const s=e.slice(r,r+n);r+=n,t.push(bl(s))}return t}(e)}set multiaddrs(e){Nv(this,"multiaddrs",e,kv)}get waku2(){const e=this.get("waku2");if(e)return function(e){const t={relay:!1,store:!1,filter:!1,lightPush:!1};return e%2&&(t.relay=!0),(e>>=1)%2&&(t.store=!0),(e>>=1)%2&&(t.filter=!0),(e>>=1)%2&&(t.lightPush=!0),t}(e[0])}set waku2(e){Nv(this,"waku2",e,(e=>new Uint8Array([Tv(e)])))}}function Rv(e,t,r){const n=e.get(t);if(n)return fl(r,n)}function Lv(e,t,r){const n=e.get(t);if(n)return Number(fl(r,n))}function Dv(e,t,r,n){Nv(e,t,n,gl.bind({},r))}function Mv(e,t,r,n){Dv(e,t,r,n?.toString(10))}function Nv(e,t,r,n){void 0!==r?e.set(t,n(r)):e.delete(t)}const Ov=new fs("enr");var Uv,Fv;(e=>{e.TCP="tcp",e.UDP="udp"})(Uv||(Uv={})),(e=>{e.TCP4="tcp4",e.UDP4="udp4",e.TCP6="tcp6",e.UDP6="udp6"})(Fv||(Fv={}));class Bv extends Pv{static RECORD_PREFIX="enr:";peerId;static create(e={},t=BigInt(1),r){const n=new Bv(e,t,r);try{const e=n.publicKey;e&&(n.peerId=function(e){const t=function(e){if(32===e.byteLength)return t=fv(t=e,32),new pv(t);if(33===e.byteLength)return function(e){return new Ev(e)}(e);var t;const r=Hw(e),n=r[1]?.[0];if("1.2.840.10045.3.1.7"===n||"1.3.132.0.34"===n||"1.3.132.0.35"===n)return function(e){const t=e[1][1][0];let r,n;if(65===t.byteLength)return r=tn(t.subarray(1,33),"base64url"),n=tn(t.subarray(33),"base64url"),new ov({...rv,key_ops:["verify"],x:r,y:n});if(97===t.byteLength)return r=tn(t.subarray(1,49),"base64url"),n=tn(t.subarray(49),"base64url"),new ov({...nv,key_ops:["verify"],x:r,y:n});if(133===t.byteLength)return r=tn(t.subarray(1,67),"base64url"),n=tn(t.subarray(67),"base64url"),new ov({...sv,key_ops:["verify"],x:r,y:n});throw new Pn(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}(r);if("1.2.840.113549.1.1.1"===r[0]?.[0])return function(e,t,r){const n=function(e){const t=Hw(e[1],{offset:0});return{kty:"RSA",n:tn(t[0],"base64url"),e:tn(t[1],"base64url")}}(e);return null==r&&(r=Re(18,en(yv.encode({Type:gv.RSA,Data:t})))),new wv(n,r)}(r,e);throw new Pn("Could not extract public key from raw bytes")}(e);if("secp256k1"!==t.type)throw Error("Keypair type not implemented");return function(e){if("Ed25519"===e.type)return new Cv({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new xv({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new _v({multihash:e.toCID().multihash,publicKey:e});throw new Qn}(t)}(e))}catch(e){Ov.error("Could not calculate peer id for ENR",e)}return n}get nodeId(){if("v4"===this.id)return this.publicKey?function(e){const t=Xb.fromHex(e).toRawBytes(!1);return sn(Bw(t.slice(1)))}(this.publicKey):void 0;throw Error(Pb)}getLocationMultiaddr=qw.bind({},this);get shardInfo(){return this.rs&&this.rsv&&Ov.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(e){const t=e.protoNames();if(2!==t.length&&"udp"!==t[1]&&"tcp"!==t[1])throw Error("Invalid multiaddr");const r=e.tuples();if(!r[0][1]||!r[1][1])throw Error("Invalid multiaddr");4===r[0][0]?(this.set("ip",r[0][1]),this.set(t[1],r[1][1])):(this.set("ip6",r[0][1]),this.set(t[1]+"6",r[1][1]))}getAllLocationMultiaddrs(){const e=[];for(const t of Object.values(Fv)){const r=this.getLocationMultiaddr(t);r&&e.push(r)}const t=this.multiaddrs??[];return e.concat(t).map((e=>this.peerId?e.encapsulate("/p2p/"+this.peerId.toString()):e))}get peerInfo(){const e=this.peerId;if(e)return{id:e,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(e){if(this.peerId){const t=this.getLocationMultiaddr(e);if(t)return t.encapsulate("/p2p/"+this.peerId.toString())}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){const e=this.peerId;return this.multiaddrs.map((t=>t.encapsulate("/p2p/"+e.toString())))}return[]}verify(e,t){if(!this.get("id")||"v4"!==this.id)throw Error(Pb);if(!this.publicKey)throw Error("Failed to verify ENR: No public key");return $w(t,Bw(e),this.publicKey)}async sign(e,t){if("v4"!==this.id)throw Error(Pb);return this.signature=await async function(e,t){return async function(e,t,r={}){const{seed:n,m:s,d:i}=function(e,t,r){if(null==e)throw Error(`sign: expected valid message hash, not "${e}"`);const n=pw(e),s=_w(t),i=[Tw(s),kw(n)];if(null!=r){!0===r&&(r=Dw.randomBytes($b));const e=pw(r);if(e.length!==$b)throw Error("sign: Expected 32 bytes of extra data");i.push(e)}return{seed:tw(...i),m:xw(n),d:s}}(e,t,r.extraEntropy),o=new Ew(32,qb);let a;for(await o.reseed(n);!(a=Iw(await o.generate(),s,i,r.canonical));)await o.reseed();return function(e,t){const{sig:r,recovery:n}=e,{der:s,recovered:i}=Object.assign({canonical:!0,der:!0},t),o=s?r.toDERRawBytes():r.toCompactRawBytes();return i?[o,n]:o}(a,r)}(Bw(t),e,{der:!1})}(t,e),this.signature}}let $v=!1,qv=!1;const zv={debug:1,default:2,info:2,warning:3,error:4,off:5};let jv=zv.default,Kv=null;const Vv=function(){try{const e=[];if(["NFD","NFC","NFKD","NFKC"].forEach((t=>{try{if("test"!=="test".normalize(t))throw Error("bad normalize")}catch(r){e.push(t)}})),e.length)throw Error("missing "+e.join(", "))}catch(e){return e.message}return null}();var Hv,Gv;(e=>{e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR",e.OFF="OFF"})(Hv||(Hv={})),(e=>{e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.TIMEOUT="TIMEOUT",e.BUFFER_OVERRUN="BUFFER_OVERRUN",e.NUMERIC_FAULT="NUMERIC_FAULT",e.MISSING_NEW="MISSING_NEW",e.INVALID_ARGUMENT="INVALID_ARGUMENT",e.MISSING_ARGUMENT="MISSING_ARGUMENT",e.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",e.CALL_EXCEPTION="CALL_EXCEPTION",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.NONCE_EXPIRED="NONCE_EXPIRED",e.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",e.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",e.TRANSACTION_REPLACED="TRANSACTION_REPLACED",e.ACTION_REJECTED="ACTION_REJECTED"})(Gv||(Gv={}));const Wv="0123456789abcdef";class Xv{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const r=e.toLowerCase();null==zv[r]&&this.throwArgumentError("invalid log level name","logLevel",e)}debug(...e){this._log(Xv.levels.DEBUG,e)}info(...e){this._log(Xv.levels.INFO,e)}warn(...e){this._log(Xv.levels.WARNING,e)}makeError(e,t,r){if(qv)return this.makeError("censored error",t,{});t||(t=Xv.errors.UNKNOWN_ERROR),r||(r={});const n=[];Object.keys(r).forEach((e=>{const t=r[e];try{if(t instanceof Uint8Array){let r="";for(let e=0;e<t.length;e++)r+=Wv[t[e]>>4],r+=Wv[15&t[e]];n.push(e+"=Uint8Array(0x"+r+")")}else n.push(e+"="+JSON.stringify(t))}catch(t){n.push(e+"="+JSON.stringify(r[e].toString()))}})),n.push("code="+t),n.push("version="+this.version);const s=e;let i="";switch(t){case Gv.NUMERIC_FAULT:{i="NUMERIC_FAULT";const t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":i+="-"+t;break;case"negative-power":case"negative-width":i+="-unsupported";break;case"unbound-bitwise-result":i+="-unbound-result"}break}case Gv.CALL_EXCEPTION:case Gv.INSUFFICIENT_FUNDS:case Gv.MISSING_NEW:case Gv.NONCE_EXPIRED:case Gv.REPLACEMENT_UNDERPRICED:case Gv.TRANSACTION_REPLACED:case Gv.UNPREDICTABLE_GAS_LIMIT:i=t}i&&(e+=" [ See: https://links.ethers.org/v5-errors-"+i+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const o=Error(e);return o.reason=s,o.code=t,Object.keys(r).forEach((e=>{o[e]=r[e]})),o}throwError(e,t,r){throw this.makeError(e,t,r)}throwArgumentError(e,t,r){return this.throwError(e,Xv.errors.INVALID_ARGUMENT,{argument:t,value:r})}assert(e,t,r,n){e||this.throwError(t,r,n)}assertArgument(e,t,r,n){e||this.throwArgumentError(t,r,n)}checkNormalize(e){Vv&&this.throwError("platform missing String.prototype.normalize",Xv.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:Vv})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,Xv.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,Xv.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",e<t&&this.throwError("missing argument"+r,Xv.errors.MISSING_ARGUMENT,{count:e,expectedCount:t}),e>t&&this.throwError("too many arguments"+r,Xv.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){e!==Object&&null!=e||this.throwError("missing new",Xv.errors.MISSING_NEW,{name:t.name})}checkAbstract(e,t){e===t?this.throwError("cannot instantiate abstract class "+JSON.stringify(t.name)+" directly; use a sub-class",Xv.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):e!==Object&&null!=e||this.throwError("missing new",Xv.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return Kv||(Kv=new Xv("logger/5.8.0")),Kv}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",Xv.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),$v){if(!e)return;this.globalLogger().throwError("error censorship permanent",Xv.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}qv=!!e,$v=!!t}static setLogLevel(e){const t=zv[e.toLowerCase()];null!=t?jv=t:Xv.globalLogger().warn("invalid log level - "+e)}static from(e){return new Xv(e)}}Xv.errors=Gv,Xv.levels=Hv;const Zv=new Xv("bytes/5.8.0");function Yv(e){return!!e.toHexString}function Qv(e){return e.slice||(e.slice=function(){const t=[].slice.call(arguments);return Qv(new Uint8Array([].slice.apply(e,t)))}),e}function Jv(e){return"number"==typeof e&&e==e&&e%1==0}function eE(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e)return!1;if(!Jv(e.length)||e.length<0)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(!Jv(r)||r<0||r>=256)return!1}return!0}function tE(e,t){if(t||(t={}),"number"==typeof e){Zv.checkSafeUint53(e,"invalid arrayify value");const t=[];for(;e;)t.unshift(255&e),e=parseInt(e/256+"");return 0===t.length&&t.push(0),Qv(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),Yv(e)&&(e=e.toHexString()),rE(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":Zv.throwArgumentError("hex data is odd-length","value",e));const n=[];for(let e=0;e<r.length;e+=2)n.push(parseInt(r.substring(e,e+2),16));return Qv(new Uint8Array(n))}return eE(e)?Qv(new Uint8Array(e)):Zv.throwArgumentError("invalid arrayify value","value",e)}function rE(e){return!("string"!=typeof e||!e.match(/^0x[0-9A-Fa-f]*$/))}const nE="0123456789abcdef";function sE(e,t){if(t||(t={}),"number"==typeof e){Zv.checkSafeUint53(e,"invalid hexlify value");let t="";for(;e;)t=nE[15&e]+t,e=Math.floor(e/16);return t.length?(t.length%2&&(t="0"+t),"0x"+t):"0x00"}if("bigint"==typeof e)return(e=e.toString(16)).length%2?"0x0"+e:"0x"+e;if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),Yv(e))return e.toHexString();if(rE(e))return e.length%2&&("left"===t.hexPad?e="0x0"+e.substring(2):"right"===t.hexPad?e+="0":Zv.throwArgumentError("hex data is odd-length","value",e)),e.toLowerCase();if(eE(e)){let t="0x";for(let r=0;r<e.length;r++){let n=e[r];t+=nE[(240&n)>>4]+nE[15&n]}return t}return Zv.throwArgumentError("invalid hexlify value","value",e)}const iE=new Xv("rlp/5.8.0");function oE(e){const t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function aE(e,t,r){let n=0;for(let s=0;s<r;s++)n=256*n+e[t+s];return n}function cE(e){if(Array.isArray(e)){let t=[];if(e.forEach((e=>{t=t.concat(cE(e))})),t.length<=55)return t.unshift(192+t.length),t;const r=oE(t.length);return r.unshift(247+r.length),r.concat(t)}var t;rE(t=e)&&!(t.length%2)||eE(t)||iE.throwArgumentError("RLP object must be BytesLike","object",e);const r=[].slice.call(tE(e));if(1===r.length&&r[0]<=127)return r;if(r.length<=55)return r.unshift(128+r.length),r;const n=oE(r.length);return n.unshift(183+n.length),n.concat(r)}function lE(e,t,r,n){const s=[];for(;r<t+1+n;){const i=uE(e,r);s.push(i.result),(r+=i.consumed)>t+1+n&&iE.throwError("child data too short",Xv.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:s}}function uE(e,t){if(0===e.length&&iE.throwError("data too short",Xv.errors.BUFFER_OVERRUN,{}),e[t]>=248){const r=e[t]-247;t+1+r>e.length&&iE.throwError("data short segment too short",Xv.errors.BUFFER_OVERRUN,{});const n=aE(e,t+1,r);return t+1+r+n>e.length&&iE.throwError("data long segment too short",Xv.errors.BUFFER_OVERRUN,{}),lE(e,t,t+1+r,r+n)}if(e[t]>=192){const r=e[t]-192;return t+1+r>e.length&&iE.throwError("data array too short",Xv.errors.BUFFER_OVERRUN,{}),lE(e,t,t+1,r)}if(e[t]>=184){const r=e[t]-183;t+1+r>e.length&&iE.throwError("data array too short",Xv.errors.BUFFER_OVERRUN,{});const n=aE(e,t+1,r);return t+1+r+n>e.length&&iE.throwError("data array too short",Xv.errors.BUFFER_OVERRUN,{}),{consumed:1+r+n,result:sE(e.slice(t+1+r,t+1+r+n))}}if(e[t]>=128){const r=e[t]-128;return t+1+r>e.length&&iE.throwError("data too short",Xv.errors.BUFFER_OVERRUN,{}),{consumed:1+r,result:sE(e.slice(t+1,t+1+r))}}return{consumed:1,result:sE(e[t])}}const hE=new fs("enr:decoder");class dE{static fromString(e){if(!e.startsWith(Bv.RECORD_PREFIX))throw Error(`"string encoded ENR must start with '${Bv.RECORD_PREFIX}'`);return dE.fromRLP(Ye(e.slice(4),"base64url"))}static fromRLP(e){return async function(e){const{signature:t,seq:r,kvs:n}=function(e){if(!Array.isArray(e))throw Error("Decoded ENR must be an array");if(e.length%2!=0)throw Error("Decoded ENR must have an even number of elements");const[t,r,...n]=e;if(!t||Array.isArray(t))throw Error("Decoded ENR invalid signature: must be a byte array");if(!r||Array.isArray(r))throw Error("Decoded ENR invalid sequence number: must be a byte array");return{signature:t,seq:r,kvs:n}}(e),s={};for(let e=0;e<n.length;e+=2)try{s[on(n[e])]=n[e+1]}catch(t){hE.error("Failed to decode ENR key to UTF-8, skipping it",n[e],t)}const i=function(e){return e.length?BigInt("0x"+sn(e)):BigInt(0)}(r),o=Bv.create(s,i,t);return function(e,t,r,n){const s=rn(sE(cE([e,...t])));if(!r.verify(s,n))throw Error("Unable to verify ENR signature")}(r,n,o,t),o}(function(e){const t=tE(e),r=uE(t,0);return r.consumed!==t.length&&iE.throwArgumentError("invalid rlp data","data",e),r.result}(e).map(rn))}}class pE extends Map{#N=0;#O=new Map;#U=new Map;#F;#B;#$;constructor(e={}){if(super(),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if("number"==typeof e.maxAge&&0===e.maxAge)throw new TypeError("`maxAge` must be a number greater than 0");this.#F=e.maxSize,this.#B=e.maxAge||1/0,this.#$=e.onEviction}get __oldCache(){return this.#U}#q(e){if("function"==typeof this.#$)for(const[t,r]of e)this.#$(t,r.value)}#z(e,t){return"number"==typeof t.expiry&&t.expiry<=Date.now()&&("function"==typeof this.#$&&this.#$(e,t.value),this.delete(e))}#j(e,t){if(!1===this.#z(e,t))return t.value}#K(e,t){return t.expiry?this.#j(e,t):t.value}#V(e,t){const r=t.get(e);return this.#K(e,r)}#H(e,t){this.#O.set(e,t),this.#N++,this.#N>=this.#F&&(this.#N=0,this.#q(this.#U),this.#U=this.#O,this.#O=new Map)}#G(e,t){this.#U.delete(e),this.#H(e,t)}*#W(){for(const e of this.#U){const[t,r]=e;this.#O.has(t)||!1===this.#z(t,r)&&(yield e)}for(const e of this.#O){const[t,r]=e;!1===this.#z(t,r)&&(yield e)}}get(e){if(this.#O.has(e)){const t=this.#O.get(e);return this.#K(e,t)}if(this.#U.has(e)){const t=this.#U.get(e);if(!1===this.#z(e,t))return this.#G(e,t),t.value}}set(e,t,{maxAge:r=this.#B}={}){const n="number"==typeof r&&r!==1/0?Date.now()+r:void 0;return this.#O.has(e)?this.#O.set(e,{value:t,expiry:n}):this.#H(e,{value:t,expiry:n}),this}has(e){return this.#O.has(e)?!this.#z(e,this.#O.get(e)):!!this.#U.has(e)&&!this.#z(e,this.#U.get(e))}peek(e){return this.#O.has(e)?this.#V(e,this.#O):this.#U.has(e)?this.#V(e,this.#U):void 0}expiresIn(e){const t=this.#O.get(e)??this.#U.get(e);if(t)return t.expiry?t.expiry-Date.now():1/0}delete(e){const t=this.#O.delete(e);return t&&this.#N--,this.#U.delete(e)||t}clear(){this.#O.clear(),this.#U.clear(),this.#N=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");const t=[...this.#W()],r=t.length-e;r<0?(this.#O=new Map(t),this.#U=new Map,this.#N=t.length):(r>0&&this.#q(t.slice(0,r)),this.#U=new Map(t.slice(r)),this.#O=new Map,this.#N=0),this.#F=e}evict(e=1){const t=Number(e);if(!t||t<=0)return;const r=[...this.#W()],n=Math.trunc(Math.min(t,Math.max(r.length-1,0)));n<=0||(this.#q(r.slice(0,n)),this.#U=new Map(r.slice(n)),this.#O=new Map,this.#N=0)}*keys(){for(const[e]of this)yield e}*values(){for(const[,e]of this)yield e}*[Symbol.iterator](){for(const e of this.#O){const[t,r]=e;!1===this.#z(t,r)&&(yield[t,r.value])}for(const e of this.#U){const[t,r]=e;this.#O.has(t)||!1===this.#z(t,r)&&(yield[t,r.value])}}*entriesDescending(){let e=[...this.#O];for(let t=e.length-1;t>=0;--t){const r=e[t],[n,s]=r;!1===this.#z(n,s)&&(yield[n,s.value])}e=[...this.#U];for(let t=e.length-1;t>=0;--t){const r=e[t],[n,s]=r;this.#O.has(n)||!1===this.#z(n,s)&&(yield[n,s.value])}}*entriesAscending(){for(const[e,t]of this.#W())yield[e,t.value]}get size(){if(!this.#N)return this.#U.size;let e=0;for(const t of this.#U.keys())this.#O.has(t)||e++;return Math.min(this.#N+e,this.#F)}get maxSize(){return this.#F}get maxAge(){return this.#B}entries(){return this.entriesAscending()}forEach(e,t=this){for(const[r,n]of this.entriesAscending())e.call(t,n,r,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}function fE(e,t,r){return`${e}?name=${t}&type=${r}`}async function gE(e,t){const r=await fetch(e,{headers:new Headers({accept:"application/dns-json"}),signal:t});return await r.json()}function mE(e,t){return`${t}_${e}`}const yE=Object.assign(yg("dns-over-http-resolver"),{error:yg("dns-over-http-resolver:error")});class bE{_cache;_TXTcache;_servers;_request;_abortControllers;constructor(e={}){this._cache=new pE({maxSize:e?.maxCache??100}),this._TXTcache=new pE({maxSize:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??gE,this._abortControllers=[]}cancel(){this._abortControllers.forEach((e=>{e.abort()}))}getServers(){return this._servers}_getShuffledServers(){const e=[...this._servers];for(let t=e.length-1;t>0;t--){const r=Math.floor(Math.random()*t),n=e[t];e[t]=e[r],e[r]=n}return e}setServers(e){this._servers=e}async resolve(e,t="A"){switch(t){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw Error(t+" is not supported")}}async resolve4(e){const t="A",r=this._cache.get(mE(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const s=new AbortController;this._abortControllers.push(s);try{const n=await this._request(fE(r,e,t),s.signal),i=n.Answer.map((e=>e.data)),o=Math.min(...n.Answer.map((e=>e.TTL)));return this._cache.set(mE(e,t),i,{maxAge:o}),i}catch(i){s.signal.aborted&&(n=!0),yE.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter((e=>e!==s))}}if(n)throw Object.assign(Error("queryA ECANCELLED"),{code:"ECANCELLED"});throw Error(`Could not resolve ${e} record ${t}`)}async resolve6(e){const t="AAAA",r=this._cache.get(mE(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const s=new AbortController;this._abortControllers.push(s);try{const n=await this._request(fE(r,e,t),s.signal),i=n.Answer.map((e=>e.data)),o=Math.min(...n.Answer.map((e=>e.TTL)));return this._cache.set(mE(e,t),i,{maxAge:o}),i}catch(i){s.signal.aborted&&(n=!0),yE.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter((e=>e!==s))}}if(n)throw Object.assign(Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"});throw Error(`Could not resolve ${e} record ${t}`)}async resolveTxt(e){const t="TXT",r=this._TXTcache.get(mE(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const s=new AbortController;this._abortControllers.push(s);try{const n=await this._request(fE(r,e,t),s.signal),i=n.Answer.map((e=>[e.data.replace(/['"]+/g,"")])),o=Math.min(...n.Answer.map((e=>e.TTL)));return this._TXTcache.set(mE(e,t),i,{maxAge:o}),i}catch(i){s.signal.aborted&&(n=!0),yE.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter((e=>e!==s))}}if(n)throw Object.assign(Error("queryTxt ECANCELLED"),{code:"ECANCELLED"});throw Error(`Could not resolve ${e} record ${t}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}}const wE=new fs("dns-over-https");class vE{resolver;static async create(){return new vE}constructor(e=new bE){this.resolver=e}async resolveTXT(e){let t;try{t=await this.resolver.resolveTxt(e)}catch(e){throw wE.error("query failed: ",e),Error("DNS query failed")}if(!t)throw Error("Could not resolve "+e);const r=[];return t.forEach((e=>{"string"==typeof e?r.push(e):Array.isArray(e)?e.forEach((e=>{"string"==typeof e?r.push(e):r.push(on(e))})):r.push(on(e))})),r}}var EE,SE={exports:{}},AE=(EE||(EE=1,(e=>{(()=>{var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof s&&s.versions&&s.versions.node&&(t=ns);var r=!t.HI_BASE32_NO_COMMON_JS&&e.exports,n="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),i={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},o=[0,0,0,0,0,0,0,0],a=(e,t)=>{t.length>10&&(t="..."+t.substr(-10));var r=Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw r.position=e,r},c=e=>{if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw Error("Invalid base32 characters");for(var t,r,n,s,o,a,c,l,u=[],h=0,d=(e=e.replace(/=/g,"")).length,p=0,f=d>>3<<3;p<f;)t=i[e.charAt(p++)],r=i[e.charAt(p++)],n=i[e.charAt(p++)],s=i[e.charAt(p++)],o=i[e.charAt(p++)],a=i[e.charAt(p++)],c=i[e.charAt(p++)],l=i[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|o>>>1),u[h++]=255&(o<<7|a<<2|c>>>3),u[h++]=255&(c<<5|l);var g=d-f;return 2===g?(t=i[e.charAt(p++)],r=i[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2)):4===g?(t=i[e.charAt(p++)],r=i[e.charAt(p++)],n=i[e.charAt(p++)],s=i[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4)):5===g?(t=i[e.charAt(p++)],r=i[e.charAt(p++)],n=i[e.charAt(p++)],s=i[e.charAt(p++)],o=i[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|o>>>1)):7===g&&(t=i[e.charAt(p++)],r=i[e.charAt(p++)],n=i[e.charAt(p++)],s=i[e.charAt(p++)],o=i[e.charAt(p++)],a=i[e.charAt(p++)],c=i[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|o>>>1),u[h++]=255&(o<<7|a<<2|c>>>3)),u},l=(e,t)=>{if(!t)return(e=>{for(var t,r,n="",s=e.length,i=0,o=0;i<s;)if((t=e[i++])<=127)n+=String.fromCharCode(t);else{t>191&&t<=223?(r=31&t,o=1):t<=239?(r=15&t,o=2):t<=247?(r=7&t,o=3):a(i,n);for(var c=0;c<o;++c)((t=e[i++])<128||t>191)&&a(i,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&a(i,n),r>1114111&&a(i,n),r<=65535?n+=String.fromCharCode(r):(n+=String.fromCharCode(55296+((r-=65536)>>10)),n+=String.fromCharCode(56320+(1023&r)))}return n})(c(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw Error("Invalid base32 characters");var r,n,s,o,l,u,h,d,p="",f=e.indexOf("=");-1===f&&(f=e.length);for(var g=0,m=f>>3<<3;g<m;)r=i[e.charAt(g++)],n=i[e.charAt(g++)],s=i[e.charAt(g++)],o=i[e.charAt(g++)],l=i[e.charAt(g++)],u=i[e.charAt(g++)],h=i[e.charAt(g++)],d=i[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|o>>>4))+String.fromCharCode(255&(o<<4|l>>>1))+String.fromCharCode(255&(l<<7|u<<2|h>>>3))+String.fromCharCode(255&(h<<5|d));var y=f-m;return 2===y?(r=i[e.charAt(g++)],n=i[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))):4===y?(r=i[e.charAt(g++)],n=i[e.charAt(g++)],s=i[e.charAt(g++)],o=i[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|o>>>4))):5===y?(r=i[e.charAt(g++)],n=i[e.charAt(g++)],s=i[e.charAt(g++)],o=i[e.charAt(g++)],l=i[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|o>>>4))+String.fromCharCode(255&(o<<4|l>>>1))):7===y&&(r=i[e.charAt(g++)],n=i[e.charAt(g++)],s=i[e.charAt(g++)],o=i[e.charAt(g++)],l=i[e.charAt(g++)],u=i[e.charAt(g++)],h=i[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|o>>>4))+String.fromCharCode(255&(o<<4|l>>>1))+String.fromCharCode(255&(l<<7|u<<2|h>>>3))),p},u={encode(e,t){var r="string"!=typeof e;return r&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),r?(e=>{for(var t,r,s,i,o,a="",c=e.length,l=0,u=5*parseInt(c/5);l<u;)t=e[l++],r=e[l++],s=e[l++],i=e[l++],o=e[l++],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[31&(i<<3|o>>>5)]+n[31&o];var h=c-u;return 1===h?(t=e[l],a+=n[t>>>3]+n[t<<2&31]+"======"):2===h?(t=e[l++],r=e[l],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[r<<4&31]+"===="):3===h?(t=e[l++],r=e[l++],s=e[l],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[s<<1&31]+"==="):4===h&&(t=e[l++],r=e[l++],s=e[l++],i=e[l],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[i<<3&31]+"="),a})(e):t?(e=>{for(var t,r,s,i,o,a="",c=e.length,l=0,u=5*parseInt(c/5);l<u;)t=e.charCodeAt(l++),r=e.charCodeAt(l++),s=e.charCodeAt(l++),i=e.charCodeAt(l++),o=e.charCodeAt(l++),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[31&(i<<3|o>>>5)]+n[31&o];var h=c-u;return 1===h?(t=e.charCodeAt(l),a+=n[t>>>3]+n[t<<2&31]+"======"):2===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[r<<4&31]+"===="):3===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l++),s=e.charCodeAt(l),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[s<<1&31]+"==="):4===h&&(t=e.charCodeAt(l++),r=e.charCodeAt(l++),s=e.charCodeAt(l++),i=e.charCodeAt(l),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[i<<3&31]+"="),a})(e):(e=>{var t,r,s,i,a,c,l,u=!1,h="",d=0,p=0,f=e.length;if(""===e)return h;do{for(o[0]=o[5],o[1]=o[6],o[2]=o[7],l=p;d<f&&l<5;++d)(c=e.charCodeAt(d))<128?o[l++]=c:c<2048?(o[l++]=192|c>>6,o[l++]=128|63&c):c<55296||c>=57344?(o[l++]=224|c>>12,o[l++]=128|c>>6&63,o[l++]=128|63&c):(c=65536+((1023&c)<<10|1023&e.charCodeAt(++d)),o[l++]=240|c>>18,o[l++]=128|c>>12&63,o[l++]=128|c>>6&63,o[l++]=128|63&c);p=l-5,d===f&&++d,d>f&&l<6&&(u=!0),t=o[0],l>4?(r=o[1],s=o[2],i=o[3],a=o[4],h+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[31&(i<<3|a>>>5)]+n[31&a]):1===l?h+=n[t>>>3]+n[t<<2&31]+"======":2===l?(r=o[1],h+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[r<<4&31]+"===="):3===l?(r=o[1],s=o[2],h+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[s<<1&31]+"==="):(r=o[1],s=o[2],i=o[3],h+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[i<<3&31]+"=")}while(!u);return h})(e)},decode:l};l.asBytes=c,r?e.exports=u:t.base32=u})()})(SE)),SE.exports),IE=ss(AE);class _E{static RECORD_PREFIX=Bv.RECORD_PREFIX;static TREE_PREFIX="enrtree:";static BRANCH_PREFIX="enrtree-branch:";static ROOT_PREFIX="enrtree-root:";static parseAndVerifyRoot(e,t){if(!e.startsWith(this.ROOT_PREFIX))throw Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);const r=_E.parseRootValues(e),n=IE.decode.asBytes(t),s=e.split(" sig")[0],i=an(s);if(!$w(Ye(r.signature,"base64url").slice(0,64),Bw(i),new Uint8Array(n)))throw Error("Unable to verify ENRTree root signature");return r.eRoot}static parseRootValues(e){const t=e.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/);if(!Array.isArray(t))throw Error("Could not parse ENRTree root entry");t.shift();const[r,n,s,i]=t;if(!r)throw Error("Could not parse 'e' value from ENRTree root entry");if(!n)throw Error("Could not parse 'l' value from ENRTree root entry");if(!s)throw Error("Could not parse 'seq' value from ENRTree root entry");if(!i)throw Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:r,lRoot:n,seq:Number(s),signature:i}}static parseTree(e){if(!e.startsWith(this.TREE_PREFIX))throw Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);const t=e.match(/^enrtree:\/\/([^@]+)@(.+)$/);if(!Array.isArray(t))throw Error("Could not parse ENRTree tree entry");t.shift();const[r,n]=t;if(!r)throw Error("Could not parse public key from ENRTree tree entry");if(!n)throw Error("Could not parse domain from ENRTree tree entry");return{publicKey:r,domain:n}}static parseBranch(e){if(!e.startsWith(this.BRANCH_PREFIX))throw Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);return e.split(this.BRANCH_PREFIX)[1].split(",")}}const CE=new fs("discovery:fetch_nodes");async function*xE(e,t=10,r=3){const n=new Set;let s=0,i=0;for(;s<t&&i<r;){s++;const t=await e();t&&t.nodeId?n.has(t.nodeId)||(n.add(t.nodeId),t.waku2&&(yield t),CE.info(`got new peer candidate from DNS address=${t.nodeId}@${t.ip}`)):i++}}const kE=new fs("discovery:dns");class TE{dns;_DNSTreeCache;static async dnsOverHttp(e){return e||(e=await vE.create()),new TE(e)}constructor(e){this._DNSTreeCache={},this.dns=e}async*getNextPeer(e){for(const t of function(e){if(e.length<=1)return e;for(let t=0;t<e.length;t++){const r=Math.floor(Math.random()*Math.floor(e.length)),n=e[t];e[t]=e[r],e[r]=n}return e}(e)){const{publicKey:e,domain:r}=_E.parseTree(t),n={domain:r,publicKey:e,visits:{}};for await(const e of xE((()=>this._search(r,n))))yield e}}async _search(e,t){try{const r=await this._getTXTRecord(e,t);let n,s;t.visits[e]=!0;const i=function(e){return e.startsWith(_E.ROOT_PREFIX)?_E.ROOT_PREFIX:e.startsWith(_E.BRANCH_PREFIX)?_E.BRANCH_PREFIX:e.startsWith(_E.RECORD_PREFIX)?_E.RECORD_PREFIX:""}(r);try{switch(i){case _E.ROOT_PREFIX:return n=_E.parseAndVerifyRoot(r,t.publicKey),await this._search(n,t);case _E.BRANCH_PREFIX:return s=_E.parseBranch(r),n=function(e,t){const r={};for(const[n,s]of e.entries())t.visits[s]&&(r[n]=!0);if(Object.keys(r).length===e.length)throw Error("Unresolvable circular path detected");let n;do{n=Math.floor(Math.random()*e.length)}while(r[n]);return e[n]}(s,t),await this._search(n,t);case _E.RECORD_PREFIX:return dE.fromString(r);default:return null}}catch(t){return kE.error(`Failed to search DNS tree ${i} at subdomain ${e}: ${t}`),null}}catch(t){return kE.error(`Failed to retrieve TXT record at subdomain ${e}: ${t}`),null}}async _getTXTRecord(e,t){if(this._DNSTreeCache[e])return this._DNSTreeCache[e];const r=e!==t.domain?`${e}.${t.domain}`:t.domain,n=await this.dns.resolveTXT(r);if(!n.length)throw Error("Received empty result array while fetching TXT record");if(!n[0].length)throw Error("Received empty TXT record");const s=n.join("");return this._DNSTreeCache[e]=s,s}}const PE=new fs("peer-discovery-dns");class RE extends Jn{nextPeer;_started;_components;_options;constructor(e,t){super(),this._started=!1,this._components=e,this._options=t;const{enrUrls:r}=t;PE.info("Use following EIP-1459 ENR Tree URLs: ",r)}async start(){PE.info("Starting peer discovery via dns"),this._started=!0,await this.findPeers()}async findPeers(){if(!this.nextPeer){let{enrUrls:e}=this._options;Array.isArray(e)||(e=[e]);const t=await TE.dnsOverHttp();this.nextPeer=t.getNextPeer.bind(t,e)}for await(const e of this.nextPeer()){if(!this._started)return;const{peerInfo:t,shardInfo:r}=e;if(!t)continue;const n={[Tb]:{value:this._options.tagValue??50,ttl:this._options.tagTTL??1e8}};let s=!1;await this._components.peerStore.has(t.id)?(await this._components.peerStore.get(t.id)).tags.has(Tb)||(s=!0,await this._components.peerStore.merge(t.id,{tags:n})):(s=!0,await this._components.peerStore.save(t.id,{tags:n,...r&&{metadata:{shardInfo:yn(r)}}})),s&&this.dispatchEvent(new CustomEvent("peer",{detail:t}))}}stop(){this._started=!1}get[vn](){return!0}get[Symbol.toStringTag](){return"@waku/bootstrap"}}const LE=xs.PEER_EXCHANGE,DE="/vac/waku/peer-exchange/2.0.0-alpha1";class ME{proto;constructor(e){this.proto=e}static createRequest(e){const{numPeers:t}=e;return new ME({query:{numPeers:t},response:void 0})}encode(){return qt.encode(this.proto)}static decode(e){const t=qt.decode(e);return new ME(t)}get query(){return this.proto.query}get response(){return this.proto.response}}const NE=new fs("peer-exchange");class OE{components;streamManager;constructor(e){this.components=e,this.streamManager=new di(DE,e)}async query(e){const{numPeers:t,peerId:r}=e,n=ME.createRequest({numPeers:BigInt(t)});if(!await this.components.peerStore.has(r))return{peerInfos:null,error:_s.NO_PEER_AVAILABLE};const s=await this.streamManager.getStream(r);if(!s)return NE.error("Failed to get a stream for remote peer:"+r?.toString?.()),{peerInfos:null,error:_s.NO_STREAM_AVAILABLE};const i=await si([n.encode()],Eu,s,Iu,(async e=>await Rs(e)));try{const e=new Us;i.forEach((t=>{e.append(t)}));const{response:t}=ME.decode(e);return t?{peerInfos:await Promise.all(t.peerInfos.map((e=>e.enr)).filter(Yt).map((async e=>({ENR:await dE.fromRLP(e)})))),error:null}:(NE.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:_s.EMPTY_PAYLOAD})}catch(e){return NE.error("Failed to decode push reply",e),{peerInfos:null,error:_s.DECODE_FAILED}}}}const UE=new fs("peer-exchange-discovery");class FE extends Jn{components;peerExchange;options;isStarted=!1;queryingPeers=new Set;peerExpirationRecords=new Map;continuousDiscoveryInterval=null;constructor(e,t={}){super(),this.components=e,this.peerExchange=new OE(e),this.options={...t,TTL:t.TTL??3e4},this.handleDiscoveredPeer=this.handleDiscoveredPeer.bind(this)}start(){this.isStarted||(UE.info("Starting peer exchange node discovery, discovering peers"),this.isStarted=!0,this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer),this.continuousDiscoveryInterval=setInterval((()=>{this.handlePeriodicDiscovery()}),this.options.TTL))}stop(){this.isStarted&&(UE.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.peerExpirationRecords.clear(),this.continuousDiscoveryInterval&&clearInterval(this.continuousDiscoveryInterval),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[vn](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}async handleDiscoveredPeer(e){this.runQuery(e.detail.peerId,e.detail.protocols)}async handlePeriodicDiscovery(){const e=this.components.connectionManager.getConnections();await Promise.all(e.map((async e=>{try{const t=e.remotePeer.toString();if(this.peerExpirationRecords.has(t)&&!(this.peerExpirationRecords.get(t)<=Date.now()))return null;const r=await this.components.peerStore.get(e.remotePeer);return this.runQuery(e.remotePeer,r.protocols)}catch(e){return UE.warn("Error getting peer info",e),null}})))}async runQuery(e,t){if(t.includes(DE)&&!this.queryingPeers.has(e.toString())){try{this.queryingPeers.add(e.toString()),await this.query(e)}catch(e){UE.error("Error querying peer",e)}this.peerExpirationRecords.set(e.toString(),Date.now()+this.options.TTL),this.queryingPeers.delete(e.toString())}else UE.info(`Skipping peer ${e} as it is already querying or does not support peer exchange`)}async query(e){const t=e.toString();UE.info("Querying peer exchange for "+t);const{error:r,peerInfos:n}=await this.peerExchange.query({numPeers:60,peerId:e});if(r)UE.error(`Peer exchange query to ${t} failed`,r);else for(const{ENR:e}of n){if(!e){UE.warn(`No ENR in peerInfo object from ${t}, skipping`);continue}const{peerInfo:r,shardInfo:n}=e;if(!r){UE.warn(`No peerInfo in ENR from ${t}, skipping`);continue}const s=!await this.hasShardInfo(r.id)&&n?{metadata:{shardInfo:yn(n)}}:void 0;await this.components.peerStore.merge(r.id,{tags:{[LE]:{value:50}},...s,...r.multiaddrs&&{multiaddrs:r.multiaddrs}}),UE.info("Discovered peer: "+r.id.toString()),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r.id,multiaddrs:r.multiaddrs}}))}}async hasShardInfo(e){try{const t=await this.components.peerStore.get(e);return!!t&&t.metadata.has("shardInfo")}catch(t){UE.warn("Error getting shard info for "+e.toString(),t)}return!1}}const BE=xs.PEER_CACHE,$E=e=>!!e&&"object"==typeof e&&"id"in e&&"string"==typeof e.id&&"multiaddrs"in e&&Array.isArray(e.multiaddrs);class qE{get(){return[]}set(e){}remove(){}}class zE{get(){try{const e=localStorage.getItem("waku:peers");return(e?JSON.parse(e):[]).filter($E)}catch(e){return[]}}set(e){try{localStorage.setItem("waku:peers",JSON.stringify(e))}catch(e){}}remove(){try{localStorage.removeItem("waku:peers")}catch(e){}}}const jE=new fs("peer-cache");class KE extends Jn{components;isStarted=!1;cache;constructor(e,t){super(),this.components=e,this.cache=t?.cache??(()=>{try{if("undefined"!=typeof localStorage)return new zE}catch(e){}return new qE})()}get[Symbol.toStringTag](){return"@waku/"+BE}async start(){this.isStarted||(jE.info("Starting Peer Cache Discovery"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer),await this.discoverPeers(),this.isStarted=!0)}stop(){this.isStarted&&(jE.info("Stopping Peer Cache Discovery"),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer),this.isStarted=!1)}handleDiscoveredPeer=e=>{const{peerId:t,listenAddrs:r}=e.detail,n=r.map((e=>e.toString())),s=t.toString(),i=this.readPeerInfoFromCache(),o=i.findIndex((e=>e.id===s));-1!==o?i[o].multiaddrs=n:i.push({id:s,multiaddrs:n}),this.writePeerInfoToCache(i)};async discoverPeers(){const e=this.readPeerInfoFromCache();for(const t of e){const e=Pc(t.id),r=t.multiaddrs.map((e=>bl(e)));await this.components.peerStore.has(e)||(await this.components.peerStore.save(e,{multiaddrs:r,tags:{[BE]:{value:50}}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:e,multiaddrs:r}})))}}readPeerInfoFromCache(){try{return this.cache.get()}catch(e){return jE.error("Error parsing peers from cache:",e),[]}}writePeerInfoToCache(e){try{this.cache.set(e)}catch(e){jE.error("Error saving peers to cache:",e)}}}function VE(e,t){const r=[xb,kb],n=[];var s;return e?.dns&&n.push((s=r,e=>new RE(e,{enrUrls:s}))),(e?.peerCache||t)&&n.push(function(e={}){return t=>new KE(t,e)}({cache:t})),e?.peerExchange&&n.push(function(e={}){return t=>new FE(t,e)}()),n}const HE=new fs("sdk:create");async function GE(e){const t=(e.networkConfig??Ts).clusterId??1;HE.info("Creating Waku node with cluster id: ",t);const r=e?.libp2p??{},n=r.peerDiscovery??[];e?.defaultBootstrap?n.push(...VE({dns:!0,peerExchange:!0,peerCache:!0,...e.discovery},e.peerCache)):n.push(...VE(e.discovery,e.peerCache));const s=[...e.bootstrapPeers||[],...e.store?.peers||[]];var i;return s.length&&n.push((i={list:s},e=>new pd(e,i))),r.peerDiscovery=n,async function(e,t,r){return!t?.hideWebSocketInfo&&Cb(),async function(e={}){e.privateKey??=await async function(){return async function(){const{privateKey:e,publicKey:t}=function(){const e=Na.utils.randomPrivateKey(),t=Na.getPublicKey(e),r=function(e,t){const r=new Uint8Array(64);for(let n=0;n<32;n++)r[n]=e[n],r[32+n]=t[n];return r}(e,t);return{privateKey:r,publicKey:t}}();return new Ka(e,t)}()}();const t=new _b({...await ag(e),peerId:(r=e.privateKey,Rc(r.publicKey))});var r;return!1!==e.start&&await t.start(),t}({transports:[Sf({filter:!1===t?.filterMultiaddrs||Cb()?wf:vf})],streamMuxers:[Yp()],connectionEncrypters:[Mh()],...t,services:{identify:Ip({agentVersion:r??"js-waku"}),ping:Jp({maxInboundStreams:t?.pingMaxInboundStreams??10}),metadata:Fl(e),...t?.services}})}(t,r,e?.userAgent)}var WE=0,XE={size:0,kind:17,base:null,node:null,finalizer:null},ZE={size:0,kind:17,base:null,node:null,finalizer:null},YE={size:0,kind:17,base:null,node:null,finalizer:null},QE={size:0,kind:17,base:null,node:null,finalizer:null},JE={size:0,kind:17,base:null,node:null,finalizer:null},eS={size:0,kind:22,base:null,node:null,finalizer:null},tS={size:0,kind:28,base:null,node:null,finalizer:null},rS={size:0,kind:22,base:null,node:null,finalizer:null},nS={size:0,kind:17,base:null,node:null,finalizer:null},sS={size:0,kind:17,base:null,node:null,finalizer:null},iS={size:0,kind:17,base:null,node:null,finalizer:null},oS={size:0,kind:17,base:null,node:{kind:2,len:0,offset:0,typ:null,name:null,sons:[]},finalizer:null};iS.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},sS.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},rS.base=nS,eS.base=nS;var aS={kind:2,len:5,offset:0,typ:null,name:null,sons:[{kind:1,offset:"parent",len:0,typ:rS,name:"parent",sons:null},{kind:1,offset:"name",len:0,typ:{size:0,kind:29,base:null,node:null,finalizer:null},name:"name",sons:null},{kind:1,offset:"message",len:0,typ:tS,name:"msg",sons:null},{kind:1,offset:"trace",len:0,typ:tS,name:"trace",sons:null},{kind:1,offset:"up",len:0,typ:eS,name:"up",sons:null}]};function cS(e,t){throw e.name=t,0==WE&&function(e){var t=[[]];0!=e.message.length?(t[0].push.call(t[0],69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32),t[0].push.apply(t[0],e.message)):t[0].push.call(t[0],69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110),t[0].push.call(t[0],32,91),function(e,t,r){null===e[0]&&(e[0]=[]);var n=e[0].length;e[0].length+=r.length;for(var s=0;s<r.length;++s)e[0][n+s]=r.charCodeAt(s)}(t,0,e.name),t[0].push.call(t[0],93,10);var r=function(e){for(var t=SS(e.length),r=0,n=0;r<e.length;){var s=e[r];if(s<128)t[n]=String.fromCharCode(s),r+=1;else{var i=SS(0);e:for(;;){var o=s.toString(16);if(1==(null==o?0:o.length)?i.push("%0"):i.push("%"),i.push(o),r+=1,e.length<=r||e[r]<128)break e;s=e[r]}++WE;try{t[n]=decodeURIComponent(i.join("")),--WE}catch(e){--WE,t[n]=i.join("")}}n+=1}if(t.length<n)for(var a=t.length;a<n;++a)t.push(null);else t.length=n;return t.join("")}(t[0]);throw void 0!==Error?Error(r):r}(e),e}function lS(e,t){return 0==t&&cS({message:[100,105,118,105,115,105,111,110,32,98,121,32,122,101,114,111],parent:null,m_type:oS,name:null,trace:[],up:null},"DivByZeroDefect"),-1==t&&2147483647==e&&AS(),Math.trunc(e%t)}function uS(e){return e<0?-1*e:e}function hS(e,t){var r=e*t;return IS(r),r}function dS(e,t){var r=e-t;return IS(r),r}function pS(e,t){var r=e+t;return IS(r),r}nS.node=aS,JE.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},nS.base=JE,sS.base=nS,iS.base=sS,oS.base=iS,QE.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},QE.base=iS,YE.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},YE.base=sS,ZE.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},ZE.base=sS,XE.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},XE.base=sS;var fS,gS,mS,yS,bS,wS=function(){for(var e={},t=0;t<arguments.length;++t){var r=arguments[t];if("object"==typeof r)for(var n=r[0];n<=r[1];++n)e[n]=!0;else e[r]=!0}return e}(17,16,4,18,27,19,23,22,21);function vS(e,t,r){var n=null;switch(r.kind){case 21:case 22:case 23:case 5:n=function(e){return!(null!=wS[e.base.kind])}(r)?[t[0],t[1]]:t;break;case 19:if(null==e)e={};else for(var s in e)delete e[s];for(var s in t)e[s]=t[s];n=e;break;case 18:case 17:CS(n=null!=r.base?vS(e,t,r.base):17==r.kind?null==e?{m_type:r}:e:null==e?{}:e,t,r.node);break;case 4:case 16:if(ArrayBuffer.isView(t))null==e||e.length!=t.length?e=new t.constructor(t):e.set(t,0),n=e;else if(null===t)n=null;else{null!=e&&e.length==t.length||(e=Array(t.length)),n=e;for(var i=0;i<t.length;++i)n[i]=vS(n[i],t[i],r.base)}break;case 24:case 27:if(null===t)n=null;else for(null!=e&&e.length==t.length||(e=Array(t.length)),n=e,i=0;i<t.length;++i)n[i]=vS(n[i],t[i],r.base);break;case 28:null!==t&&(n=t.slice(0));break;default:n=t}return n}function ES(e,t,r){var n=0;return t<=e&&e<=r?n=e:function(e,t,r){cS({message:vS(null,r<t?[105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]:[105,110,100,101,120,32].concat(_S(e),[32,110,111,116,32,105,110,32],_S(t),[32,46,46,32],_S(r)),tS),parent:null,m_type:ZE,name:null,trace:[],up:null},"IndexDefect")}(e,t,r),n}function SS(e){var t=[];t=Array(e);for(var r=0;r<e;++r)t[r]=null;return t}function AS(){cS({message:[111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119],parent:null,m_type:QE,name:null,trace:[],up:null},"OverflowDefect")}function IS(e){(e>2147483647||e<-2147483648)&&AS()}function _S(e){var t=[[]];return function(e,t,r){!function(e,t,r){!function(e,t,r){!function(e,t,r,n,s){var i,o=e[t].length;if(e[t].length<(i=function(e,t,r){var n=0;return 0<=e&&e<=2147483647?n=e:cS({message:[118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101],parent:null,m_type:YE,name:null,trace:[],up:null},"RangeDefect"),n}(pS(o,s))))for(var a=e[t].length;a<i;++a)e[t].push(0);else e[t].length=i;for(var c=0,l=0;l<s;)c=l,e[t][ES(pS(o,c),0,e[t].length-1)]=r.charCodeAt(ES(pS(0,c),0,r.length-1)),l=pS(l,1)}(e,t,r,0,null==r?0:r.length)}(e,0,r+"")}(e,0,r)}(t,0,e),t[0]}function CS(e,t,r){switch(r.kind){case 0:break;case 1:e[r.offset]=vS(e[r.offset],t[r.offset],r.typ);break;case 2:for(var n=0;n<r.sons.length;n++)CS(e,t,r.sons[n]);break;case 3:for(e[r.offset]=vS(e[r.offset],t[r.offset],r.typ),n=0;n<r.sons.length;++n)CS(e,t,r.sons[n][1])}}function xS(e,t){var r=65535,n=(e&r)>>>0,s=(t&r)>>>0;return(n*s>>>0)+((((e>>>16&r)>>>0)*s>>>0)+(n*((t>>>16&r)>>>0)>>>0)>>>0<<16>>>0)>>>0}function kS(e,t){return(e<<t>>>0|e>>>dS(32,t))>>>0}function TS(e){return function(e){for(var t=e.length,r=(a=t,Math.trunc(a/4)),n=0,s=0;s<hS(r,4);){for(var i=0,o=4;0<o;)o=dS(o,1),i=(i<<8>>>0|Number(BigInt.asUintN(32,BigInt(e[ES(pS(s,o),0,e.length-1)]))))>>>0;s=pS(s,4),i=kS(i=xS(i,3432918353),15),n=3864292196+(5*(n=kS(n=(n^(i=xS(i,461845907)))>>>0,13))>>>0)>>>0}for(var a,c=0,l=lS(t,4);0<l;)l=dS(l,1),c=(c<<8>>>0|Number(BigInt.asUintN(32,BigInt(e[ES(pS(s,l),0,e.length-1)]))))>>>0;return c=xS(c,3432918353),c=xS(c=kS(c,15),461845907),n=xS(n=((n=((n=(n^c)>>>0)^Number(BigInt.asUintN(32,BigInt(t))))>>>0)^n>>>16)>>>0,2246822507),n=((n=xS(n=(n^n>>>13)>>>0,3266489909))^n>>>16)>>>0,Number(BigInt.asIntN(32,BigInt(n)))}(e.slice(0,e.length-1+1))}0!=(gS=lS(uS(TS(fS=[100,117,109,109,121])),1),mS=lS(uS(TS(fS.concat([32,98]))),1),lS(uS(pS(gS,hS(0,mS))),1))&&cS({message:vS(null,[110,105,109,95,104,97,115,104,46,110,105,109,40,50,54,44,32,51,41,32,96,104,97,115,104,78,40,34,100,117,109,109,121,34,44,32,48,44,32,49,41,32,61,61,32,48,96,32],tS),m_type:XE,parent:null,name:null,trace:[],up:null},"AssertionDefect"),(e=>{e.Send="send",e.Receive="receive",e.SendEphemeral="sendEphemeral"})(yS||(yS={})),(e=>{e.OutMessageSent="sds:out:message-sent",e.InMessageDelivered="sds:in:message-delivered",e.InMessageReceived="sds:in:message-received",e.OutMessageAcknowledged="sds:out:message-acknowledged",e.OutMessagePossiblyAcknowledged="sds:out:message-possibly-acknowledged",e.InMessageMissing="sds:in:message-missing",e.OutSyncSent="sds:out:sync-sent",e.InSyncReceived="sds:in:sync-received",e.InMessageLost="sds:in:message-irretrievably-lost",e.ErrorTask="sds:error-task"})(bS||(bS={}));var PS,RS,LS={exports:{}};PS||(PS=1,function(e,t){!function(){var r,n="Expected a function",s="__lodash_hash_undefined__",i="__lodash_placeholder__",o=32,a=128,c=1/0,l=9007199254740991,u=NaN,h=4294967295,d=[["ary",a],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",o],["partialRight",64],["rearg",256]],p="[object Arguments]",f="[object Array]",g="[object Boolean]",m="[object Date]",y="[object Error]",b="[object Function]",w="[object GeneratorFunction]",v="[object Map]",E="[object Number]",S="[object Object]",A="[object Promise]",I="[object RegExp]",_="[object Set]",C="[object String]",x="[object Symbol]",k="[object WeakMap]",T="[object ArrayBuffer]",P="[object DataView]",R="[object Float32Array]",L="[object Float64Array]",D="[object Int8Array]",M="[object Int16Array]",N="[object Int32Array]",O="[object Uint8Array]",U="[object Uint8ClampedArray]",F="[object Uint16Array]",B="[object Uint32Array]",$=/\b__p \+= '';/g,q=/\b(__p \+=) '' \+/g,z=/(__e\(.*?\)|\b__t\)) \+\n'';/g,j=/&(?:amp|lt|gt|quot|#39);/g,K=/[&<>"']/g,V=RegExp(j.source),H=RegExp(K.source),G=/<%-([\s\S]+?)%>/g,W=/<%([\s\S]+?)%>/g,X=/<%=([\s\S]+?)%>/g,Z=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Y=/^\w*$/,Q=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,J=/[\\^$.*+?()[\]{}|]/g,ee=RegExp(J.source),te=/^\s+/,re=/\s/,ne=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,se=/\{\n\/\* \[wrapped with (.+)\] \*/,ie=/,? & /,oe=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,ae=/[()=,{}\[\]\/\s]/,ce=/\\(\\)?/g,le=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,ue=/\w*$/,he=/^[-+]0x[0-9a-f]+$/i,de=/^0b[01]+$/i,pe=/^\[object .+?Constructor\]$/,fe=/^0o[0-7]+$/i,ge=/^(?:0|[1-9]\d*)$/,me=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,ye=/($^)/,be=/['\n\r\u2028\u2029\\]/g,we="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",ve="\\u2700-\\u27bf",Ee="a-z\\xdf-\\xf6\\xf8-\\xff",Se="A-Z\\xc0-\\xd6\\xd8-\\xde",Ae="\\ufe0e\\ufe0f",Ie="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",_e="["+Ie+"]",Ce="["+we+"]",xe="\\d+",ke="["+ve+"]",Te="["+Ee+"]",Pe="[^\ud800-\udfff"+Ie+xe+ve+Ee+Se+"]",Re="\ud83c[\udffb-\udfff]",Le="[^\ud800-\udfff]",De="(?:\ud83c[\udde6-\uddff]){2}",Me="[\ud800-\udbff][\udc00-\udfff]",Ne="["+Se+"]",Oe="\\u200d",Ue="(?:"+Te+"|"+Pe+")",Fe="(?:"+Ne+"|"+Pe+")",Be="(?:['’](?:d|ll|m|re|s|t|ve))?",$e="(?:['’](?:D|LL|M|RE|S|T|VE))?",qe="(?:"+Ce+"|"+Re+")?",ze="["+Ae+"]?",je=ze+qe+"(?:"+Oe+"(?:"+[Le,De,Me].join("|")+")"+ze+qe+")*",Ke="(?:"+[ke,De,Me].join("|")+")"+je,Ve="(?:"+[Le+Ce+"?",Ce,De,Me,"[\ud800-\udfff]"].join("|")+")",He=RegExp("['’]","g"),Ge=RegExp(Ce,"g"),We=RegExp(Re+"(?="+Re+")|"+Ve+je,"g"),Xe=RegExp([Ne+"?"+Te+"+"+Be+"(?="+[_e,Ne,"$"].join("|")+")",Fe+"+"+$e+"(?="+[_e,Ne+Ue,"$"].join("|")+")",Ne+"?"+Ue+"+"+Be,Ne+"+"+$e,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])|\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",xe,Ke].join("|"),"g"),Ze=RegExp("["+Oe+"\ud800-\udfff"+we+Ae+"]"),Ye=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Qe=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Je=-1,et={};et[R]=et[L]=et[D]=et[M]=et[N]=et[O]=et[U]=et[F]=et[B]=!0,et[p]=et[f]=et[T]=et[g]=et[P]=et[m]=et[y]=et[b]=et[v]=et[E]=et[S]=et[I]=et[_]=et[C]=et[k]=!1;var tt={};tt[p]=tt[f]=tt[T]=tt[P]=tt[g]=tt[m]=tt[R]=tt[L]=tt[D]=tt[M]=tt[N]=tt[v]=tt[E]=tt[S]=tt[I]=tt[_]=tt[C]=tt[x]=tt[O]=tt[U]=tt[F]=tt[B]=!0,tt[y]=tt[b]=tt[k]=!1;var rt={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},nt=parseFloat,st=parseInt,it="object"==typeof ns&&ns&&ns.Object===Object&&ns,ot="object"==typeof self&&self&&self.Object===Object&&self,at=it||ot||Function("return this")(),ct=t&&!t.nodeType&&t,lt=ct&&e&&!e.nodeType&&e,ut=lt&&lt.exports===ct,ht=ut&&it.process,dt=(()=>{try{return lt&&lt.require&&lt.require("util").types||ht&&ht.binding&&ht.binding("util")}catch(e){}})(),pt=dt&&dt.isArrayBuffer,ft=dt&&dt.isDate,gt=dt&&dt.isMap,mt=dt&&dt.isRegExp,yt=dt&&dt.isSet,bt=dt&&dt.isTypedArray;function wt(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}function vt(e,t,r,n){for(var s=-1,i=null==e?0:e.length;++s<i;){var o=e[s];t(n,o,r(o),e)}return n}function Et(e,t){for(var r=-1,n=null==e?0:e.length;++r<n&&!1!==t(e[r],r,e););return e}function St(e,t){for(var r=null==e?0:e.length;r--&&!1!==t(e[r],r,e););return e}function At(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(!t(e[r],r,e))return!1;return!0}function It(e,t){for(var r=-1,n=null==e?0:e.length,s=0,i=[];++r<n;){var o=e[r];t(o,r,e)&&(i[s++]=o)}return i}function _t(e,t){return!(null==e||!e.length)&&Nt(e,t,0)>-1}function Ct(e,t,r){for(var n=-1,s=null==e?0:e.length;++n<s;)if(r(t,e[n]))return!0;return!1}function xt(e,t){for(var r=-1,n=null==e?0:e.length,s=Array(n);++r<n;)s[r]=t(e[r],r,e);return s}function kt(e,t){for(var r=-1,n=t.length,s=e.length;++r<n;)e[s+r]=t[r];return e}function Tt(e,t,r,n){var s=-1,i=null==e?0:e.length;for(n&&i&&(r=e[++s]);++s<i;)r=t(r,e[s],s,e);return r}function Pt(e,t,r,n){var s=null==e?0:e.length;for(n&&s&&(r=e[--s]);s--;)r=t(r,e[s],s,e);return r}function Rt(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}var Lt=Bt("length");function Dt(e,t,r){var n;return r(e,((e,r,s)=>{if(t(e,r,s))return n=r,!1})),n}function Mt(e,t,r,n){for(var s=e.length,i=r+(n?1:-1);n?i--:++i<s;)if(t(e[i],i,e))return i;return-1}function Nt(e,t,r){return t==t?((e,t,r)=>{for(var n=r-1,s=e.length;++n<s;)if(e[n]===t)return n;return-1})(e,t,r):Mt(e,Ut,r)}function Ot(e,t,r,n){for(var s=r-1,i=e.length;++s<i;)if(n(e[s],t))return s;return-1}function Ut(e){return e!=e}function Ft(e,t){var r=null==e?0:e.length;return r?zt(e,t)/r:u}function Bt(e){return t=>null==t?r:t[e]}function $t(e){return t=>null==e?r:e[t]}function qt(e,t,r,n,s){return s(e,((e,s,i)=>{r=n?(n=!1,e):t(r,e,s,i)})),r}function zt(e,t){for(var n,s=-1,i=e.length;++s<i;){var o=t(e[s]);o!==r&&(n=n===r?o:n+o)}return n}function jt(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}function Kt(e){return e?e.slice(0,or(e)+1).replace(te,""):e}function Vt(e){return t=>e(t)}function Ht(e,t){return xt(t,(t=>e[t]))}function Gt(e,t){return e.has(t)}function Wt(e,t){for(var r=-1,n=e.length;++r<n&&Nt(t,e[r],0)>-1;);return r}function Xt(e,t){for(var r=e.length;r--&&Nt(t,e[r],0)>-1;);return r}var Zt=$t({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),Yt=$t({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"});function Qt(e){return"\\"+rt[e]}function Jt(e){return Ze.test(e)}function er(e){var t=-1,r=Array(e.size);return e.forEach(((e,n)=>{r[++t]=[n,e]})),r}function tr(e,t){return r=>e(t(r))}function rr(e,t){for(var r=-1,n=e.length,s=0,o=[];++r<n;){var a=e[r];a!==t&&a!==i||(e[r]=i,o[s++]=r)}return o}function nr(e){var t=-1,r=Array(e.size);return e.forEach((e=>{r[++t]=e})),r}function sr(e){return Jt(e)?(e=>{for(var t=We.lastIndex=0;We.test(e);)++t;return t})(e):Lt(e)}function ir(e){return Jt(e)?(e=>e.match(We)||[])(e):(e=>e.split(""))(e)}function or(e){for(var t=e.length;t--&&re.test(e.charAt(t)););return t}var ar=$t({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"}),cr=function e(t){var re,we=(t=null==t?at:cr.defaults(at.Object(),t,cr.pick(at,Qe))).Array,ve=t.Date,Ee=t.Error,Se=t.Function,Ae=t.Math,Ie=t.Object,_e=t.RegExp,Ce=t.String,xe=t.TypeError,ke=we.prototype,Te=Se.prototype,Pe=Ie.prototype,Re=t["__core-js_shared__"],Le=Te.toString,De=Pe.hasOwnProperty,Me=0,Ne=(re=/[^.]+$/.exec(Re&&Re.keys&&Re.keys.IE_PROTO||""))?"Symbol(src)_1."+re:"",Oe=Pe.toString,Ue=Le.call(Ie),Fe=at._,Be=_e("^"+Le.call(De).replace(J,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),$e=ut?t.Buffer:r,qe=t.Symbol,ze=t.Uint8Array,je=$e?$e.allocUnsafe:r,Ke=tr(Ie.getPrototypeOf,Ie),Ve=Ie.create,We=Pe.propertyIsEnumerable,Ze=ke.splice,rt=qe?qe.isConcatSpreadable:r,it=qe?qe.iterator:r,ot=qe?qe.toStringTag:r,ct=(()=>{try{var e=ai(Ie,"defineProperty");return e({},"",{}),e}catch(e){}})(),lt=t.clearTimeout!==at.clearTimeout&&t.clearTimeout,ht=ve&&ve.now!==at.Date.now&&ve.now,dt=t.setTimeout!==at.setTimeout&&t.setTimeout,Lt=Ae.ceil,$t=Ae.floor,lr=Ie.getOwnPropertySymbols,ur=$e?$e.isBuffer:r,hr=t.isFinite,dr=ke.join,pr=tr(Ie.keys,Ie),fr=Ae.max,gr=Ae.min,mr=ve.now,yr=t.parseInt,br=Ae.random,wr=ke.reverse,vr=ai(t,"DataView"),Er=ai(t,"Map"),Sr=ai(t,"Promise"),Ar=ai(t,"Set"),Ir=ai(t,"WeakMap"),_r=ai(Ie,"create"),Cr=Ir&&new Ir,xr={},kr=Di(vr),Tr=Di(Er),Pr=Di(Sr),Rr=Di(Ar),Lr=Di(Ir),Dr=qe?qe.prototype:r,Mr=Dr?Dr.valueOf:r,Nr=Dr?Dr.toString:r;function Or(e){if(Yo(e)&&!$o(e)&&!(e instanceof $r)){if(e instanceof Br)return e;if(De.call(e,"__wrapped__"))return Mi(e)}return new Br(e)}var Ur=(()=>{function e(){}return t=>{if(!Zo(t))return{};if(Ve)return Ve(t);e.prototype=t;var n=new e;return e.prototype=r,n}})();function Fr(){}function Br(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=r}function $r(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=h,this.__views__=[]}function qr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function zr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function jr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Kr(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new jr;++t<r;)this.add(e[t])}function Vr(e){var t=this.__data__=new zr(e);this.size=t.size}function Hr(e,t){var r=$o(e),n=!r&&Bo(e),s=!r&&!n&&Ko(e),i=!r&&!n&&!s&&ia(e),o=r||n||s||i,a=o?jt(e.length,Ce):[],c=a.length;for(var l in e)!t&&!De.call(e,l)||o&&("length"==l||s&&("offset"==l||"parent"==l)||i&&("buffer"==l||"byteLength"==l||"byteOffset"==l)||fi(l,c))||a.push(l);return a}function Gr(e){var t=e.length;return t?e[Kn(0,t-1)]:r}function Wr(e,t){return Pi(_s(e),nn(t,0,e.length))}function Xr(e){return Pi(_s(e))}function Zr(e,t,n){(n!==r&&!Oo(e[t],n)||n===r&&!(t in e))&&tn(e,t,n)}function Yr(e,t,n){var s=e[t];De.call(e,t)&&Oo(s,n)&&(n!==r||t in e)||tn(e,t,n)}function Qr(e,t){for(var r=e.length;r--;)if(Oo(e[r][0],t))return r;return-1}function Jr(e,t,r,n){return ln(e,((e,s,i)=>{t(n,e,r(e),i)})),n}function en(e,t){return e&&Cs(t,xa(t),e)}function tn(e,t,r){"__proto__"==t&&ct?ct(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}function rn(e,t){for(var n=-1,s=t.length,i=we(s),o=null==e;++n<s;)i[n]=o?r:Sa(e,t[n]);return i}function nn(e,t,n){return e==e&&(n!==r&&(e=e<=n?e:n),t!==r&&(e=e>=t?e:t)),e}function sn(e,t,n,s,i,o){var a,c=1&t,l=2&t,u=4&t;if(n&&(a=i?n(e,s,i,o):n(e)),a!==r)return a;if(!Zo(e))return e;var h=$o(e);if(h){if(a=(e=>{var t=e.length,r=new e.constructor(t);return t&&"string"==typeof e[0]&&De.call(e,"index")&&(r.index=e.index,r.input=e.input),r})(e),!c)return _s(e,a)}else{var d=ui(e),f=d==b||d==w;if(Ko(e))return ws(e,c);if(d==S||d==p||f&&!i){if(a=l||f?{}:di(e),!c)return l?((e,t)=>Cs(e,li(e),t))(e,((e,t)=>e&&Cs(t,ka(t),e))(a,e)):((e,t)=>Cs(e,ci(e),t))(e,en(a,e))}else{if(!tt[d])return i?e:{};a=((e,t,r)=>{var n=e.constructor;switch(t){case T:return vs(e);case g:case m:return new n(+e);case P:return((e,t)=>{var r=t?vs(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)})(e,r);case R:case L:case D:case M:case N:case O:case U:case F:case B:return Es(e,r);case v:return new n;case E:case C:return new n(e);case I:return(e=>{var t=new e.constructor(e.source,ue.exec(e));return t.lastIndex=e.lastIndex,t})(e);case _:return new n;case x:return(e=>Mr?Ie(Mr.call(e)):{})(e)}})(e,d,c)}}o||(o=new Vr);var y=o.get(e);if(y)return y;o.set(e,a),ra(e)?e.forEach((r=>{a.add(sn(r,t,n,r,e,o))})):Qo(e)&&e.forEach(((r,s)=>{a.set(s,sn(r,t,n,s,e,o))}));var A=h?r:(u?l?ei:Js:l?ka:xa)(e);return Et(A||e,((r,s)=>{A&&(r=e[s=r]),Yr(a,s,sn(r,t,n,s,e,o))})),a}function on(e,t,n){var s=n.length;if(null==e)return!s;for(e=Ie(e);s--;){var i=n[s],o=t[i],a=e[i];if(a===r&&!(i in e)||!o(a))return!1}return!0}function an(e,t,s){if("function"!=typeof e)throw new xe(n);return Ci((()=>{e.apply(r,s)}),t)}function cn(e,t,r,n){var s=-1,i=_t,o=!0,a=e.length,c=[],l=t.length;if(!a)return c;r&&(t=xt(t,Vt(r))),n?(i=Ct,o=!1):t.length>=200&&(i=Gt,o=!1,t=new Kr(t));e:for(;++s<a;){var u=e[s],h=null==r?u:r(u);if(u=n||0!==u?u:0,o&&h==h){for(var d=l;d--;)if(t[d]===h)continue e;c.push(u)}else i(t,h,n)||c.push(u)}return c}Or.templateSettings={escape:G,evaluate:W,interpolate:X,variable:"",imports:{_:Or}},Or.prototype=Fr.prototype,Or.prototype.constructor=Or,Br.prototype=Ur(Fr.prototype),Br.prototype.constructor=Br,$r.prototype=Ur(Fr.prototype),$r.prototype.constructor=$r,qr.prototype.clear=function(){this.__data__=_r?_r(null):{},this.size=0},qr.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},qr.prototype.get=function(e){var t=this.__data__;if(_r){var n=t[e];return n===s?r:n}return De.call(t,e)?t[e]:r},qr.prototype.has=function(e){var t=this.__data__;return _r?t[e]!==r:De.call(t,e)},qr.prototype.set=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=_r&&t===r?s:t,this},zr.prototype.clear=function(){this.__data__=[],this.size=0},zr.prototype.delete=function(e){var t=this.__data__,r=Qr(t,e);return!(r<0||(r==t.length-1?t.pop():Ze.call(t,r,1),--this.size,0))},zr.prototype.get=function(e){var t=this.__data__,n=Qr(t,e);return n<0?r:t[n][1]},zr.prototype.has=function(e){return Qr(this.__data__,e)>-1},zr.prototype.set=function(e,t){var r=this.__data__,n=Qr(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this},jr.prototype.clear=function(){this.size=0,this.__data__={hash:new qr,map:new(Er||zr),string:new qr}},jr.prototype.delete=function(e){var t=ii(this,e).delete(e);return this.size-=t?1:0,t},jr.prototype.get=function(e){return ii(this,e).get(e)},jr.prototype.has=function(e){return ii(this,e).has(e)},jr.prototype.set=function(e,t){var r=ii(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this},Kr.prototype.add=Kr.prototype.push=function(e){return this.__data__.set(e,s),this},Kr.prototype.has=function(e){return this.__data__.has(e)},Vr.prototype.clear=function(){this.__data__=new zr,this.size=0},Vr.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},Vr.prototype.get=function(e){return this.__data__.get(e)},Vr.prototype.has=function(e){return this.__data__.has(e)},Vr.prototype.set=function(e,t){var r=this.__data__;if(r instanceof zr){var n=r.__data__;if(!Er||n.length<199)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new jr(n)}return r.set(e,t),this.size=r.size,this};var ln=Ts(yn),un=Ts(bn,!0);function hn(e,t){var r=!0;return ln(e,((e,n,s)=>r=!!t(e,n,s))),r}function dn(e,t,n){for(var s=-1,i=e.length;++s<i;){var o=e[s],a=t(o);if(null!=a&&(c===r?a==a&&!sa(a):n(a,c)))var c=a,l=o}return l}function pn(e,t){var r=[];return ln(e,((e,n,s)=>{t(e,n,s)&&r.push(e)})),r}function fn(e,t,r,n,s){var i=-1,o=e.length;for(r||(r=pi),s||(s=[]);++i<o;){var a=e[i];t>0&&r(a)?t>1?fn(a,t-1,r,n,s):kt(s,a):n||(s[s.length]=a)}return s}var gn=Ps(),mn=Ps(!0);function yn(e,t){return e&&gn(e,t,xa)}function bn(e,t){return e&&mn(e,t,xa)}function wn(e,t){return It(t,(t=>Go(e[t])))}function vn(e,t){for(var n=0,s=(t=gs(t,e)).length;null!=e&&n<s;)e=e[Li(t[n++])];return n&&n==s?e:r}function En(e,t,r){var n=t(e);return $o(e)?n:kt(n,r(e))}function Sn(e){return null==e?e===r?"[object Undefined]":"[object Null]":ot&&ot in Ie(e)?(e=>{var t=De.call(e,ot),n=e[ot];try{e[ot]=r;var s=!0}catch(e){}var i=Oe.call(e);return s&&(t?e[ot]=n:delete e[ot]),i})(e):(e=>Oe.call(e))(e)}function An(e,t){return e>t}function In(e,t){return null!=e&&De.call(e,t)}function _n(e,t){return null!=e&&t in Ie(e)}function Cn(e,t,n){for(var s=n?Ct:_t,i=e[0].length,o=e.length,a=o,c=we(o),l=1/0,u=[];a--;){var h=e[a];a&&t&&(h=xt(h,Vt(t))),l=gr(h.length,l),c[a]=!n&&(t||i>=120&&h.length>=120)?new Kr(a&&h):r}h=e[0];var d=-1,p=c[0];e:for(;++d<i&&u.length<l;){var f=h[d],g=t?t(f):f;if(f=n||0!==f?f:0,!(p?Gt(p,g):s(u,g,n))){for(a=o;--a;){var m=c[a];if(!(m?Gt(m,g):s(e[a],g,n)))continue e}p&&p.push(g),u.push(f)}}return u}function xn(e,t,n){var s=null==(e=Ai(e,t=gs(t,e)))?e:e[Li(Vi(t))];return null==s?r:wt(s,e,n)}function kn(e){return Yo(e)&&Sn(e)==p}function Tn(e,t,n,s,i){return e===t||(null==e||null==t||!Yo(e)&&!Yo(t)?e!=e&&t!=t:((e,t,n,s,i,o)=>{var a=$o(e),c=$o(t),l=a?f:ui(e),u=c?f:ui(t),h=(l=l==p?S:l)==S,d=(u=u==p?S:u)==S,b=l==u;if(b&&Ko(e)){if(!Ko(t))return!1;a=!0,h=!1}if(b&&!h)return o||(o=new Vr),a||ia(e)?Ys(e,t,n,s,i,o):((e,t,r,n,s,i,o)=>{switch(r){case P:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case T:return!(e.byteLength!=t.byteLength||!i(new ze(e),new ze(t)));case g:case m:case E:return Oo(+e,+t);case y:return e.name==t.name&&e.message==t.message;case I:case C:return e==t+"";case v:var a=er;case _:var c=1&n;if(a||(a=nr),e.size!=t.size&&!c)return!1;var l=o.get(e);if(l)return l==t;n|=2,o.set(e,t);var u=Ys(a(e),a(t),n,s,i,o);return o.delete(e),u;case x:if(Mr)return Mr.call(e)==Mr.call(t)}return!1})(e,t,l,n,s,i,o);if(!(1&n)){var w=h&&De.call(e,"__wrapped__"),A=d&&De.call(t,"__wrapped__");if(w||A){var k=w?e.value():e,R=A?t.value():t;return o||(o=new Vr),i(k,R,n,s,o)}}return!!b&&(o||(o=new Vr),((e,t,n,s,i,o)=>{var a=1&n,c=Js(e),l=c.length;if(l!=Js(t).length&&!a)return!1;for(var u=l;u--;){var h=c[u];if(!(a?h in t:De.call(t,h)))return!1}var d=o.get(e),p=o.get(t);if(d&&p)return d==t&&p==e;var f=!0;o.set(e,t),o.set(t,e);for(var g=a;++u<l;){var m=e[h=c[u]],y=t[h];if(s)var b=a?s(y,m,h,t,e,o):s(m,y,h,e,t,o);if(!(b===r?m===y||i(m,y,n,s,o):b)){f=!1;break}g||(g="constructor"==h)}if(f&&!g){var w=e.constructor,v=t.constructor;w==v||!("constructor"in e)||!("constructor"in t)||"function"==typeof w&&w instanceof w&&"function"==typeof v&&v instanceof v||(f=!1)}return o.delete(e),o.delete(t),f})(e,t,n,s,i,o))})(e,t,n,s,Tn,i))}function Pn(e,t,n,s){var i=n.length,o=i,a=!s;if(null==e)return!o;for(e=Ie(e);i--;){var c=n[i];if(a&&c[2]?c[1]!==e[c[0]]:!(c[0]in e))return!1}for(;++i<o;){var l=(c=n[i])[0],u=e[l],h=c[1];if(a&&c[2]){if(u===r&&!(l in e))return!1}else{var d=new Vr;if(s)var p=s(u,h,l,e,t,d);if(!(p===r?Tn(h,u,3,s,d):p))return!1}}return!0}function Rn(e){return!(!Zo(e)||(e=>!!Ne&&Ne in e)(e))&&(Go(e)?Be:pe).test(Di(e))}function Ln(e){return"function"==typeof e?e:null==e?Ja:"object"==typeof e?$o(e)?Un(e[0],e[1]):On(e):cc(e)}function Dn(e){if(!wi(e))return pr(e);var t=[];for(var r in Ie(e))De.call(e,r)&&"constructor"!=r&&t.push(r);return t}function Mn(e,t){return e<t}function Nn(e,t){var r=-1,n=zo(e)?we(e.length):[];return ln(e,((e,s,i)=>{n[++r]=t(e,s,i)})),n}function On(e){var t=oi(e);return 1==t.length&&t[0][2]?Ei(t[0][0],t[0][1]):r=>r===e||Pn(r,e,t)}function Un(e,t){return mi(e)&&vi(t)?Ei(Li(e),t):n=>{var s=Sa(n,e);return s===r&&s===t?Aa(n,e):Tn(t,s,3)}}function Fn(e,t,n,s,i){e!==t&&gn(t,((o,a)=>{if(i||(i=new Vr),Zo(o))((e,t,n,s,i,o,a)=>{var c=Ii(e,n),l=Ii(t,n),u=a.get(l);if(u)Zr(e,n,u);else{var h=o?o(c,l,n+"",e,t,a):r,d=h===r;if(d){var p=$o(l),f=!p&&Ko(l),g=!p&&!f&&ia(l);h=l,p||f||g?$o(c)?h=c:jo(c)?h=_s(c):f?(d=!1,h=ws(l,!0)):g?(d=!1,h=Es(l,!0)):h=[]:ea(l)||Bo(l)?(h=c,Bo(c)?h=pa(c):Zo(c)&&!Go(c)||(h=di(l))):d=!1}d&&(a.set(l,h),i(h,l,s,o,a),a.delete(l)),Zr(e,n,h)}})(e,t,a,n,Fn,s,i);else{var c=s?s(Ii(e,a),o,a+"",e,t,i):r;c===r&&(c=o),Zr(e,a,c)}}),ka)}function Bn(e,t){var n=e.length;if(n)return fi(t+=t<0?n:0,n)?e[t]:r}function $n(e,t,r){t=t.length?xt(t,(e=>$o(e)?t=>vn(t,1===e.length?e[0]:e):e)):[Ja];var n=-1;t=xt(t,Vt(si()));var s=Nn(e,(e=>{var r=xt(t,(t=>t(e)));return{criteria:r,index:++n,value:e}}));return((e,t)=>{var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e})(s,((e,t)=>((e,t,r)=>{for(var n=-1,s=e.criteria,i=t.criteria,o=s.length,a=r.length;++n<o;){var c=Ss(s[n],i[n]);if(c)return n>=a?c:c*("desc"==r[n]?-1:1)}return e.index-t.index})(e,t,r)))}function qn(e,t,r){for(var n=-1,s=t.length,i={};++n<s;){var o=t[n],a=vn(e,o);r(a,o)&&Xn(i,gs(o,e),a)}return i}function zn(e,t,r,n){var s=n?Ot:Nt,i=-1,o=t.length,a=e;for(e===t&&(t=_s(t)),r&&(a=xt(e,Vt(r)));++i<o;)for(var c=0,l=t[i],u=r?r(l):l;(c=s(a,u,c,n))>-1;)a!==e&&Ze.call(a,c,1),Ze.call(e,c,1);return e}function jn(e,t){for(var r=e?t.length:0,n=r-1;r--;){var s=t[r];if(r==n||s!==i){var i=s;fi(s)?Ze.call(e,s,1):as(e,s)}}return e}function Kn(e,t){return e+$t(br()*(t-e+1))}function Vn(e,t){var r="";if(!e||t<1||t>l)return r;do{t%2&&(r+=e),(t=$t(t/2))&&(e+=e)}while(t);return r}function Hn(e,t){return xi(Si(e,t,Ja),e+"")}function Gn(e){return Gr(Oa(e))}function Wn(e,t){var r=Oa(e);return Pi(r,nn(t,0,r.length))}function Xn(e,t,n,s){if(!Zo(e))return e;for(var i=-1,o=(t=gs(t,e)).length,a=o-1,c=e;null!=c&&++i<o;){var l=Li(t[i]),u=n;if("__proto__"===l||"constructor"===l||"prototype"===l)return e;if(i!=a){var h=c[l];(u=s?s(h,l,c):r)===r&&(u=Zo(h)?h:fi(t[i+1])?[]:{})}Yr(c,l,u),c=c[l]}return e}var Zn=Cr?(e,t)=>(Cr.set(e,t),e):Ja,Yn=ct?(e,t)=>ct(e,"toString",{configurable:!0,enumerable:!1,value:Za(t),writable:!0}):Ja;function Qn(e){return Pi(Oa(e))}function Jn(e,t,r){var n=-1,s=e.length;t<0&&(t=-t>s?0:s+t),(r=r>s?s:r)<0&&(r+=s),s=t>r?0:r-t>>>0,t>>>=0;for(var i=we(s);++n<s;)i[n]=e[n+t];return i}function es(e,t){var r;return ln(e,((e,n,s)=>!(r=t(e,n,s)))),!!r}function ts(e,t,r){var n=0,s=null==e?n:e.length;if("number"==typeof t&&t==t&&s<=2147483647){for(;n<s;){var i=n+s>>>1,o=e[i];null!==o&&!sa(o)&&(r?o<=t:o<t)?n=i+1:s=i}return s}return rs(e,t,Ja,r)}function rs(e,t,n,s){var i=0,o=null==e?0:e.length;if(0===o)return 0;for(var a=(t=n(t))!=t,c=null===t,l=sa(t),u=t===r;i<o;){var h=$t((i+o)/2),d=n(e[h]),p=d!==r,f=null===d,g=d==d,m=sa(d);if(a)var y=s||g;else y=u?g&&(s||p):c?g&&p&&(s||!f):l?g&&p&&!f&&(s||!m):!f&&!m&&(s?d<=t:d<t);y?i=h+1:o=h}return gr(o,4294967294)}function ns(e,t){for(var r=-1,n=e.length,s=0,i=[];++r<n;){var o=e[r],a=t?t(o):o;if(!r||!Oo(a,c)){var c=a;i[s++]=0===o?0:o}}return i}function ss(e){return"number"==typeof e?e:sa(e)?u:+e}function is(e){if("string"==typeof e)return e;if($o(e))return xt(e,is)+"";if(sa(e))return Nr?Nr.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function os(e,t,r){var n=-1,s=_t,i=e.length,o=!0,a=[],c=a;if(r)o=!1,s=Ct;else if(i>=200){var l=t?null:Vs(e);if(l)return nr(l);o=!1,s=Gt,c=new Kr}else c=t?[]:a;e:for(;++n<i;){var u=e[n],h=t?t(u):u;if(u=r||0!==u?u:0,o&&h==h){for(var d=c.length;d--;)if(c[d]===h)continue e;t&&c.push(h),a.push(u)}else s(c,h,r)||(c!==a&&c.push(h),a.push(u))}return a}function as(e,t){return null==(e=Ai(e,t=gs(t,e)))||delete e[Li(Vi(t))]}function cs(e,t,r,n){return Xn(e,t,r(vn(e,t)),n)}function ls(e,t,r,n){for(var s=e.length,i=n?s:-1;(n?i--:++i<s)&&t(e[i],i,e););return r?Jn(e,n?0:i,n?i+1:s):Jn(e,n?i+1:0,n?s:i)}function us(e,t){var r=e;return r instanceof $r&&(r=r.value()),Tt(t,((e,t)=>t.func.apply(t.thisArg,kt([e],t.args))),r)}function hs(e,t,r){var n=e.length;if(n<2)return n?os(e[0]):[];for(var s=-1,i=we(n);++s<n;)for(var o=e[s],a=-1;++a<n;)a!=s&&(i[s]=cn(i[s]||o,e[a],t,r));return os(fn(i,1),t,r)}function ds(e,t,n){for(var s=-1,i=e.length,o=t.length,a={};++s<i;){var c=s<o?t[s]:r;n(a,e[s],c)}return a}function ps(e){return jo(e)?e:[]}function fs(e){return"function"==typeof e?e:Ja}function gs(e,t){return $o(e)?e:mi(e,t)?[e]:Ri(fa(e))}var ms=Hn;function ys(e,t,n){var s=e.length;return n=n===r?s:n,!t&&n>=s?e:Jn(e,t,n)}var bs=lt||(e=>at.clearTimeout(e));function ws(e,t){if(t)return e.slice();var r=e.length,n=je?je(r):new e.constructor(r);return e.copy(n),n}function vs(e){var t=new e.constructor(e.byteLength);return new ze(t).set(new ze(e)),t}function Es(e,t){var r=t?vs(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}function Ss(e,t){if(e!==t){var n=e!==r,s=null===e,i=e==e,o=sa(e),a=t!==r,c=null===t,l=t==t,u=sa(t);if(!c&&!u&&!o&&e>t||o&&a&&l&&!c&&!u||s&&a&&l||!n&&l||!i)return 1;if(!s&&!o&&!u&&e<t||u&&n&&i&&!s&&!o||c&&n&&i||!a&&i||!l)return-1}return 0}function As(e,t,r,n){for(var s=-1,i=e.length,o=r.length,a=-1,c=t.length,l=fr(i-o,0),u=we(c+l),h=!n;++a<c;)u[a]=t[a];for(;++s<o;)(h||s<i)&&(u[r[s]]=e[s]);for(;l--;)u[a++]=e[s++];return u}function Is(e,t,r,n){for(var s=-1,i=e.length,o=-1,a=r.length,c=-1,l=t.length,u=fr(i-a,0),h=we(u+l),d=!n;++s<u;)h[s]=e[s];for(var p=s;++c<l;)h[p+c]=t[c];for(;++o<a;)(d||s<i)&&(h[p+r[o]]=e[s++]);return h}function _s(e,t){var r=-1,n=e.length;for(t||(t=we(n));++r<n;)t[r]=e[r];return t}function Cs(e,t,n,s){var i=!n;n||(n={});for(var o=-1,a=t.length;++o<a;){var c=t[o],l=s?s(n[c],e[c],c,n,e):r;l===r&&(l=e[c]),i?tn(n,c,l):Yr(n,c,l)}return n}function xs(e,t){return(r,n)=>{var s=$o(r)?vt:Jr,i=t?t():{};return s(r,e,si(n,2),i)}}function ks(e){return Hn(((t,n)=>{var s=-1,i=n.length,o=i>1?n[i-1]:r,a=i>2?n[2]:r;for(o=e.length>3&&"function"==typeof o?(i--,o):r,a&&gi(n[0],n[1],a)&&(o=i<3?r:o,i=1),t=Ie(t);++s<i;){var c=n[s];c&&e(t,c,s,o)}return t}))}function Ts(e,t){return(r,n)=>{if(null==r)return r;if(!zo(r))return e(r,n);for(var s=r.length,i=t?s:-1,o=Ie(r);(t?i--:++i<s)&&!1!==n(o[i],i,o););return r}}function Ps(e){return(t,r,n)=>{for(var s=-1,i=Ie(t),o=n(t),a=o.length;a--;){var c=o[e?a:++s];if(!1===r(i[c],c,i))break}return t}}function Rs(e){return t=>{var n=Jt(t=fa(t))?ir(t):r,s=n?n[0]:t.charAt(0),i=n?ys(n,1).join(""):t.slice(1);return s[e]()+i}}function Ls(e){return t=>Tt(Ga(Ba(t).replace(He,"")),e,"")}function Ds(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var r=Ur(e.prototype),n=e.apply(r,t);return Zo(n)?n:r}}function Ms(e){return(t,n,s)=>{var i=Ie(t);if(!zo(t)){var o=si(n,3);t=xa(t),n=e=>o(i[e],e,i)}var a=e(t,n,s);return a>-1?i[o?t[a]:a]:r}}function Ns(e){return Qs((function(t){var s=t.length,i=s,o=Br.prototype.thru;for(e&&t.reverse();i--;){var a=t[i];if("function"!=typeof a)throw new xe(n);if(o&&!c&&"wrapper"==ri(a))var c=new Br([],!0)}for(i=c?i:s;++i<s;){var l=ri(a=t[i]),u="wrapper"==l?ti(a):r;c=u&&yi(u[0])&&424==u[1]&&!u[4].length&&1==u[9]?c[ri(u[0])].apply(c,u[3]):1==a.length&&yi(a)?c[l]():c.thru(a)}return function(){var e=arguments,r=e[0];if(c&&1==e.length&&$o(r))return c.plant(r).value();for(var n=0,i=s?t[n].apply(this,e):r;++n<s;)i=t[n].call(this,i);return i}}))}function Os(e,t,n,s,i,o,c,l,u,h){var d=t&a,p=1&t,f=2&t,g=24&t,m=512&t,y=f?r:Ds(e);return function a(){for(var b=arguments.length,w=we(b),v=b;v--;)w[v]=arguments[v];if(g)var E=ni(a),S=((e,t)=>{for(var r=e.length,n=0;r--;)e[r]===t&&++n;return n})(w,E);if(s&&(w=As(w,s,i,g)),o&&(w=Is(w,o,c,g)),b-=S,g&&b<h){var A=rr(w,E);return js(e,t,Os,a.placeholder,n,w,A,l,u,h-b)}var I=p?n:this,_=f?I[e]:e;return b=w.length,l?w=((e,t)=>{for(var n=e.length,s=gr(t.length,n),i=_s(e);s--;){var o=t[s];e[s]=fi(o,n)?i[o]:r}return e})(w,l):m&&b>1&&w.reverse(),d&&u<b&&(w.length=u),this&&this!==at&&this instanceof a&&(_=y||Ds(_)),_.apply(I,w)}}function Us(e,t){return(r,n)=>((e,t,r,n)=>(yn(e,((e,s,i)=>{t(n,r(e),s,i)})),n))(r,e,t(n),{})}function Fs(e,t){return(n,s)=>{var i;if(n===r&&s===r)return t;if(n!==r&&(i=n),s!==r){if(i===r)return s;"string"==typeof n||"string"==typeof s?(n=is(n),s=is(s)):(n=ss(n),s=ss(s)),i=e(n,s)}return i}}function Bs(e){return Qs((function(t){return t=xt(t,Vt(si())),Hn((function(r){var n=this;return e(t,(e=>wt(e,n,r)))}))}))}function $s(e,t){var n=(t=t===r?" ":is(t)).length;if(n<2)return n?Vn(t,e):t;var s=Vn(t,Lt(e/sr(t)));return Jt(t)?ys(ir(s),0,e).join(""):s.slice(0,e)}function qs(e){return(t,n,s)=>(s&&"number"!=typeof s&&gi(t,n,s)&&(n=s=r),t=la(t),n===r?(n=t,t=0):n=la(n),((e,t,r,n)=>{for(var s=-1,i=fr(Lt((t-e)/(r||1)),0),o=we(i);i--;)o[n?i:++s]=e,e+=r;return o})(t,n,s=s===r?t<n?1:-1:la(s),e))}function zs(e){return(t,r)=>("string"==typeof t&&"string"==typeof r||(t=da(t),r=da(r)),e(t,r))}function js(e,t,n,s,i,a,c,l,u,h){var d=8&t;t|=d?o:64,4&(t&=~(d?64:o))||(t&=-4);var p=[e,t,i,d?a:r,d?c:r,d?r:a,d?r:c,l,u,h],f=n.apply(r,p);return yi(e)&&_i(f,p),f.placeholder=s,ki(f,e,t)}function Ks(e){var t=Ae[e];return(e,r)=>{if(e=da(e),(r=null==r?0:gr(ua(r),292))&&hr(e)){var n=(fa(e)+"e").split("e");return+((n=(fa(t(n[0]+"e"+(+n[1]+r)))+"e").split("e"))[0]+"e"+(+n[1]-r))}return t(e)}}var Vs=Ar&&1/nr(new Ar([,-0]))[1]==c?e=>new Ar(e):sc;function Hs(e){return t=>{var r=ui(t);return r==v?er(t):r==_?function(e){var t=-1,r=Array(e.size);return e.forEach((e=>{r[++t]=[e,e]})),r}(t):((e,t)=>xt(t,(t=>[t,e[t]])))(t,e(t))}}function Gs(e,t,s,c,l,u,h,d){var p=2&t;if(!p&&"function"!=typeof e)throw new xe(n);var f=c?c.length:0;if(f||(t&=-97,c=l=r),h=h===r?h:fr(ua(h),0),d=d===r?d:ua(d),f-=l?l.length:0,64&t){var g=c,m=l;c=l=r}var y=p?r:ti(e),b=[e,t,s,c,l,g,m,u,h,d];if(y&&((e,t)=>{var r=e[1],n=t[1],s=r|n,o=s<131,c=n==a&&8==r||n==a&&256==r&&e[7].length<=t[8]||384==n&&t[7].length<=t[8]&&8==r;if(!o&&!c)return e;1&n&&(e[2]=t[2],s|=1&r?0:4);var l=t[3];if(l){var u=e[3];e[3]=u?As(u,l,t[4]):l,e[4]=u?rr(e[3],i):t[4]}(l=t[5])&&(u=e[5],e[5]=u?Is(u,l,t[6]):l,e[6]=u?rr(e[5],i):t[6]),(l=t[7])&&(e[7]=l),n&a&&(e[8]=null==e[8]?t[8]:gr(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=s})(b,y),e=b[0],t=b[1],s=b[2],c=b[3],l=b[4],!(d=b[9]=b[9]===r?p?0:e.length:fr(b[9]-f,0))&&24&t&&(t&=-25),t&&1!=t)w=8==t||16==t?function(e,t,n){var s=Ds(e);return function i(){for(var o=arguments.length,a=we(o),c=o,l=ni(i);c--;)a[c]=arguments[c];var u=o<3&&a[0]!==l&&a[o-1]!==l?[]:rr(a,l);return(o-=u.length)<n?js(e,t,Os,i.placeholder,r,a,u,r,r,n-o):wt(this&&this!==at&&this instanceof i?s:e,this,a)}}(e,t,d):t!=o&&33!=t||l.length?Os.apply(r,b):function(e,t,r,n){var s=1&t,i=Ds(e);return function t(){for(var o=-1,a=arguments.length,c=-1,l=n.length,u=we(l+a),h=this&&this!==at&&this instanceof t?i:e;++c<l;)u[c]=n[c];for(;a--;)u[c++]=arguments[++o];return wt(h,s?r:this,u)}}(e,t,s,c);else var w=function(e,t,r){var n=1&t,s=Ds(e);return function t(){return(this&&this!==at&&this instanceof t?s:e).apply(n?r:this,arguments)}}(e,t,s);return ki((y?Zn:_i)(w,b),e,t)}function Ws(e,t,n,s){return e===r||Oo(e,Pe[n])&&!De.call(s,n)?t:e}function Xs(e,t,n,s,i,o){return Zo(e)&&Zo(t)&&(o.set(t,e),Fn(e,t,r,Xs,o),o.delete(t)),e}function Zs(e){return ea(e)?r:e}function Ys(e,t,n,s,i,o){var a=1&n,c=e.length,l=t.length;if(c!=l&&!(a&&l>c))return!1;var u=o.get(e),h=o.get(t);if(u&&h)return u==t&&h==e;var d=-1,p=!0,f=2&n?new Kr:r;for(o.set(e,t),o.set(t,e);++d<c;){var g=e[d],m=t[d];if(s)var y=a?s(m,g,d,t,e,o):s(g,m,d,e,t,o);if(y!==r){if(y)continue;p=!1;break}if(f){if(!Rt(t,((e,t)=>{if(!Gt(f,t)&&(g===e||i(g,e,n,s,o)))return f.push(t)}))){p=!1;break}}else if(g!==m&&!i(g,m,n,s,o)){p=!1;break}}return o.delete(e),o.delete(t),p}function Qs(e){return xi(Si(e,r,$i),e+"")}function Js(e){return En(e,xa,ci)}function ei(e){return En(e,ka,li)}var ti=Cr?e=>Cr.get(e):sc;function ri(e){for(var t=e.name+"",r=xr[t],n=De.call(xr,t)?r.length:0;n--;){var s=r[n],i=s.func;if(null==i||i==e)return s.name}return t}function ni(e){return(De.call(Or,"placeholder")?Or:e).placeholder}function si(){var e=Or.iteratee||ec;return e=e===ec?Ln:e,arguments.length?e(arguments[0],arguments[1]):e}function ii(e,t){var r,n,s=e.__data__;return("string"==(n=typeof(r=t))||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==r:null===r)?s["string"==typeof t?"string":"hash"]:s.map}function oi(e){for(var t=xa(e),r=t.length;r--;){var n=t[r],s=e[n];t[r]=[n,s,vi(s)]}return t}function ai(e,t){var n=((e,t)=>null==e?r:e[t])(e,t);return Rn(n)?n:r}var ci=lr?e=>null==e?[]:(e=Ie(e),It(lr(e),(t=>We.call(e,t)))):hc,li=lr?e=>{for(var t=[];e;)kt(t,ci(e)),e=Ke(e);return t}:hc,ui=Sn;function hi(e,t,r){for(var n=-1,s=(t=gs(t,e)).length,i=!1;++n<s;){var o=Li(t[n]);if(!(i=null!=e&&r(e,o)))break;e=e[o]}return i||++n!=s?i:!!(s=null==e?0:e.length)&&Xo(s)&&fi(o,s)&&($o(e)||Bo(e))}function di(e){return"function"!=typeof e.constructor||wi(e)?{}:Ur(Ke(e))}function pi(e){return $o(e)||Bo(e)||!!(rt&&e&&e[rt])}function fi(e,t){var r=typeof e;return!!(t=null==t?l:t)&&("number"==r||"symbol"!=r&&ge.test(e))&&e>-1&&e%1==0&&e<t}function gi(e,t,r){if(!Zo(r))return!1;var n=typeof t;return!!("number"==n?zo(r)&&fi(t,r.length):"string"==n&&t in r)&&Oo(r[t],e)}function mi(e,t){if($o(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!sa(e))||Y.test(e)||!Z.test(e)||null!=t&&e in Ie(t)}function yi(e){var t=ri(e),r=Or[t];if("function"!=typeof r||!(t in $r.prototype))return!1;if(e===r)return!0;var n=ti(r);return!!n&&e===n[0]}(vr&&ui(new vr(new ArrayBuffer(1)))!=P||Er&&ui(new Er)!=v||Sr&&ui(Sr.resolve())!=A||Ar&&ui(new Ar)!=_||Ir&&ui(new Ir)!=k)&&(ui=e=>{var t=Sn(e),n=t==S?e.constructor:r,s=n?Di(n):"";if(s)switch(s){case kr:return P;case Tr:return v;case Pr:return A;case Rr:return _;case Lr:return k}return t});var bi=Re?Go:dc;function wi(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Pe)}function vi(e){return e==e&&!Zo(e)}function Ei(e,t){return n=>null!=n&&n[e]===t&&(t!==r||e in Ie(n))}function Si(e,t,n){return t=fr(t===r?e.length-1:t,0),function(){for(var r=arguments,s=-1,i=fr(r.length-t,0),o=we(i);++s<i;)o[s]=r[t+s];s=-1;for(var a=we(t+1);++s<t;)a[s]=r[s];return a[t]=n(o),wt(e,this,a)}}function Ai(e,t){return t.length<2?e:vn(e,Jn(t,0,-1))}function Ii(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}var _i=Ti(Zn),Ci=dt||((e,t)=>at.setTimeout(e,t)),xi=Ti(Yn);function ki(e,t,r){var n=t+"";return xi(e,((e,t)=>{var r=t.length;if(!r)return e;var n=r-1;return t[n]=(r>1?"& ":"")+t[n],t=t.join(r>2?", ":" "),e.replace(ne,"{\n/* [wrapped with "+t+"] */\n")})(n,((e,t)=>(Et(d,(r=>{var n="_."+r[0];t&r[1]&&!_t(e,n)&&e.push(n)})),e.sort()))((e=>{var t=e.match(se);return t?t[1].split(ie):[]})(n),r)))}function Ti(e){var t=0,n=0;return function(){var s=mr(),i=16-(s-n);if(n=s,i>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(r,arguments)}}function Pi(e,t){var n=-1,s=e.length,i=s-1;for(t=t===r?s:t;++n<t;){var o=Kn(n,i),a=e[o];e[o]=e[n],e[n]=a}return e.length=t,e}var Ri=(e=>{var t=Po((e=>{var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(Q,((e,r,n,s)=>{t.push(n?s.replace(ce,"$1"):r||e)})),t}),(e=>(500===r.size&&r.clear(),e))),r=t.cache;return t})();function Li(e){if("string"==typeof e||sa(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function Di(e){if(null!=e){try{return Le.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Mi(e){if(e instanceof $r)return e.clone();var t=new Br(e.__wrapped__,e.__chain__);return t.__actions__=_s(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}var Ni=Hn(((e,t)=>jo(e)?cn(e,fn(t,1,jo,!0)):[])),Oi=Hn(((e,t)=>{var n=Vi(t);return jo(n)&&(n=r),jo(e)?cn(e,fn(t,1,jo,!0),si(n,2)):[]})),Ui=Hn(((e,t)=>{var n=Vi(t);return jo(n)&&(n=r),jo(e)?cn(e,fn(t,1,jo,!0),r,n):[]}));function Fi(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var s=null==r?0:ua(r);return s<0&&(s=fr(n+s,0)),Mt(e,si(t,3),s)}function Bi(e,t,n){var s=null==e?0:e.length;if(!s)return-1;var i=s-1;return n!==r&&(i=ua(n),i=n<0?fr(s+i,0):gr(i,s-1)),Mt(e,si(t,3),i,!0)}function $i(e){return null!=e&&e.length?fn(e,1):[]}function qi(e){return e&&e.length?e[0]:r}var zi=Hn((e=>{var t=xt(e,ps);return t.length&&t[0]===e[0]?Cn(t):[]})),ji=Hn((e=>{var t=Vi(e),n=xt(e,ps);return t===Vi(n)?t=r:n.pop(),n.length&&n[0]===e[0]?Cn(n,si(t,2)):[]})),Ki=Hn((e=>{var t=Vi(e),n=xt(e,ps);return(t="function"==typeof t?t:r)&&n.pop(),n.length&&n[0]===e[0]?Cn(n,r,t):[]}));function Vi(e){var t=null==e?0:e.length;return t?e[t-1]:r}var Hi=Hn(Gi);function Gi(e,t){return e&&e.length&&t&&t.length?zn(e,t):e}var Wi=Qs(((e,t)=>{var r=null==e?0:e.length,n=rn(e,t);return jn(e,xt(t,(e=>fi(e,r)?+e:e)).sort(Ss)),n}));function Xi(e){return null==e?e:wr.call(e)}var Zi=Hn((e=>os(fn(e,1,jo,!0)))),Yi=Hn((e=>{var t=Vi(e);return jo(t)&&(t=r),os(fn(e,1,jo,!0),si(t,2))})),Qi=Hn((e=>{var t=Vi(e);return t="function"==typeof t?t:r,os(fn(e,1,jo,!0),r,t)}));function Ji(e){if(!e||!e.length)return[];var t=0;return e=It(e,(e=>{if(jo(e))return t=fr(e.length,t),!0})),jt(t,(t=>xt(e,Bt(t))))}function eo(e,t){if(!e||!e.length)return[];var n=Ji(e);return null==t?n:xt(n,(e=>wt(t,r,e)))}var to=Hn(((e,t)=>jo(e)?cn(e,t):[])),ro=Hn((e=>hs(It(e,jo)))),no=Hn((e=>{var t=Vi(e);return jo(t)&&(t=r),hs(It(e,jo),si(t,2))})),so=Hn((e=>{var t=Vi(e);return t="function"==typeof t?t:r,hs(It(e,jo),r,t)})),io=Hn(Ji),oo=Hn((e=>{var t=e.length,n=t>1?e[t-1]:r;return n="function"==typeof n?(e.pop(),n):r,eo(e,n)}));function ao(e){var t=Or(e);return t.__chain__=!0,t}function co(e,t){return t(e)}var lo=Qs((function(e){var t=e.length,n=t?e[0]:0,s=this.__wrapped__,i=t=>rn(t,e);return!(t>1||this.__actions__.length)&&s instanceof $r&&fi(n)?((s=s.slice(n,+n+(t?1:0))).__actions__.push({func:co,args:[i],thisArg:r}),new Br(s,this.__chain__).thru((e=>(t&&!e.length&&e.push(r),e)))):this.thru(i)})),uo=xs(((e,t,r)=>{De.call(e,r)?++e[r]:tn(e,r,1)})),ho=Ms(Fi),po=Ms(Bi);function fo(e,t){return($o(e)?Et:ln)(e,si(t,3))}function go(e,t){return($o(e)?St:un)(e,si(t,3))}var mo=xs(((e,t,r)=>{De.call(e,r)?e[r].push(t):tn(e,r,[t])})),yo=Hn(((e,t,r)=>{var n=-1,s="function"==typeof t,i=zo(e)?we(e.length):[];return ln(e,(e=>{i[++n]=s?wt(t,e,r):xn(e,t,r)})),i})),bo=xs(((e,t,r)=>{tn(e,r,t)}));function wo(e,t){return($o(e)?xt:Nn)(e,si(t,3))}var vo=xs(((e,t,r)=>{e[r?0:1].push(t)}),(()=>[[],[]])),Eo=Hn(((e,t)=>{if(null==e)return[];var r=t.length;return r>1&&gi(e,t[0],t[1])?t=[]:r>2&&gi(t[0],t[1],t[2])&&(t=[t[0]]),$n(e,fn(t,1),[])})),So=ht||(()=>at.Date.now());function Ao(e,t,n){return t=n?r:t,t=e&&null==t?e.length:t,Gs(e,a,r,r,r,r,t)}function Io(e,t){var s;if("function"!=typeof t)throw new xe(n);return e=ua(e),function(){return--e>0&&(s=t.apply(this,arguments)),e<=1&&(t=r),s}}var _o=Hn(((e,t,r)=>{var n=1;if(r.length){var s=rr(r,ni(_o));n|=o}return Gs(e,n,t,r,s)})),Co=Hn(((e,t,r)=>{var n=3;if(r.length){var s=rr(r,ni(Co));n|=o}return Gs(t,n,e,r,s)}));function xo(e,t,s){var i,o,a,c,l,u,h=0,d=!1,p=!1,f=!0;if("function"!=typeof e)throw new xe(n);function g(t){var n=i,s=o;return i=o=r,h=t,c=e.apply(s,n)}function m(e){var n=e-u;return u===r||n>=t||n<0||p&&e-h>=a}function y(){var e=So();if(m(e))return b(e);l=Ci(y,(e=>{var r=t-(e-u);return p?gr(r,a-(e-h)):r})(e))}function b(e){return l=r,f&&i?g(e):(i=o=r,c)}function w(){var e=So(),n=m(e);if(i=arguments,o=this,u=e,n){if(l===r)return(e=>(h=e,l=Ci(y,t),d?g(e):c))(u);if(p)return bs(l),l=Ci(y,t),g(u)}return l===r&&(l=Ci(y,t)),c}return t=da(t)||0,Zo(s)&&(d=!!s.leading,a=(p="maxWait"in s)?fr(da(s.maxWait)||0,t):a,f="trailing"in s?!!s.trailing:f),w.cancel=()=>{l!==r&&bs(l),h=0,i=u=o=l=r},w.flush=()=>l===r?c:b(So()),w}var ko=Hn(((e,t)=>an(e,1,t))),To=Hn(((e,t,r)=>an(e,da(t)||0,r)));function Po(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new xe(n);var r=function(){var n=arguments,s=t?t.apply(this,n):n[0],i=r.cache;if(i.has(s))return i.get(s);var o=e.apply(this,n);return r.cache=i.set(s,o)||i,o};return r.cache=new(Po.Cache||jr),r}function Ro(e){if("function"!=typeof e)throw new xe(n);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}Po.Cache=jr;var Lo=ms((function(e,t){var r=(t=1==t.length&&$o(t[0])?xt(t[0],Vt(si())):xt(fn(t,1),Vt(si()))).length;return Hn((function(n){for(var s=-1,i=gr(n.length,r);++s<i;)n[s]=t[s].call(this,n[s]);return wt(e,this,n)}))})),Do=Hn(((e,t)=>{var n=rr(t,ni(Do));return Gs(e,o,r,t,n)})),Mo=Hn(((e,t)=>{var n=rr(t,ni(Mo));return Gs(e,64,r,t,n)})),No=Qs(((e,t)=>Gs(e,256,r,r,r,t)));function Oo(e,t){return e===t||e!=e&&t!=t}var Uo=zs(An),Fo=zs(((e,t)=>e>=t)),Bo=kn(function(){return arguments}())?kn:e=>Yo(e)&&De.call(e,"callee")&&!We.call(e,"callee"),$o=we.isArray,qo=pt?Vt(pt):e=>Yo(e)&&Sn(e)==T;function zo(e){return null!=e&&Xo(e.length)&&!Go(e)}function jo(e){return Yo(e)&&zo(e)}var Ko=ur||dc,Vo=ft?Vt(ft):e=>Yo(e)&&Sn(e)==m;function Ho(e){if(!Yo(e))return!1;var t=Sn(e);return t==y||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!ea(e)}function Go(e){if(!Zo(e))return!1;var t=Sn(e);return t==b||t==w||"[object AsyncFunction]"==t||"[object Proxy]"==t}function Wo(e){return"number"==typeof e&&e==ua(e)}function Xo(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=l}function Zo(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function Yo(e){return null!=e&&"object"==typeof e}var Qo=gt?Vt(gt):e=>Yo(e)&&ui(e)==v;function Jo(e){return"number"==typeof e||Yo(e)&&Sn(e)==E}function ea(e){if(!Yo(e)||Sn(e)!=S)return!1;var t=Ke(e);if(null===t)return!0;var r=De.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Le.call(r)==Ue}var ta=mt?Vt(mt):e=>Yo(e)&&Sn(e)==I,ra=yt?Vt(yt):e=>Yo(e)&&ui(e)==_;function na(e){return"string"==typeof e||!$o(e)&&Yo(e)&&Sn(e)==C}function sa(e){return"symbol"==typeof e||Yo(e)&&Sn(e)==x}var ia=bt?Vt(bt):e=>Yo(e)&&Xo(e.length)&&!!et[Sn(e)],oa=zs(Mn),aa=zs(((e,t)=>e<=t));function ca(e){if(!e)return[];if(zo(e))return na(e)?ir(e):_s(e);if(it&&e[it])return(e=>{for(var t,r=[];!(t=e.next()).done;)r.push(t.value);return r})(e[it]());var t=ui(e);return(t==v?er:t==_?nr:Oa)(e)}function la(e){return e?(e=da(e))===c||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}function ua(e){var t=la(e),r=t%1;return t==t?r?t-r:t:0}function ha(e){return e?nn(ua(e),0,h):0}function da(e){if("number"==typeof e)return e;if(sa(e))return u;if(Zo(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=Zo(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=Kt(e);var r=de.test(e);return r||fe.test(e)?st(e.slice(2),r?2:8):he.test(e)?u:+e}function pa(e){return Cs(e,ka(e))}function fa(e){return null==e?"":is(e)}var ga=ks(((e,t)=>{if(wi(t)||zo(t))Cs(t,xa(t),e);else for(var r in t)De.call(t,r)&&Yr(e,r,t[r])})),ma=ks(((e,t)=>{Cs(t,ka(t),e)})),ya=ks(((e,t,r,n)=>{Cs(t,ka(t),e,n)})),ba=ks(((e,t,r,n)=>{Cs(t,xa(t),e,n)})),wa=Qs(rn),va=Hn(((e,t)=>{e=Ie(e);var n=-1,s=t.length,i=s>2?t[2]:r;for(i&&gi(t[0],t[1],i)&&(s=1);++n<s;)for(var o=t[n],a=ka(o),c=-1,l=a.length;++c<l;){var u=a[c],h=e[u];(h===r||Oo(h,Pe[u])&&!De.call(e,u))&&(e[u]=o[u])}return e})),Ea=Hn((e=>(e.push(r,Xs),wt(Pa,r,e))));function Sa(e,t,n){var s=null==e?r:vn(e,t);return s===r?n:s}function Aa(e,t){return null!=e&&hi(e,t,_n)}var Ia=Us(((e,t,r)=>{null!=t&&"function"!=typeof t.toString&&(t=Oe.call(t)),e[t]=r}),Za(Ja)),_a=Us(((e,t,r)=>{null!=t&&"function"!=typeof t.toString&&(t=Oe.call(t)),De.call(e,t)?e[t].push(r):e[t]=[r]}),si),Ca=Hn(xn);function xa(e){return zo(e)?Hr(e):Dn(e)}function ka(e){return zo(e)?Hr(e,!0):function(e){if(!Zo(e))return(e=>{var t=[];if(null!=e)for(var r in Ie(e))t.push(r);return t})(e);var t=wi(e),r=[];for(var n in e)("constructor"!=n||!t&&De.call(e,n))&&r.push(n);return r}(e)}var Ta=ks(((e,t,r)=>{Fn(e,t,r)})),Pa=ks(((e,t,r,n)=>{Fn(e,t,r,n)})),Ra=Qs(((e,t)=>{var r={};if(null==e)return r;var n=!1;t=xt(t,(t=>(t=gs(t,e),n||(n=t.length>1),t))),Cs(e,ei(e),r),n&&(r=sn(r,7,Zs));for(var s=t.length;s--;)as(r,t[s]);return r})),La=Qs(((e,t)=>null==e?{}:((e,t)=>qn(e,t,((t,r)=>Aa(e,r))))(e,t)));function Da(e,t){if(null==e)return{};var r=xt(ei(e),(e=>[e]));return t=si(t),qn(e,r,((e,r)=>t(e,r[0])))}var Ma=Hs(xa),Na=Hs(ka);function Oa(e){return null==e?[]:Ht(e,xa(e))}var Ua=Ls(((e,t,r)=>(t=t.toLowerCase(),e+(r?Fa(t):t))));function Fa(e){return Ha(fa(e).toLowerCase())}function Ba(e){return(e=fa(e))&&e.replace(me,Zt).replace(Ge,"")}var $a=Ls(((e,t,r)=>e+(r?"-":"")+t.toLowerCase())),qa=Ls(((e,t,r)=>e+(r?" ":"")+t.toLowerCase())),za=Rs("toLowerCase"),ja=Ls(((e,t,r)=>e+(r?"_":"")+t.toLowerCase())),Ka=Ls(((e,t,r)=>e+(r?" ":"")+Ha(t))),Va=Ls(((e,t,r)=>e+(r?" ":"")+t.toUpperCase())),Ha=Rs("toUpperCase");function Ga(e,t,n){return e=fa(e),(t=n?r:t)===r?(e=>Ye.test(e))(e)?(e=>e.match(Xe)||[])(e):(e=>e.match(oe)||[])(e):e.match(t)||[]}var Wa=Hn(((e,t)=>{try{return wt(e,r,t)}catch(e){return Ho(e)?e:new Ee(e)}})),Xa=Qs(((e,t)=>(Et(t,(t=>{t=Li(t),tn(e,t,_o(e[t],e))})),e)));function Za(e){return()=>e}var Ya=Ns(),Qa=Ns(!0);function Ja(e){return e}function ec(e){return Ln("function"==typeof e?e:sn(e,1))}var tc=Hn(((e,t)=>r=>xn(r,e,t))),rc=Hn(((e,t)=>r=>xn(e,r,t)));function nc(e,t,r){var n=xa(t),s=wn(t,n);null!=r||Zo(t)&&(s.length||!n.length)||(r=t,t=e,e=this,s=wn(t,xa(t)));var i=!(Zo(r)&&"chain"in r&&!r.chain),o=Go(e);return Et(s,(function(r){var n=t[r];e[r]=n,o&&(e.prototype[r]=function(){var t=this.__chain__;if(i||t){var r=e(this.__wrapped__);return(r.__actions__=_s(this.__actions__)).push({func:n,args:arguments,thisArg:e}),r.__chain__=t,r}return n.apply(e,kt([this.value()],arguments))})})),e}function sc(){}var ic=Bs(xt),oc=Bs(At),ac=Bs(Rt);function cc(e){return mi(e)?Bt(Li(e)):(e=>t=>vn(t,e))(e)}var lc=qs(),uc=qs(!0);function hc(){return[]}function dc(){return!1}var pc=Fs(((e,t)=>e+t),0),fc=Ks("ceil"),gc=Fs(((e,t)=>e/t),1),mc=Ks("floor"),yc=Fs(((e,t)=>e*t),1),bc=Ks("round"),wc=Fs(((e,t)=>e-t),0);return Or.after=function(e,t){if("function"!=typeof t)throw new xe(n);return e=ua(e),function(){if(--e<1)return t.apply(this,arguments)}},Or.ary=Ao,Or.assign=ga,Or.assignIn=ma,Or.assignInWith=ya,Or.assignWith=ba,Or.at=wa,Or.before=Io,Or.bind=_o,Or.bindAll=Xa,Or.bindKey=Co,Or.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return $o(e)?e:[e]},Or.chain=ao,Or.chunk=(e,t,n)=>{t=(n?gi(e,t,n):t===r)?1:fr(ua(t),0);var s=null==e?0:e.length;if(!s||t<1)return[];for(var i=0,o=0,a=we(Lt(s/t));i<s;)a[o++]=Jn(e,i,i+=t);return a},Or.compact=e=>{for(var t=-1,r=null==e?0:e.length,n=0,s=[];++t<r;){var i=e[t];i&&(s[n++]=i)}return s},Or.concat=function(){var e=arguments.length;if(!e)return[];for(var t=we(e-1),r=arguments[0],n=e;n--;)t[n-1]=arguments[n];return kt($o(r)?_s(r):[r],fn(t,1))},Or.cond=function(e){var t=null==e?0:e.length,r=si();return e=t?xt(e,(e=>{if("function"!=typeof e[1])throw new xe(n);return[r(e[0]),e[1]]})):[],Hn((function(r){for(var n=-1;++n<t;){var s=e[n];if(wt(s[0],this,r))return wt(s[1],this,r)}}))},Or.conforms=e=>(e=>{var t=xa(e);return r=>on(r,e,t)})(sn(e,1)),Or.constant=Za,Or.countBy=uo,Or.create=(e,t)=>{var r=Ur(e);return null==t?r:en(r,t)},Or.curry=function e(t,n,s){var i=Gs(t,8,r,r,r,r,r,n=s?r:n);return i.placeholder=e.placeholder,i},Or.curryRight=function e(t,n,s){var i=Gs(t,16,r,r,r,r,r,n=s?r:n);return i.placeholder=e.placeholder,i},Or.debounce=xo,Or.defaults=va,Or.defaultsDeep=Ea,Or.defer=ko,Or.delay=To,Or.difference=Ni,Or.differenceBy=Oi,Or.differenceWith=Ui,Or.drop=(e,t,n)=>{var s=null==e?0:e.length;return s?Jn(e,(t=n||t===r?1:ua(t))<0?0:t,s):[]},Or.dropRight=(e,t,n)=>{var s=null==e?0:e.length;return s?Jn(e,0,(t=s-(t=n||t===r?1:ua(t)))<0?0:t):[]},Or.dropRightWhile=(e,t)=>e&&e.length?ls(e,si(t,3),!0,!0):[],Or.dropWhile=(e,t)=>e&&e.length?ls(e,si(t,3),!0):[],Or.fill=(e,t,n,s)=>{var i=null==e?0:e.length;return i?(n&&"number"!=typeof n&&gi(e,t,n)&&(n=0,s=i),((e,t,n,s)=>{var i=e.length;for((n=ua(n))<0&&(n=-n>i?0:i+n),(s=s===r||s>i?i:ua(s))<0&&(s+=i),s=n>s?0:ha(s);n<s;)e[n++]=t;return e})(e,t,n,s)):[]},Or.filter=(e,t)=>($o(e)?It:pn)(e,si(t,3)),Or.flatMap=(e,t)=>fn(wo(e,t),1),Or.flatMapDeep=(e,t)=>fn(wo(e,t),c),Or.flatMapDepth=(e,t,n)=>(n=n===r?1:ua(n),fn(wo(e,t),n)),Or.flatten=$i,Or.flattenDeep=e=>null!=e&&e.length?fn(e,c):[],Or.flattenDepth=(e,t)=>null!=e&&e.length?fn(e,t=t===r?1:ua(t)):[],Or.flip=e=>Gs(e,512),Or.flow=Ya,Or.flowRight=Qa,Or.fromPairs=e=>{for(var t=-1,r=null==e?0:e.length,n={};++t<r;){var s=e[t];n[s[0]]=s[1]}return n},Or.functions=e=>null==e?[]:wn(e,xa(e)),Or.functionsIn=e=>null==e?[]:wn(e,ka(e)),Or.groupBy=mo,Or.initial=e=>null!=e&&e.length?Jn(e,0,-1):[],Or.intersection=zi,Or.intersectionBy=ji,Or.intersectionWith=Ki,Or.invert=Ia,Or.invertBy=_a,Or.invokeMap=yo,Or.iteratee=ec,Or.keyBy=bo,Or.keys=xa,Or.keysIn=ka,Or.map=wo,Or.mapKeys=(e,t)=>{var r={};return t=si(t,3),yn(e,((e,n,s)=>{tn(r,t(e,n,s),e)})),r},Or.mapValues=(e,t)=>{var r={};return t=si(t,3),yn(e,((e,n,s)=>{tn(r,n,t(e,n,s))})),r},Or.matches=e=>On(sn(e,1)),Or.matchesProperty=(e,t)=>Un(e,sn(t,1)),Or.memoize=Po,Or.merge=Ta,Or.mergeWith=Pa,Or.method=tc,Or.methodOf=rc,Or.mixin=nc,Or.negate=Ro,Or.nthArg=e=>(e=ua(e),Hn((t=>Bn(t,e)))),Or.omit=Ra,Or.omitBy=(e,t)=>Da(e,Ro(si(t))),Or.once=e=>Io(2,e),Or.orderBy=(e,t,n,s)=>null==e?[]:($o(t)||(t=null==t?[]:[t]),$o(n=s?r:n)||(n=null==n?[]:[n]),$n(e,t,n)),Or.over=ic,Or.overArgs=Lo,Or.overEvery=oc,Or.overSome=ac,Or.partial=Do,Or.partialRight=Mo,Or.partition=vo,Or.pick=La,Or.pickBy=Da,Or.property=cc,Or.propertyOf=e=>t=>null==e?r:vn(e,t),Or.pull=Hi,Or.pullAll=Gi,Or.pullAllBy=(e,t,r)=>e&&e.length&&t&&t.length?zn(e,t,si(r,2)):e,Or.pullAllWith=(e,t,n)=>e&&e.length&&t&&t.length?zn(e,t,r,n):e,Or.pullAt=Wi,Or.range=lc,Or.rangeRight=uc,Or.rearg=No,Or.reject=(e,t)=>($o(e)?It:pn)(e,Ro(si(t,3))),Or.remove=(e,t)=>{var r=[];if(!e||!e.length)return r;var n=-1,s=[],i=e.length;for(t=si(t,3);++n<i;){var o=e[n];t(o,n,e)&&(r.push(o),s.push(n))}return jn(e,s),r},Or.rest=(e,t)=>{if("function"!=typeof e)throw new xe(n);return Hn(e,t=t===r?t:ua(t))},Or.reverse=Xi,Or.sampleSize=(e,t,n)=>(t=(n?gi(e,t,n):t===r)?1:ua(t),($o(e)?Wr:Wn)(e,t)),Or.set=(e,t,r)=>null==e?e:Xn(e,t,r),Or.setWith=(e,t,n,s)=>(s="function"==typeof s?s:r,null==e?e:Xn(e,t,n,s)),Or.shuffle=e=>($o(e)?Xr:Qn)(e),Or.slice=(e,t,n)=>{var s=null==e?0:e.length;return s?(n&&"number"!=typeof n&&gi(e,t,n)?(t=0,n=s):(t=null==t?0:ua(t),n=n===r?s:ua(n)),Jn(e,t,n)):[]},Or.sortBy=Eo,Or.sortedUniq=e=>e&&e.length?ns(e):[],Or.sortedUniqBy=(e,t)=>e&&e.length?ns(e,si(t,2)):[],Or.split=(e,t,n)=>(n&&"number"!=typeof n&&gi(e,t,n)&&(t=n=r),(n=n===r?h:n>>>0)?(e=fa(e))&&("string"==typeof t||null!=t&&!ta(t))&&!(t=is(t))&&Jt(e)?ys(ir(e),0,n):e.split(t,n):[]),Or.spread=function(e,t){if("function"!=typeof e)throw new xe(n);return t=null==t?0:fr(ua(t),0),Hn((function(r){var n=r[t],s=ys(r,0,t);return n&&kt(s,n),wt(e,this,s)}))},Or.tail=e=>{var t=null==e?0:e.length;return t?Jn(e,1,t):[]},Or.take=(e,t,n)=>e&&e.length?Jn(e,0,(t=n||t===r?1:ua(t))<0?0:t):[],Or.takeRight=(e,t,n)=>{var s=null==e?0:e.length;return s?Jn(e,(t=s-(t=n||t===r?1:ua(t)))<0?0:t,s):[]},Or.takeRightWhile=(e,t)=>e&&e.length?ls(e,si(t,3),!1,!0):[],Or.takeWhile=(e,t)=>e&&e.length?ls(e,si(t,3)):[],Or.tap=(e,t)=>(t(e),e),Or.throttle=(e,t,r)=>{var s=!0,i=!0;if("function"!=typeof e)throw new xe(n);return Zo(r)&&(s="leading"in r?!!r.leading:s,i="trailing"in r?!!r.trailing:i),xo(e,t,{leading:s,maxWait:t,trailing:i})},Or.thru=co,Or.toArray=ca,Or.toPairs=Ma,Or.toPairsIn=Na,Or.toPath=e=>$o(e)?xt(e,Li):sa(e)?[e]:_s(Ri(fa(e))),Or.toPlainObject=pa,Or.transform=(e,t,r)=>{var n=$o(e),s=n||Ko(e)||ia(e);if(t=si(t,4),null==r){var i=e&&e.constructor;r=s?n?new i:[]:Zo(e)&&Go(i)?Ur(Ke(e)):{}}return(s?Et:yn)(e,((e,n,s)=>t(r,e,n,s))),r},Or.unary=e=>Ao(e,1),Or.union=Zi,Or.unionBy=Yi,Or.unionWith=Qi,Or.uniq=e=>e&&e.length?os(e):[],Or.uniqBy=(e,t)=>e&&e.length?os(e,si(t,2)):[],Or.uniqWith=(e,t)=>(t="function"==typeof t?t:r,e&&e.length?os(e,r,t):[]),Or.unset=(e,t)=>null==e||as(e,t),Or.unzip=Ji,Or.unzipWith=eo,Or.update=(e,t,r)=>null==e?e:cs(e,t,fs(r)),Or.updateWith=(e,t,n,s)=>(s="function"==typeof s?s:r,null==e?e:cs(e,t,fs(n),s)),Or.values=Oa,Or.valuesIn=e=>null==e?[]:Ht(e,ka(e)),Or.without=to,Or.words=Ga,Or.wrap=(e,t)=>Do(fs(t),e),Or.xor=ro,Or.xorBy=no,Or.xorWith=so,Or.zip=io,Or.zipObject=(e,t)=>ds(e||[],t||[],Yr),Or.zipObjectDeep=(e,t)=>ds(e||[],t||[],Xn),Or.zipWith=oo,Or.entries=Ma,Or.entriesIn=Na,Or.extend=ma,Or.extendWith=ya,nc(Or,Or),Or.add=pc,Or.attempt=Wa,Or.camelCase=Ua,Or.capitalize=Fa,Or.ceil=fc,Or.clamp=(e,t,n)=>(n===r&&(n=t,t=r),n!==r&&(n=(n=da(n))==n?n:0),t!==r&&(t=(t=da(t))==t?t:0),nn(da(e),t,n)),Or.clone=e=>sn(e,4),Or.cloneDeep=e=>sn(e,5),Or.cloneDeepWith=(e,t)=>sn(e,5,t="function"==typeof t?t:r),Or.cloneWith=(e,t)=>sn(e,4,t="function"==typeof t?t:r),Or.conformsTo=(e,t)=>null==t||on(e,t,xa(t)),Or.deburr=Ba,Or.defaultTo=(e,t)=>null==e||e!=e?t:e,Or.divide=gc,Or.endsWith=(e,t,n)=>{e=fa(e),t=is(t);var s=e.length,i=n=n===r?s:nn(ua(n),0,s);return(n-=t.length)>=0&&e.slice(n,i)==t},Or.eq=Oo,Or.escape=e=>(e=fa(e))&&H.test(e)?e.replace(K,Yt):e,Or.escapeRegExp=e=>(e=fa(e))&&ee.test(e)?e.replace(J,"\\$&"):e,Or.every=(e,t,n)=>{var s=$o(e)?At:hn;return n&&gi(e,t,n)&&(t=r),s(e,si(t,3))},Or.find=ho,Or.findIndex=Fi,Or.findKey=(e,t)=>Dt(e,si(t,3),yn),Or.findLast=po,Or.findLastIndex=Bi,Or.findLastKey=(e,t)=>Dt(e,si(t,3),bn),Or.floor=mc,Or.forEach=fo,Or.forEachRight=go,Or.forIn=(e,t)=>null==e?e:gn(e,si(t,3),ka),Or.forInRight=(e,t)=>null==e?e:mn(e,si(t,3),ka),Or.forOwn=(e,t)=>e&&yn(e,si(t,3)),Or.forOwnRight=(e,t)=>e&&bn(e,si(t,3)),Or.get=Sa,Or.gt=Uo,Or.gte=Fo,Or.has=(e,t)=>null!=e&&hi(e,t,In),Or.hasIn=Aa,Or.head=qi,Or.identity=Ja,Or.includes=(e,t,r,n)=>{e=zo(e)?e:Oa(e),r=r&&!n?ua(r):0;var s=e.length;return r<0&&(r=fr(s+r,0)),na(e)?r<=s&&e.indexOf(t,r)>-1:!!s&&Nt(e,t,r)>-1},Or.indexOf=(e,t,r)=>{var n=null==e?0:e.length;if(!n)return-1;var s=null==r?0:ua(r);return s<0&&(s=fr(n+s,0)),Nt(e,t,s)},Or.inRange=(e,t,n)=>(t=la(t),n===r?(n=t,t=0):n=la(n),((e,t,r)=>e>=gr(t,r)&&e<fr(t,r))(e=da(e),t,n)),Or.invoke=Ca,Or.isArguments=Bo,Or.isArray=$o,Or.isArrayBuffer=qo,Or.isArrayLike=zo,Or.isArrayLikeObject=jo,Or.isBoolean=e=>!0===e||!1===e||Yo(e)&&Sn(e)==g,Or.isBuffer=Ko,Or.isDate=Vo,Or.isElement=e=>Yo(e)&&1===e.nodeType&&!ea(e),Or.isEmpty=e=>{if(null==e)return!0;if(zo(e)&&($o(e)||"string"==typeof e||"function"==typeof e.splice||Ko(e)||ia(e)||Bo(e)))return!e.length;var t=ui(e);if(t==v||t==_)return!e.size;if(wi(e))return!Dn(e).length;for(var r in e)if(De.call(e,r))return!1;return!0},Or.isEqual=(e,t)=>Tn(e,t),Or.isEqualWith=(e,t,n)=>{var s=(n="function"==typeof n?n:r)?n(e,t):r;return s===r?Tn(e,t,r,n):!!s},Or.isError=Ho,Or.isFinite=e=>"number"==typeof e&&hr(e),Or.isFunction=Go,Or.isInteger=Wo,Or.isLength=Xo,Or.isMap=Qo,Or.isMatch=(e,t)=>e===t||Pn(e,t,oi(t)),Or.isMatchWith=(e,t,n)=>(n="function"==typeof n?n:r,Pn(e,t,oi(t),n)),Or.isNaN=e=>Jo(e)&&e!=+e,Or.isNative=e=>{if(bi(e))throw new Ee("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");return Rn(e)},Or.isNil=e=>null==e,Or.isNull=e=>null===e,Or.isNumber=Jo,Or.isObject=Zo,Or.isObjectLike=Yo,Or.isPlainObject=ea,Or.isRegExp=ta,Or.isSafeInteger=e=>Wo(e)&&e>=-9007199254740991&&e<=l,Or.isSet=ra,Or.isString=na,Or.isSymbol=sa,Or.isTypedArray=ia,Or.isUndefined=e=>e===r,Or.isWeakMap=e=>Yo(e)&&ui(e)==k,Or.isWeakSet=e=>Yo(e)&&"[object WeakSet]"==Sn(e),Or.join=(e,t)=>null==e?"":dr.call(e,t),Or.kebabCase=$a,Or.last=Vi,Or.lastIndexOf=(e,t,n)=>{var s=null==e?0:e.length;if(!s)return-1;var i=s;return n!==r&&(i=(i=ua(n))<0?fr(s+i,0):gr(i,s-1)),t==t?((e,t,r)=>{for(var n=r+1;n--;)if(e[n]===t)return n;return n})(e,t,i):Mt(e,Ut,i,!0)},Or.lowerCase=qa,Or.lowerFirst=za,Or.lt=oa,Or.lte=aa,Or.max=e=>e&&e.length?dn(e,Ja,An):r,Or.maxBy=(e,t)=>e&&e.length?dn(e,si(t,2),An):r,Or.mean=e=>Ft(e,Ja),Or.meanBy=(e,t)=>Ft(e,si(t,2)),Or.min=e=>e&&e.length?dn(e,Ja,Mn):r,Or.minBy=(e,t)=>e&&e.length?dn(e,si(t,2),Mn):r,Or.stubArray=hc,Or.stubFalse=dc,Or.stubObject=()=>({}),Or.stubString=()=>"",Or.stubTrue=()=>!0,Or.multiply=yc,Or.nth=(e,t)=>e&&e.length?Bn(e,ua(t)):r,Or.noConflict=function(){return at._===this&&(at._=Fe),this},Or.noop=sc,Or.now=So,Or.pad=(e,t,r)=>{e=fa(e);var n=(t=ua(t))?sr(e):0;if(!t||n>=t)return e;var s=(t-n)/2;return $s($t(s),r)+e+$s(Lt(s),r)},Or.padEnd=(e,t,r)=>{e=fa(e);var n=(t=ua(t))?sr(e):0;return t&&n<t?e+$s(t-n,r):e},Or.padStart=(e,t,r)=>{e=fa(e);var n=(t=ua(t))?sr(e):0;return t&&n<t?$s(t-n,r)+e:e},Or.parseInt=(e,t,r)=>(r||null==t?t=0:t&&(t=+t),yr(fa(e).replace(te,""),t||0)),Or.random=(e,t,n)=>{if(n&&"boolean"!=typeof n&&gi(e,t,n)&&(t=n=r),n===r&&("boolean"==typeof t?(n=t,t=r):"boolean"==typeof e&&(n=e,e=r)),e===r&&t===r?(e=0,t=1):(e=la(e),t===r?(t=e,e=0):t=la(t)),e>t){var s=e;e=t,t=s}if(n||e%1||t%1){var i=br();return gr(e+i*(t-e+nt("1e-"+((i+"").length-1))),t)}return Kn(e,t)},Or.reduce=function(e,t,r){var n=$o(e)?Tt:qt,s=arguments.length<3;return n(e,si(t,4),r,s,ln)},Or.reduceRight=function(e,t,r){var n=$o(e)?Pt:qt,s=arguments.length<3;return n(e,si(t,4),r,s,un)},Or.repeat=(e,t,n)=>(t=(n?gi(e,t,n):t===r)?1:ua(t),Vn(fa(e),t)),Or.replace=function(){var e=arguments,t=fa(e[0]);return e.length<3?t:t.replace(e[1],e[2])},Or.result=(e,t,n)=>{var s=-1,i=(t=gs(t,e)).length;for(i||(i=1,e=r);++s<i;){var o=null==e?r:e[Li(t[s])];o===r&&(s=i,o=n),e=Go(o)?o.call(e):o}return e},Or.round=bc,Or.runInContext=e,Or.sample=e=>($o(e)?Gr:Gn)(e),Or.size=e=>{if(null==e)return 0;if(zo(e))return na(e)?sr(e):e.length;var t=ui(e);return t==v||t==_?e.size:Dn(e).length},Or.snakeCase=ja,Or.some=(e,t,n)=>{var s=$o(e)?Rt:es;return n&&gi(e,t,n)&&(t=r),s(e,si(t,3))},Or.sortedIndex=(e,t)=>ts(e,t),Or.sortedIndexBy=(e,t,r)=>rs(e,t,si(r,2)),Or.sortedIndexOf=(e,t)=>{var r=null==e?0:e.length;if(r){var n=ts(e,t);if(n<r&&Oo(e[n],t))return n}return-1},Or.sortedLastIndex=(e,t)=>ts(e,t,!0),Or.sortedLastIndexBy=(e,t,r)=>rs(e,t,si(r,2),!0),Or.sortedLastIndexOf=(e,t)=>{if(null!=e&&e.length){var r=ts(e,t,!0)-1;if(Oo(e[r],t))return r}return-1},Or.startCase=Ka,Or.startsWith=(e,t,r)=>(e=fa(e),r=null==r?0:nn(ua(r),0,e.length),t=is(t),e.slice(r,r+t.length)==t),Or.subtract=wc,Or.sum=e=>e&&e.length?zt(e,Ja):0,Or.sumBy=(e,t)=>e&&e.length?zt(e,si(t,2)):0,Or.template=(e,t,n)=>{var s=Or.templateSettings;n&&gi(e,t,n)&&(t=r),e=fa(e),t=ya({},t,s,Ws);var i,o,a=ya({},t.imports,s.imports,Ws),c=xa(a),l=Ht(a,c),u=0,h=t.interpolate||ye,d="__p += '",p=_e((t.escape||ye).source+"|"+h.source+"|"+(h===X?le:ye).source+"|"+(t.evaluate||ye).source+"|$","g"),f="//# sourceURL="+(De.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++Je+"]")+"\n";e.replace(p,((t,r,n,s,a,c)=>(n||(n=s),d+=e.slice(u,c).replace(be,Qt),r&&(i=!0,d+="' +\n__e("+r+") +\n'"),a&&(o=!0,d+="';\n"+a+";\n__p += '"),n&&(d+="' +\n((__t = ("+n+")) == null ? '' : __t) +\n'"),u=c+t.length,t))),d+="';\n";var g=De.call(t,"variable")&&t.variable;if(g){if(ae.test(g))throw new Ee("Invalid `variable` option passed into `_.template`")}else d="with (obj) {\n"+d+"\n}\n";d=(o?d.replace($,""):d).replace(q,"$1").replace(z,"$1;"),d="function("+(g||"obj")+") {\n"+(g?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(i?", __e = _.escape":"")+(o?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+d+"return __p\n}";var m=Wa((()=>Se(c,f+"return "+d).apply(r,l)));if(m.source=d,Ho(m))throw m;return m},Or.times=(e,t)=>{if((e=ua(e))<1||e>l)return[];var r=h,n=gr(e,h);t=si(t),e-=h;for(var s=jt(n,t);++r<e;)t(r);return s},Or.toFinite=la,Or.toInteger=ua,Or.toLength=ha,Or.toLower=e=>fa(e).toLowerCase(),Or.toNumber=da,Or.toSafeInteger=e=>e?nn(ua(e),-9007199254740991,l):0===e?e:0,Or.toString=fa,Or.toUpper=e=>fa(e).toUpperCase(),Or.trim=(e,t,n)=>{if((e=fa(e))&&(n||t===r))return Kt(e);if(!e||!(t=is(t)))return e;var s=ir(e),i=ir(t);return ys(s,Wt(s,i),Xt(s,i)+1).join("")},Or.trimEnd=(e,t,n)=>{if((e=fa(e))&&(n||t===r))return e.slice(0,or(e)+1);if(!e||!(t=is(t)))return e;var s=ir(e);return ys(s,0,Xt(s,ir(t))+1).join("")},Or.trimStart=(e,t,n)=>{if((e=fa(e))&&(n||t===r))return e.replace(te,"");if(!e||!(t=is(t)))return e;var s=ir(e);return ys(s,Wt(s,ir(t))).join("")},Or.truncate=(e,t)=>{var n=30,s="...";if(Zo(t)){var i="separator"in t?t.separator:i;n="length"in t?ua(t.length):n,s="omission"in t?is(t.omission):s}var o=(e=fa(e)).length;if(Jt(e)){var a=ir(e);o=a.length}if(n>=o)return e;var c=n-sr(s);if(c<1)return s;var l=a?ys(a,0,c).join(""):e.slice(0,c);if(i===r)return l+s;if(a&&(c+=l.length-c),ta(i)){if(e.slice(c).search(i)){var u,h=l;for(i.global||(i=_e(i.source,fa(ue.exec(i))+"g")),i.lastIndex=0;u=i.exec(h);)var d=u.index;l=l.slice(0,d===r?c:d)}}else if(e.indexOf(is(i),c)!=c){var p=l.lastIndexOf(i);p>-1&&(l=l.slice(0,p))}return l+s},Or.unescape=e=>(e=fa(e))&&V.test(e)?e.replace(j,ar):e,Or.uniqueId=e=>{var t=++Me;return fa(e)+t},Or.upperCase=Va,Or.upperFirst=Ha,Or.each=fo,Or.eachRight=go,Or.first=qi,nc(Or,(()=>{var e={};return yn(Or,((t,r)=>{De.call(Or.prototype,r)||(e[r]=t)})),e})(),{chain:!1}),Or.VERSION="4.17.21",Et(["bind","bindKey","curry","curryRight","partial","partialRight"],(e=>{Or[e].placeholder=Or})),Et(["drop","take"],(function(e,t){$r.prototype[e]=function(n){n=n===r?1:fr(ua(n),0);var s=this.__filtered__&&!t?new $r(this):this.clone();return s.__filtered__?s.__takeCount__=gr(n,s.__takeCount__):s.__views__.push({size:gr(n,h),type:e+(s.__dir__<0?"Right":"")}),s},$r.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),Et(["filter","map","takeWhile"],(function(e,t){var r=t+1,n=1==r||3==r;$r.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:si(e,3),type:r}),t.__filtered__=t.__filtered__||n,t}})),Et(["head","last"],(function(e,t){var r="take"+(t?"Right":"");$r.prototype[e]=function(){return this[r](1).value()[0]}})),Et(["initial","tail"],(function(e,t){var r="drop"+(t?"":"Right");$r.prototype[e]=function(){return this.__filtered__?new $r(this):this[r](1)}})),$r.prototype.compact=function(){return this.filter(Ja)},$r.prototype.find=function(e){return this.filter(e).head()},$r.prototype.findLast=function(e){return this.reverse().find(e)},$r.prototype.invokeMap=Hn((function(e,t){return"function"==typeof e?new $r(this):this.map((r=>xn(r,e,t)))})),$r.prototype.reject=function(e){return this.filter(Ro(si(e)))},$r.prototype.slice=function(e,t){e=ua(e);var n=this;return n.__filtered__&&(e>0||t<0)?new $r(n):(e<0?n=n.takeRight(-e):e&&(n=n.drop(e)),t!==r&&(n=(t=ua(t))<0?n.dropRight(-t):n.take(t-e)),n)},$r.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},$r.prototype.toArray=function(){return this.take(h)},yn($r.prototype,(function(e,t){var n=/^(?:filter|find|map|reject)|While$/.test(t),s=/^(?:head|last)$/.test(t),i=Or[s?"take"+("last"==t?"Right":""):t],o=s||/^find/.test(t);i&&(Or.prototype[t]=function(){var t=this.__wrapped__,a=s?[1]:arguments,c=t instanceof $r,l=a[0],u=c||$o(t),h=e=>{var t=i.apply(Or,kt([e],a));return s&&d?t[0]:t};u&&n&&"function"==typeof l&&1!=l.length&&(c=u=!1);var d=this.__chain__,p=!!this.__actions__.length,f=o&&!d,g=c&&!p;if(!o&&u){t=g?t:new $r(this);var m=e.apply(t,a);return m.__actions__.push({func:co,args:[h],thisArg:r}),new Br(m,d)}return f&&g?e.apply(this,a):(m=this.thru(h),f?s?m.value()[0]:m.value():m)})})),Et(["pop","push","shift","sort","splice","unshift"],(function(e){var t=ke[e],r=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",n=/^(?:pop|shift)$/.test(e);Or.prototype[e]=function(){var e=arguments;if(n&&!this.__chain__){var s=this.value();return t.apply($o(s)?s:[],e)}return this[r]((r=>t.apply($o(r)?r:[],e)))}})),yn($r.prototype,((e,t)=>{var r=Or[t];if(r){var n=r.name+"";De.call(xr,n)||(xr[n]=[]),xr[n].push({name:t,func:r})}})),xr[Os(r,2).name]=[{name:"wrapper",func:r}],$r.prototype.clone=function(){var e=new $r(this.__wrapped__);return e.__actions__=_s(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=_s(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=_s(this.__views__),e},$r.prototype.reverse=function(){if(this.__filtered__){var e=new $r(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},$r.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,r=$o(e),n=t<0,s=r?e.length:0,i=((e,t,r)=>{for(var n=-1,s=r.length;++n<s;){var i=r[n],o=i.size;switch(i.type){case"drop":e+=o;break;case"dropRight":t-=o;break;case"take":t=gr(t,e+o);break;case"takeRight":e=fr(e,t-o)}}return{start:e,end:t}})(0,s,this.__views__),o=i.start,a=i.end,c=a-o,l=n?a:o-1,u=this.__iteratees__,h=u.length,d=0,p=gr(c,this.__takeCount__);if(!r||!n&&s==c&&p==c)return us(e,this.__actions__);var f=[];e:for(;c--&&d<p;){for(var g=-1,m=e[l+=t];++g<h;){var y=u[g],b=y.iteratee,w=y.type,v=b(m);if(2==w)m=v;else if(!v){if(1==w)continue e;break e}}f[d++]=m}return f},Or.prototype.at=lo,Or.prototype.chain=function(){return ao(this)},Or.prototype.commit=function(){return new Br(this.value(),this.__chain__)},Or.prototype.next=function(){this.__values__===r&&(this.__values__=ca(this.value()));var e=this.__index__>=this.__values__.length;return{done:e,value:e?r:this.__values__[this.__index__++]}},Or.prototype.plant=function(e){for(var t,n=this;n instanceof Fr;){var s=Mi(n);s.__index__=0,s.__values__=r,t?i.__wrapped__=s:t=s;var i=s;n=n.__wrapped__}return i.__wrapped__=e,t},Or.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof $r){var t=e;return this.__actions__.length&&(t=new $r(this)),(t=t.reverse()).__actions__.push({func:co,args:[Xi],thisArg:r}),new Br(t,this.__chain__)}return this.thru(Xi)},Or.prototype.toJSON=Or.prototype.valueOf=Or.prototype.value=function(){return us(this.__wrapped__,this.__actions__)},Or.prototype.first=Or.prototype.head,it&&(Or.prototype[it]=function(){return this}),Or}();lt?((lt.exports=cr)._=cr,ct._=cr):at._=cr}()}(LS,LS.exports)),new fs("sds:message"),new fs("sds:message-channel"),new fs("sdk:query-on-connect"),(e=>{e.MessagesRetrieved="messages:retrieved"})(RS||(RS={})),new fs("sdk:missing-message-retriever"),new fs("sdk:reliable-channel"),As.ENCODE_FAILED,As.EMPTY_PAYLOAD,As.SIZE_TOO_BIG,As.RLN_PROOF_GENERATION;const{floor:DS,random:MS}=Math,NS="Trystero",OS=(e,t)=>Array(e).fill().map(t),US=OS(20,(()=>"0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"[DS(62*MS())])).join(""),FS=Promise.all.bind(Promise),BS="undefined"!=typeof window,{entries:$S,fromEntries:qS,keys:zS}=Object,jS=()=>{},KS=e=>Error(`${NS}: ${e}`),VS=new TextEncoder,HS=new TextDecoder,GS=e=>VS.encode(e),WS=e=>HS.decode(e),XS=(...e)=>e.join("@"),ZS=JSON.stringify,YS=JSON.parse;let QS=null,JS=null;const eA=()=>{QS||(QS=new Promise((e=>{JS=e})).finally((()=>{JS=null,QS=null})))},tA=()=>JS?.(),rA="AES-GCM",nA={},sA=async e=>nA[e]||=Array.from(await(async(e,t)=>new Uint8Array(await crypto.subtle.digest("SHA-1",GS(t))))(0,e)).map((e=>e.toString(36))).join(""),iA=async(e,t)=>{const r=crypto.getRandomValues(new Uint8Array(16));var n;return r.join(",")+"$"+(n=await crypto.subtle.encrypt({name:rA,iv:r},await e,GS(t)),btoa(String.fromCharCode.apply(null,new Uint8Array(n))))},oA=async(e,t)=>{const[r,n]=t.split("$");return WS(await crypto.subtle.decrypt({name:rA,iv:new Uint8Array(r.split(","))},await e,(e=>{const t=atob(e);return new Uint8Array(t.length).map(((e,r)=>t.charCodeAt(r))).buffer})(n)))},aA="icegatheringstatechange",cA="offer";var lA=(e,{rtcConfig:t,rtcPolyfill:r,turnConfig:n})=>{const s=new(r||RTCPeerConnection)({iceServers:uA.concat(n||[]),...t}),i={};let o=!1,a=!1,c=null;const l=e=>{e.binaryType="arraybuffer",e.bufferedAmountLowThreshold=65535,e.onmessage=e=>i.data?.(e.data),e.onopen=()=>i.connect?.(),e.onclose=()=>i.close?.(),e.onerror=e=>i.error?.(e)},u=e=>Promise.race([new Promise((t=>{const r=()=>{"complete"===e.iceGatheringState&&(e.removeEventListener(aA,r),t())};e.addEventListener(aA,r),r()})),new Promise((e=>setTimeout(e,5e3)))]).then((()=>({type:e.localDescription.type,sdp:e.localDescription.sdp.replace(/a=ice-options:trickle\s\n/g,"")})));return e?(c=s.createDataChannel("data"),l(c)):s.ondatachannel=({channel:e})=>{c=e,l(e)},s.onnegotiationneeded=async()=>{try{o=!0,await s.setLocalDescription();const e=await u(s);i.signal?.(e)}catch(e){i.error?.(e)}finally{o=!1}},s.onconnectionstatechange=()=>{["disconnected","failed","closed"].includes(s.connectionState)&&i.close?.()},s.ontrack=e=>{i.track?.(e.track,e.streams[0]),i.stream?.(e.streams[0])},s.onremovestream=e=>i.stream?.(e.stream),e&&(s.canTrickleIceCandidates||s.onnegotiationneeded()),{created:Date.now(),connection:s,get channel(){return c},get isDead(){return"closed"===s.connectionState},async signal(t){if("open"!==c?.readyState||t.sdp?.includes("a=rtpmap"))try{if(t.type===cA){if(o||"stable"!==s.signalingState&&!a){if(e)return;await FS([s.setLocalDescription({type:"rollback"}),s.setRemoteDescription(t)])}else await s.setRemoteDescription(t);await s.setLocalDescription();const r=await u(s);return i.signal?.(r),r}if("answer"===t.type){a=!0;try{await s.setRemoteDescription(t)}finally{a=!1}}}catch(e){i.error?.(e)}},sendData:e=>c.send(e),destroy(){c?.close(),s.close(),o=!1,a=!1},setHandlers:e=>Object.assign(i,e),offerPromise:e?new Promise((e=>i.signal=t=>{t.type===cA&&e(t)})):Promise.resolve(),addStream:e=>e.getTracks().forEach((t=>s.addTrack(t,e))),removeStream:e=>s.getSenders().filter((t=>e.getTracks().includes(t.track))).forEach((e=>s.removeTrack(e))),addTrack:(e,t)=>s.addTrack(e,t),removeTrack(e){const t=s.getSenders().find((t=>t.track===e));t&&s.removeTrack(t)},replaceTrack(e,t){const r=s.getSenders().find((t=>t.track===e));if(r)return r.replaceTrack(t)}}};const uA=[...OS(3,((e,t)=>`stun:stun${t||""}.l.google.com:19302`)),"stun:stun.cloudflare.com:3478"].map((e=>({urls:e}))),hA=Object.getPrototypeOf(Uint8Array),dA=16369,pA=255,fA="bufferedamountlow",gA=e=>"@_"+e,mA=e=>`/${NS}-${e}/0/msg/json`,yA=(e,t,r)=>e.lightPush.send(e.createEncoder({contentTopic:mA(t),ephemeral:!0}),{payload:GS(r)},{autoRetry:!0}),bA=(({init:e,subscribe:t,announce:r})=>{const n={};let s,i,o,a,c=!1;return(l,u,h)=>{const{appId:d}=l;if(n[d]?.[u])return n[d][u];const p={},f={},g=XS(NS,d,u),m=sA(g),y=sA(XS(g,US)),b=(async(e,t,r)=>crypto.subtle.importKey("raw",await crypto.subtle.digest({name:"SHA-256"},GS(`${e}:${t}:${r}`)),{name:rA},!1,["encrypt","decrypt"]))(l.password||"",d,u),w=e=>async t=>({type:t.type,sdp:await e(b,t.sdp)}),v=w(oA),E=w(iA),S=()=>lA(!0,l),A=(e,t,r)=>{f[t]?f[t]!==e&&e.destroy():(f[t]=e,P(e,t),p[t]?.forEach(((e,t)=>{t!==r&&e.destroy()})),delete p[t])},I=(e,t)=>{f[t]===e&&delete f[t]},_=e=>(i.push(...OS(e,S)),FS(i.splice(0,e).map((e=>e.offerPromise.then(E).then((t=>({peer:e,offer:t}))))))),C=(e,t)=>h?.({error:`incorrect password (${l.password}) when decrypting ${t}`,appId:d,peerId:e,roomId:u});if(!l)throw KS("requires a config map as the first argument");if(!d&&!l.firebaseApp)throw KS("config map is missing appId field");if(!u)throw KS("roomId argument required");if(!c){const t=e(l);i=OS(20,S),s=Array.isArray(t)?t:[t],c=!0,o=setInterval((()=>i=i.filter((e=>{const t=Date.now()-e.created<57333;return t||e.destroy(),t}))),59052.99),a=l.manualRelayReconnection?jS:(()=>{if(BS){const e=new AbortController;return addEventListener("online",tA,{signal:e.signal}),addEventListener("offline",eA,{signal:e.signal}),()=>e.abort()}return jS})()}const x=s.map((()=>5333)),k=[],T=s.map((async(e,r)=>t(await e,await m,await y,(e=>async(t,r,n)=>{const[s,i]=await FS([m,y]);if(t!==s&&t!==i)return;const{peerId:o,offer:a,answer:c,peer:u}="string"==typeof r?YS(r):r;if(o!==US&&!f[o])if(!o||a||c){if(a){const t=p[o]?.[e];if(t&&US>o)return;const r=lA(!1,l);let s;r.setHandlers({connect:()=>A(r,o,e),close:()=>I(r,o)});try{s=await v(a)}catch{return void C(o,"offer")}if(r.isDead)return;const[i,c]=await FS([sA(XS(g,o)),r.signal(s)]);n(i,ZS({peerId:US,answer:await E(c)}))}else if(c){let t;try{t=await v(c)}catch(e){return void C(o,"answer")}if(u)u.setHandlers({connect:()=>A(u,o,e),close:()=>I(u,o)}),u.signal(t);else{const r=p[o]?.[e];r&&!r.isDead&&r.signal(t)}}}else{if(p[o]?.[e])return;const[[{peer:t,offer:r}],s]=await FS([_(1),sA(XS(g,o))]);p[o]||=[],p[o][e]=t,setTimeout((()=>((e,t)=>{if(f[e])return;const r=p[e]?.[t];r&&(delete p[e][t],r.destroy())})(o,e)),.9*x[e]),t.setHandlers({connect:()=>A(t,o,e),close:()=>I(t,o)}),n(s,ZS({peerId:US,offer:r}))}})(r),_)));FS([m,y]).then((([e,t])=>{const n=async(s,i)=>{const o=await r(s,e,t);"number"==typeof o&&(x[i]=o),k[i]=setTimeout((()=>n(s,i)),x[i])};T.forEach((async(e,t)=>{await e,n(await s[t],t)}))}));let P=jS;return n[d]||={},n[d][u]=((e,t,r)=>{const n={},s={},i={},o={},a={},c={},l={},u={onPeerJoin:jS,onPeerLeave:jS,onPeerStream:jS,onPeerTrack:jS},h=(e,t)=>(e?Array.isArray(e)?e:[e]:zS(n)).flatMap((e=>{const r=n[e];return r?t(e,r):(console.warn(`${NS}: no peer with id ${e} found`),[])})),d=e=>{n[e]&&(n[e].destroy(),delete n[e],delete o[e],delete a[e],u.onPeerLeave(e),t(e))},p=e=>{if(s[e])return i[e];if(!e)throw KS("action type argument is required");const t=GS(e);if(t.byteLength>12)throw KS(`action type string "${e}" (${t.byteLength}b) exceeds byte limit (12). Hint: choose a shorter name.`);const r=new Uint8Array(12);r.set(t);let o=0;return s[e]={onComplete:jS,onProgress:jS,setOnComplete:t=>s[e]={...s[e],onComplete:t},setOnProgress:t=>s[e]={...s[e],onProgress:t},async send(e,t,s,i){if(s&&"object"!=typeof s)throw KS("action meta argument must be an object");const a=typeof e;if("undefined"===a)throw KS("action data cannot be undefined");const c="string"!==a,l=e instanceof Blob,u=l||e instanceof ArrayBuffer||e instanceof hA;if(s&&!u)throw KS("action meta argument can only be used with binary data");const d=u?new Uint8Array(l?await e.arrayBuffer():e):GS(c?ZS(e):e),p=s?GS(ZS(s)):null,f=Math.ceil(d.byteLength/dA)+(s?1:0)||1,g=OS(f,((e,t)=>{const n=t===f-1,i=s&&0===t,a=new Uint8Array(15+(i?p.byteLength:n?d.byteLength-dA*(f-(s?2:1)):dA));return a.set(r),a.set([o],12),a.set([n|i<<1|u<<2|c<<3],13),a.set([Math.round((t+1)/f*pA)],14),a.set(s?i?p:d.subarray((t-1)*dA,t*dA):d.subarray(t*dA,(t+1)*dA),15),a}));return o=o+1&pA,FS(h(t,(async(e,t)=>{const{channel:r}=t;let o=0;for(;o<f;){const a=g[o];if(r.bufferedAmount>r.bufferedAmountLowThreshold&&await new Promise((e=>{const t=()=>{r.removeEventListener(fA,t),e()};r.addEventListener(fA,t)})),!n[e])break;t.sendData(a),o++,i?.(a[14]/pA,e,s)}})))}},i[e]||=[s[e].send,s[e].setOnComplete,s[e].setOnProgress]},f=async()=>{await _(""),await new Promise((e=>setTimeout(e,99))),$S(n).forEach((([e,t])=>{t.destroy(),delete n[e]})),r()},[g,m]=p(gA("ping")),[y,b]=p(gA("pong")),[w,v]=p(gA("signal")),[E,S]=p(gA("stream")),[A,I]=p(gA("track")),[_,C]=p(gA("leave"));return(e=>{P=e})(((e,t)=>{n[t]||(n[t]=e,e.setHandlers({data:e=>((e,t)=>{const r=new Uint8Array(t),n=WS(r.subarray(0,12)).replaceAll("\0",""),[i]=r.subarray(12,13),[a]=r.subarray(13,14),[c]=r.subarray(14,15),l=r.subarray(15),u=!!(1&a),h=!!(2&a),d=!!(4&a),p=!!(8&a);if(!s[n])return void console.warn(`${NS}: received message with unregistered type (${n})`);o[e]||={},o[e][n]||={};const f=o[e][n][i]||={chunks:[]};if(h?f.meta=YS(WS(l)):f.chunks.push(l),s[n].onProgress(c/pA,e,f.meta),!u)return;const g=new Uint8Array(f.chunks.reduce(((e,t)=>e+t.byteLength),0));if(f.chunks.reduce(((e,t)=>(g.set(t,e),e+t.byteLength)),0),delete o[e][n][i],d)s[n].onComplete(g,e,f.meta);else{const t=WS(g);s[n].onComplete(p?YS(t):t,e)}})(t,e),stream(e){u.onPeerStream(e,t,c[t]),delete c[t]},track(e,r){u.onPeerTrack(e,r,t,l[t]),delete l[t]},signal:e=>w(e,t),close:()=>d(t),error(e){console.error(e),d(t)}}),u.onPeerJoin(t))})),m(((e,t)=>y("",t))),b(((e,t)=>{a[t]?.(),delete a[t]})),v(((e,t)=>n[t]?.signal(e))),S(((e,t)=>c[t]=e)),I(((e,t)=>l[t]=e)),C(((e,t)=>d(t))),BS&&addEventListener("beforeunload",f),{makeAction:p,leave:f,async ping(e){if(!e)throw KS("ping() must be called with target peer ID");const t=Date.now();return g("",e),await new Promise((t=>a[e]=t)),Date.now()-t},getPeers:()=>qS($S(n).map((([e,t])=>[e,t.connection]))),addStream:(e,t,r)=>h(t,(async(t,n)=>{r&&await E(r,t),n.addStream(e)})),removeStream:(e,t)=>h(t,((t,r)=>r.removeStream(e))),addTrack:(e,t,r,n)=>h(r,(async(r,s)=>{n&&await A(n,r),s.addTrack(e,t)})),removeTrack:(e,t)=>h(t,((t,r)=>r.removeTrack(e))),replaceTrack:(e,t,r,n)=>h(r,(async(r,s)=>{n&&await A(n,r),s.replaceTrack(e,t)})),onPeerJoin:e=>u.onPeerJoin=e,onPeerLeave:e=>u.onPeerLeave=e,onPeerStream:e=>u.onPeerStream=e,onPeerTrack:e=>u.onPeerTrack=e}})(0,(e=>delete f[e]),(()=>{delete n[d][u],k.forEach(clearTimeout),T.forEach((async e=>(await e)())),clearInterval(o),a(),c=!1}))}})({init:()=>async function(e={}){const t=await GE(e),r=new du(e,t,{store:!0,lightpush:!0,filter:!0});return!1!==e?.autoStart&&await r.start(),r}({defaultBootstrap:!0,discovery:{dns:!0,peerExchange:!0,peerCache:!0}}).then((async e=>(await e.start(),await e.waitForPeers(),e))),async subscribe(e,t,r,n){const s=await FS([t,r].map((t=>{const r=e.createDecoder({contentTopic:mA(t)});return e.filter.subscribe(r,(t=>r=>{r.payload&&n(t,WS(r.payload),((t,r)=>yA(e,t,r)))})(t)),()=>e.filter.unsubscribe(r)})));return()=>s.forEach((e=>e()))},announce:(e,t)=>yA(e,t,ZS({peerId:US}))})},{c1f15e2440b26488:"fDdlt","@parcel/transformer-js/src/esmodule-helpers.js":"XTfsy"}]},[],0,"parcelRequire55a5");
1
+ !function(e,t,r,n,s){var i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},o="function"==typeof i[n]&&i[n],a=o.cache||{},c="undefined"!=typeof module&&"function"==typeof module.require&&module.require.bind(module);function l(t,r){if(!a[t]){if(!e[t]){var s="function"==typeof i[n]&&i[n];if(!r&&s)return s(t,!0);if(o)return o(t,!0);if(c&&"string"==typeof t)return c(t);var u=new Error("Cannot find module '"+t+"'");throw u.code="MODULE_NOT_FOUND",u}d.resolve=function(r){var n=e[t][1][r];return null!=n?n:r},d.cache={};var h=a[t]=new l.Module(t);e[t][0].call(h.exports,d,h,h.exports,this)}return a[t].exports;function d(e){var t=d.resolve(e);return!1===t?{}:l(t)}}l.isParcelRequire=!0,l.Module=function(e){this.id=e,this.bundle=l,this.exports={}},l.modules=e,l.cache=a,l.parent=o,l.register=function(t,r){e[t]=[function(e,t){t.exports=r},{}]},Object.defineProperty(l,"root",{get:function(){return i[n]}}),i[n]=l;for(var u=0;u<t.length;u++)l(t[u])}({aZqqK:[function(e,t,r){var n=e("@parcel/transformer-js/src/esmodule-helpers.js");n.defineInteropFlag(r),n.export(r,"joinRoom",(()=>bA)),n.export(r,"selfId",(()=>US));var s=arguments[3],i=e("c1f15e2440b26488");function o(e=0){return new Uint8Array(e)}function a(e=0){return new Uint8Array(e)}const c=268435456,l=34359738368,u=4398046511104,h=Math.pow(2,49),d=128,p=127;function f(e){if(e<128)return 1;if(e<16384)return 2;if(e<2097152)return 3;if(e<c)return 4;if(e<l)return 5;if(e<u)return 6;if(e<h)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function g(e,t,r=0){switch(f(e)){case 8:t[r++]=255&e|d,e/=128;case 7:t[r++]=255&e|d,e/=128;case 6:t[r++]=255&e|d,e/=128;case 5:t[r++]=255&e|d,e/=128;case 4:t[r++]=255&e|d,e>>>=7;case 3:t[r++]=255&e|d,e>>>=7;case 2:t[r++]=255&e|d,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw Error("unreachable")}return t}function m(e,t){let r=e[t],n=0;if(n+=r&p,r<d)return n;if(r=e[t+1],n+=(r&p)<<7,r<d)return n;if(r=e[t+2],n+=(r&p)<<14,r<d)return n;if(r=e[t+3],n+=(r&p)<<21,r<d)return n;if(r=e[t+4],n+=(r&p)*c,r<d)return n;if(r=e[t+5],n+=(r&p)*l,r<d)return n;if(r=e[t+6],n+=(r&p)*u,r<d)return n;if(r=e[t+7],n+=(r&p)*h,r<d)return n;throw new RangeError("Could not decode varint")}function y(e,t,r=0){return null==t&&(t=a(f(e))),t instanceof Uint8Array?g(e,t,r):function(e,t,r=0){switch(f(e)){case 8:t.set(r++,255&e|d),e/=128;case 7:t.set(r++,255&e|d),e/=128;case 6:t.set(r++,255&e|d),e/=128;case 5:t.set(r++,255&e|d),e/=128;case 4:t.set(r++,255&e|d),e>>>=7;case 3:t.set(r++,255&e|d),e>>>=7;case 2:t.set(r++,255&e|d),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw Error("unreachable")}return t}(e,t,r)}function b(e,t=0){return e instanceof Uint8Array?m(e,t):function(e,t){let r=e.get(t),n=0;if(n+=r&p,r<d)return n;if(r=e.get(t+1),n+=(r&p)<<7,r<d)return n;if(r=e.get(t+2),n+=(r&p)<<14,r<d)return n;if(r=e.get(t+3),n+=(r&p)<<21,r<d)return n;if(r=e.get(t+4),n+=(r&p)*c,r<d)return n;if(r=e.get(t+5),n+=(r&p)*l,r<d)return n;if(r=e.get(t+6),n+=(r&p)*u,r<d)return n;if(r=e.get(t+7),n+=(r&p)*h,r<d)return n;throw new RangeError("Could not decode varint")}(e,t)}const w=new Float32Array([-0]),v=new Uint8Array(w.buffer);function E(e,t,r){w[0]=e,t[r]=v[0],t[r+1]=v[1],t[r+2]=v[2],t[r+3]=v[3]}const S=new Float64Array([-0]),A=new Uint8Array(S.buffer);function I(e,t,r){S[0]=e,t[r]=A[0],t[r+1]=A[1],t[r+2]=A[2],t[r+3]=A[3],t[r+4]=A[4],t[r+5]=A[5],t[r+6]=A[6],t[r+7]=A[7]}const _=BigInt(Number.MAX_SAFE_INTEGER),C=BigInt(Number.MIN_SAFE_INTEGER);class x{lo;hi;constructor(e,t){this.lo=0|e,this.hi=0|t}toNumber(e=!1){if(!e&&this.hi>>>31>0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(0n===e)return k;if(e<_&&e>C)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let r=e>>32n,n=e-(r<<32n);return t&&(r=0n|~r,n=0n|~n,++n>T&&(n=0n,++r>T&&(r=0n))),new x(Number(n),Number(r))}static fromNumber(e){if(0===e)return k;const t=e<0;t&&(e=-e);let r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new x(r,n)}static from(e){return"number"==typeof e?x.fromNumber(e):"bigint"==typeof e?x.fromBigInt(e):"string"==typeof e?x.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new x(e.low>>>0,e.high>>>0):k}}const k=new x(0,0);k.toBigInt=()=>0n,k.zzEncode=k.zzDecode=function(){return this},k.length=()=>1;const T=4294967296n;function P(e,t,r){const n=r;let s,i;for(let n=0;n<e.length;++n)s=e.charCodeAt(n),s<128?t[r++]=s:s<2048?(t[r++]=s>>6|192,t[r++]=63&s|128):55296==(64512&s)&&56320==(64512&(i=e.charCodeAt(n+1)))?(s=65536+((1023&s)<<10)+(1023&i),++n,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128);return r-n}function R(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function L(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class D{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,R(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw R(this,4);return L(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw R(this,4);return 0|L(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw R(this,4);const e=(t=this.buf,r=this.pos,v[0]=t[r],v[1]=t[r+1],v[2]=t[r+2],v[3]=t[r+3],w[0]);var t,r;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw R(this,4);const e=(t=this.buf,r=this.pos,A[0]=t[r],A[1]=t[r+1],A[2]=t[r+2],A[3]=t[r+3],A[4]=t[r+4],A[5]=t[r+5],A[6]=t[r+6],A[7]=t[r+7],S[0]);var t,r;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw R(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){const e=this.bytes();return function(e,t,r){if(r-t<1)return"";let n;const s=[];let i,o=0;for(;t<r;)i=e[t++],i<128?s[o++]=i:i>191&&i<224?s[o++]=(31&i)<<6|63&e[t++]:i>239&&i<365?(i=((7&i)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[o++]=55296+(i>>10),s[o++]=56320+(1023&i)):s[o++]=(15&i)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,s)),o=0);return null!=n?(o>0&&n.push(String.fromCharCode.apply(String,s.slice(0,o))),n.join("")):String.fromCharCode.apply(String,s.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw R(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw R(this)}while(128&this.buf[this.pos++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new x(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw R(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw R(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw R(this,8);const e=L(this.buf,this.pos+=4),t=L(this.buf,this.pos+=4);return new x(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=m(this.buf,this.pos);return this.pos+=f(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function M(e,t,r){const n=function(e){return new D(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}function N(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error("Unknown type, must be binary type")}var O=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var s=0;s<e.length;s++){var i=e.charAt(s),o=i.charCodeAt(0);if(255!==r[o])throw new TypeError(i+" is ambiguous");r[o]=s}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var n=0,s=0;e[t]===c;)n++,t++;for(var i=(e.length-t)*l+1>>>0,o=new Uint8Array(i);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var h=0,d=i-1;(0!==u||h<s)&&-1!==d;d--,h++)u+=a*o[d]>>>0,o[d]=u%256>>>0,u=u/256>>>0;if(0!==u)throw Error("Non-zero carry");s=h,t++}if(" "!==e[t]){for(var p=i-s;p!==i&&0===o[p];)p++;for(var f=new Uint8Array(n+(i-p)),g=n;p!==i;)f[g++]=o[p++];return f}}}return{encode(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,s=0,i=t.length;s!==i&&0===t[s];)s++,r++;for(var o=(i-s)*u+1>>>0,l=new Uint8Array(o);s!==i;){for(var h=t[s],d=0,p=o-1;(0!==h||d<n)&&-1!==p;p--,d++)h+=256*l[p]>>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw Error("Non-zero carry");n=d,s++}for(var f=o-n;f!==o&&0===l[f];)f++;for(var g=c.repeat(r);f<o;++f)g+=e.charAt(l[f]);return g},decodeUnsafe:h,decode(e){var r=h(e);if(r)return r;throw Error(`Non-${t} character`)}}};class U{decoders;constructor(e){this.decoders=e}or(e){return F(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(null!=r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function F(e,t){return new U({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}class B{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,r,n){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new class{name;prefix;baseEncode;constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}(e,t,r),this.decoder=new class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){this.name=e,this.prefix=t;const n=t.codePointAt(0);if(void 0===n)throw Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return F(this,e)}}(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function $({name:e,prefix:t,encode:r,decode:n}){return new B(e,t,r,n)}function q({name:e,prefix:t,alphabet:r}){const{encode:n,decode:s}=O(r,e);return $({prefix:t,name:e,encode:n,decode:e=>N(s(e))})}function z({name:e,prefix:t,bitsPerChar:r,alphabet:n}){const s=function(e){const t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}(n);return $({prefix:t,name:e,encode:e=>function(e,t,r){const n="="===t[t.length-1],s=(1<<r)-1;let i="",o=0,a=0;for(let n=0;n<e.length;++n)for(a=a<<8|e[n],o+=8;o>r;)o-=r,i+=t[s&a>>o];if(0!==o&&(i+=t[s&a<<r-o]),n)for(;i.length*r&7;)i+="=";return i}(e,n,r),decode:t=>function(e,t,r,n){let s=e.length;for(;"="===e[s-1];)--s;const i=new Uint8Array(s*r/8|0);let o=0,a=0,c=0;for(let l=0;l<s;++l){const s=t[e[l]];if(void 0===s)throw new SyntaxError(`Non-${n} character`);a=a<<r|s,o+=r,o>=8&&(o-=8,i[c++]=255&a>>o)}if(o>=r||255&a<<8-o)throw new SyntaxError("Unexpected end of data");return i}(t,s,r,e)})}const j=q({prefix:"9",name:"base10",alphabet:"0123456789"});var K=Object.freeze({__proto__:null,base10:j});const V=z({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),H=z({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var G=Object.freeze({__proto__:null,base16:V,base16upper:H});const W=z({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var X=Object.freeze({__proto__:null,base2:W});const Z=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Y=Z.reduce(((e,t,r)=>(e[r]=t,e)),[]),Q=Z.reduce(((e,t,r)=>{const n=t.codePointAt(0);if(null==n)throw Error("Invalid character: "+t);return e[n]=r,e}),[]),J=$({prefix:"🚀",name:"base256emoji",encode:e=>e.reduce(((e,t)=>e+Y[t]),""),decode(e){const t=[];for(const r of e){const e=r.codePointAt(0);if(null==e)throw Error("Invalid character: "+r);const n=Q[e];if(null==n)throw Error("Non-base256emoji character: "+r);t.push(n)}return new Uint8Array(t)}});var ee=Object.freeze({__proto__:null,base256emoji:J});const te=z({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),re=z({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ne=z({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),se=z({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ie=z({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),oe=z({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ae=z({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ce=z({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),le=z({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ue=Object.freeze({__proto__:null,base32:te,base32hex:ie,base32hexpad:ae,base32hexpadupper:ce,base32hexupper:oe,base32pad:ne,base32padupper:se,base32upper:re,base32z:le});const he=q({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),de=q({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var pe=Object.freeze({__proto__:null,base36:he,base36upper:de});const fe=q({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ge=q({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var me=Object.freeze({__proto__:null,base58btc:fe,base58flickr:ge});const ye=z({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),be=z({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),we=z({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ve=z({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ee=Object.freeze({__proto__:null,base64:ye,base64pad:be,base64url:we,base64urlpad:ve});const Se=z({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ae=Object.freeze({__proto__:null,base8:Se});const Ie=$({prefix:"\0",name:"identity",encode(e){var t;return t=e,(new TextDecoder).decode(t)},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)});var _e=Object.freeze({__proto__:null,identity:Ie});new TextEncoder,new TextDecoder;var Ce=Math.pow(2,63),xe={encode:function e(t,r,n){r=r||[];for(var s=n=n||0;t>=2147483648;)r[n++]=255&t|128,t/=128;for(;-128&t;)r[n++]=255&t|128,t>>>=7;return r[n]=0|t,e.bytes=n-s+1,r},decode:function e(t,r){var n,s=0,i=0,o=r=r||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[o++],s+=i<28?(127&n)<<i:(127&n)*Math.pow(2,i),i+=7}while(n>=128);return e.bytes=o-r,s},encodingLength:e=>e<128?1:e<16384?2:e<2097152?3:e<268435456?4:e<34359738368?5:e<4398046511104?6:e<562949953421312?7:e<72057594037927940?8:e<Ce?9:10};function ke(e,t=0){return[xe.decode(e,t),xe.decode.bytes]}function Te(e,t,r=0){return xe.encode(e,t,r),t}function Pe(e){return xe.encodingLength(e)}function Re(e,t){const r=t.byteLength,n=Pe(e),s=n+Pe(r),i=new Uint8Array(s+r);return Te(e,i,0),Te(r,i,n),i.set(t,s),new De(e,r,t,i)}function Le(e){const t=N(e),[r,n]=ke(t),[s,i]=ke(t.subarray(n)),o=t.subarray(n+i);if(o.byteLength!==s)throw Error("Incorrect length");return new De(r,s,o,t)}class De{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}}const Me=N,Ne={code:0,name:"identity",encode:Me,digest:e=>Re(0,Me(e))};class Oe{name;code;encode;constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Re(this.code,t):t.then((e=>Re(this.code,e)))}throw Error("Unknown type, must be binary type")}}const Ue=function({name:e,code:t,encode:r}){return new Oe(e,t,r)}({name:"sha2-256",code:18,encode:async e=>new Uint8Array(await crypto.subtle.digest("SHA-256",e))});function Fe(e,t){const{bytes:r,version:n}=e;return 0===n?function(e,t,r){const{prefix:n}=r;if(n!==fe.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const s=t.get(n);if(null==s){const s=r.encode(e).slice(1);return t.set(n,s),s}return s}(r,$e(e),t??fe.encoder):function(e,t,r){const{prefix:n}=r,s=t.get(n);if(null==s){const s=r.encode(e);return t.set(n,s),s}return s}(r,$e(e),t??te.encoder)}const Be=new WeakMap;function $e(e){const t=Be.get(e);if(null==t){const t=new Map;return Be.set(e,t),t}return t}class qe{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=n,this["/"]=n}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:e,multihash:t}=this;if(e!==ze)throw Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==je)throw Error("Cannot convert non sha2-256 multihash CID to CIDv0");return qe.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:e,digest:t}=this.multihash,r=Re(e,t);return qe.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return qe.equals(this,e)}static equals(e,t){const r=t;return null!=r&&e.code===r.code&&e.version===r.version&&function(e,t){if(e===t)return!0;{const r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&((e,t)=>{if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0})(e.bytes,r.bytes)}}(e.multihash,r.multihash)}toString(e){return Fe(this,e)}toJSON(){return{"/":Fe(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(null==e)return null;const t=e;if(t instanceof qe)return t;if(null!=t["/"]&&t["/"]===t.bytes||t.asCID===t){const{version:e,code:r,multihash:n,bytes:s}=t;return new qe(e,r,n,s??Ke(e,r,n.bytes))}if(!0===t[Ve]){const{version:e,multihash:r,code:n}=t,s=Le(r);return qe.create(e,n,s)}return null}static create(e,t,r){if("number"!=typeof t)throw Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw Error("Invalid digest");switch(e){case 0:if(t!==ze)throw Error(`Version 0 CID must use dag-pb (code: ${ze}) block encoding`);return new qe(e,t,r,r.bytes);case 1:{const n=Ke(e,t,r.bytes);return new qe(e,t,r,n)}default:throw Error("Invalid version")}}static createV0(e){return qe.create(0,ze,e)}static createV1(e,t){return qe.create(1,e,t)}static decode(e){const[t,r]=qe.decodeFirst(e);if(0!==r.length)throw Error("Incorrect length");return t}static decodeFirst(e){const t=qe.inspectBytes(e),r=t.size-t.multihashSize,n=N(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw Error("Incorrect length");const s=n.subarray(t.multihashSize-t.digestSize),i=new De(t.multihashCode,t.digestSize,s,n);return[0===t.version?qe.createV0(i):qe.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0;const r=()=>{const[r,n]=ke(e.subarray(t));return t+=n,r};let n=r(),s=ze;if(18===n?(n=0,t=0):s=r(),0!==n&&1!==n)throw new RangeError("Invalid CID version "+n);const i=t,o=r(),a=r(),c=t+a;return{version:n,codec:s,multihashCode:o,digestSize:a,multihashSize:c-i,size:c}}static parse(e,t){const[r,n]=function(e,t){switch(e[0]){case"Q":{const r=t??fe;return[fe.prefix,r.decode(`${fe.prefix}${e}`)]}case fe.prefix:{const r=t??fe;return[fe.prefix,r.decode(e)]}case te.prefix:{const r=t??te;return[te.prefix,r.decode(e)]}case he.prefix:{const r=t??he;return[he.prefix,r.decode(e)]}default:if(null==t)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(e,t),s=qe.decode(n);if(0===s.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return $e(s).set(r,e),s}}const ze=112,je=18;function Ke(e,t,r){const n=Pe(e),s=n+Pe(t),i=new Uint8Array(s+r.byteLength);return Te(e,i,0),Te(t,i,n),i.set(r,s),i}const Ve=Symbol.for("@ipld/js-cid/CID"),He={..._e,...X,...Ae,...K,...G,...ue,...pe,...me,...Ee,...ee};function Ge(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}const We=Ge("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Xe=Ge("ascii","a",(e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}),(e=>{const t=a((e=e.substring(1)).length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t})),Ze={utf8:We,"utf-8":We,hex:He.base16,latin1:Xe,ascii:Xe,binary:Xe,...He};function Ye(e,t="utf8"){const r=Ze[t];if(null==r)throw Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}class Qe{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}}function Je(){}class et{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const tt=function(){const e=8192;let t,r=e;return function(n){if(n<1||n>4096)return a(n);r+n>e&&(t=a(e),r=0);const s=t.subarray(r,r+=n);return 7&r&&(r=1+(7|r)),s}}();class rt{len;head;tail;states;constructor(){this.len=0,this.head=new Qe(Je,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new Qe(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new it((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(ot,10,x.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=x.fromBigInt(e);return this._push(ot,t.length(),t)}uint64Number(e){return this._push(g,f(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const t=x.fromBigInt(e).zzEncode();return this._push(ot,t.length(),t)}sint64Number(e){const t=x.fromNumber(e).zzEncode();return this._push(ot,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(nt,1,e?1:0)}fixed32(e){return this._push(at,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=x.fromBigInt(e);return this._push(at,4,t.lo)._push(at,4,t.hi)}fixed64Number(e){const t=x.fromNumber(e);return this._push(at,4,t.lo)._push(at,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(E,4,e)}double(e){return this._push(I,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(nt,1,0):this.uint32(t)._push(ct,t,e)}string(e){const t=function(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(n+1))?(++n,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(P,t,e):this._push(nt,1,0)}fork(){return this.states=new et(this),this.head=this.tail=new Qe(Je,0,0),this.len=0,this}reset(){return null!=this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Qe(Je,0,0),this.len=0),this}ldelim(){const e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),0!==r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this}finish(){let e=this.head.next;const t=(r=this.len,null!=globalThis.Buffer?a(r):tt(r));var r;let n=0;for(;null!=e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}}function nt(e,t,r){t[r]=255&e}function st(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class it extends Qe{next;constructor(e,t){super(st,e,t),this.next=void 0}}function ot(e,t,r){for(;0!==e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function at(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function ct(e,t,r){t.set(e,r)}function lt(e,t,r){t.set(e,r)}function ut(e,t,r){e.length<40?P(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set(Ye(e),r)}function ht(e,t){const r=new rt;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var dt,pt,ft,gt,mt,yt,bt,wt,vt,Et,St,At,It,_t,Ct,xt,kt,Tt,Pt,Rt,Lt,Dt,Mt,Nt,Ot,Ut,Ft,Bt,$t,qt,zt,jt,Kt,Vt;function Ht(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function Gt(e){function t(t){if(null==e[t.toString()])throw Error("Invalid enum value");return e[t]}return Ht("enum",dt.VARINT,(function(e,r){const n=t(e);r.int32(n)}),(function(e){return t(e.int32())}))}function Wt(e,t){return Ht("message",dt.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(rt.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(lt,t,e),this},rt.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(ut,t,e),this}),(e=>{e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(dt||(dt={}));class Xt extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}class Zt extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}function Yt(e){return!!e}(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(pt||(pt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),pt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=pt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(ft||(ft={})),(e=>{let t;(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(10),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={contentTopic:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.contentTopic=e.string():e.skipType(7&t)}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(e.ContentFilter||(e.ContentFilter={})),e.codec=()=>(null==t&&(t=Wt(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.subscribe&&!1!==t.subscribe&&(r.uint32(8),r.bool(t.subscribe)),null!=t.topic&&""!==t.topic&&(r.uint32(18),r.string(t.topic)),null!=t.contentFilters)for(const n of t.contentFilters)r.uint32(26),e.ContentFilter.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={subscribe:!1,topic:"",contentFilters:[]},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:s.subscribe=t.bool();break;case 2:s.topic=t.string();break;case 3:if(null!=n.limits?.contentFilters&&s.contentFilters.length===n.limits.contentFilters)throw new Xt('Decode error - map field "contentFilters" had too many elements');s.contentFilters.push(e.ContentFilter.codec().decode(t,t.uint32(),{limits:n.limits?.contentFilters$}));break;default:t.skipType(7&r)}}return s}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(gt||(gt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(const r of e.messages)t.uint32(10),wt.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messages:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();if(t>>>3==1){if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new Xt('Decode error - map field "messages" had too many elements');n.messages.push(wt.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(mt||(mt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),gt.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),mt.codec().encode(e.push,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.request=gt.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=mt.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(yt||(yt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(bt||(bt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),bt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=bt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(wt||(wt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={contentTopic:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==2?r.contentTopic=e.string():e.skipType(7&t)}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(vt||(vt={})),(e=>{let t,r,n;(e=>{e.SUBSCRIBER_PING="SUBSCRIBER_PING",e.SUBSCRIBE="SUBSCRIBE",e.UNSUBSCRIBE="UNSUBSCRIBE",e.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL"})(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),(e=>{e[e.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",e[e.SUBSCRIBE=1]="SUBSCRIBE",e[e.UNSUBSCRIBE=2]="UNSUBSCRIBE",e[e.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL"})(r||(r={})),(e=>{e.codec=()=>Gt(r)})(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),e.codec=()=>(null==n&&(n=Wt(((t,n,s={})=>{if(!1!==s.lengthDelimited&&n.fork(),null!=t.requestId&&""!==t.requestId&&(n.uint32(10),n.string(t.requestId)),null!=t.filterSubscribeType&&0!==r[t.filterSubscribeType]&&(n.uint32(16),e.FilterSubscribeType.codec().encode(t.filterSubscribeType,n)),null!=t.pubsubTopic&&(n.uint32(82),n.string(t.pubsubTopic)),null!=t.contentTopics)for(const e of t.contentTopics)n.uint32(90),n.string(e);!1!==s.lengthDelimited&&n.ldelim()}),((r,n,s={})=>{const i={requestId:"",filterSubscribeType:t.SUBSCRIBER_PING,contentTopics:[]},o=null==n?r.len:r.pos+n;for(;r.pos<o;){const t=r.uint32();switch(t>>>3){case 1:i.requestId=r.string();break;case 2:i.filterSubscribeType=e.FilterSubscribeType.codec().decode(r);break;case 10:i.pubsubTopic=r.string();break;case 11:if(null!=s.limits?.contentTopics&&i.contentTopics.length===s.limits.contentTopics)throw new Xt('Decode error - map field "contentTopics" had too many elements');i.contentTopics.push(r.string());break;default:r.skipType(7&t)}}return i}))),n),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Et||(Et={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&0!==e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={requestId:"",statusCode:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.requestId=e.string();break;case 10:r.statusCode=e.uint32();break;case 11:r.statusDesc=e.string();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(St||(St={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),_t.codec().encode(e.wakuMessage,t)),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.wakuMessage=_t.codec().decode(e,e.uint32(),{limits:r.limits?.wakuMessage});break;case 2:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(At||(At={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(It||(It={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),It.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=It.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(_t||(_t={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.pubsubTopic&&""!==e.pubsubTopic&&(t.uint32(10),t.string(e.pubsubTopic)),null!=e.message&&(t.uint32(18),Lt.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={pubsubTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.pubsubTopic=e.string();break;case 2:n.message=Lt.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ct||(Ct={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.isSuccess&&!1!==e.isSuccess&&(t.uint32(8),t.bool(e.isSuccess)),null!=e.info&&(t.uint32(18),t.string(e.info)),null!=e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.relayPeerCount&&(t.uint32(96),t.uint32(e.relayPeerCount)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={isSuccess:!1},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.isSuccess=e.bool();break;case 2:r.info=e.string();break;case 10:r.statusCode=e.uint32();break;case 11:r.statusDesc=e.string();break;case 12:r.relayPeerCount=e.uint32();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(xt||(xt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),Ct.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),xt.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.request=Ct.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=xt.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(kt||(kt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.pubsubTopic&&(t.uint32(162),t.string(e.pubsubTopic)),null!=e.message&&(t.uint32(170),Lt.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 20:n.pubsubTopic=e.string();break;case 21:n.message=Lt.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Tt||(Tt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&0!==e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.relayPeerCount&&(t.uint32(96),t.uint32(e.relayPeerCount)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={requestId:"",statusCode:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.requestId=e.string();break;case 10:r.statusCode=e.uint32();break;case 11:r.statusDesc=e.string();break;case 12:r.relayPeerCount=e.uint32();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Pt||(Pt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Rt||(Rt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),Rt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=Rt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Lt||(Lt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.messageHash&&(t.uint32(10),t.bytes(e.messageHash)),null!=e.message&&(t.uint32(18),Ut.codec().encode(e.message,t)),null!=e.pubsubTopic&&(t.uint32(26),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.messageHash=e.bytes();break;case 2:n.message=Ut.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;case 3:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Dt||(Dt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.includeData&&!1!==e.includeData&&(t.uint32(16),t.bool(e.includeData)),null!=e.pubsubTopic&&(t.uint32(82),t.string(e.pubsubTopic)),null!=e.contentTopics)for(const r of e.contentTopics)t.uint32(90),t.string(r);if(null!=e.timeStart&&(t.uint32(96),t.sint64(e.timeStart)),null!=e.timeEnd&&(t.uint32(104),t.sint64(e.timeEnd)),null!=e.messageHashes)for(const r of e.messageHashes)t.uint32(162),t.bytes(r);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),null!=e.paginationForward&&!1!==e.paginationForward&&(t.uint32(416),t.bool(e.paginationForward)),null!=e.paginationLimit&&(t.uint32(424),t.uint64(e.paginationLimit)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",includeData:!1,contentTopics:[],messageHashes:[],paginationForward:!1},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.includeData=e.bool();break;case 10:n.pubsubTopic=e.string();break;case 11:if(null!=r.limits?.contentTopics&&n.contentTopics.length===r.limits.contentTopics)throw new Xt('Decode error - map field "contentTopics" had too many elements');n.contentTopics.push(e.string());break;case 12:n.timeStart=e.sint64();break;case 13:n.timeEnd=e.sint64();break;case 20:if(null!=r.limits?.messageHashes&&n.messageHashes.length===r.limits.messageHashes)throw new Xt('Decode error - map field "messageHashes" had too many elements');n.messageHashes.push(e.bytes());break;case 51:n.paginationCursor=e.bytes();break;case 52:n.paginationForward=e.bool();break;case 53:n.paginationLimit=e.uint64();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Mt||(Mt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.messages)for(const r of e.messages)t.uint32(162),Dt.codec().encode(r,t);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",messages:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;case 20:if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new Xt('Decode error - map field "messages" had too many elements');n.messages.push(Dt.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}));break;case 51:n.paginationCursor=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Nt||(Nt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={proof:o(0),merkleRoot:o(0),epoch:o(0),shareX:o(0),shareY:o(0),nullifier:o(0),rlnIdentifier:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.proof=e.bytes();break;case 2:r.merkleRoot=e.bytes();break;case 3:r.epoch=e.bytes();break;case 4:r.shareX=e.bytes();break;case 5:r.shareY=e.bytes();break;case 6:r.nullifier=e.bytes();break;case 7:r.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ot||(Ot={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),Ot.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:o(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=Ot.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ut||(Ut={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.enr&&(t.uint32(10),t.bytes(e.enr)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.enr=e.bytes():e.skipType(7&t)}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Ft||(Ft={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.numPeers&&(t.uint32(8),t.uint64(e.numPeers)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.numPeers=e.uint64():e.skipType(7&t)}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Bt||(Bt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(const r of e.peerInfos)t.uint32(10),Ft.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={peerInfos:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();if(t>>>3==1){if(null!=r.limits?.peerInfos&&n.peerInfos.length===r.limits.peerInfos)throw new Xt('Decode error - map field "peerInfos" had too many elements');n.peerInfos.push(Ft.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})($t||($t={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),Bt.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),$t.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.query=Bt.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=$t.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(qt||(qt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new Xt('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(zt||(zt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new Xt('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(jt||(jt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.messageId&&""!==e.messageId&&(t.uint32(10),t.string(e.messageId)),null!=e.retrievalHint&&(t.uint32(18),t.bytes(e.retrievalHint)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={messageId:""},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.messageId=e.string();break;case 2:r.retrievalHint=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Kt||(Kt={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.senderId&&""!==e.senderId&&(t.uint32(10),t.string(e.senderId)),null!=e.messageId&&""!==e.messageId&&(t.uint32(18),t.string(e.messageId)),null!=e.channelId&&""!==e.channelId&&(t.uint32(26),t.string(e.channelId)),null!=e.lamportTimestamp&&(t.uint32(80),t.int32(e.lamportTimestamp)),null!=e.causalHistory)for(const r of e.causalHistory)t.uint32(90),Kt.codec().encode(r,t);null!=e.bloomFilter&&(t.uint32(98),t.bytes(e.bloomFilter)),null!=e.content&&(t.uint32(162),t.bytes(e.content)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={senderId:"",messageId:"",channelId:"",causalHistory:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.senderId=e.string();break;case 2:n.messageId=e.string();break;case 3:n.channelId=e.string();break;case 10:n.lamportTimestamp=e.int32();break;case 11:if(null!=r.limits?.causalHistory&&n.causalHistory.length===r.limits.causalHistory)throw new Xt('Decode error - map field "causalHistory" had too many elements');n.causalHistory.push(Kt.codec().decode(e,e.uint32(),{limits:r.limits?.causalHistory$}));break;case 12:n.bloomFilter=e.bytes();break;case 20:n.content=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Vt||(Vt={}));const Qt="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Jt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function er(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function tr(e,...t){if(!Jt(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function rr(e){if("function"!=typeof e||"function"!=typeof e.create)throw Error("Hash should be wrapped by utils.createHasher");er(e.outputLen),er(e.blockLen)}function nr(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function sr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ir(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function or(e,t){return e<<32-t|e>>>t}const ar="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,cr=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function lr(e){if(tr(e),ar)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=cr[e[r]];return t}const ur=48,hr=57,dr=65,pr=70,fr=97,gr=102;function mr(e){return e>=ur&&e<=hr?e-ur:e>=dr&&e<=pr?e-(dr-10):e>=fr&&e<=gr?e-(fr-10):void 0}function yr(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);if(ar)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,s=0;t<r;t++,s+=2){const r=mr(e.charCodeAt(s)),i=mr(e.charCodeAt(s+1));if(void 0===r||void 0===i){const t=e[s]+e[s+1];throw Error('hex string expected, got non-hex character "'+t+'" at index '+s)}n[t]=16*r+i}return n}function br(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),tr(e),e}function wr(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];tr(n),t+=n.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}class vr{}function Er(e){const t=t=>e().update(br(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Sr(e=32){if(Qt&&"function"==typeof Qt.getRandomValues)return Qt.getRandomValues(new Uint8Array(e));if(Qt&&"function"==typeof Qt.randomBytes)return Uint8Array.from(Qt.randomBytes(e));throw Error("crypto.getRandomValues must be defined")}function Ar(e,t,r){return e&t^e&r^t&r}class Ir extends vr{constructor(e,t,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=ir(this.buffer)}update(e){nr(this),tr(e=br(e));const{view:t,buffer:r,blockLen:n}=this,s=e.length;for(let i=0;i<s;){const o=Math.min(n-this.pos,s-i);if(o!==n)r.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===n&&(this.process(t,0),this.pos=0);else{const t=ir(e);for(;n<=s-i;i+=n)this.process(t,i)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){nr(this),function(e,t){tr(e);const r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:s}=this;let{pos:i}=this;t[i++]=128,sr(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(r,0),i=0);for(let e=i;e<n;e++)t[e]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}(r,n-8,BigInt(8*this.length),s),this.process(r,0);const o=ir(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],s)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:s,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=s,e.length=n,e.pos=o,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const _r=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Cr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),xr=BigInt(2**32-1),kr=BigInt(32);function Tr(e,t=!1){return t?{h:Number(e&xr),l:Number(e>>kr&xr)}:{h:0|Number(e>>kr&xr),l:0|Number(e&xr)}}const Pr=(e,t,r)=>e>>>r,Rr=(e,t,r)=>e<<32-r|t>>>r,Lr=(e,t,r)=>e>>>r|t<<32-r,Dr=(e,t,r)=>e<<32-r|t>>>r,Mr=(e,t,r)=>e<<64-r|t>>>r-32,Nr=(e,t,r)=>e>>>r-32|t<<64-r;function Or(e,t,r,n){const s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:0|s}}const Ur=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Fr=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,Br=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),$r=(e,t,r,n,s)=>t+r+n+s+(e/2**32|0)|0,qr=(e,t,r,n,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(s>>>0),zr=(e,t,r,n,s,i)=>t+r+n+s+i+(e/2**32|0)|0,jr=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Kr=new Uint32Array(64);class Vr extends Ir{constructor(e=32){super(64,e,8,!1),this.A=0|_r[0],this.B=0|_r[1],this.C=0|_r[2],this.D=0|_r[3],this.E=0|_r[4],this.F=0|_r[5],this.G=0|_r[6],this.H=0|_r[7]}get(){const{A:e,B:t,C:r,D:n,E:s,F:i,G:o,H:a}=this;return[e,t,r,n,s,i,o,a]}set(e,t,r,n,s,i,o,a){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|s,this.F=0|i,this.G=0|o,this.H=0|a}process(e,t){for(let r=0;r<16;r++,t+=4)Kr[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Kr[e-15],r=Kr[e-2],n=or(t,7)^or(t,18)^t>>>3,s=or(r,17)^or(r,19)^r>>>10;Kr[e]=s+Kr[e-7]+n+Kr[e-16]|0}let{A:r,B:n,C:s,D:i,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(or(o,6)^or(o,11)^or(o,25))+((u=o)&a^~u&c)+jr[e]+Kr[e]|0,h=(or(r,2)^or(r,13)^or(r,22))+Ar(r,n,s)|0;l=c,c=a,a=o,o=i+t|0,i=s,s=n,n=r,r=t+h|0}var u;r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,s,i,o,a,c,l)}roundClean(){sr(Kr)}destroy(){this.set(0,0,0,0,0,0,0,0),sr(this.buffer)}}const Hr=function(e,t=!1){const r=e.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:r,l:o}=Tr(e[i],t);[n[i],s[i]]=[r,o]}return[n,s]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))),Gr=Hr[0],Wr=Hr[1],Xr=new Uint32Array(80),Zr=new Uint32Array(80);class Yr extends Ir{constructor(e=64){super(128,e,16,!1),this.Ah=0|Cr[0],this.Al=0|Cr[1],this.Bh=0|Cr[2],this.Bl=0|Cr[3],this.Ch=0|Cr[4],this.Cl=0|Cr[5],this.Dh=0|Cr[6],this.Dl=0|Cr[7],this.Eh=0|Cr[8],this.El=0|Cr[9],this.Fh=0|Cr[10],this.Fl=0|Cr[11],this.Gh=0|Cr[12],this.Gl=0|Cr[13],this.Hh=0|Cr[14],this.Hl=0|Cr[15]}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:s,Cl:i,Dh:o,Dl:a,Eh:c,El:l,Fh:u,Fl:h,Gh:d,Gl:p,Hh:f,Hl:g}=this;return[e,t,r,n,s,i,o,a,c,l,u,h,d,p,f,g]}set(e,t,r,n,s,i,o,a,c,l,u,h,d,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|s,this.Cl=0|i,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|h,this.Gh=0|d,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let r=0;r<16;r++,t+=4)Xr[r]=e.getUint32(t),Zr[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Xr[e-15],r=0|Zr[e-15],n=Lr(t,r,1)^Lr(t,r,8)^Pr(t,0,7),s=Dr(t,r,1)^Dr(t,r,8)^Rr(t,r,7),i=0|Xr[e-2],o=0|Zr[e-2],a=Lr(i,o,19)^Mr(i,o,61)^Pr(i,0,6),c=Dr(i,o,19)^Nr(i,o,61)^Rr(i,o,6),l=Br(s,c,Zr[e-7],Zr[e-16]),u=$r(l,n,a,Xr[e-7],Xr[e-16]);Xr[e]=0|u,Zr[e]=0|l}let{Ah:r,Al:n,Bh:s,Bl:i,Ch:o,Cl:a,Dh:c,Dl:l,Eh:u,El:h,Fh:d,Fl:p,Gh:f,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=Lr(u,h,14)^Lr(u,h,18)^Mr(u,h,41),b=Dr(u,h,14)^Dr(u,h,18)^Nr(u,h,41),w=u&d^~u&f,v=qr(y,b,h&p^~h&g,Wr[e],Zr[e]),E=zr(v,m,t,w,Gr[e],Xr[e]),S=0|v,A=Lr(r,n,28)^Mr(r,n,34)^Mr(r,n,39),I=Dr(r,n,28)^Nr(r,n,34)^Nr(r,n,39),_=r&s^r&o^s&o,C=n&i^n&a^i&a;m=0|f,y=0|g,f=0|d,g=0|p,d=0|u,p=0|h,({h:u,l:h}=Or(0|c,0|l,0|E,0|S)),c=0|o,l=0|a,o=0|s,a=0|i,s=0|r,i=0|n;const x=Ur(S,I,C);r=Fr(x,E,A,_),n=0|x}({h:r,l:n}=Or(0|this.Ah,0|this.Al,0|r,0|n)),({h:s,l:i}=Or(0|this.Bh,0|this.Bl,0|s,0|i)),({h:o,l:a}=Or(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=Or(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=Or(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:p}=Or(0|this.Fh,0|this.Fl,0|d,0|p)),({h:f,l:g}=Or(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=Or(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(r,n,s,i,o,a,c,l,u,h,d,p,f,g,m,y)}roundClean(){sr(Xr,Zr)}destroy(){sr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Qr=Er((()=>new Vr)),Jr=Er((()=>new Yr)),en=Qr;function tn(e,t="utf8"){const r=Ze[t];if(null==r)throw Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}function rn(e){return"string"==typeof e?Ye(e.replace(/^0x/i,"").toLowerCase(),"base16"):e}function nn(e){const t=new ArrayBuffer(8),r=new DataView(t);return"number"==typeof e?r.setFloat64(0,e,!1):r.setBigInt64(0,e,!1),new Uint8Array(t)}const sn=e=>tn(e,"base16"),on=e=>tn(e,"utf8"),an=e=>Ye(e,"utf8");function cn(e){const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}const ln=(e,t)=>`/waku/2/rs/${e}/${t}`,un=e=>{const t=e.split("/");if(6!=t.length||"waku"!==t[1]||"2"!==t[2]||"rs"!==t[3])throw Error("Invalid pubsub topic");const r=parseInt(t[4]),n=parseInt(t[5]);if(isNaN(r)||isNaN(n))throw Error("Invalid clusterId or shard");return{clusterId:r,shard:n}};function hn(e){const t=e.split("/");if(t.length<5||t.length>6)throw Error("Content topic format is invalid: "+e);let r=0;if(6==t.length){if(r=parseInt(t[1]),isNaN(r))throw Error("Invalid generation field in content topic: "+e);if(r>0)throw Error("Generation greater than 0 is not supported: "+e)}const n=t.splice(-4);if(0==n[0].length)throw Error("Application field cannot be empty: "+e);if(0==n[1].length)throw Error("Version field cannot be empty: "+e);if(0==n[2].length)throw Error("Topic name field cannot be empty: "+e);if(0==n[3].length)throw Error("Encoding field cannot be empty: "+e);return{generation:r,application:n[0],version:n[1],topicName:n[2],encoding:n[3]}}class dn{networkConfig;pubsubTopic;shardId;constructor(e,t,r){this.networkConfig=e,this.pubsubTopic=t,this.shardId=r}}class pn extends dn{networkConfig;pubsubTopic;shardId;contentTopic;static fromContentTopic(e,t){hn(e);const r=function(e,t){const{application:r,version:n}=hn(e),s=en(cn([an(r),an(n)])),i=new DataView(s.buffer.slice(-8));return Number(i.getBigUint64(0,!1)%BigInt(t))}(e,t.numShardsInCluster),n=ln(t.clusterId,r);return new pn(t,n,r,e)}constructor(e,t,r,n){super(e,t,r),this.networkConfig=e,this.pubsubTopic=t,this.shardId=r,this.contentTopic=n}get clusterId(){return this.networkConfig.clusterId}get isAutoSharding(){return!0}get isStaticSharding(){return!1}}class fn extends dn{networkConfig;pubsubTopic;shardId;static fromShard(e,t){const r=ln(t.clusterId,e);return new fn(t,r,e)}static fromPubsubTopic(e,t){const{clusterId:r,shard:n}=un(e);if(r!=t.clusterId)throw"Pubsub topic does not match network config's cluster id";return new fn(t,e,n)}constructor(e,t,r){super(e,t,r),this.networkConfig=e,this.pubsubTopic=t,this.shardId=r}get clusterId(){return this.networkConfig.clusterId}get isAutoSharding(){return!1}get isStaticSharding(){return!0}}function gn(e,t){if("clusterId"in(r=e)&&"numShardsInCluster"in r){if(t.contentTopic)return pn.fromContentTopic(t.contentTopic,e);throw Error("AutoSharding requires contentTopic")}if(void 0!==t.shardId)return fn.fromShard(t.shardId,e);if(t.pubsubTopic)return fn.fromPubsubTopic(t.pubsubTopic,e);var r;throw Error("StaticSharding requires shardId or pubsubTopic")}const mn=e=>{if((e=new Uint8Array(e)).length<3)throw Error("Insufficient data");const t=new DataView(e.buffer),r=t.getUint16(0),n=[];if(130===e.length)for(let e=0;e<1024;e++){const r=Math.floor(e/8)+2,s=7-e%8;t.getUint8(r)&1<<s&&n.push(e)}else{const r=t.getUint8(2);for(let s=0,i=3;s<r;s++,i+=2){if(i+1>=e.length)throw Error("Unexpected end of data");n.push(t.getUint16(i))}}return{clusterId:r,shards:n}},yn=e=>{const{clusterId:t,shards:r}=e,n=r.length>=64?130:3+2*r.length,s=new ArrayBuffer(n),i=new DataView(s);if(i.setUint16(0,t),r.length>=64)for(const e of r){const t=Math.floor(e/8)+2,r=7-e%8;i.setUint8(t,i.getUint8(t)|1<<r)}else{i.setUint8(2,r.length);for(let e=0,t=3;e<r.length;e++,t+=2)i.setUint16(t,r[e])}return new Uint8Array(s)},bn=Symbol.for("@libp2p/connection"),wn=Symbol.for("@libp2p/content-routing"),vn=Symbol.for("@libp2p/peer-discovery"),En=Symbol.for("@libp2p/peer-id");function Sn(e){return!!e?.[En]}const An=Symbol.for("@libp2p/peer-routing"),In="keep-alive",_n=Symbol.for("@libp2p/transport");var Cn;(e=>{e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(Cn||(Cn={}));let xn=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};class kn extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let Tn=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},Pn=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class Rn extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Ln extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}}class Dn extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}}class Mn extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}}class Nn extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}}class On extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class Un extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}let Fn=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};class Bn extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}}let $n=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}};class qn extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class zn extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class jn extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}}class Kn extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}}let Vn=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Hn=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}};class Gn extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}}class Wn extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}}class Xn extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}}class Zn extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}}class Yn extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}}class Qn extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}class Jn extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const t=this.#e.get(e);return null==t?0:t.length}addEventListener(e,t,r){super.addEventListener(e,t,r);let n=this.#e.get(e);null==n&&(n=[],this.#e.set(e,n)),n.push({callback:t,once:(!0!==r&&!1!==r&&r?.once)??!1})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let n=this.#e.get(e);null!=n&&(n=n.filter((({callback:e})=>e!==t)),this.#e.set(e,n))}dispatchEvent(e){const t=super.dispatchEvent(e);let r=this.#e.get(e.type);return null==r||(r=r.filter((({once:e})=>!e)),this.#e.set(e.type,r)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}}function es(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}const ts=Symbol.for("@libp2p/service-capabilities"),rs=Symbol.for("@libp2p/service-dependencies");var ns="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==s?s:"undefined"!=typeof self?self:{};function ss(e){return e&&e.__esModule&&{}.hasOwnProperty.call(e,"default")?e.default:e}var is,os,as,cs,ls,us={exports:{}},hs=(ls||(ls=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),t.splice(s,0,r)},t.save=e=>{try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=()=>{let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}return!e&&void 0!==i&&"env"in i&&(e=void 0),e},t.useColors=()=>{if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=(()=>{try{return localStorage}catch(e){}})(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=(cs||(cs=1,as=function(e){function t(e){let n,s,i,o=null;function a(...e){if(!a.enabled)return;const r=a,s=Number(new Date),i=s-(n||s);r.diff=i,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];n=i.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set(e){o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e,t){let r=0,n=0,s=-1,i=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(s=n,i=r,n++):(r++,n++);else{if(-1===s)return!1;n=s+1,i++,r=i}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=e=>e instanceof Error?e.stack||e.message:e,t.disable=()=>{const e=[...t.names,...t.skips.map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=e=>{t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=e=>{for(const r of t.skips)if(n(e,r))return!1;for(const r of t.names)if(n(e,r))return!0;return!1},t.humanize=function(){if(os)return is;os=1;var e=1e3,t=60*e,r=60*t,n=24*r;function s(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}return is=(i,o)=>{o=o||{};var a=typeof i;if("string"===a&&i.length>0)return function(s){if(!((s+="").length>100)){var i=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(i){var o=parseFloat(i[1]);switch((i[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*o;case"weeks":case"week":case"w":return 6048e5*o;case"days":case"day":case"d":return o*n;case"hours":case"hour":case"hrs":case"hr":case"h":return o*r;case"minutes":case"minute":case"mins":case"min":case"m":return o*t;case"seconds":case"second":case"secs":case"sec":case"s":return o*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}(i);if("number"===a&&isFinite(i))return o.long?function(i){var o=Math.abs(i);return o>=n?s(i,o,n,"day"):o>=r?s(i,o,r,"hour"):o>=t?s(i,o,t,"minute"):o>=e?s(i,o,e,"second"):i+" ms"}(i):function(s){var i=Math.abs(s);return i>=n?Math.round(s/n)+"d":i>=r?Math.round(s/r)+"h":i>=t?Math.round(s/t)+"m":i>=e?Math.round(s/e)+"s":s+"ms"}(i);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(i))},is}(),t.destroy=()=>{console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=e=>{let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}),as)(t);const{formatters:r}=e.exports;r.j=e=>{try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(us,us.exports)),us.exports),ds=ss(hs);const ps="waku";let fs=class e{_info;_warn;_error;static createDebugNamespace(e,t){return t?`${ps}:${t}:${e}`:`${ps}:${e}`}constructor(t){this._info=ds(e.createDebugNamespace("info",t)),this._warn=ds(e.createDebugNamespace("warn",t)),this._error=ds(e.createDebugNamespace("error",t))}get info(){return this._info}get warn(){return this._warn}get error(){return this._error}log(e,...t){(this[e]||this.log)(...t)}};function gs(e,t){const r=an(e),n=an(t.contentTopic),s=function(e){if(!e)return;let t;return t="bigint"==typeof e?e:1000000n*BigInt(e.valueOf()),nn(t)}(t.timestamp),i=cn([r,t.payload,n,t.meta,s].filter(Yt));return en(i)}const ms=new fs("message:version-0"),ys=BigInt(1e6);class bs{pubsubTopic;proto;_hash;_hashStr;constructor(e,t){this.pubsubTopic=e,this.proto=t}get ephemeral(){return!!this.proto.ephemeral}get payload(){return this.proto.payload}get contentTopic(){return this.proto.contentTopic}get hash(){return void 0===this._hash&&(this._hash=gs(this.pubsubTopic,this.proto)),this._hash}get hashStr(){return void 0===this._hashStr&&(this._hashStr=sn(this.hash)),this._hashStr}get timestamp(){try{if(this.proto.timestamp){const e=this.proto.timestamp/ys;return new Date(Number(e))}return}catch(e){return}}get meta(){return this.proto.meta}get version(){return this.proto.version??0}get rateLimitProof(){return this.proto.rateLimitProof}}let ws=class{contentTopic;ephemeral;routingInfo;metaSetter;constructor(e,t=!1,r,n){if(this.contentTopic=e,this.ephemeral=t,this.routingInfo=r,this.metaSetter=n,!e||""===e)throw Error("Content topic must be specified")}get pubsubTopic(){return this.routingInfo.pubsubTopic}async toWire(e){return ft.encode(await this.toProtoObj(e))}async toProtoObj(e){const t=e.timestamp??new Date,r={payload:e.payload,version:0,contentTopic:this.contentTopic,timestamp:BigInt(t.valueOf())*ys,meta:void 0,rateLimitProof:e.rateLimitProof,ephemeral:this.ephemeral};if(this.metaSetter){const e=this.metaSetter(r);return{...r,meta:e}}return r}};function vs({contentTopic:e,routingInfo:t,ephemeral:r,metaSetter:n}){return new ws(e,r,t,n)}var Es,Ss,As,Is,_s,Cs,xs;(e=>{e[e.SUCCESS=200]="SUCCESS",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",e[e.INVALID_MESSAGE=420]="INVALID_MESSAGE",e[e.UNSUPPORTED_TOPIC=421]="UNSUPPORTED_TOPIC",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.INTERNAL_ERROR=500]="INTERNAL_ERROR",e[e.UNAVAILABLE=503]="UNAVAILABLE",e[e.NO_RLN_PROOF=504]="NO_RLN_PROOF",e[e.NO_PEERS=505]="NO_PEERS"})(Es||(Es={})),Es.SUCCESS,Es.BAD_REQUEST,Es.PAYLOAD_TOO_LARGE,Es.INVALID_MESSAGE,Es.UNSUPPORTED_TOPIC,Es.TOO_MANY_REQUESTS,Es.INTERNAL_ERROR,Es.UNAVAILABLE,Es.NO_RLN_PROOF,Es.NO_PEERS,(e=>{e.Relay="relay",e.Store="store",e.LightPush="lightpush",e.Filter="filter"})(Ss||(Ss={})),(e=>{e.GENERIC_FAIL="Generic error",e.DECODE_FAILED="Failed to decode",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.STREAM_ABORTED="Stream aborted",e.ENCODE_FAILED="Failed to encode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.RLN_PROOF_GENERATION="Proof generation failed",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.BAD_REQUEST="Bad request format",e.PAYLOAD_TOO_LARGE="Message payload exceeds maximum size",e.INVALID_MESSAGE="Message validation failed",e.UNSUPPORTED_TOPIC="Unsupported pubsub topic",e.TOO_MANY_REQUESTS="Rate limit exceeded",e.INTERNAL_ERROR="Internal server error",e.UNAVAILABLE="Service temporarily unavailable",e.NO_RLN_PROOF="RLN proof generation failed",e.NO_PEERS="No relay peers available"})(As||(As={})),(e=>{e.GENERIC_FAIL="Generic error",e.DECODE_FAILED="Failed to decode",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.STREAM_ABORTED="Stream aborted",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.SUBSCRIPTION_FAILED="Subscription failed",e.UNSUBSCRIBE_FAILED="Unsubscribe failed",e.PING_FAILED="Ping failed",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.INVALID_DECODER_TOPICS="Invalid decoder topics",e.SUBSCRIPTION_LIMIT_EXCEEDED="Subscription limit exceeded",e.INVALID_CONTENT_TOPIC="Invalid content topic",e.PUSH_MESSAGE_FAILED="Push message failed",e.EMPTY_MESSAGE="Empty message received",e.MISSING_PUBSUB_TOPIC="Pubsub topic missing from push message"})(Is||(Is={})),(e=>{e.GENERIC_FAIL="Generic error",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.DECODE_FAILED="Failed to decode",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.ENCODE_FAILED="Failed to encode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.STREAM_ABORTED="Stream aborted",e.RLN_PROOF_GENERATION="Proof generation failed",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.INVALID_DECODER_TOPICS="Invalid decoder topics"})(_s||(_s={})),(e=>{e.Connection="waku:connection",e.Health="waku:health"})(Cs||(Cs={})),(e=>{e.BOOTSTRAP="bootstrap",e.PEER_EXCHANGE="peer-exchange",e.PEER_CACHE="peer-cache"})(xs||(xs={}));const ks="locked",Ts={clusterId:1,numShardsInCluster:8};var Ps;function Rs(e){if(null!=e[Symbol.asyncIterator])return(async()=>{const t=[];for await(const r of e)t.push(r);return t})();const t=[];for(const r of e)t.push(r);return t}function Ls(e,t){null==t&&(t=e.reduce(((e,t)=>e+t.length),0));const r=a(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}function Ds(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}(e=>{e.Unhealthy="Unhealthy",e.MinimallyHealthy="MinimallyHealthy",e.SufficientlyHealthy="SufficientlyHealthy"})(Ps||(Ps={}));const Ms=Symbol.for("@achingbrain/uint8arraylist");function Ns(e,t){if(null==t||t<0)throw new RangeError("index is out of bounds");let r=0;for(const n of e){const e=r+n.byteLength;if(t<e)return{buf:n,index:t-r};r=e}throw new RangeError("index is out of bounds")}function Os(e){return!!e?.[Ms]}class Us{bufs;length;[Ms]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(const r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else{if(!Os(r))throw Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.push(...r.bufs)}this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(const r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else{if(!Os(r))throw Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.unshift(...r.bufs)}this.length+=t}get(e){const t=Ns(this.bufs,e);return t.buf[t.index]}set(e,t){const r=Ns(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else{if(!Os(e))throw Error("Could not write value, must be an Uint8Array or a Uint8ArrayList");for(let r=0;r<e.length;r++)this.set(t+r,e.get(r))}}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength)return this.bufs=[],void(this.length=0);for(;this.bufs.length>0;){if(!(e>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}}slice(e,t){const{bufs:r,length:n}=this._subList(e,t);return Ls(r,n)}subarray(e,t){const{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:Ls(r,n)}sublist(e,t){const{bufs:r,length:n}=this._subList(e,t),s=new Us;return s.length=n,s.bufs=[...r],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};const r=[];let n=0;for(let s=0;s<this.bufs.length;s++){const i=this.bufs[s],o=n,a=o+i.byteLength;if(n=a,e>=a)continue;const c=e>=o&&e<a,l=t>o&&t<=a;if(c&&l){if(e===o&&t===a){r.push(i);break}const n=e-o;r.push(i.subarray(n,n+(t-e)));break}if(c){if(0===e){r.push(i);continue}r.push(i.subarray(e-o))}else{if(l){if(t===a){r.push(i);break}r.push(i.subarray(0,t-o));break}r.push(i)}}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!(Os(e)||e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(isNaN(t=Number(t??0))&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const n=r.byteLength;if(0===n)throw new TypeError("search must be at least 1 byte long");const s=new Int32Array(256);for(let e=0;e<256;e++)s[e]=-1;for(let e=0;e<n;e++)s[r[e]]=e;const i=s,o=this.byteLength-r.byteLength,a=r.byteLength-1;let c;for(let e=t;e<=o;e+=c){c=0;for(let t=a;t>=0;t--){const n=this.get(e+t);if(r[t]!==n){c=Math.max(1,t-i[n]);break}}if(0===c)return e}return-1}getInt8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){const r=a(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){const n=o(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){const n=o(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){const n=o(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){const r=a(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){const n=o(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){const n=o(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){const n=o(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){const n=o(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){const n=o(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(null==e)return!1;if(!(e instanceof Us))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Ds(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){const r=new Us;return r.bufs=e,null==t&&(t=e.reduce(((e,t)=>e+t.byteLength),0)),r.length=t,r}}function Fs(e){return null!=e[Symbol.asyncIterator]}const Bs=e=>{const t=f(e),r=a(t);return y(e,r),Bs.bytes=t,r};function $s(e,t){const r=(t=t??{}).lengthEncoder??Bs;function*n(e){const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return Fs(e)?async function*(){for await(const t of e)yield*n(t)}():function*(){for(const t of e)yield*n(t)}()}Bs.bytes=0,$s.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??Bs;return new Us(r(e.byteLength),e)};let qs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},zs=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},js=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Ks=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Vs;(e=>{e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(Vs||(Vs={}));const Hs=e=>{const t=b(e);return Hs.bytes=f(t),t};function Gs(e,t){const r=new Us;let n=Vs.LENGTH,s=-1;const i=t?.lengthDecoder??Hs,o=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===Vs.LENGTH)try{if(s=i(r),s<0)throw new qs("Invalid message length");if(s>a)throw new zs("Message length too long");const e=i.bytes;r.consume(e),null!=t?.onLength&&t.onLength(s),n=Vs.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>o)throw new js("Message length length too long");break}throw e}if(n===Vs.DATA){if(r.byteLength<s)break;const e=r.sublist(0,s);r.consume(s),null!=t?.onData&&t.onData(e),yield e,n=Vs.LENGTH}}}return Fs(e)?async function*(){for await(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Ks("Unexpected end of input")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Ks("Unexpected end of input")}()}function Ws(){const e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}Hs.bytes=0,Gs.fromReader=(e,t)=>{let r=1;return Gs(async function*(){for(;;)try{const{done:t,value:n}=await e.next(r);if(!0===t)return;null!=n&&(yield n)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{r=1}}(),{...t??{},onLength(e){r=e}})};class Xs{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw Error("Max size for a FixedFIFO should be a power of two");this.buffer=Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return void 0===this.buffer[this.btm]}}class Zs{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Xs(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return null!=e?.byteLength?e.byteLength:1}push(e){if(null!=e?.value&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const t=this.head;this.head=t.next=new Xs(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(void 0===e&&null!=this.tail.next){const t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return null!=e?.value&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}let Ys=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Qs(e={}){return function(e,t){let r,n,s,i=(t=t??{}).onEnd,o=new Zs,a=Ws();const c=e=>null!=n?n(e):(o.push(e),r),l=e=>{if(s)return r;if(!0!==t?.objectMode&&null==e?.byteLength)throw Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:e})},u=e=>s?r:(s=!0,null!=e?(e=>(o=new Zs,null!=n?n({error:e}):(o.push({error:e}),r)))(e):c({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:async()=>{try{return o.isEmpty()?s?{done:!0}:await new Promise(((t,s)=>{n=i=>{n=null,o.push(i);try{t(e(o))}catch(e){s(e)}return r}})):e(o)}finally{o.isEmpty()&&queueMicrotask((()=>{a.resolve(),a=Ws()}))}},return:()=>(o=new Zs,u(),{done:!0}),throw:e=>(u(e),{done:!0}),push:l,end:u,get readableLength(){return o.size},async onEmpty(e){const t=e?.signal;if(t?.throwIfAborted(),o.isEmpty())return;let r,n;null!=t&&(r=new Promise(((e,r)=>{n=()=>{r(new Ys)},t.addEventListener("abort",n)})));try{await Promise.race([a.promise,r])}finally{null!=n&&null!=t&&t?.removeEventListener("abort",n)}}},null==i)return r;const h=r;return r={[Symbol.asyncIterator](){return this},next:()=>h.next(),throw:e=>(h.throw(e),null!=i&&(i(e),i=void 0),{done:!0}),return:()=>(h.return(),null!=i&&(i(),i=void 0),{done:!0}),push:l,end:e=>(h.end(e),null!=i&&(i(e),i=void 0),r),get readableLength(){return h.readableLength},onEmpty:e=>h.onEmpty(e)},r}((e=>{const t=e.shift();if(null==t)return{done:!0};if(null!=t.error)throw t.error;return{done:!0===t.done,value:t.value}}),e)}let Js=class extends Error{type;code;constructor(e,t,r){super(e??"The operation was aborted"),this.type="aborted",this.name=r??"AbortError",this.code=t??"ABORT_ERR"}};async function ei(e,t,r){if(null==t)return e;if(t.aborted)return e.catch((()=>{})),Promise.reject(new Js(r?.errorMessage,r?.errorCode,r?.errorName));let n;const s=new Js(r?.errorMessage,r?.errorCode,r?.errorName);try{return await Promise.race([e,new Promise(((e,r)=>{n=()=>{r(s)},t.addEventListener("abort",n)}))])}finally{null!=n&&t.removeEventListener("abort",n)}}class ti{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ws(),this.haveNext=Ws()}[Symbol.asyncIterator](){return this}async next(){if(null==this.nextResult&&await this.haveNext.promise,null==this.nextResult)throw Error("HaveNext promise resolved but nextResult was undefined");const e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Ws(),e}async throw(e){return this.ended=!0,this.error=e,null!=e&&(this.haveNext.promise.catch((()=>{})),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){const e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){null!=e?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(null!=e&&this.ended)throw this.error??Error("Cannot push value onto an ended pushable");for(;null!=this.nextResult;)await this.readNext.promise;null!=e?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Ws(),await ei(this.readNext.promise,t?.signal,t)}}function ri(){return new ti}function ni(...e){const t=[];for(const r of e)null==r[Symbol.asyncIterator]&&t.push(r);return t.length===e.length?function*(e){for(const t of e)yield*t}(t):async function*(e){const t=new AbortController,r=ri();(async function(e,t,r){try{await Promise.all(e.map((async e=>{for await(const n of e)await t.push(n,{signal:r}),r.throwIfAborted()}))),await t.end(void 0,{signal:r})}catch(e){await t.end(e,{signal:r}).catch((()=>{}))}})(e,r,t.signal).catch((()=>{}));try{yield*r}finally{t.abort()}}(e)}function si(e,...t){if(null==e)throw Error("Empty pipeline");if(ci(e)){const t=e;e=()=>t.source}else if(ai(e)||oi(e)){const t=e;e=()=>t}const r=[e,...t];if(r.length>1&&ci(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let e=1;e<r.length-1;e++)ci(r[e])&&(r[e]=li(r[e]));return ii(...r)}const ii=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},oi=e=>null!=e?.[Symbol.asyncIterator],ai=e=>null!=e?.[Symbol.iterator],ci=e=>null!=e&&null!=e.sink&&null!=e.source,li=e=>t=>{const r=e.sink(t);if(null!=r?.then){const t=Qs({objectMode:!0});let n;r.then((()=>{t.end()}),(e=>{t.end(e)}));const s=e.source;if(oi(s))n=async function*(){yield*s,t.end()};else{if(!ai(s))throw Error("Unknown duplex source type - must be Iterable or AsyncIterable");n=function*(){yield*s,t.end()}}return ni(t,n())}return e.source};function ui(e){return e.filter((e=>"open"===e.status)).sort(((e,t)=>t.timeline.open-e.timeline.open)).at(0)}const hi="consumed";class di{multicodec;libp2p;log;ongoingCreation=new Set;streamPool=new Map;constructor(e,t){this.multicodec=e,this.libp2p=t,this.log=new fs("stream-manager:"+e),this.libp2p.events.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(e){try{const t=e.toString(),r=this.streamPool.get(t);r&&(this.streamPool.delete(t),await r);const n=this.getOpenStreamForCodec(e)||await this.createStream(e);if(!n)return;return this.log.info(`Using stream for peerId=${t} multicodec=${this.multicodec}`),this.lockStream(t,n),n}catch(e){return void this.log.error("Failed to getStream:",e)}}async createStream(e,t=0){const r=ui(this.libp2p.connectionManager.getConnections(e));if(!r)return void this.log.error(`Failed to get a connection to the peer peerId=${e.toString()} multicodec=${this.multicodec}`);let n,s;for(let i=0;i<t+1;i++)try{this.log.info(`Attempting to create a stream for peerId=${e.toString()} multicodec=${this.multicodec}`),s=await r.newStream(this.multicodec),this.log.info(`Created stream for peerId=${e.toString()} multicodec=${this.multicodec}`);break}catch(e){n=e}if(s)return s;this.log.error(`Failed to create a new stream for ${e.toString()} -- `+n)}async createStreamWithLock(e){const t=e.id.toString();if(this.ongoingCreation.has(t))this.log.info(`Skipping creation of a stream due to lock for peerId=${t} multicodec=${this.multicodec}`);else try{this.ongoingCreation.add(t),await this.createStream(e.id)}catch(e){this.log.error("Failed to createStreamWithLock:",e)}finally{this.ongoingCreation.delete(t)}}handlePeerUpdateStreamPool=e=>{const{peer:t}=e.detail;t.protocols.includes(this.multicodec)&&(this.getOpenStreamForCodec(t.id)||this.scheduleNewStream(t))};scheduleNewStream(e){this.log.info(`Scheduling creation of a stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.streamPool.has(e.id.toString())&&this.streamPool.delete(e.id.toString()),this.streamPool.set(e.id.toString(),this.createStreamWithLock(e))}getOpenStreamForCodec(e){const t=ui(this.libp2p.connectionManager.getConnections(e));if(!t)return void this.log.info(`No open connection found for peerId=${e.toString()} multicodec=${this.multicodec}`);const r=t.streams.find((e=>e.protocol===this.multicodec));if(r)return["done","closed","closing"].includes(r.writeStatus||"")||this.isStreamLocked(r)?void this.log.info(`Stream for peerId=${e.toString()} multicodec=${this.multicodec} is unusable`):(this.log.info(`Found open stream for peerId=${e.toString()} multicodec=${this.multicodec}`),r);this.log.info(`No open stream found for peerId=${e.toString()} multicodec=${this.multicodec}`)}lockStream(e,t){this.log.info(`Locking stream for peerId:${e}\tstreamId:${t.id}`),t.metadata[hi]=!0}isStreamLocked(e){return!!e.metadata[hi]}}let pi;const fi=new Uint8Array(16);function gi(){if(!pi&&(pi="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!pi))throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return pi(fi)}const mi=[];for(let e=0;e<256;++e)mi.push((e+256).toString(16).slice(1));var yi={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function bi(e){if(yi.randomUUID&&!e)return yi.randomUUID();const t=(e=e||{}).random||(e.rng||gi)();return t[6]=15&t[6]|64,t[8]=63&t[8]|128,function(e,t=0){return mi[e[t+0]]+mi[e[t+1]]+mi[e[t+2]]+mi[e[t+3]]+"-"+mi[e[t+4]]+mi[e[t+5]]+"-"+mi[e[t+6]]+mi[e[t+7]]+"-"+mi[e[t+8]]+mi[e[t+9]]+"-"+mi[e[t+10]]+mi[e[t+11]]+mi[e[t+12]]+mi[e[t+13]]+mi[e[t+14]]+mi[e[t+15]]}(t)}class wi{proto;constructor(e){this.proto=e}static decode(e){const t=At.decode(e);return new wi(t)}encode(){return At.encode(this.proto)}get wakuMessage(){return this.proto.wakuMessage}get pubsubTopic(){return this.proto.pubsubTopic}}class vi{proto;constructor(e){this.proto=e}static createSubscribeRequest(e,t){return new vi({requestId:bi(),filterSubscribeType:Et.FilterSubscribeType.SUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeRequest(e,t){return new vi({requestId:bi(),filterSubscribeType:Et.FilterSubscribeType.UNSUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeAllRequest(e){return new vi({requestId:bi(),filterSubscribeType:Et.FilterSubscribeType.UNSUBSCRIBE_ALL,pubsubTopic:e,contentTopics:[]})}static createSubscriberPingRequest(){return new vi({requestId:bi(),filterSubscribeType:Et.FilterSubscribeType.SUBSCRIBER_PING,pubsubTopic:"",contentTopics:[]})}static decode(e){const t=Et.decode(e);return new vi(t)}encode(){return Et.encode(this.proto)}get filterSubscribeType(){return this.proto.filterSubscribeType}get requestId(){return this.proto.requestId}get pubsubTopic(){return this.proto.pubsubTopic}get contentTopics(){return this.proto.contentTopics}}class Ei{proto;constructor(e){this.proto=e}static decode(e){const t=St.decode(e);return new Ei(t)}encode(){return St.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get requestId(){return this.proto.requestId}}const Si=new fs("filter-core"),Ai="/vac/waku/filter-subscribe/2.0.0-beta1",Ii="/vac/waku/filter-push/2.0.0-beta1";class _i{handleIncomingMessage;libp2p;streamManager;multicodec=Ai;constructor(e,t){this.handleIncomingMessage=e,this.libp2p=t,this.streamManager=new di(Ai,t.components)}async start(){try{await this.libp2p.handle(Ii,this.onRequest.bind(this),{maxInboundStreams:100})}catch(e){Si.error("Failed to register ",Ii,e)}}async stop(){try{await this.libp2p.unhandle(Ii)}catch(e){Si.error("Failed to unregister ",Ii,e)}}async subscribe(e,t,r){const n=await this.streamManager.getStream(t);if(!n)return{success:null,failure:{error:Is.NO_STREAM_AVAILABLE,peerId:t}};const s=vi.createSubscribeRequest(e,r);let i;try{if(i=await si([s.encode()],$s,n,Gs,(async e=>await Rs(e))),!i?.length)throw Error("Received no response from subscription request.")}catch(e){return Si.error("Failed to send subscribe request",e),{success:null,failure:{error:Is.GENERIC_FAIL,peerId:t}}}const{statusCode:o,requestId:a,statusDesc:c}=Ei.decode(i[0].slice());return o<200||o>=300?(Si.error(`Filter subscribe request ${a} failed with status code ${o}: ${c}`),{failure:{error:Is.REMOTE_PEER_REJECTED,peerId:t},success:null}):{failure:null,success:t}}async unsubscribe(e,t,r){const n=await this.streamManager.getStream(t);if(!n)return Si.error("Failed to get a stream for remote peer:"+t.toString()),{success:null,failure:{error:Is.NO_STREAM_AVAILABLE,peerId:t}};const s=vi.createUnsubscribeRequest(e,r);try{await si([s.encode()],$s,n.sink)}catch(e){return Si.error("Failed to send unsubscribe request",e),{success:null,failure:{error:Is.GENERIC_FAIL,peerId:t}}}return{success:t,failure:null}}async unsubscribeAll(e,t){const r=await this.streamManager.getStream(t);if(!r)return Si.error("Failed to get a stream for remote peer:"+t.toString()),{success:null,failure:{error:Is.NO_STREAM_AVAILABLE,peerId:t}};const n=vi.createUnsubscribeAllRequest(e),s=await si([n.encode()],$s,r,Gs,(async e=>await Rs(e)));if(!s||!s.length)return{failure:{error:Is.NO_RESPONSE,peerId:t},success:null};const{statusCode:i,requestId:o,statusDesc:a}=Ei.decode(s[0].slice());return i<200||i>=300?(Si.error(`Filter unsubscribe all request ${o} failed with status code ${i}: ${a}`),{failure:{error:Is.REMOTE_PEER_REJECTED,peerId:t},success:null}):{failure:null,success:t}}async ping(e){const t=await this.streamManager.getStream(e);if(!t)return Si.error("Failed to get a stream for remote peer:"+e.toString()),{success:null,failure:{error:Is.NO_STREAM_AVAILABLE,peerId:e}};const r=vi.createSubscriberPingRequest();let n;try{n=await si([r.encode()],$s,t,Gs,(async e=>await Rs(e)))}catch(t){return Si.error("Failed to send ping request",t),{success:null,failure:{error:Is.GENERIC_FAIL,peerId:e}}}if(!n||!n.length)return{success:null,failure:{error:Is.NO_RESPONSE,peerId:e}};const{statusCode:s,requestId:i,statusDesc:o}=Ei.decode(n[0].slice());return s<200||s>=300?(Si.error(`Filter ping request ${i} failed with status code ${s}: ${o}`),{success:null,failure:{error:Is.REMOTE_PEER_REJECTED,peerId:e}}):{success:e,failure:null}}onRequest(e){const{connection:t,stream:r}=e,{remotePeer:n}=t;Si.info("Received message from "+n.toString());try{si(r,Gs,(async e=>{for await(const r of e){const e=wi.decode(r.slice()),{pubsubTopic:n,wakuMessage:s}=e;if(!s)return void Si.error("Received empty message");if(!n)return void Si.error("Pubsub topic missing from push message");await this.handleIncomingMessage(n,s,t.remotePeer.toString())}})).then((()=>{Si.info("Receiving pipe closed.")}),(async e=>{Si.error(`Error with receiving pipe on peer:${t.remotePeer.toString()} -- stream:${r.id} -- protocol:${r.protocol}: `,e)}))}catch(e){Si.error("Error decoding message",e)}}}const Ci="/vac/waku/lightpush/2.0.0-beta1",xi="/vac/waku/lightpush/3.0.0",ki=Ci,Ti=xi;class Pi{proto;constructor(e){this.proto=e}static createRequest(e,t){return new Pi({requestId:bi(),request:{message:e,pubsubTopic:t},response:void 0})}static decode(e){const t=kt.decode(e);return new Pi(t)}encode(){return kt.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}class Ri{proto;constructor(e){this.proto=e}static createRequest(e,t){return new Ri({requestId:bi(),pubsubTopic:t,message:e})}static createResponse(e,t,r,n){return new Ri({requestId:e,statusCode:t,statusDesc:r,relayPeerCount:n})}static decodeRequest(e){const t=Tt.decode(e);return new Ri(t)}static decodeResponse(e){const t=Pt.decode(e);return new Ri(t)}encode(){return this.isRequest()?Tt.encode(this.proto):Pt.encode(this.proto)}get request(){return this.isRequest()?this.proto:void 0}get response(){return this.isResponse()?this.proto:void 0}get requestId(){return this.proto.requestId}get pubsubTopic(){return this.isRequest()?this.proto.pubsubTopic:void 0}get message(){return this.isRequest()?this.proto.message:void 0}get statusCode(){return this.isResponse()?this.proto.statusCode:void 0}get statusDesc(){return this.isResponse()?this.proto.statusDesc:void 0}get relayPeerCount(){return this.isResponse()?this.proto.relayPeerCount:void 0}isRequest(){return"pubsubTopic"in this.proto&&"message"in this.proto}isResponse(){return"statusCode"in this.proto}}const Li=new fs("light-push:protocol-handler");class Di{static async preparePushMessage(e,t,r){try{if(!t.payload||0===t.payload.length)return Li.error("Failed to send waku light push: payload is empty"),{rpc:null,error:As.EMPTY_PAYLOAD};if(!await async function(e,t){const r=await e.toWire(t);return!!r&&(e=>e.length/1048576<=1)(r)}(e,t))return Li.error("Failed to send waku light push: message is bigger than 1MB"),{rpc:null,error:As.SIZE_TOO_BIG};const n=await e.toProtoObj(t);return n?r===xi?(Li.info("Creating v3 RPC message"),{rpc:Di.createV3Rpc(n,e.pubsubTopic),error:null}):(Li.info("Creating v2 RPC message"),{rpc:Di.createV2Rpc(n,e.pubsubTopic),error:null}):(Li.error("Failed to encode to protoMessage, aborting push"),{rpc:null,error:As.ENCODE_FAILED})}catch(e){return Li.error("Failed to prepare push message",e),{rpc:null,error:As.GENERIC_FAIL}}}static handleResponse(e,t,r){return t===xi?Di.handleV3Response(e,r):Di.handleV2Response(e,r)}static handleV3Response(e,t){try{const r=Ri.decodeResponse(e),n=r.statusCode,s=r.statusDesc;if(n!==Es.SUCCESS){const e=As.REMOTE_PEER_REJECTED;return Li.error(`Remote peer rejected with v3 status code ${n}: ${s}`),{success:null,failure:{error:e,peerId:t}}}return void 0!==r.relayPeerCount&&Li.info(`Message relayed to ${r.relayPeerCount} peers`),{success:t,failure:null}}catch(e){return{success:null,failure:{error:As.DECODE_FAILED,peerId:t}}}}static handleV2Response(e,t){let r;try{r=Pi.decode(e).response}catch(e){return{success:null,failure:{error:As.DECODE_FAILED,peerId:t}}}var n;return r?(n=r.info)&&(n.includes("could not generate rln proof")||n.includes("could not get new message id to generate an rln proof")||n.includes("RLN validation failed"))?(Li.error("Remote peer fault: RLN generation"),{success:null,failure:{error:As.RLN_PROOF_GENERATION,peerId:t}}):r.isSuccess?{success:t,failure:null}:(Li.error("Remote peer rejected the message: ",r.info),{success:null,failure:{error:As.REMOTE_PEER_REJECTED,peerId:t}}):{success:null,failure:{error:As.NO_RESPONSE,peerId:t}}}static createV2Rpc(e,t){const r=Pi.createRequest(e,t);return Object.assign(r,{version:"v2"})}static createV3Rpc(e,t){e.timestamp||(e.timestamp=BigInt(Date.now())*BigInt(1e6));const r=Ri.createRequest(e,t);return Object.assign(r,{version:"v3"})}}const Mi=new fs("light-push");class Ni{libp2p;streamManager;streamManagerV2;multicodec=[xi,Ci];constructor(e){this.libp2p=e,this.streamManagerV2=new di(Ci,e.components),this.streamManager=new di(xi,e.components)}async send(e,t,r,n=!1){const s=await this.getProtocol(r,n);if(Mi.info(`Sending light push request to peer:${r.toString()}, protocol:${s}`),!s)return{success:null,failure:{error:As.GENERIC_FAIL,peerId:r}};const{rpc:i,error:o}=await Di.preparePushMessage(e,t,s);if(o)return{success:null,failure:{error:o,peerId:r}};const a=await this.getStream(r,s);if(!a)return Mi.error("Failed to get a stream for remote peer:"+r.toString()),{success:null,failure:{error:As.NO_STREAM_AVAILABLE,peerId:r}};let c;try{c=await si([i.encode()],$s,a,Gs,(async e=>await Rs(e)))}catch(e){return Mi.error("Failed to send waku light push request",e),{success:null,failure:{error:As.STREAM_ABORTED,peerId:r}}}const l=new Us;return c.forEach((e=>l.append(e))),0===l.length?{success:null,failure:{error:As.NO_RESPONSE,peerId:r}}:Di.handleResponse(l,s,r)}async getProtocol(e,t){try{const r=await this.libp2p.peerStore.get(e);if(t||!r.protocols.includes(xi)&&r.protocols.includes(Ci))return Ci;if(r.protocols.includes(xi))return xi;throw Error("No supported protocol found")}catch(e){return void Mi.error("Failed to get protocol",e)}}async getStream(e,t){switch(t){case Ci:return this.streamManagerV2.getStream(e);case xi:return this.streamManager.getStream(e);default:return}}}const Oi={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},Ui=864e5,Fi=1e6;class Bi{proto;constructor(e){this.proto=e}static create(e){const t=new Bi({...e,contentTopics:e.contentTopics||[],requestId:bi(),timeStart:e.timeStart?BigInt(e.timeStart.getTime()*Fi):void 0,timeEnd:e.timeEnd?BigInt(e.timeEnd.getTime()*Fi):void 0,messageHashes:e.messageHashes||[],paginationLimit:e.paginationLimit?BigInt(e.paginationLimit):void 0}),r=e.messageHashes&&e.messageHashes.length>0,n=e.contentTopics&&e.contentTopics.length>0,s=e.timeStart||e.timeEnd;if(r){if(n||s)throw Error("Message hash lookup queries cannot include content filter criteria (contentTopics, timeStart, or timeEnd)")}else if(e.pubsubTopic&&(!e.contentTopics||0===e.contentTopics.length)||!e.pubsubTopic&&e.contentTopics&&e.contentTopics.length>0)throw Error("Both pubsubTopic and contentTopics must be set together for content-filtered queries");return t}static decode(e){const t=Mt.decode(e);return new Bi(t)}encode(){return Mt.encode(this.proto)}}class $i{proto;constructor(e){this.proto=e}static decode(e){const t=Nt.decode(e);return new $i(t)}encode(){return Nt.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get messages(){return this.proto.messages}get paginationCursor(){return this.proto.paginationCursor}}const qi=new fs("store"),zi="/vac/waku/store-query/3.0.0";class ji{streamManager;multicodec=zi;constructor(e){this.streamManager=new di(zi,e.components)}get maxTimeLimit(){return Ui}async*queryPerPage(e,t,r){if(e.timeStart&&e.timeEnd&&e.timeEnd.getTime()-e.timeStart.getTime()>Ui)throw Error("Time range bigger than 24h");if(!(e.messageHashes&&e.messageHashes.length>0)&&e.contentTopics&&e.contentTopics.toString()!==Array.from(t.keys()).toString())throw Error("Internal error, the decoders should match the query's content topics");let n=e.paginationCursor;for(;;){const s=Bi.create({...e,paginationCursor:n});qi.info("Sending store query request:",{hasMessageHashes:!!e.messageHashes?.length,messageHashCount:e.messageHashes?.length,pubsubTopic:e.pubsubTopic,contentTopics:e.contentTopics});const i=await this.streamManager.getStream(r);if(!i){qi.error("Failed to get a stream for remote peer:"+r.toString());break}const o=await si([s.encode()],$s,i,Gs,(async e=>await Rs(e))),a=new Us;o.forEach((e=>{a.append(e)}));const c=$i.decode(a);if(!c.statusCode||c.statusCode>=300){const e=`Store query failed with status code: ${c.statusCode}, description: ${c.statusDesc}`;throw qi.error(e),Error(e)}if(!c.messages||!c.messages.length){qi.warn("Stopping pagination due to empty messages in response");break}qi.info(c.messages.length+" messages retrieved from store");const l=c.messages.map((e=>{if(!e.message)return Promise.resolve(void 0);const r=e.message.contentTopic;if(r){const s=t.get(r);if(s)return s.fromProtoObj(e.pubsubTopic||"",(n=e.message,{...Oi,...n}))}var n;return Promise.resolve(void 0)}));if(yield l,n=e.paginationForward?c.messages[c.messages.length-1].messageHash:c.messages[0].messageHash,c.messages.length>100&&c.messages.length<(e.paginationLimit||20))break}}}const Ki=parseInt("11111",2),Vi=parseInt("10000000",2),Hi=parseInt("01111111",2),Gi={0:Zi,1:Zi,2(e,t){const r=Xi(e,t),n=t.offset,s=t.offset+r,i=[];for(let t=n;t<s;t++)t===n&&0===e[t]||i.push(e[t]);return t.offset+=r,Uint8Array.from(i)},3(e,t){const r=Xi(e,t),n=e[t.offset];t.offset++;const s=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,0!==n)throw Error("Unused bits in bit string is unimplemented");return s},4(e,t){const r=Xi(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n},5:(e,t)=>(t.offset++,null),6(e,t){const r=Xi(e,t),n=t.offset+r,s=e[t.offset];t.offset++;let i=0,o=0;s<40?(i=0,o=s):s<80?(i=1,o=s-40):(i=2,o=s-80);let a=`${i}.${o}`,c=[];for(;t.offset<n;){const r=e[t.offset];if(t.offset++,c.push(127&r),r<128){c.reverse();let e=0;for(let t=0;t<c.length;t++)e+=c[t]<<7*t;a+="."+e,c=[]}}return a},16:Zi,22:Zi,48:Zi};function Wi(e,t={offset:0}){const r=e[t.offset]&Ki;if(t.offset++,null!=Gi[r])return Gi[r](e,t);throw Error("No decoder for tag "+r)}function Xi(e,t){let r=0;if((e[t.offset]&Vi)===Vi){const n=e[t.offset]&Hi;let s="0x";t.offset++;for(let r=0;r<n;r++,t.offset++)s+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(s,16)}else r=e[t.offset],t.offset++;return r}function Zi(e,t){Xi(e,t);const r=[];for(;!(t.offset>=e.byteLength);){const n=Wi(e,t);if(null===n)break;r.push(n)}return r}function Yi(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);const t=function(e){let t=e.toString(16);t.length%2==1&&(t="0"+t);const r=new Us;for(let e=0;e<t.length;e+=2)r.append(Uint8Array.from([parseInt(`${t[e]}${t[e+1]}`,16)]));return r}(e.byteLength);return new Us(Uint8Array.from([t.byteLength|Vi]),t)}function Qi(e){const t=new Us;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new Us(Uint8Array.from([2]),Yi(t),t)}function Ji(e){const t=Uint8Array.from([0]),r=new Us(t,e);return new Us(Uint8Array.from([3]),Yi(r),r)}function eo(e,t=48){const r=new Us;for(const t of e)r.append(t);return new Us(Uint8Array.from([t]),Yi(r),r)}const to=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),ro=Uint8Array.from([6,5,43,129,4,0,34]),no=Uint8Array.from([6,5,43,129,4,0,35]),so={ext:!0,kty:"EC",crv:"P-256"},io={ext:!0,kty:"EC",crv:"P-384"},oo={ext:!0,kty:"EC",crv:"P-521"},ao=32,co=48,lo=66;function uo(e){return function(e){const t=e[1][1][0];let r,n;if(65===t.byteLength)return r=tn(t.subarray(1,1+ao),"base64url"),n=tn(t.subarray(1+ao),"base64url"),new po({...so,key_ops:["verify"],x:r,y:n});if(97===t.byteLength)return r=tn(t.subarray(1,1+co),"base64url"),n=tn(t.subarray(1+co),"base64url"),new po({...io,key_ops:["verify"],x:r,y:n});if(133===t.byteLength)return r=tn(t.subarray(1,1+lo),"base64url"),n=tn(t.subarray(1+lo),"base64url"),new po({...oo,key_ops:["verify"],x:r,y:n});throw new Pn(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}(Wi(e))}function ho(e){if("P-256"===e)return to;if("P-384"===e)return ro;if("P-521"===e)return no;throw new Pn("Invalid curve "+e)}let po=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){var e;return null==this._raw&&(this._raw=(e=this.jwk,eo([Qi(Uint8Array.from([1])),eo([ho(e.crv)],160),eo([Ji(new Us(Uint8Array.from([4]),Ye(e.x??"","base64url"),Ye(e.y??"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return Ne.digest(Ac(this))}toCID(){return qe.createV1(114,this.toMultihash())}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}async verify(e,t,r){return async function(e,t,r,n){const s=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();const i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}};const fo=BigInt(0),go=BigInt(1);function mo(e,t=""){if("boolean"!=typeof e)throw Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e);return e}function yo(e,t,r=""){const n=Jt(e),s=e?.length,i=void 0!==t;if(!n||i&&s!==t)throw Error((r&&`"${r}" `)+"expected Uint8Array"+(i?" of length "+t:"")+", got "+(n?"length="+s:"type="+typeof e));return e}function bo(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function wo(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);return""===e?fo:BigInt("0x"+e)}function vo(e){return wo(lr(e))}function Eo(e){return tr(e),wo(lr(Uint8Array.from(e).reverse()))}function So(e,t){return yr(e.toString(16).padStart(2*t,"0"))}function Ao(e,t){return So(e,t).reverse()}function Io(e,t,r){let n;if("string"==typeof t)try{n=yr(t)}catch(t){throw Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Jt(t))throw Error(e+" must be hex string or Uint8Array");n=Uint8Array.from(t)}const s=n.length;if("number"==typeof r&&s!==r)throw Error(e+" of length "+r+" expected, got "+s);return n}function _o(e){return Uint8Array.from(e)}const Co=e=>"bigint"==typeof e&&fo<=e;function xo(e,t,r,n){if(!function(e,t,r){return Co(e)&&Co(t)&&Co(r)&&t<=e&&e<r}(t,r,n))throw Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function ko(e){let t;for(t=0;e>fo;e>>=go,t+=1);return t}const To=e=>(go<<BigInt(e))-go;function Po(e,t,r={}){if(!e||"object"!=typeof e)throw Error("expected valid options object");function n(t,r,n){const s=e[t];if(n&&void 0===s)return;const i=typeof s;if(i!==r||null===s)throw Error(`param "${t}" is invalid: expected ${r}, got ${i}`)}Object.entries(t).forEach((([e,t])=>n(e,t,!1))),Object.entries(r).forEach((([e,t])=>n(e,t,!0)))}function Ro(e){const t=new WeakMap;return(r,...n)=>{const s=t.get(r);if(void 0!==s)return s;const i=e(r,...n);return t.set(r,i),i}}const Lo=BigInt(0),Do=BigInt(1),Mo=BigInt(2),No=BigInt(3),Oo=BigInt(4),Uo=BigInt(5),Fo=BigInt(7),Bo=BigInt(8),$o=BigInt(9),qo=BigInt(16);function zo(e,t){const r=e%t;return r>=Lo?r:t+r}function jo(e,t,r){let n=e;for(;t-- >Lo;)n*=n,n%=r;return n}function Ko(e,t){if(e===Lo)throw Error("invert: expected non-zero number");if(t<=Lo)throw Error("invert: expected positive modulus, got "+t);let r=zo(e,t),n=t,s=Lo,i=Do;for(;r!==Lo;){const e=n%r,t=s-i*(n/r);n=r,r=e,s=i,i=t}if(n!==Do)throw Error("invert: does not exist");return zo(s,t)}function Vo(e,t,r){if(!e.eql(e.sqr(t),r))throw Error("Cannot find square root")}function Ho(e,t){const r=(e.ORDER+Do)/Oo,n=e.pow(t,r);return Vo(e,n,t),n}function Go(e,t){const r=(e.ORDER-Uo)/Bo,n=e.mul(t,Mo),s=e.pow(n,r),i=e.mul(t,s),o=e.mul(e.mul(i,Mo),s),a=e.mul(i,e.sub(o,e.ONE));return Vo(e,a,t),a}function Wo(e){if(e<No)throw Error("sqrt is not defined for small field");let t=e-Do,r=0;for(;t%Mo===Lo;)t/=Mo,r++;let n=Mo;const s=Jo(e);for(;1===Yo(s,n);)if(n++>1e3)throw Error("Cannot find square root: probably non-prime P");if(1===r)return Ho;let i=s.pow(n,t);const o=(t+Do)/Mo;return function(e,n){if(e.is0(n))return n;if(1!==Yo(e,n))throw Error("Cannot find square root");let s=r,a=e.mul(e.ONE,i),c=e.pow(n,t),l=e.pow(n,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,r=e.sqr(c);for(;!e.eql(r,e.ONE);)if(t++,r=e.sqr(r),t===s)throw Error("Cannot find square root");const n=Do<<BigInt(s-t-1),i=e.pow(a,n);s=t,a=e.sqr(i),c=e.mul(c,a),l=e.mul(l,i)}return l}}const Xo=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Zo(e,t,r=!1){const n=Array(t.length).fill(r?e.ZERO:void 0),s=t.reduce(((t,r,s)=>e.is0(r)?t:(n[s]=t,e.mul(t,r))),e.ONE),i=e.inv(s);return t.reduceRight(((t,r,s)=>e.is0(r)?t:(n[s]=e.mul(t,n[s]),e.mul(t,r))),i),n}function Yo(e,t){const r=(e.ORDER-Do)/Mo,n=e.pow(t,r),s=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),o=e.eql(n,e.neg(e.ONE));if(!s&&!i&&!o)throw Error("invalid Legendre symbol result");return s?1:i?0:-1}function Qo(e,t){void 0!==t&&er(t);const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function Jo(e,t,r=!1,n={}){if(e<=Lo)throw Error("invalid field: expected ORDER > 0, got "+e);let s,i,o,a=!1;if("object"==typeof t&&null!=t){if(n.sqrt||r)throw Error("cannot specify opts in two arguments");const e=t;e.BITS&&(s=e.BITS),e.sqrt&&(i=e.sqrt),"boolean"==typeof e.isLE&&(r=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),o=e.allowedLengths}else"number"==typeof t&&(s=t),n.sqrt&&(i=n.sqrt);const{nBitLength:c,nByteLength:l}=Qo(e,s);if(l>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");let u;const h=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:l,MASK:To(c),ZERO:Lo,ONE:Do,allowedLengths:o,create:t=>zo(t,e),isValid(t){if("bigint"!=typeof t)throw Error("invalid field element: expected bigint, got "+typeof t);return Lo<=t&&t<e},is0:e=>e===Lo,isValidNot0:e=>!h.is0(e)&&h.isValid(e),isOdd:e=>(e&Do)===Do,neg:t=>zo(-t,e),eql:(e,t)=>e===t,sqr:t=>zo(t*t,e),add:(t,r)=>zo(t+r,e),sub:(t,r)=>zo(t-r,e),mul:(t,r)=>zo(t*r,e),pow:(e,t)=>function(e,t,r){if(r<Lo)throw Error("invalid exponent, negatives unsupported");if(r===Lo)return e.ONE;if(r===Do)return t;let n=e.ONE,s=t;for(;r>Lo;)r&Do&&(n=e.mul(n,s)),s=e.sqr(s),r>>=Do;return n}(h,e,t),div:(t,r)=>zo(t*Ko(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Ko(t,e),sqrt:i||(t=>(u||(u=function(e){return e%Oo===No?Ho:e%Bo===Uo?Go:e%qo===$o?function(e){const t=Jo(e),r=Wo(e),n=r(t,t.neg(t.ONE)),s=r(t,n),i=r(t,t.neg(n)),o=(e+Fo)/qo;return(e,t)=>{let r=e.pow(t,o),a=e.mul(r,n);const c=e.mul(r,s),l=e.mul(r,i),u=e.eql(e.sqr(a),t),h=e.eql(e.sqr(c),t);r=e.cmov(r,a,u),a=e.cmov(l,c,h);const d=e.eql(e.sqr(a),t),p=e.cmov(r,a,d);return Vo(e,p,t),p}}(e):Wo(e)}(e)),u(h,t))),toBytes:e=>r?Ao(e,l):So(e,l),fromBytes(t,n=!0){if(o){if(!o.includes(t.length)||t.length>l)throw Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);const e=new Uint8Array(l);e.set(t,r?0:e.length-t.length),t=e}if(t.length!==l)throw Error("Field.fromBytes: expected "+l+" bytes, got "+t.length);let s=r?Eo(t):vo(t);if(a&&(s=zo(s,e)),!n&&!h.isValid(s))throw Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>Zo(h,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(h)}function ea(e){if("bigint"!=typeof e)throw Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function ta(e){const t=ea(e);return t+Math.ceil(t/2)}const ra=BigInt(0),na=BigInt(1);function sa(e,t){const r=t.negate();return e?r:t}function ia(e,t){const r=Zo(e.Fp,t.map((e=>e.Z)));return t.map(((t,n)=>e.fromAffine(t.toAffine(r[n]))))}function oa(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function aa(e,t){oa(e,t);const r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:To(e),maxNumber:r,shiftBy:BigInt(e)}}function ca(e,t,r){const{windowSize:n,mask:s,maxNumber:i,shiftBy:o}=r;let a=Number(e&s),c=e>>o;a>n&&(a-=i,c+=na);const l=t*n;return{nextN:c,offset:l+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:l}}const la=new WeakMap,ua=new WeakMap;function ha(e){return ua.get(e)||1}function da(e){if(e!==ra)throw Error("invalid wNAF")}class pa{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let n=e;for(;t>ra;)t&na&&(r=r.add(n)),n=n.double(),t>>=na;return r}precomputeWindow(e,t){const{windows:r,windowSize:n}=aa(t,this.bits),s=[];let i=e,o=i;for(let e=0;e<r;e++){o=i,s.push(o);for(let e=1;e<n;e++)o=o.add(i),s.push(o);i=o.double()}return s}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let n=this.ZERO,s=this.BASE;const i=aa(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:o,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:h}=ca(r,e,i);r=o,c?s=s.add(sa(u,t[h])):n=n.add(sa(l,t[a]))}return da(r),{p:n,f:s}}wNAFUnsafe(e,t,r,n=this.ZERO){const s=aa(e,this.bits);for(let e=0;e<s.windows&&r!==ra;e++){const{nextN:i,offset:o,isZero:a,isNeg:c}=ca(r,e,s);if(r=i,!a){const e=t[o];n=n.add(c?e.negate():e)}}return da(r),n}getPrecomputes(e,t,r){let n=la.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&("function"==typeof r&&(n=r(n)),la.set(t,n))),n}cached(e,t,r){const n=ha(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){const s=ha(e);return 1===s?this._unsafeLadder(e,t,n):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),t,n)}createCache(e,t){oa(t,this.bits),ua.set(e,t),la.delete(e)}hasCache(e){return 1!==ha(e)}}function fa(e,t,r,n){!function(e,t){if(!Array.isArray(e))throw Error("array expected");e.forEach(((e,r)=>{if(!(e instanceof t))throw Error("invalid point at index "+r)}))}(r,e),function(e,t){if(!Array.isArray(e))throw Error("array of scalars expected");e.forEach(((e,r)=>{if(!t.isValid(e))throw Error("invalid scalar at index "+r)}))}(n,t);const s=r.length,i=n.length;if(s!==i)throw Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=ko(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=To(c),u=Array(Number(l)+1).fill(o);let h=o;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){u.fill(o);for(let t=0;t<i;t++){const s=n[t],i=Number(s>>BigInt(e)&l);u[i]=u[i].add(r[t])}let t=o;for(let e=u.length-1,r=o;e>0;e--)r=r.add(u[e]),t=t.add(r);if(h=h.add(t),0!==e)for(let e=0;e<c;e++)h=h.double()}return h}function ga(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){const t=Xo.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"});Po(e,t)}(t),t}return Jo(e,{isLE:r})}function ma(e,t,r={},n){if(void 0===n&&(n="edwards"===e),!t||"object"!=typeof t)throw Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const r=t[e];if(!("bigint"==typeof r&&r>ra))throw Error(`CURVE.${e} must be positive bigint`)}const s=ga(t.p,r.Fp,n),i=ga(t.n,r.Fn,n),o=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of o)if(!s.isValid(t[e]))throw Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:s,Fn:i}}const ya=BigInt(0),ba=BigInt(1),wa=BigInt(2),va=BigInt(8);const Ea=BigInt(0),Sa=BigInt(1),Aa=BigInt(2),Ia=BigInt(1),_a=BigInt(2),Ca=BigInt(3),xa=BigInt(5),ka=BigInt(8),Ta=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Pa={p:Ta,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ka,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ra(e){const t=BigInt(10),r=BigInt(20),n=BigInt(40),s=BigInt(80),i=Ta,o=e*e%i*e%i,a=jo(o,_a,i)*o%i,c=jo(a,Ia,i)*e%i,l=jo(c,xa,i)*c%i,u=jo(l,t,i)*l%i,h=jo(u,r,i)*u%i,d=jo(h,n,i)*h%i,p=jo(d,s,i)*d%i,f=jo(p,s,i)*d%i,g=jo(f,t,i)*l%i;return{pow_p_5_8:jo(g,_a,i)*e%i,b2:o}}function La(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Da=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");const Ma=Jo(Pa.p,{isLE:!0}),Na=function(e){const{CURVE:t,curveOpts:r,hash:n,eddsaOpts:s}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r={Fp:e.Fp,Fn:Jo(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},n={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:r,hash:e.hash,eddsaOpts:n}}(e),i=function(e,t={}){const r=ma("edwards",e,t,t.FpFnLE),{Fp:n,Fn:s}=r;let i=r.CURVE;const{h:o}=i;Po(t,{},{uvRatio:"function"});const a=wa<<BigInt(8*s.BYTES)-ba,c=e=>n.create(e),l=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:n.sqrt(n.div(e,t))}}catch(e){return{isValid:!1,value:ya}}});if(!((e,t,r,n)=>{const s=e.sqr(r),i=e.sqr(n),o=e.add(e.mul(t.a,s),i),a=e.add(e.ONE,e.mul(t.d,e.mul(s,i)));return e.eql(o,a)})(n,i,i.Gx,i.Gy))throw Error("bad curve params: generator point");function u(e,t,r=!1){return xo("coordinate "+e,t,r?ba:ya,a),t}function h(e){if(!(e instanceof f))throw Error("ExtendedPoint expected")}const d=Ro(((e,t)=>{const{X:r,Y:s,Z:i}=e,o=e.is0();null==t&&(t=o?va:n.inv(i));const a=c(r*t),l=c(s*t),u=n.mul(i,t);if(o)return{x:ya,y:ba};if(u!==ba)throw Error("invZ was invalid");return{x:a,y:l}})),p=Ro((e=>{const{a:t,d:r}=i;if(e.is0())throw Error("bad point: ZERO");const{X:n,Y:s,Z:o,T:a}=e,l=c(n*n),u=c(s*s),h=c(o*o),d=c(h*h),p=c(l*t);if(c(h*c(p+u))!==c(d+c(r*c(l*u))))throw Error("bad point: equation left != right (1)");if(c(n*s)!==c(o*a))throw Error("bad point: equation left != right (2)");return!0}));class f{constructor(e,t,r,n){this.X=u("x",e),this.Y=u("y",t),this.Z=u("z",r,!0),this.T=u("t",n),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){if(e instanceof f)throw Error("extended point not allowed");const{x:t,y:r}=e||{};return u("x",t),u("y",r),new f(t,r,ba,c(t*r))}static fromBytes(e,t=!1){const r=n.BYTES,{a:s,d:o}=i;e=_o(yo(e,r,"point")),mo(t,"zip215");const u=_o(e),h=e[r-1];u[r-1]=-129&h;const d=Eo(u),p=t?a:n.ORDER;xo("point.y",d,ya,p);const g=c(d*d),m=c(g-ba),y=c(o*g-s);let{isValid:b,value:w}=l(m,y);if(!b)throw Error("bad point: invalid y coordinate");const v=(w&ba)===ba,E=!!(128&h);if(!t&&w===ya&&E)throw Error("bad point: x=0 and x_0=1");return E!==v&&(w=c(-w)),f.fromAffine({x:w,y:d})}static fromHex(e,t=!1){return f.fromBytes(Io("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return g.createCache(this,e),t||this.multiply(wa),this}assertValidity(){p(this)}equals(e){h(e);const{X:t,Y:r,Z:n}=this,{X:s,Y:i,Z:o}=e,a=c(t*o),l=c(s*n),u=c(r*o),d=c(i*n);return a===l&&u===d}is0(){return this.equals(f.ZERO)}negate(){return new f(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=i,{X:t,Y:r,Z:n}=this,s=c(t*t),o=c(r*r),a=c(wa*c(n*n)),l=c(e*s),u=t+r,h=c(c(u*u)-s-o),d=l+o,p=d-a,g=l-o,m=c(h*p),y=c(d*g),b=c(h*g),w=c(p*d);return new f(m,y,w,b)}add(e){h(e);const{a:t,d:r}=i,{X:n,Y:s,Z:o,T:a}=this,{X:l,Y:u,Z:d,T:p}=e,g=c(n*l),m=c(s*u),y=c(a*r*p),b=c(o*d),w=c((n+s)*(l+u)-g-m),v=b-y,E=b+y,S=c(m-t*g),A=c(w*v),I=c(E*S),_=c(w*S),C=c(v*E);return new f(A,I,C,_)}subtract(e){return this.add(e.negate())}multiply(e){if(!s.isValidNot0(e))throw Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:r}=g.cached(this,e,(e=>ia(f,e)));return ia(f,[t,r])[0]}multiplyUnsafe(e,t=f.ZERO){if(!s.isValid(e))throw Error("invalid scalar: expected 0 <= sc < curve.n");return e===ya?f.ZERO:this.is0()||e===ba?this:g.unsafe(this,e,(e=>ia(f,e)),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return g.unsafe(this,i.n).is0()}toAffine(e){return d(this,e)}clearCofactor(){return o===ba?this:this.multiplyUnsafe(o)}toBytes(){const{x:e,y:t}=this.toAffine(),r=n.toBytes(t);return r[r.length-1]|=e&ba?128:0,r}toHex(){return lr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return ia(f,e)}static msm(e,t){return fa(f,s,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}f.BASE=new f(i.Gx,i.Gy,ba,c(i.Gx*i.Gy)),f.ZERO=new f(ya,ba,ba,ya),f.Fp=n,f.Fn=s;const g=new pa(f,s.BITS);return f.BASE.precompute(8),f}(t,r);return function(e,t){const r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}(e,function(e,t,r={}){if("function"!=typeof t)throw Error('"hash" function param is required');Po(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:s,Fp:i,Fn:o}=e,a=r.randomBytes||Sr,c=r.adjustScalarBytes||(e=>e),l=r.domain||((e,t,r)=>{if(mo(r,"phflag"),t.length||r)throw Error("Contexts/pre-hash are not supported");return e});function u(e){return o.create(Eo(e))}function h(e){const{head:r,prefix:n,scalar:i}=function(e){const r=m.secretKey;e=Io("private key",e,r);const n=Io("hashed private key",t(e),2*r),s=c(n.slice(0,r));return{head:s,prefix:n.slice(r,2*r),scalar:u(s)}}(e),o=s.multiply(i),a=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:a}}function d(e){return h(e).pointBytes}function p(e=Uint8Array.of(),...r){const s=wr(...r);return u(t(l(s,Io("context",e),!!n)))}const f={zip215:!0},g=i.BYTES,m={secretKey:g,publicKey:g,signature:2*g,seed:g};function y(e=a(m.seed)){return yo(e,m.seed,"seed")}const b={getExtendedPublicKey:h,randomSecretKey:y,isValidSecretKey:e=>Jt(e)&&e.length===o.BYTES,isValidPublicKey(t,r){try{return!!e.fromBytes(t,r)}catch(e){return!1}},toMontgomery(t){const{y:r}=e.fromBytes(t),n=m.publicKey,s=32===n;if(!s&&57!==n)throw Error("only defined for 25519 and 448");const o=s?i.div(ba+r,ba-r):i.div(r-ba,r+ba);return i.toBytes(o)},toMontgomerySecret(e){const r=m.secretKey;yo(e,r);const n=t(e.subarray(0,r));return c(n).subarray(0,r)},randomPrivateKey:y,precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({keygen(e){const t=b.randomSecretKey(e);return{secretKey:t,publicKey:d(t)}},getPublicKey:d,sign(e,t,r={}){e=Io("message",e),n&&(e=n(e));const{prefix:i,scalar:a,pointBytes:c}=h(t),l=p(r.context,i,e),u=s.multiply(l).toBytes(),d=p(r.context,u,c,e),f=o.create(l+d*a);if(!o.isValid(f))throw Error("sign failed: invalid s");return yo(wr(u,o.toBytes(f)),m.signature,"result")},verify(t,r,i,o=f){const{context:a,zip215:c}=o,l=m.signature;t=Io("signature",t,l),r=Io("message",r),i=Io("publicKey",i,m.publicKey),void 0!==c&&mo(c,"zip215"),n&&(r=n(r));const u=l/2,h=t.subarray(0,u),d=Eo(t.subarray(u,l));let g,y,b;try{g=e.fromBytes(i,c),y=e.fromBytes(h,c),b=s.multiplyUnsafe(d)}catch(e){return!1}if(!c&&g.isSmallOrder())return!1;const w=p(a,y.toBytes(),g.toBytes(),r);return y.add(g.multiplyUnsafe(w)).subtract(b).clearCofactor().is0()},utils:b,Point:e,lengths:m})}(i,n,s))}({...Pa,Fp:Ma,hash:Jr,adjustScalarBytes:La,uvRatio:function(e,t){const r=Ta,n=zo(t*t*t,r),s=zo(n*n*t,r);let i=zo(e*n*Ra(e*s).pow_p_5_8,r);const o=zo(t*i*i,r),a=i,c=zo(i*Da,r),l=o===e,u=o===zo(-e,r),h=o===zo(-e*Da,r);return l&&(i=a),(u||h)&&(i=c),(zo(i,r)&Do)===Do&&(i=zo(-i,r)),{isValid:l||u,value:i}}}),Oa=(()=>{const e=Ma.ORDER;return function(e){const t=(Po(r=e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r}));var r;const{P:n,type:s,adjustScalarBytes:i,powPminus2:o,randomBytes:a}=t,c="x25519"===s;if(!c&&"x448"!==s)throw Error("invalid type");const l=a||Sr,u=c?255:448,h=c?32:56,d=c?BigInt(9):BigInt(5),p=c?BigInt(121665):BigInt(39081),f=c?Aa**BigInt(254):Aa**BigInt(447),g=c?BigInt(8)*Aa**BigInt(251)-Sa:BigInt(4)*Aa**BigInt(445)-Sa,m=f+g+Sa,y=e=>zo(e,n),b=w(d);function w(e){return Ao(y(e),h)}function v(e,t){const r=function(e,t){xo("u",e,Ea,n),xo("scalar",t,f,m);const r=t,s=e;let i=Sa,a=Ea,c=e,l=Sa,h=Ea;for(let e=BigInt(u-1);e>=Ea;e--){const t=r>>e&Sa;h^=t,({x_2:i,x_3:c}=S(h,i,c)),({x_2:a,x_3:l}=S(h,a,l)),h=t;const n=i+a,o=y(n*n),u=i-a,d=y(u*u),f=o-d,g=c+l,m=y((c-l)*n),b=y(g*u),w=m+b,v=m-b;c=y(w*w),l=y(s*y(v*v)),i=y(o*d),a=y(f*(o+y(p*f)))}({x_2:i,x_3:c}=S(h,i,c)),({x_2:a,x_3:l}=S(h,a,l));const d=o(a);return y(i*d)}(function(e){const t=Io("u coordinate",e,h);return c&&(t[31]&=127),y(Eo(t))}(t),function(e){return Eo(i(Io("scalar",e,h)))}(e));if(r===Ea)throw Error("invalid private or public key received");return w(r)}function E(e){return v(e,b)}function S(e,t,r){const n=y(e*(t-r));return{x_2:t=y(t-n),x_3:r=y(r+n)}}const A={secretKey:h,publicKey:h,seed:h},I=(e=l(h))=>(tr(e,A.seed),e);return{keygen(e){const t=I(e);return{secretKey:t,publicKey:E(t)}},getSharedSecret:(e,t)=>v(e,t),getPublicKey:e=>E(e),scalarMult:v,scalarMultBase:E,utils:{randomSecretKey:I,randomPrivateKey:I},GuBytes:b.slice(),lengths:A}}({P:e,type:"x25519",powPminus2(t){const{pow_p_5_8:r,b2:n}=Ra(t);return zo(jo(r,Ca,e)*n,e)},adjustScalarBytes:La})})();let Ua=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Fa=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ba={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new Fa("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};let $a;const qa=(async()=>{try{return await Ba.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function za(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}let ja=class{type="Ed25519";raw;constructor(e){this.raw=Ha(e,32)}toMultihash(){return Ne.digest(Ac(this))}toCID(){return qe.createV1(114,this.toMultihash())}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();const n=async function(e,t,r){return null==$a&&($a=await qa),$a?async function(e,t,r){if(e.buffer instanceof ArrayBuffer){const n=await Ba.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Ba.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(e,t,r):function(e,t,r){return Na.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(e,t,r)}(this.raw,t,e);return za(n)?n.then((e=>(r?.signal?.throwIfAborted(),e))):n}};class Ka{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Ha(e,64),this.publicKey=new ja(t)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();const r=async function(e,t){return null==$a&&($a=await qa),$a?async function(e,t){let r;r=64===e.length?e.subarray(0,32):e;const n={crv:"Ed25519",kty:"OKP",x:tn(e.subarray(32),"base64url"),d:tn(r,"base64url"),ext:!0,key_ops:["sign"]},s=await Ba.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),i=await Ba.get().subtle.sign({name:"Ed25519"},s,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(i,0,i.byteLength)}(e,t):function(e,t){const r=e.subarray(0,32);return Na.sign(t instanceof Uint8Array?t:t.subarray(),r)}(e,t)}(this.raw,e);return za(r)?r.then((e=>(t?.signal?.throwIfAborted(),e))):(t?.signal?.throwIfAborted(),r)}}function Va(e){return e=Ha(e,32),new ja(e)}function Ha(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Pn(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var Ga,Wa,Xa,Za;function Ya(e){if(isNaN(e)||e<=0)throw new Pn("random bytes length must be a Number bigger than 0");return Sr(e)}(e=>{e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(Ga||(Ga={})),(e=>{e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(Wa||(Wa={})),(Ga||(Ga={})).codec=()=>Gt(Wa),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Ga.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=Ga.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Xa||(Xa={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Ga.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=Ga.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Za||(Za={}));let Qa=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return null==this._raw&&(this._raw=function(e){if(null==e.n||null==e.e)throw new Pn("JWK was missing components");return eo([Ja,Ji(eo([Qi(Ye(e.n,"base64url")),Qi(Ye(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return qe.createV1(114,this._multihash)}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}verify(e,t,r){return async function(e,t,r,n){const s=await Ba.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();const i=await Ba.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}};const Ja=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);class ec extends vr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,rr(e);const r=br(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,s=new Uint8Array(n);s.set(r.length>n?e.create().update(r).digest():r);for(let e=0;e<s.length;e++)s[e]^=54;this.iHash.update(s),this.oHash=e.create();for(let e=0;e<s.length;e++)s[e]^=106;this.oHash.update(s),sr(s)}update(e){return nr(this),this.iHash.update(e),this}digestInto(e){nr(this),tr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:n,destroyed:s,blockLen:i,outputLen:o}=this;return e.finished=n,e.destroyed=s,e.blockLen=i,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const tc=(e,t,r)=>new ec(e,t).update(r).digest();tc.create=(e,t)=>new ec(e,t);const rc=(e,t)=>(e+(e>=0?t:-t)/cc)/t;function nc(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function sc(e,t){const r={};for(let n of Object.keys(t))r[n]=void 0===e[n]?t[n]:e[n];return mo(r.lowS,"lowS"),mo(r.prehash,"prehash"),void 0!==r.format&&nc(r.format),r}const ic={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode(e,t){const{Err:r}=ic;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const n=t.length/2,s=bo(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const i=n>127?bo(s.length/2|128):"";return bo(e)+i+s+t},decode(e,t){const{Err:r}=ic;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const s=t[n++];let i=0;if(128&s){const e=127&s;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const o=t.subarray(n,n+e);if(o.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===o[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of o)i=i<<8|e;if(n+=e,i<128)throw new r("tlv.decode(long): not minimal encoding")}else i=s;const o=t.subarray(n,n+i);if(o.length!==i)throw new r("tlv.decode: wrong value length");return{v:o,l:t.subarray(n+i)}}},_int:{encode(e){const{Err:t}=ic;if(e<oc)throw new t("integer: negative integers are not allowed");let r=bo(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=ic;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return vo(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=ic,s=Io("signature",e),{v:i,l:o}=n.decode(48,s);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){const{_tlv:t,_int:r}=ic,n=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,n)}},oc=BigInt(0),ac=BigInt(1),cc=BigInt(2),lc=BigInt(3),uc=BigInt(4);function hc(e,t){const{BYTES:r}=e;let n;if("bigint"==typeof t)n=t;else{let s=Io("private key",t);try{n=e.fromBytes(s)}catch(e){throw Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw Error("invalid private key: out of range [1..N-1]");return n}function dc(e){return Uint8Array.of(e?2:3)}function pc(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function fc(e){const{CURVE:t,curveOpts:r,hash:n,ecdsaOpts:s}=function(e){const{CURVE:t,curveOpts:r}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp;let n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map((e=>Math.ceil(e/2))))):void 0;return{CURVE:t,curveOpts:{Fp:r,Fn:Jo(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,hash:e.hash,ecdsaOpts:n}}(e);return function(e,t){const r=t.Point;return Object.assign({},t,{ProjectivePoint:r,CURVE:Object.assign({},e,Qo(r.Fn.ORDER,r.Fn.BITS))})}(e,function(e,t,r={}){rr(t),Po(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||Sr,s=r.hmac||((e,...r)=>tc(t,e,wr(...r))),{Fp:i,Fn:o}=e,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:p}=function(e,t={}){const{Fn:r}=e,n=t.randomBytes||Sr,s=Object.assign(pc(e.Fp,r),{seed:ta(r.ORDER)});function i(e){try{return!!hc(r,e)}catch(e){return!1}}function o(e=n(s.seed)){return function(e,t,r=!1){const n=e.length,s=ea(t),i=ta(t);if(n<16||n<i||n>1024)throw Error("expected "+i+"-1024 bytes of input, got "+n);const o=zo(r?Eo(e):vo(e),t-Do)+Do;return r?Ao(o,s):So(o,s)}(yo(e,s.seed,"seed"),r.ORDER)}function a(t,n=!0){return e.BASE.multiply(hc(r,t)).toBytes(n)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:n,publicKey:i,publicKeyUncompressed:o}=s;if(r.allowedLengths||n===i)return;const a=Io("key",t).length;return a===i||a===o}const l={isValidSecretKey:i,isValidPublicKey(t,r){const{publicKey:n,publicKeyUncompressed:i}=s;try{const s=t.length;return!(!0===r&&s!==n||!1===r&&s!==i||!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:o,isValidPrivateKey:i,randomPrivateKey:o,normPrivateKeyToScalar:e=>hc(r,e),precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret(t,n,s=!0){if(!0===c(t))throw Error("first arg must be private key");if(!1===c(n))throw Error("second arg must be public key");const i=hc(r,t);return e.fromHex(n).multiply(i).toBytes(s)},keygen(e){const t=o(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:l,lengths:s})}(e,r),f={prehash:!1,lowS:"boolean"==typeof r.lowS&&r.lowS,format:void 0,extraEntropy:!1},g="compact";function m(e){return e>a>>ac}function y(e,t){if(!o.isValidNot0(t))throw Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class b{constructor(e,t,r){this.r=y("r",e),this.s=y("s",t),null!=r&&(this.recovery=r),Object.freeze(this)}static fromBytes(e,t=g){let r;if(function(e,t){nc(t);const r=p.signature;yo(e,"compact"===t?r:"recovered"===t?r+1:void 0,t+" signature")}(e,t),"der"===t){const{r:t,s:r}=ic.toSig(yo(e));return new b(t,r)}"recovered"===t&&(r=e[0],t="compact",e=e.subarray(1));const n=o.BYTES,s=e.subarray(0,n),i=e.subarray(n,2*n);return new b(o.fromBytes(s),o.fromBytes(i),r)}static fromHex(e,t){return this.fromBytes(yr(e),t)}addRecoveryBit(e){return new b(this.r,this.s,e)}recoverPublicKey(t){const r=i.ORDER,{r:n,s:s,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw Error("recovery id invalid");if(a*cc<r&&c>1)throw Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?n+a:n;if(!i.isValid(l))throw Error("recovery id 2 or 3 invalid");const u=i.toBytes(l),h=e.fromBytes(wr(dc(!(1&c)),u)),d=o.inv(l),p=v(Io("msgHash",t)),f=o.create(-p*d),g=o.create(s*d),m=e.BASE.multiplyUnsafe(f).add(h.multiplyUnsafe(g));if(m.is0())throw Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(e=g){if(nc(e),"der"===e)return yr(ic.hexFromSig(this));const t=o.toBytes(this.r),r=o.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw Error("recovery bit must be present");return wr(Uint8Array.of(this.recovery),t,r)}return wr(t,r)}toHex(e){return lr(this.toBytes(e))}assertValidity(){}static fromCompact(e){return b.fromBytes(Io("sig",e),"compact")}static fromDER(e){return b.fromBytes(Io("sig",e),"der")}normalizeS(){return this.hasHighS()?new b(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return lr(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return lr(this.toBytes("compact"))}}const w=r.bits2int||function(e){if(e.length>8192)throw Error("input is too large");const t=vo(e),r=8*e.length-c;return r>0?t>>BigInt(r):t},v=r.bits2int_modN||function(e){return o.create(w(e))},E=To(c);function S(e){return xo("num < 2^"+c,e,oc,E),o.toBytes(e)}function A(e,r){return yo(e,void 0,"message"),r?yo(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:p,Point:e,sign(r,i,a={}){r=Io("message",r);const{seed:c,k2sig:l}=function(t,r,s){if(["recovered","canonical"].some((e=>e in s)))throw Error("sign() legacy options not supported");const{lowS:i,prehash:a,extraEntropy:c}=sc(s,f);t=A(t,a);const l=v(t),u=hc(o,r),h=[S(u),S(l)];if(null!=c&&!1!==c){const e=!0===c?n(p.secretKey):c;h.push(Io("extraEntropy",e))}const d=wr(...h),g=l;return{seed:d,k2sig(t){const r=w(t);if(!o.isValidNot0(r))return;const n=o.inv(r),s=e.BASE.multiply(r).toAffine(),a=o.create(s.x);if(a===oc)return;const c=o.create(n*o.create(g+a*u));if(c===oc)return;let l=(s.x===a?0:2)|Number(s.y&ac),h=c;return i&&m(c)&&(h=o.neg(c),l^=1),new b(a,h,l)}}}(r,i,a),u=function(e,t,r){if("number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");if("function"!=typeof r)throw Error("hmacFn must be a function");const n=e=>new Uint8Array(e),s=e=>Uint8Array.of(e);let i=n(e),o=n(e),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...e)=>r(o,i,...e),u=(e=n(0))=>{o=l(s(0),e),i=l(),0!==e.length&&(o=l(s(1),e),i=l())},h=()=>{if(a++>=1e3)throw Error("drbg: tried 1000 values");let e=0;const r=[];for(;e<t;){i=l();const t=i.slice();r.push(t),e+=i.length}return wr(...r)};return(e,t)=>{let r;for(c(),u(e);!(r=t(h()));)u();return c(),r}}(t.outputLen,o.BYTES,s);return u(c,l)},verify(t,r,n,s={}){const{lowS:i,prehash:a,format:c}=sc(s,f);if(n=Io("publicKey",n),r=A(Io("message",r),a),"strict"in s)throw Error("options.strict was renamed to lowS");const l=void 0===c?function(e){let t;const r="string"==typeof e||Jt(e),n=!r&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!r&&!n)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(n)t=new b(e.r,e.s);else if(r){try{t=b.fromBytes(Io("sig",e),"der")}catch(e){if(!(e instanceof ic.Err))throw e}if(!t)try{t=b.fromBytes(Io("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):b.fromBytes(Io("sig",t),c);if(!1===l)return!1;try{const t=e.fromBytes(n);if(i&&l.hasHighS())return!1;const{r:s,s:a}=l,c=v(r),u=o.inv(a),h=o.create(c*u),d=o.create(s*u),p=e.BASE.multiplyUnsafe(h).add(t.multiplyUnsafe(d));return!p.is0()&&o.create(p.x)===s}catch(e){return!1}},recoverPublicKey(e,t,r={}){const{prehash:n}=sc(r,f);return t=A(t,n),b.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:b,hash:t})}(function(e,t={}){const r=ma("weierstrass",e,t),{Fp:n,Fn:s}=r;let i=r.CURVE;const{h:o,n:a}=i;Po(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!n.is0(i.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw Error('invalid endo: expected "beta": bigint and "basises": array');const l=pc(n,s);function u(){if(!n.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}const h=t.toBytes||function(e,t,r){const{x:s,y:i}=t.toAffine(),o=n.toBytes(s);return mo(r,"isCompressed"),r?(u(),wr(dc(!n.isOdd(i)),o)):wr(Uint8Array.of(4),o,n.toBytes(i))},d=t.fromBytes||function(e){yo(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:r}=l,s=e.length,i=e[0],o=e.subarray(1);if(s!==t||2!==i&&3!==i){if(s===r&&4===i){const e=n.BYTES,t=n.fromBytes(o.subarray(0,e)),r=n.fromBytes(o.subarray(e,2*e));if(!f(t,r))throw Error("bad point: is not on curve");return{x:t,y:r}}throw Error(`bad point: got length ${s}, expected compressed=${t} or uncompressed=${r}`)}{const t=n.fromBytes(o);if(!n.isValid(t))throw Error("bad point: is not on curve, wrong x");const r=p(t);let s;try{s=n.sqrt(r)}catch(e){const t=e instanceof Error?": "+e.message:"";throw Error("bad point: is not on curve, sqrt error"+t)}return u(),!(1&~i)!==n.isOdd(s)&&(s=n.neg(s)),{x:t,y:s}}};function p(e){const t=n.sqr(e),r=n.mul(t,e);return n.add(n.add(r,n.mul(e,i.a)),i.b)}function f(e,t){const r=n.sqr(t),s=p(e);return n.eql(r,s)}if(!f(i.Gx,i.Gy))throw Error("bad curve params: generator point");const g=n.mul(n.pow(i.a,lc),uc),m=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(g,m)))throw Error("bad curve params: a or b");function y(e,t,r=!1){if(!n.isValid(t)||r&&n.is0(t))throw Error("bad point coordinate "+e);return t}function b(e){if(!(e instanceof A))throw Error("ProjectivePoint expected")}function w(e){if(!c||!c.basises)throw Error("no endo");return function(e,t,r){const[[n,s],[i,o]]=t,a=rc(o*e,r),c=rc(-s*e,r);let l=e-a*n-c*i,u=-a*s-c*o;const h=l<oc,d=u<oc;h&&(l=-l),d&&(u=-u);const p=To(Math.ceil(ko(r)/2))+ac;if(l<oc||l>=p||u<oc||u>=p)throw Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}(e,c.basises,s.ORDER)}const v=Ro(((e,t)=>{const{X:r,Y:s,Z:i}=e;if(n.eql(i,n.ONE))return{x:r,y:s};const o=e.is0();null==t&&(t=o?n.ONE:n.inv(i));const a=n.mul(r,t),c=n.mul(s,t),l=n.mul(i,t);if(o)return{x:n.ZERO,y:n.ZERO};if(!n.eql(l,n.ONE))throw Error("invZ was invalid");return{x:a,y:c}})),E=Ro((e=>{if(e.is0()){if(t.allowInfinityPoint&&!n.is0(e.Y))return;throw Error("bad point: ZERO")}const{x:r,y:s}=e.toAffine();if(!n.isValid(r)||!n.isValid(s))throw Error("bad point: x or y not field elements");if(!f(r,s))throw Error("bad point: equation left != right");if(!e.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0}));function S(e,t,r,s,i){return r=new A(n.mul(r.X,e),r.Y,r.Z),t=sa(s,t),r=sa(i,r),t.add(r)}class A{constructor(e,t,r){this.X=y("x",e),this.Y=y("y",t,!0),this.Z=y("z",r),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){const{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw Error("invalid affine point");if(e instanceof A)throw Error("projective point not allowed");return n.is0(t)&&n.is0(r)?A.ZERO:new A(t,r,n.ONE)}static fromBytes(e){const t=A.fromAffine(d(yo(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return A.fromBytes(Io("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return _.createCache(this,e),t||this.multiply(lc),this}assertValidity(){E(this)}hasEvenY(){const{y:e}=this.toAffine();if(!n.isOdd)throw Error("Field doesn't support isOdd");return!n.isOdd(e)}equals(e){b(e);const{X:t,Y:r,Z:s}=this,{X:i,Y:o,Z:a}=e,c=n.eql(n.mul(t,a),n.mul(i,s)),l=n.eql(n.mul(r,a),n.mul(o,s));return c&&l}negate(){return new A(this.X,n.neg(this.Y),this.Z)}double(){const{a:e,b:t}=i,r=n.mul(t,lc),{X:s,Y:o,Z:a}=this;let c=n.ZERO,l=n.ZERO,u=n.ZERO,h=n.mul(s,s),d=n.mul(o,o),p=n.mul(a,a),f=n.mul(s,o);return f=n.add(f,f),u=n.mul(s,a),u=n.add(u,u),c=n.mul(e,u),l=n.mul(r,p),l=n.add(c,l),c=n.sub(d,l),l=n.add(d,l),l=n.mul(c,l),c=n.mul(f,c),u=n.mul(r,u),p=n.mul(e,p),f=n.sub(h,p),f=n.mul(e,f),f=n.add(f,u),u=n.add(h,h),h=n.add(u,h),h=n.add(h,p),h=n.mul(h,f),l=n.add(l,h),p=n.mul(o,a),p=n.add(p,p),h=n.mul(p,f),c=n.sub(c,h),u=n.mul(p,d),u=n.add(u,u),u=n.add(u,u),new A(c,l,u)}add(e){b(e);const{X:t,Y:r,Z:s}=this,{X:o,Y:a,Z:c}=e;let l=n.ZERO,u=n.ZERO,h=n.ZERO;const d=i.a,p=n.mul(i.b,lc);let f=n.mul(t,o),g=n.mul(r,a),m=n.mul(s,c),y=n.add(t,r),w=n.add(o,a);y=n.mul(y,w),w=n.add(f,g),y=n.sub(y,w),w=n.add(t,s);let v=n.add(o,c);return w=n.mul(w,v),v=n.add(f,m),w=n.sub(w,v),v=n.add(r,s),l=n.add(a,c),v=n.mul(v,l),l=n.add(g,m),v=n.sub(v,l),h=n.mul(d,w),l=n.mul(p,m),h=n.add(l,h),l=n.sub(g,h),h=n.add(g,h),u=n.mul(l,h),g=n.add(f,f),g=n.add(g,f),m=n.mul(d,m),w=n.mul(p,w),g=n.add(g,m),m=n.sub(f,m),m=n.mul(d,m),w=n.add(w,m),f=n.mul(g,w),u=n.add(u,f),f=n.mul(v,w),l=n.mul(y,l),l=n.sub(l,f),f=n.mul(y,g),h=n.mul(v,h),h=n.add(h,f),new A(l,u,h)}subtract(e){return this.add(e.negate())}is0(){return this.equals(A.ZERO)}multiply(e){const{endo:r}=t;if(!s.isValidNot0(e))throw Error("invalid scalar: out of range");let n,i;const o=e=>_.cached(this,e,(e=>ia(A,e)));if(r){const{k1neg:t,k1:s,k2neg:a,k2:c}=w(e),{p:l,f:u}=o(s),{p:h,f:d}=o(c);i=u.add(d),n=S(r.beta,l,h,t,a)}else{const{p:t,f:r}=o(e);n=t,i=r}return ia(A,[n,i])[0]}multiplyUnsafe(e){const{endo:r}=t,n=this;if(!s.isValid(e))throw Error("invalid scalar: out of range");if(e===oc||n.is0())return A.ZERO;if(e===ac)return n;if(_.hasCache(this))return this.multiply(e);if(r){const{k1neg:t,k1:s,k2neg:i,k2:o}=w(e),{p1:a,p2:c}=function(e,t,r,n){let s=t,i=e.ZERO,o=e.ZERO;for(;r>ra||n>ra;)r&na&&(i=i.add(s)),n&na&&(o=o.add(s)),s=s.double(),r>>=na,n>>=na;return{p1:i,p2:o}}(A,n,s,o);return S(r.beta,a,c,t,i)}return _.unsafe(n,e)}multiplyAndAddUnsafe(e,t,r){const n=this.multiplyUnsafe(t).add(e.multiplyUnsafe(r));return n.is0()?void 0:n}toAffine(e){return v(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return o===ac||(e?e(A,this):_.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return o===ac?this:e?e(A,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return mo(e,"isCompressed"),this.assertValidity(),h(A,this,e)}toHex(e=!0){return lr(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return ia(A,e)}static msm(e,t){return fa(A,s,e,t)}static fromPrivateKey(e){return A.BASE.multiply(hc(s,e))}}A.BASE=new A(i.Gx,i.Gy,n.ONE),A.ZERO=new A(n.ZERO,n.ONE,n.ZERO),A.Fp=n,A.Fn=s;const I=s.BITS,_=new pa(A,t.endo?Math.ceil(I/2):I);return A.BASE.precompute(8),A}(t,r),n,s))}const gc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},mc={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},yc=BigInt(2),bc=Jo(gc.p,{sqrt(e){const t=gc.p,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,h=jo(u,r,t)*u%t,d=jo(h,r,t)*u%t,p=jo(d,yc,t)*l%t,f=jo(p,s,t)*p%t,g=jo(f,i,t)*f%t,m=jo(g,a,t)*g%t,y=jo(m,c,t)*m%t,b=jo(y,a,t)*g%t,w=jo(b,r,t)*u%t,v=jo(w,o,t)*f%t,E=jo(v,n,t)*l%t,S=jo(E,yc,t);if(!bc.eql(bc.sqr(S),e))throw Error("Cannot find square root");return S}}),wc=function(e,t){const r=t=>fc({...e,hash:t});return{...r(t),create:r}}({...gc,Fp:bc,lowS:!0,endo:mc},Qr);let vc=class{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return wc.ProjectivePoint.fromHex(e),e}catch(e){throw new Rn(e+"")}}(e),this.raw=function(e){return wc.ProjectivePoint.fromHex(e).toRawBytes(!0)}(this._key)}toMultihash(){return Ne.digest(Ac(this))}toCID(){return qe.createV1(114,this.toMultihash())}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}verify(e,t,r){return function(e,t,r,n){const s=Ue.digest(r instanceof Uint8Array?r:r.subarray());if(za(s))return s.then((({digest:r})=>(n?.signal?.throwIfAborted(),wc.verify(t,r,e)))).catch((e=>{if("AbortError"===e.name)throw e;throw new Ua(e+"")}));try{return n?.signal?.throwIfAborted(),wc.verify(t,s.digest,e)}catch(e){throw new Ua(e+"")}}(this._key,t,e,r)}};function Ec(e){return new vc(e)}function Sc(e,t){const{Type:r,Data:n}=Xa.decode(e),s=n??new Uint8Array;switch(r){case Ga.RSA:return function(e,t){if(e.byteLength>=1062)throw new Rn("Key size is too large");return function(e,t,r){const n=function(e){const t=Wi(e[1],{offset:0});return{kty:"RSA",n:tn(t[0],"base64url"),e:tn(t[1],"base64url")}}(e);return null==r&&(r=Re(18,en(Xa.encode({Type:Ga.RSA,Data:t})))),new Qa(n,r)}(Wi(e,{offset:0}),e,t)}(s,t);case Ga.Ed25519:return Va(s);case Ga.secp256k1:return Ec(s);case Ga.ECDSA:return uo(s);default:throw new Qn}}function Ac(e){return Xa.encode({Type:Ga[e.type],Data:e.raw})}const Ic=Symbol.for("nodejs.util.inspect.custom");let _c=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[En]=!0;toString(){return null==this.string&&(this.string=fe.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return qe.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Ds(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return Ds(this.multihash.bytes,e.toMultihash().bytes);throw Error("not valid Id")}[Ic](){return`PeerId(${this.toString()})`}},Cc=class extends _c{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},xc=class extends _c{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},kc=class extends _c{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}};class Tc{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ne.digest(Ye(this.url))}[Ic](){return`PeerId(${this.url})`}[En]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return qe.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=tn(e)),e.toString()===this.toString())}}function Pc(e){let t;if("1"!==e.charAt(0)&&"Q"!==e.charAt(0)){if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return Dc(qe.parse(e));throw new Pn('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return t=Le(fe.decode("z"+e)),Lc(t)}function Rc(e){if("Ed25519"===e.type)return new xc({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new kc({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Cc({multihash:e.toCID().multihash,publicKey:e});throw new Qn}function Lc(e){if(function(e){return e.code===Ue.code}(e))return new Cc({multihash:e});if(function(e){return e.code===Ne.code}(e))try{const t=function(e){const{Type:t,Data:r}=Xa.decode(e.digest),n=r??new Uint8Array;switch(t){case Ga.Ed25519:return Va(n);case Ga.secp256k1:return Ec(n);case Ga.ECDSA:return uo(n);default:throw new Qn}}(e);if("Ed25519"===t.type)return new xc({multihash:e,publicKey:t});if("secp256k1"===t.type)return new kc({multihash:e,publicKey:t})}catch(t){const r=tn(e.digest);return new Tc(new URL(r))}throw new zn("Supplied PeerID Multihash is invalid")}function Dc(e){if(null==e?.multihash||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new qn("Supplied PeerID CID is invalid");if(2336===e.code){const t=tn(e.multihash.digest);return new Tc(new URL(t))}return Lc(e.multihash)}class Mc extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"}class Nc extends Error{static name="ValidationError";name="ValidationError"}class Oc extends Error{static name="InvalidParametersError";name="InvalidParametersError"}class Uc extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"}const Fc=new class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){const t=this.index,r=e();return void 0===r&&(this.index=t),r}parseWith(e){const t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically((()=>{const t=this.readChar();if(t===e)return t}))}readSeparator(e,t,r){return this.readAtomically((()=>{if(!(t>0&&void 0===this.readGivenChar(e)))return r()}))}readNumber(e,t,r,n){return this.readAtomically((()=>{let s=0,i=0;const o=this.peekChar();if(void 0===o)return;const a="0"===o,c=2**(8*n)-1;for(;;){const r=this.readAtomically((()=>{const t=this.readChar();if(void 0===t)return;const r=Number.parseInt(t,e);return Number.isNaN(r)?void 0:r}));if(void 0===r)break;if(s*=e,s+=r,s>c)return;if(i+=1,void 0!==t&&i>t)return}return 0===i||!r&&a&&i>1?void 0:s}))}readIPv4Addr(){return this.readAtomically((()=>{const e=new Uint8Array(4);for(let t=0;t<e.length;t++){const r=this.readSeparator(".",t,(()=>this.readNumber(10,3,!1,1)));if(void 0===r)return;e[t]=r}return e}))}readIPv6Addr(){const e=e=>{for(let t=0;t<e.length/2;t++){const r=2*t;if(t<e.length-3){const n=this.readSeparator(":",t,(()=>this.readIPv4Addr()));if(void 0!==n)return e[r]=n[0],e[r+1]=n[1],e[r+2]=n[2],e[r+3]=n[3],[r+4,!0]}const n=this.readSeparator(":",t,(()=>this.readNumber(16,4,!0,2)));if(void 0===n)return[r,!1];e[r]=n>>8,e[r+1]=255&n}return[e.length,!1]};return this.readAtomically((()=>{const t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(n)return;if(void 0===this.readGivenChar(":"))return;if(void 0===this.readGivenChar(":"))return;const s=new Uint8Array(14),i=16-(r+2),[o]=e(s.subarray(0,i));return t.set(s.subarray(0,o),16-o),t}))}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function Bc(e){if(!(e.length>15))return Fc.new(e).parseWith((()=>Fc.readIPv4Addr()))}function $c(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Fc.new(e).parseWith((()=>Fc.readIPv6Addr()))}function qc(e,t=!1){if(e.includes("%")&&(e=e.split("%")[0]),e.length>45)return;const r=Fc.new(e).parseWith((()=>Fc.readIPAddr()));return r?t&&4===r.length?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,r[0],r[1],r[2],r[3]]):r:void 0}function zc(e){return!!Bc(e)}function jc(e){return!!$c(e)}const Kc=41,Vc=42;function Hc(e){return t=>tn(t,e)}function Gc(e){return t=>Ye(t,e)}function Wc(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function Xc(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function Zc(e){const t=e.subarray(0,e.length-2),r=e.subarray(e.length-2);return`${tn(t,"base32")}:${Wc(r)}`}const Yc=e=>{e=e.toString().trim();const t=new Uint8Array(4);return e.split(/\./g).forEach(((e,r)=>{const n=parseInt(e,10);if(isNaN(n)||n<0||n>255)throw new Mc("Invalid byte value in IP address");t[r]=n})),t},Qc=Object.values(He).map((e=>e.decoder)),Jc=(()=>{let e=Qc[0].or(Qc[1]);return Qc.slice(2).forEach((t=>e=e.or(t))),e})(),el=function(...e){return t=>{for(const r of e)r(t)}}((function(e){if(parseInt(e).toString()!==e)throw new Nc("Value must be an integer")}),(function(e){if(e<0)throw new Nc("Value must be a positive integer, or zero")}),(e=>{if(e>65535)throw new Nc("Value must be smaller than or equal to 65535")})),tl=-1,rl=new class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(t="string"==typeof e?this.protocolsByName.get(e):this.protocolsByCode.get(e),null==t)throw new Uc(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach((t=>{this.protocolsByName.set(t,e)}))}removeProtocol(e){const t=this.protocolsByCode.get(e);null!=t&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach((e=>{this.protocolsByName.delete(e)})))}},nl=[{code:4,name:"ip4",size:32,valueToBytes:Yc,bytesToValue(e){if(4!==e.byteLength)throw new Mc("IPv4 address was incorrect length");const t=[];for(let r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},validate(e){if(!zc(e))throw new Nc(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Xc,bytesToValue:Wc,validate:el},{code:273,name:"udp",size:16,valueToBytes:Xc,bytesToValue:Wc,validate:el},{code:33,name:"dccp",size:16,valueToBytes:Xc,bytesToValue:Wc,validate:el},{code:Kc,name:"ip6",size:128,valueToBytes(e){let t=0;const r=(e=e.toString().trim()).split(":",8);let n;for(n=0;n<r.length;n++){let e;zc(r[n])&&(e=Yc(r[n]),r[n]=tn(e.subarray(0,2),"base16")),null!=e&&++n<8&&r.splice(n,0,tn(e.subarray(2,4),"base16"))}if(""===r[0])for(;r.length<8;)r.unshift("0");else if(""===r[r.length-1])for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&""!==r[n];n++);const e=[n,1];for(n=9-r.length;n>0;n--)e.push("0");r.splice.apply(r,e)}const s=new Uint8Array(t+16);for(n=0;n<r.length;n++){""===r[n]&&(r[n]="0");const e=parseInt(r[n],16);if(isNaN(e)||e<0||e>65535)throw new Mc("Invalid byte value in IP address");s[t++]=e>>8&255,s[t++]=255&e}return s},bytesToValue(e){if(16!==e.byteLength)throw new Mc("IPv6 address was incorrect length");const t=[];for(let r=0;r<e.byteLength;r+=2){const n=e[r],s=e[r+1],i=`${n.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}const r=t.join(":");try{const e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Mc(`Invalid IPv6 address "${r}"`)}},stringToValue(e){try{const t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new Mc(`Invalid IPv6 address "${e}"`)}},validate(e){if(!jc(e))throw new Nc(`Invalid IPv6 address "${e}"`)}},{code:Vc,name:"ip6zone",size:tl},{code:43,name:"ipcidr",size:8,bytesToValue:Hc("base10"),valueToBytes:Gc("base10")},{code:53,name:"dns",size:tl,resolvable:!0},{code:54,name:"dns4",size:tl,resolvable:!0},{code:55,name:"dns6",size:tl,resolvable:!0},{code:56,name:"dnsaddr",size:tl,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Xc,bytesToValue:Wc,validate:el},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:tl,path:!0,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:tl,bytesToValue:Hc("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?Gc("base58btc")(e):qe.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Zc,valueToBytes(e){const t=e.split(":");if(2!==t.length)throw Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(16!==t[0].length)throw Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);const r=Ye(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw Error("Port number is not in range(1, 65536)");const s=Xc(n);return Ls([r,s],r.length+s.length)}},{code:445,name:"onion3",size:296,bytesToValue:Zc,valueToBytes(e){const t=e.split(":");if(2!==t.length)throw Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(56!==t[0].length)throw Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);const r=te.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw Error("Port number is not in range(1, 65536)");const s=Xc(n);return Ls([r,s],r.length+s.length)}},{code:446,name:"garlic64",size:tl},{code:447,name:"garlic32",size:tl},{code:448,name:"tls"},{code:449,name:"sni",size:tl},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:tl,bytesToValue:function(e){return t=>e.encoder.encode(t)}(we),valueToBytes:e=>Jc.decode(e)},{code:480,name:"http"},{code:481,name:"http-path",size:tl,stringToValue:e=>"/"+decodeURIComponent(e),valueToString:e=>encodeURIComponent(e.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:tl}];function sl(e,t,r){return null==e.size||0===e.size?0:e.size>0?e.size/8:b(t,r)}nl.forEach((e=>{rl.addProtocol(e)}));const il=Symbol.for("nodejs.util.inspect.custom"),ol=Symbol.for("@multiformats/multiaddr"),al=[53,54,55,56];class cl extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}}class ll{[ol]=!0;#t;#r;#n;constructor(e="/",t={}){this.#t=function(e){if(null==e&&(e="/"),yl(e))return e.getComponents();if(e instanceof Uint8Array)return function(e){const t=[];let r=0;for(;r<e.length;){const n=b(e,r),s=rl.getProtocol(n),i=f(n),o=sl(s,e,r+i);let a=0;o>0&&s.size===tl&&(a=f(o));const c=i+a+o,l={code:n,name:s.name,bytes:e.subarray(r,r+c)};if(o>0){const t=r+i+a,n=e.subarray(t,t+o);l.value=s.bytesToValue?.(n)??tn(n)}t.push(l),r+=c}return t}(e);if("string"==typeof e)return""===(e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""))&&(e="/"),function(e){if("/"!==e.charAt(0))throw new Mc('String multiaddr must start with "/"');const t=[];let r="protocol",n="",s="";for(let i=1;i<e.length;i++){const o=e.charAt(i);"/"!==o&&("protocol"===r?s+=e.charAt(i):n+=e.charAt(i));const a=i===e.length-1;if("/"===o||a){const e=rl.getProtocol(s);if("protocol"===r){if(null==e.size||0===e.size){t.push({code:e.code,name:e.name}),n="",s="",r="protocol";continue}if(a)throw new Mc(`Component ${s} was missing value`);r="value"}else if("value"===r){const i={code:e.code,name:e.name};if(null!=e.size&&0!==e.size){if(""===n)throw new Mc(`Component ${s} was missing value`);i.value=e.stringToValue?.(n)??n}t.push(i),n="",s="",r="protocol"}}}if(""!==s&&""!==n)throw new Mc("Incomplete multiaddr");return t}(e);if(Array.isArray(e))return e;throw new Mc("Must be a string, Uint8Array, Component[], or another Multiaddr")}(e),!1!==t.validate&&function(e){e.getComponents().forEach((e=>{const t=rl.getProtocol(e.code);null!=e.value&&t.validate?.(e.value)}))}(this)}get bytes(){return null==this.#n&&(this.#n=function(e){let t=0;const r=[];for(const n of e){if(null==n.bytes){const e=rl.getProtocol(n.code),t=f(n.code);let r,s=0,i=0;null!=n.value&&(r=e.valueToBytes?.(n.value)??Ye(n.value),s=r.byteLength,e.size===tl&&(i=f(s)));const o=new Uint8Array(t+i+s);let a=0;g(n.code,o,a),a+=t,null!=r&&(e.size===tl&&(g(s,o,a),a+=i),o.set(r,a)),n.bytes=o}r.push(n.bytes),t+=n.bytes.byteLength}return Ls(r,t)}(this.#t)),this.#n}toString(){return null==this.#r&&(this.#r="/"+this.#t.flatMap((e=>{if(null==e.value)return e.name;const t=rl.getProtocol(e.code);if(null==t)throw new Mc("Unknown protocol code "+e.code);return[e.name,t.valueToString?.(e.value)??e.value]})).join("/")),this.#r}toJSON(){return this.toString()}toOptions(){let e,t,r,n,s="";for(const{code:i,name:o,value:a}of this.#t)i===Vc&&(s="%"+(a??"")),al.includes(i)&&(t="tcp",n=443,r=`${a??""}${s}`,e=55===i?6:4),6!==i&&273!==i||(t="tcp"===o?"tcp":"udp",n=parseInt(a??"")),4!==i&&i!==Kc||(t="tcp",r=`${a??""}${s}`,e=i===Kc?6:4);if(null==e||null==t||null==r||null==n)throw Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:r,transport:t,port:n}}getComponents(){return[...this.#t]}protos(){return this.#t.map((({code:e,value:t})=>{const r=rl.getProtocol(e);return{code:e,size:r.size??0,name:r.name,resolvable:!!r.resolvable,path:!!r.path}}))}protoCodes(){return this.#t.map((({code:e})=>e))}protoNames(){return this.#t.map((({name:e})=>e))}tuples(){return this.#t.map((({code:e,value:t})=>{if(null==t)return[e];const r=rl.getProtocol(e),n=[e];return null!=t&&n.push(r.valueToBytes?.(t)??Ye(t)),n}))}stringTuples(){return this.#t.map((({code:e,value:t})=>null==t?[e]:[e,t]))}encapsulate(e){const t=new ll(e);return new ll([...this.#t,...t.getComponents()],{validate:!1})}decapsulate(e){const t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw new Oc(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new ll(r.slice(0,n),{validate:!1})}decapsulateCode(e){let t;for(let r=this.#t.length-1;r>-1;r--)if(this.#t[r].code===e){t=r;break}return new ll(this.#t.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#t.forEach((({code:t,value:r})=>{421===t&&e.push([t,r]),290===t&&(e=[])}));const t=e.pop();if(null!=t?.[1]){const e=t[1];return"Q"===e[0]||"1"===e[0]?tn(fe.decode("z"+e),"base58btc"):tn(qe.parse(e).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){for(const e of this.#t)if(rl.getProtocol(e.code).path)return e.value??null;return null}equals(e){return Ds(this.bytes,e.bytes)}async resolve(e){const t=this.protos().find((e=>e.resolvable));if(null==t)return[this];const r=ml.get(t.name);if(null==r)throw new cl("no available resolver for "+t.name);return(await r(this,e)).map((e=>bl(e)))}nodeAddress(){const e=this.toOptions();if("tcp"!==e.transport&&"udp"!==e.transport)throw Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return!(2!==this.#t.length||4!==this.#t[0].code&&this.#t[0].code!==Kc||6!==this.#t[1].code&&273!==this.#t[1].code)}[il](){return`Multiaddr(${this.toString()})`}}const ul=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function hl(e,t){16===t.length&&4===e.length&&function(e,t,r){let n=0;for(const t of e)if(!(n<0)){if(n>11)break;if(255!==t)return!1;n++}return!0}(t)&&(t=t.slice(12)),4===t.length&&16===e.length&&function(e,t,r,n){let s=0;for(const r of e)if(!(s<0)){if(s>11)break;if(r!==t[s])return!1;s++}return!0}(e,ul)&&(e=e.slice(12));const r=e.length;if(r!=t.length)throw Error("Failed to mask ip");const n=new Uint8Array(r);for(let s=0;s<r;s++)n[s]=e[s]&t[s];return n}function dl(e,t){if(32!==t&&128!==t)throw Error("Invalid CIDR mask");if(e<0||e>t)throw Error("Invalid CIDR mask");const r=t/8,n=new Uint8Array(r);for(let t=0;t<r;t++)e>=8?(n[t]=255,e-=8):(n[t]=255-(255>>e),e=0);return n}class pl{constructor(e,t){if(null==t)({network:this.network,mask:this.mask}=function(e){const[t,r]=e.split("/");if(!t||!r)throw Error("Failed to parse given CIDR: "+e);let n=4,s=Bc(t);if(null==s&&(n=16,s=$c(t),null==s))throw Error("Failed to parse given CIDR: "+e);const i=parseInt(r,10);if(Number.isNaN(i)||(i+"").length!==r.length||i<0||i>8*n)throw Error("Failed to parse given CIDR: "+e);const o=dl(i,8*n);return{network:hl(s,o),mask:o}}(e));else{const r=qc(e);if(null==r)throw Error("Failed to parse network");const n=parseInt(t+="",10);if(Number.isNaN(n)||(n+"").length!==t.length||n<0||n>8*r.length){const e=qc(t);if(null==e)throw Error("Failed to parse mask");this.mask=e}else this.mask=dl(n,8*r.length);this.network=hl(r,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=qc(t)),null==t)throw Error("Invalid ip");if(t.length!==e.network.length)return!1;for(let r=0;r<t.length;r++)if((e.network[r]&e.mask[r])!=(t[r]&e.mask[r]))return!1;return!0}({network:this.network,mask:this.mask},e)}toString(){const e=function(e){let t=0;for(let[r,n]of e.entries()){if(255!==n){for(;128&n;)t++,n<<=1;if(128&n)return-1;for(let t=r+1;t<e.length;t++)if(0!=e[t])return-1;break}t+=8}return t}(this.mask),t=-1!==e?e+"":function(e){let t="0x";for(const r of e)t+=(r>>4).toString(16)+(15&r).toString(16);return t}(this.mask);return function(e){switch(e.length){case 4:return e.join(".");case 16:{const t=[];for(let r=0;r<e.length;r++)r%2==0&&t.push(e[r].toString(16).padStart(2,"0")+e[r+1].toString(16).padStart(2,"0"));return t.join(":")}default:throw Error("Invalid ip length")}}(this.network)+"/"+t}}function fl(e,t){return rl.getProtocol(e).bytesToValue?.(t)??tn(t,"base16")}function gl(e,t){return rl.getProtocol(e).valueToBytes?.(t)??Ye(t,"base16")}const ml=new Map;function yl(e){return!!e?.[ol]}function bl(e){return new ll(e)}function wl(e){const t=rl.getProtocol(e);return{code:t.code,size:t.size??0,name:t.name,resolvable:!!t.resolvable,path:!!t.path}}const vl=e=>{if(!e)return-1;try{const t=e.metadata.get("ping");return t?Number(on(t)):-1}catch(e){return-1}},El=new fs("connection-limiter");class Sl{libp2p;events;networkMonitor;dialer;connectionMonitorInterval=null;options;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.networkMonitor=e.networkMonitor,this.dialer=e.dialer,this.options=e.options,this.onWakuConnectionEvent=this.onWakuConnectionEvent.bind(this),this.onDisconnectedEvent=this.onDisconnectedEvent.bind(this)}start(){this.dialPeersFromStore(),this.options.enableAutoRecovery&&null===this.connectionMonitorInterval&&(this.connectionMonitorInterval=setInterval((()=>{this.maintainConnections()}),5e3)),this.events.addEventListener(Cs.Connection,this.onWakuConnectionEvent),this.libp2p.addEventListener("peer:disconnect",this.onDisconnectedEvent)}stop(){this.events.removeEventListener(Cs.Connection,this.onWakuConnectionEvent),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnectedEvent),this.connectionMonitorInterval&&(clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=null)}onWakuConnectionEvent(){this.options.enableAutoRecovery?this.networkMonitor.isBrowserConnected()&&this.dialPeersFromStore():El.info("Auto recovery is disabled, skipping")}async maintainConnections(){await this.maintainConnectionsCount(),await this.maintainBootstrapConnections(),await this.maintainTTLConnectedPeers()}async onDisconnectedEvent(){0===this.libp2p.getConnections().length&&(El.info("No connections, dialing peers from store"),await this.dialPeersFromStore())}async maintainConnectionsCount(){El.info("Maintaining connections count");const e=this.libp2p.getConnections();if(e.length<=this.options.maxConnections){El.info(`Node has less than max connections ${this.options.maxConnections}, trying to dial more peers`);const t=await this.getPrioritizedPeers();if(0===t.length)return El.info("No peers to dial, skipping"),void await this.triggerBootstrap();const r=t.slice(0,this.options.maxConnections-e.length).map((e=>this.dialer.dial(e.id)));await Promise.all(r)}else{El.info(`Node has more than max connections ${this.options.maxConnections}, dropping connections`);try{const t=e.filter((e=>!e.tags.includes(ks))).slice(this.options.maxConnections);if(0===t.length)return void El.info("No connections to drop, skipping");const r=t.map((e=>this.libp2p.hangUp(e.remotePeer)));await Promise.all(r),El.info(`Dropped ${t.length} connections`)}catch(e){El.error("Unexpected error while maintaining connections",e)}}}async maintainBootstrapConnections(){El.info("Maintaining bootstrap connections");const e=await this.getBootstrapPeers();if(!(e.length<=this.options.maxBootstrapPeers))try{const t=e.slice(this.options.maxBootstrapPeers);El.info(`Dropping ${t.length} bootstrap connections because node has more than max bootstrap connections ${this.options.maxBootstrapPeers}`);const r=t.map((e=>this.libp2p.hangUp(e.id)));await Promise.all(r),El.info(`Dropped ${t.length} bootstrap connections`)}catch(e){El.error("Unexpected error while maintaining bootstrap connections",e)}}async maintainTTLConnectedPeers(){El.info("Maintaining TTL connected peers");const e=this.libp2p.getConnections().map((async e=>{try{await this.libp2p.peerStore.merge(e.remotePeer,{metadata:{ttl:nn(Date.now())}}),El.info("TTL updated for connected peer "+e.remotePeer.toString())}catch(e){El.error("Unexpected error while maintaining TTL connected peer",e)}}));await Promise.all(e)}async dialPeersFromStore(){El.info("Dialing peers from store");try{const e=await this.getPrioritizedPeers();if(0===e.length)return El.info("No peers to dial, skipping"),void await this.triggerBootstrap();const t=e.map((e=>this.dialer.dial(e.id)));El.info(`Dialing ${e.length} peers from store`),await Promise.all(t),El.info(`Dialed ${t.length} peers from store`)}catch(e){El.error("Unexpected error while dialing peer store peers",e)}}async getPrioritizedPeers(){const e=await this.libp2p.peerStore.all(),t=this.libp2p.getConnections();El.info(`Found ${e.length} peers in store, and found ${t.length} connections`);const r=e.filter((e=>!t.some((t=>t.remotePeer.equals(e.id)))&&((e,t)=>{const r=e?.components?.transportManager?.getTransports()||[];return 0!==r.length&&r.map((e=>e.dialFilter(t))).some((e=>e.length>0))})(this.libp2p,e.addresses.map((e=>e.multiaddr)))));return[...r.filter((e=>e.tags.has(xs.BOOTSTRAP))),...r.filter((e=>e.tags.has(xs.PEER_EXCHANGE))),...r.filter((e=>e.tags.has(xs.PEER_CACHE))),...r.filter((e=>!e.tags.has(xs.BOOTSTRAP)&&!e.tags.has(xs.PEER_EXCHANGE)&&!e.tags.has(xs.PEER_CACHE)))]}async getBootstrapPeers(){return(await Promise.all(this.libp2p.getConnections().map((e=>e.remotePeer)).map((e=>this.getPeer(e))))).filter((e=>e&&e.tags.has(xs.BOOTSTRAP)))}async getPeer(e){try{return await this.libp2p.peerStore.get(e)}catch(t){return El.error(`Failed to get peer ${e}, error: ${t}`),null}}async triggerBootstrap(){El.info("Triggering bootstrap discovery");const e=Object.values(this.libp2p.components.components).filter((e=>!!e)).filter((e=>["@waku/"+xs.BOOTSTRAP,"@waku/"+xs.PEER_CACHE].includes(e?.[Symbol.toStringTag])));if(0===e.length)return void El.warn("No bootstrap components found to trigger");El.info(`Found ${e.length} bootstrap components, starting them`);const t=e.map((async e=>{try{await(e?.stop?.()),await(e?.start?.()),El.info("Successfully started bootstrap component")}catch(e){El.error("Failed to start bootstrap component",e)}}));await Promise.all(t)}}const Al=new fs("dialer");class Il{libp2p;shardReader;options;dialingQueue=[];dialHistory=new Map;failedDials=new Map;dialingInterval=null;isProcessing=!1;isImmediateDialing=!1;constructor(e){this.libp2p=e.libp2p,this.shardReader=e.shardReader,this.options=e.options}start(){Al.info("Starting dialer"),this.dialingInterval||(this.dialingInterval=setInterval((()=>{this.processQueue()}),500)),this.dialHistory.clear(),this.failedDials.clear()}stop(){Al.info("Stopping dialer"),this.dialingInterval&&(clearInterval(this.dialingInterval),this.dialingInterval=null),this.dialHistory.clear(),this.failedDials.clear()}async dial(e){if(await this.shouldSkipPeer(e))return void Al.info("Skipping peer: "+e);const t=0===this.dialingQueue.length,r=!this.isProcessing&&!this.isImmediateDialing;t&&r?(this.isImmediateDialing=!0,Al.info("Dialed peer immediately"),await this.dialPeer(e),this.isImmediateDialing=!1,Al.info("Released immediate dial lock")):(this.dialingQueue.push(e),Al.info("Added peer to dialing queue, queue size: "+this.dialingQueue.length))}async processQueue(){if(0!==this.dialingQueue.length&&!this.isProcessing){this.isProcessing=!0;try{const e=this.dialingQueue.slice(0,this.options.maxDialingPeers);this.dialingQueue=this.dialingQueue.slice(e.length),Al.info(`Processing dial queue: dialing ${e.length} peers, ${this.dialingQueue.length} remaining in queue`),await Promise.all(e.map((e=>this.dialPeer(e))))}finally{this.isProcessing=!1}}}async dialPeer(e){try{Al.info("Dialing peer from queue: "+e),await this.libp2p.dial(e),this.dialHistory.set(e.toString(),Date.now()),this.failedDials.delete(e.toString()),Al.info("Successfully dialed peer from queue: "+e)}catch(t){Al.error("Error dialing peer "+e,t),this.failedDials.set(e.toString(),Date.now())}}async shouldSkipPeer(e){if(this.libp2p.getPeers().some((t=>t.equals(e))))return Al.info(`Skipping peer ${e} - already connected`),!0;if(this.isRecentlyDialed(e))return Al.info(`Skipping peer ${e} - already dialed in the last 10 seconds`),!0;if(this.isRecentlyFailed(e))return Al.info(`Skipping peer ${e} - recently failed to dial`),!0;try{return await this.shardReader.hasShardInfo(e)?!await this.shardReader.isPeerOnCluster(e)&&(Al.info(`Skipping peer ${e} - not on same cluster`),!0):(Al.info(`Skipping peer ${e} - no shard info`),!1)}catch(t){return Al.error("Error checking shard info for peer "+e,t),!0}}isRecentlyDialed(e){const t=this.dialHistory.get(e.toString());return!!(t&&Date.now()-t<1e3*this.options.dialCooldown)}isRecentlyFailed(e){const t=this.failedDials.get(e.toString());return!!(t&&Date.now()-t<1e3*this.options.failedDialCooldown)}}const _l=new fs("discovery-dialer");class Cl{libp2p;dialer;constructor(e){this.libp2p=e.libp2p,this.dialer=e.dialer,this.onPeerDiscovery=this.onPeerDiscovery.bind(this)}start(){this.libp2p.addEventListener("peer:discovery",this.onPeerDiscovery)}stop(){this.libp2p.removeEventListener("peer:discovery",this.onPeerDiscovery)}async onPeerDiscovery(e){const t=e.detail.id;_l.info("Discovered new peer: "+t);try{await this.updatePeerStore(t,e.detail.multiaddrs),await this.dialer.dial(t)}catch(e){_l.error("Error dialing peer "+t,e)}}async updatePeerStore(e,t){try{_l.info("Updating peer store for "+e);const r=await this.getPeer(e);if(!r)return _l.info(`Peer ${e} not found in store, saving`),void await this.libp2p.peerStore.save(e,{multiaddrs:t});if(t.every((e=>r.addresses.some((t=>t.multiaddr.equals(e))))))return void _l.info(`Peer ${e} has same addresses in peer store, skipping`);_l.info(`Merging peer ${e} addresses in peer store`),await this.libp2p.peerStore.merge(e,{multiaddrs:t})}catch(t){_l.error("Error updating peer store for "+e,t)}}async getPeer(e){try{return await this.libp2p.peerStore.get(e)}catch(t){return void _l.error("Error getting peer info for "+e,t)}}}const xl="/relay-ping/1/ping/null",kl=new fs("keep-alive");class Tl{relay;networkConfig;libp2p;options;pingKeepAliveTimers=new Map;relayKeepAliveTimers=new Map;constructor({options:e,relay:t,networkConfig:r,libp2p:n}){this.options=e,this.relay=t,this.networkConfig=r,this.libp2p=n,this.onPeerConnect=this.onPeerConnect.bind(this),this.onPeerDisconnect=this.onPeerDisconnect.bind(this)}start(){this.libp2p.addEventListener("peer:connect",this.onPeerConnect),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnect)}stop(){this.libp2p.removeEventListener("peer:connect",this.onPeerConnect),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnect);for(const e of this.pingKeepAliveTimers.values())clearInterval(e);for(const e of this.relayKeepAliveTimers.values())for(const t of e)clearInterval(t);this.pingKeepAliveTimers.clear(),this.relayKeepAliveTimers.clear()}onPeerConnect(e){const t=e.detail;this.startPingForPeer(t)}onPeerDisconnect(e){const t=e.detail;this.stopPingForPeer(t)}startPingForPeer(e){this.stopPingForPeer(e),this.startLibp2pPing(e),this.startRelayPing(e)}stopPingForPeer(e){this.stopLibp2pPing(e),this.stopRelayPing(e)}startLibp2pPing(e){if(0===this.options.pingKeepAlive)return void kl.warn(`Ping keep alive is disabled pingKeepAlive:${this.options.pingKeepAlive}, skipping start for libp2p ping`);const t=e.toString();if(this.pingKeepAliveTimers.has(t))return void kl.warn(`Ping already started for peer: ${t}, skipping start for libp2p ping`);const r=setInterval((()=>{this.pingLibp2p(e)}),1e3*this.options.pingKeepAlive);this.pingKeepAliveTimers.set(t,r)}stopLibp2pPing(e){const t=e.toString();this.pingKeepAliveTimers.has(t)?(clearInterval(this.pingKeepAliveTimers.get(t)),this.pingKeepAliveTimers.delete(t)):kl.warn(`Ping not started for peer: ${t}, skipping stop for ping`)}startRelayPing(e){if(!this.relay)return;if(0===this.options.relayKeepAlive)return void kl.warn(`Relay keep alive is disabled relayKeepAlive:${this.options.relayKeepAlive}, skipping start for relay ping`);if(this.relayKeepAliveTimers.has(e.toString()))return void kl.warn(`Relay ping already started for peer: ${e.toString()}, skipping start for relay ping`);const t=[];for(const r of this.relay.pubsubTopics){if(!this.relay.getMeshPeers(r).includes(e.toString())){kl.warn(`Peer: ${e.toString()} is not in the mesh for topic: ${r}, skipping start for relay ping`);continue}const n=vs({routingInfo:gn(this.networkConfig,{contentTopic:xl,pubsubTopic:r}),contentTopic:xl,ephemeral:!0}),s=setInterval((()=>{this.pingRelay(n)}),1e3*this.options.relayKeepAlive);t.push(s)}this.relayKeepAliveTimers.set(e.toString(),t)}stopRelayPing(e){if(!this.relay)return;const t=e.toString();this.relayKeepAliveTimers.has(t)?(this.relayKeepAliveTimers.get(t)?.map(clearInterval),this.relayKeepAliveTimers.delete(t)):kl.warn(`Relay ping not started for peer: ${t}, skipping stop for relay ping`)}async pingRelay(e){try{kl.info("Sending Waku Relay ping message"),await this.relay.send(e,{payload:new Uint8Array([1])})}catch(e){kl.error("Failed to send relay ping",e)}}async pingLibp2p(e){try{kl.info(`Pinging libp2p peer (${e.toString()})`);const t=await this.libp2p.services.ping.ping(e);kl.info(`Ping succeeded (${e.toString()})`,t),await this.libp2p.peerStore.merge(e,{metadata:{ping:an(t.toString())}}),kl.info(`Ping updated for peer (${e.toString()})`)}catch(t){kl.error(`Ping failed for peer (${e.toString()})`,t)}}}class Pl{libp2p;events;isNetworkConnected=!1;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.onConnectedEvent=this.onConnectedEvent.bind(this),this.onDisconnectedEvent=this.onDisconnectedEvent.bind(this),this.dispatchNetworkEvent=this.dispatchNetworkEvent.bind(this)}start(){this.libp2p.addEventListener("peer:connect",this.onConnectedEvent),this.libp2p.addEventListener("peer:disconnect",this.onDisconnectedEvent);try{globalThis.addEventListener("online",this.dispatchNetworkEvent),globalThis.addEventListener("offline",this.dispatchNetworkEvent)}catch(e){}}stop(){this.libp2p.removeEventListener("peer:connect",this.onConnectedEvent),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnectedEvent);try{globalThis.removeEventListener("online",this.dispatchNetworkEvent),globalThis.removeEventListener("offline",this.dispatchNetworkEvent)}catch(e){}}isConnected(){return!!this.isBrowserConnected()&&this.isP2PConnected()}isP2PConnected(){return this.isNetworkConnected}isBrowserConnected(){try{if(globalThis?.navigator&&!globalThis?.navigator?.onLine)return!1}catch(e){}return!0}onConnectedEvent(){this.isNetworkConnected||(this.isNetworkConnected=!0,this.dispatchNetworkEvent())}onDisconnectedEvent(){this.isNetworkConnected&&0===this.libp2p.getConnections().length&&(this.isNetworkConnected=!1,this.dispatchNetworkEvent())}dispatchNetworkEvent(){this.events.dispatchEvent(new CustomEvent(Cs.Connection,{detail:this.isConnected()}))}}const Rl=new fs("shard-reader");class Ll{libp2p;clusterId;constructor(e){this.libp2p=e.libp2p,this.clusterId=e.networkConfig.clusterId}async isPeerOnCluster(e){const t=await this.getRelayShards(e);return!!t&&t.clusterId===this.clusterId}async hasShardInfo(e){return!!await this.getRelayShards(e)}async isPeerOnTopic(e,t){try{const{clusterId:r,shard:n}=un(t);return r===this.clusterId&&await this.isPeerOnShard(e,n)}catch(r){return Rl.error(`Error comparing pubsub topic ${t} with shard info for ${e}`,r),!1}}async isPeerOnShard(e,t){const r=await this.getRelayShards(e);return Rl.info(`Checking if peer on same shard: this { clusterId: ${this.clusterId}, shardId: ${t} },${e} { clusterId: ${r?.clusterId}, shards: ${r?.shards} }`),!!r&&r.clusterId===this.clusterId&&r.shards.includes(t)}async getRelayShards(e){try{const t=(await this.libp2p.peerStore.get(e)).metadata.get("shardInfo");if(!t)return;return mn(t)}catch(t){return void Rl.error("Error getting shard info for "+e,t)}}}const Dl=new fs("connection-manager");class Ml{keepAliveManager;discoveryDialer;dialer;shardReader;networkMonitor;connectionLimiter;options;libp2p;constructor(e){this.libp2p=e.libp2p,this.options={maxBootstrapPeers:3,maxConnections:10,pingKeepAlive:300,relayKeepAlive:300,enableAutoRecovery:!0,maxDialingPeers:3,failedDialCooldown:60,dialCooldown:10,...e.config},this.keepAliveManager=new Tl({relay:e.relay,libp2p:e.libp2p,networkConfig:e.networkConfig,options:{pingKeepAlive:this.options.pingKeepAlive,relayKeepAlive:this.options.relayKeepAlive}}),this.shardReader=new Ll({libp2p:e.libp2p,networkConfig:e.networkConfig}),this.dialer=new Il({libp2p:e.libp2p,shardReader:this.shardReader,options:this.options}),this.discoveryDialer=new Cl({libp2p:e.libp2p,dialer:this.dialer}),this.networkMonitor=new Pl({libp2p:e.libp2p,events:e.events}),this.connectionLimiter=new Sl({libp2p:e.libp2p,events:e.events,networkMonitor:this.networkMonitor,dialer:this.dialer,options:this.options})}start(){this.dialer.start(),this.networkMonitor.start(),this.discoveryDialer.start(),this.keepAliveManager.start(),this.connectionLimiter.start()}stop(){this.dialer.stop(),this.networkMonitor.stop(),this.discoveryDialer.stop(),this.keepAliveManager.stop(),this.connectionLimiter.stop()}isConnected(){return this.networkMonitor.isConnected()}async dial(e,t){const r=Sn(n=e)?n:bl(n);var n;Dl.info(`Dialing peer ${r.toString()} with protocols ${t}`);const s=await this.libp2p.dialProtocol(r,t);return Dl.info(`Dialed peer ${r.toString()} with protocols ${t}`),s}async hangUp(e){const t=Sn(r=e)?r:Pc(bl(r).getPeerId());var r;try{return Dl.info("Dropping connection with peer "+t.toString()),await this.libp2p.hangUp(t),Dl.info("Dropped connection with peer "+t.toString()),!0}catch(e){return Dl.error(`Error dropping connection with peer ${t.toString()} - ${e}`),!1}}async getConnectedPeers(e){const t=this.libp2p.getPeers();if(Dl.info("Getting connected peers for codec "+e),0===t.length)return Dl.info("No connected peers"),[];const r=(await Promise.all(t.map((async e=>{try{return await this.libp2p.peerStore.get(e)}catch(e){return null}})))).filter((e=>!!e)).filter((t=>!e||t.protocols.includes(e))).sort(((e,t)=>vl(e)-vl(t)));return Dl.info(`Found ${r.length} connected peers for codec ${e}`),r}async hasShardInfo(e){return this.shardReader.hasShardInfo(e)}async isPeerOnTopic(e,t){return this.shardReader.isPeerOnTopic(e,t)}async isPeerOnShard(e,t){return this.shardReader.isPeerOnShard(e,t)}}const Nl=new fs("metadata"),Ol="/vac/waku/metadata/1.0.0";class Ul{clusterId;streamManager;libp2pComponents;handshakesConfirmed=new Map;multicodec=Ol;constructor(e,t){this.clusterId=e,this.streamManager=new di(Ol,t),this.libp2pComponents=t,t.registrar.handle(Ol,(e=>{this.onRequest(e)}))}async query(e){const t=zt.encode({clusterId:this.clusterId,shards:[]});if(!await this.libp2pComponents.peerStore.get(e))return{shardInfo:null,error:_s.NO_PEER_AVAILABLE};const r=await this.streamManager.getStream(e);if(!r)return Nl.error("Failed to get a stream for remote peer:"+e.toString()),{shardInfo:null,error:_s.NO_STREAM_AVAILABLE};const n=await si([t],$s,r,Gs,(async e=>await Rs(e))),{error:s,shardInfo:i}=this.decodeMetadataResponse(n);return s?{shardInfo:null,error:s}:(await this.savePeerShardInfo(e,i),{shardInfo:i,error:null})}async confirmOrAttemptHandshake(e){const t=this.handshakesConfirmed.get(e.toString());return t?{shardInfo:t,error:null}:await this.query(e)}async onRequest(e){try{const{stream:t,connection:r}=e,n=jt.encode({clusterId:this.clusterId,shards:[]}),s=await si([n],$s,t,Gs,(async e=>await Rs(e))),{error:i,shardInfo:o}=this.decodeMetadataResponse(s);if(i)return;await this.savePeerShardInfo(r.remotePeer,o)}catch(e){Nl.error("Error handling metadata request",e)}}decodeMetadataResponse(e){const t=new Us;e.forEach((e=>{t.append(e)}));const r=jt.decode(t);return r?{shardInfo:r,error:null}:(Nl.error("Error decoding metadata response"),{shardInfo:null,error:_s.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:yn(t)}}),this.handshakesConfirmed.set(e.toString(),t)}}function Fl(e){return t=>new Ul(e,t)}const Bl=new fs("peer-manager");var $l;(e=>{e.FilterConnect="filter:connect",e.FilterDisconnect="filter:disconnect",e.StoreConnect="store:connect"})($l||($l={}));class ql{events=new Jn;numPeersToUse;libp2p;connectionManager;lockedPeers=new Set;unlockedPeers=new Map;constructor(e){this.onConnected=this.onConnected.bind(this),this.onDisconnected=this.onDisconnected.bind(this),this.numPeersToUse=e?.config?.numPeersToUse||2,this.libp2p=e.libp2p,this.connectionManager=e.connectionManager}start(){this.libp2p.addEventListener("peer:identify",this.onConnected),this.libp2p.addEventListener("peer:disconnect",this.onDisconnected)}stop(){this.libp2p.removeEventListener("peer:identify",this.onConnected),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnected)}async getPeers(e){Bl.info(`Getting peers for protocol: ${e.protocol}, pubsubTopic: ${e.pubsubTopic}`);const t=await this.connectionManager.getConnectedPeers();Bl.info(`Found ${t.length} connected peers`);let r=[];for(const n of t){const t=this.hasPeerProtocol(n,e.protocol),s=await this.isPeerOnPubsub(n.id,e.pubsubTopic),i=this.isPeerAvailableForUse(n.id);t&&s&&i&&(r.push(n),Bl.info(`Peer ${n.id} qualifies for protocol ${e.protocol}`))}const n=r.filter((e=>this.isPeerLocked(e.id)));if(Bl.info(`Found ${n.length} locked peers out of ${r.length} qualifying peers`),n.length>=this.numPeersToUse){const e=n.slice(0,this.numPeersToUse).map((e=>e.id));return Bl.info(`Using ${e.length} locked peers: ${e.map((e=>e.toString()))}`),e}const s=r.filter((e=>!this.isPeerLocked(e.id)));Bl.info(`Found ${s.length} unlocked peers, need ${this.numPeersToUse-n.length} more`),r=[...n,...s].slice(0,this.numPeersToUse).map((e=>(this.lockPeer(e.id),e)));const i=r.map((e=>e.id));return Bl.info(`Selected ${i.length} peers: ${i.map((e=>e.toString()))}`),i}async renewPeer(e,t){Bl.info(`Renewing peer ${e} for protocol: ${t.protocol}, pubsubTopic: ${t.pubsubTopic}`);const r=(await this.connectionManager.getConnectedPeers()).find((t=>t.id.equals(e)));r?(Bl.info(`Found peer ${e} in connected peers, unlocking and getting new peers`),this.unlockPeer(r.id),await this.getPeers(t)):Bl.warn(`Cannot renew peer:${e}, no connection to the peer.`)}async isPeerOnPubsub(e,t){return!await this.connectionManager.hasShardInfo(e)||this.connectionManager.isPeerOnTopic(e,t)}async onConnected(e){const t=e.detail,r=t.protocols.includes(this.getProtocolCodecs(Ss.Filter)),n=t.protocols.includes(this.getProtocolCodecs(Ss.Store));r&&this.dispatchFilterPeerConnect(t.peerId),n&&this.dispatchStorePeerConnect(t.peerId)}async onDisconnected(e){const t=e.detail;try{const e=await this.libp2p.peerStore.get(t);this.hasPeerProtocol(e,Ss.Filter)&&this.dispatchFilterPeerDisconnect(e.id)}catch(e){Bl.error("Failed to dispatch Filter disconnect event:"+e)}}hasPeerProtocol(e,t){return e.protocols.includes(this.getProtocolCodecs(t))}lockPeer(e){Bl.info("Locking peer "+e),this.lockedPeers.add(e.toString()),this.libp2p.getConnections().filter((t=>t.remotePeer.equals(e))).forEach((e=>e.tags.push(ks))),this.unlockedPeers.delete(e.toString())}isPeerLocked(e){return this.lockedPeers.has(e.toString())}unlockPeer(e){Bl.info("Unlocking peer "+e),this.lockedPeers.delete(e.toString()),this.libp2p.getConnections().filter((t=>t.remotePeer.equals(e))).forEach((e=>{e.tags=e.tags.filter((e=>e!==ks))})),this.unlockedPeers.set(e.toString(),Date.now())}isPeerAvailableForUse(e){const t=this.unlockedPeers.get(e.toString());if(!t)return!0;const r=new Date(t).getTime();return Date.now()-r>=1e4}dispatchFilterPeerConnect(e){this.events.dispatchEvent(new CustomEvent($l.FilterConnect,{detail:e}))}dispatchStorePeerConnect(e){this.events.dispatchEvent(new CustomEvent($l.StoreConnect,{detail:e}))}dispatchFilterPeerDisconnect(e){this.events.dispatchEvent(new CustomEvent($l.FilterDisconnect,{detail:e}))}getProtocolCodecs(e){if(e===Ss.Relay)throw Error("Relay protocol is not supported");return{[Ss.Filter]:Ai,[Ss.LightPush]:Ti,[Ss.Store]:zi,"light-push-v2":ki}[e]}}class zl{ttlMs;cleanupIntervalId=null;entryTimestamps=new Map;constructor(e,t=5e3){this.ttlMs=e,this.startCleanupInterval(t)}dispose(){null!==this.cleanupIntervalId&&(clearInterval(this.cleanupIntervalId),this.cleanupIntervalId=null),this.entryTimestamps.clear()}add(e){return this.entryTimestamps.set(e,Date.now()),this}has(e){return this.entryTimestamps.has(e)}startCleanupInterval(e){this.cleanupIntervalId=setInterval((()=>{this.removeExpiredEntries()}),e)}removeExpiredEntries(){const e=Date.now();for(const[t,r]of this.entryTimestamps.entries())e-r>this.ttlMs&&this.entryTimestamps.delete(t)}}const jl=new fs("sdk:filter-subscription");class Kl{pubsubTopic;protocol;peerManager;config;isStarted=!1;inProgress=!1;peers=new Map;peerFailures=new Map;receivedMessages=new zl(6e4);callbacks=new Map;messageEmitter=new Jn;toSubscribeContentTopics=new Set;toUnsubscribeContentTopics=new Set;subscribeIntervalId=null;keepAliveIntervalId=null;get contentTopics(){const e=Array.from(this.callbacks.keys()).map((e=>e.contentTopic)),t=new Set(e).values();return Array.from(t)}constructor(e){this.config=e.config,this.pubsubTopic=e.pubsubTopic,this.protocol=e.protocol,this.peerManager=e.peerManager,this.onPeerConnected=this.onPeerConnected.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this)}start(){jl.info("Starting subscription for pubsubTopic: "+this.pubsubTopic),this.isStarted||this.inProgress?jl.info("Subscription already started or in progress, skipping start"):(this.inProgress=!0,this.attemptSubscribe({useNewContentTopics:!1}),this.setupSubscriptionInterval(),this.setupKeepAliveInterval(),this.setupEventListeners(),this.isStarted=!0,this.inProgress=!1,jl.info("Subscription started for pubsubTopic: "+this.pubsubTopic))}stop(){jl.info("Stopping subscription for pubsubTopic: "+this.pubsubTopic),this.isStarted&&!this.inProgress?(this.inProgress=!0,this.disposeEventListeners(),this.disposeIntervals(),this.disposePeers(),this.disposeHandlers(),this.receivedMessages.dispose(),this.inProgress=!1,this.isStarted=!1,jl.info("Subscription stopped for pubsubTopic: "+this.pubsubTopic)):jl.info("Subscription not started or stop in progress, skipping stop")}isEmpty(){return 0===this.callbacks.size}async add(e,t){const r=Array.isArray(e)?e:[e];for(const e of r)this.addSingle(e,t);return!(this.toSubscribeContentTopics.size>0)||await this.attemptSubscribe({useNewContentTopics:!0})}async remove(e){const t=Array.isArray(e)?e:[e];for(const e of t)this.removeSingle(e);return!(this.toUnsubscribeContentTopics.size>0)||await this.attemptUnsubscribe({useNewContentTopics:!0})}invoke(e,t){this.isMessageReceived(e)?jl.info(`Skipping invoking callbacks for already received message: pubsubTopic:${this.pubsubTopic}, peerId:${t.toString()}, contentTopic:${e.contentTopic}`):(jl.info("Invoking message for contentTopic: "+e.contentTopic),this.messageEmitter.dispatchEvent(new CustomEvent(e.contentTopic,{detail:e})))}addSingle(e,t){jl.info("Adding subscription for contentTopic: "+e.contentTopic);const r=!this.contentTopics.includes(e.contentTopic);if(r&&this.toSubscribeContentTopics.add(e.contentTopic),this.callbacks.has(e)){jl.warn(`Replacing callback associated associated with decoder with pubsubTopic:${e.pubsubTopic} and contentTopic:${e.contentTopic}`);const t=this.callbacks.get(e);this.callbacks.delete(e),this.messageEmitter.removeEventListener(e.contentTopic,t)}const n=r=>{(async()=>{try{const n=await e.fromProtoObj(e.pubsubTopic,r.detail);t(n)}catch(e){jl.error("Error decoding message",e)}})()};this.callbacks.set(e,n),this.messageEmitter.addEventListener(e.contentTopic,n),jl.info(`Subscription added for contentTopic: ${e.contentTopic}, isNewContentTopic: ${r}`)}removeSingle(e){jl.info("Removing subscription for contentTopic: "+e.contentTopic);const t=this.callbacks.get(e);t||jl.warn(`No callback associated with decoder with pubsubTopic:${e.pubsubTopic} and contentTopic:${e.contentTopic}`),this.callbacks.delete(e),this.messageEmitter.removeEventListener(e.contentTopic,t);const r=!this.contentTopics.includes(e.contentTopic);r&&this.toUnsubscribeContentTopics.add(e.contentTopic),jl.info(`Subscription removed for contentTopic: ${e.contentTopic}, isCompletelyRemoved: ${r}`)}isMessageReceived(e){try{const t=function(e,t){const r=gs(e,t);return sn(r)}(this.pubsubTopic,e);if(this.receivedMessages.has(t))return!0;this.receivedMessages.add(t)}catch(e){}return!1}setupSubscriptionInterval(){jl.info("Setting up subscription interval with period 1000ms"),this.subscribeIntervalId=setInterval((()=>{(async()=>{this.toSubscribeContentTopics.size>0&&(jl.info(`Subscription interval: ${this.toSubscribeContentTopics.size} topics to subscribe`),await this.attemptSubscribe({useNewContentTopics:!0})),this.toUnsubscribeContentTopics.size>0&&(jl.info(`Subscription interval: ${this.toUnsubscribeContentTopics.size} topics to unsubscribe`),await this.attemptUnsubscribe({useNewContentTopics:!0}))})()}),1e3)}setupKeepAliveInterval(){jl.info(`Setting up keep-alive interval with period ${this.config.keepAliveIntervalMs}ms`),this.keepAliveIntervalId=setInterval((()=>{(async()=>{jl.info(`Keep-alive interval running for ${this.peers.size} peers`);let e=await Promise.all(Array.from(this.peers.values()).map((async e=>{if((await this.protocol.ping(e)).success)return jl.info("Ping successful for peer: "+e.toString()),void this.peerFailures.set(e.toString(),0);let t=this.peerFailures.get(e.toString())||0;return t+=1,this.peerFailures.set(e.toString(),t),jl.warn(`Ping failed for peer: ${e.toString()}, failures: ${t}/${this.config.pingsBeforePeerRenewed}`),t<this.config.pingsBeforePeerRenewed?void 0:(jl.info(`Peer ${e.toString()} exceeded max failures (${this.config.pingsBeforePeerRenewed}), will be replaced`),e)})));e=e.filter((e=>!!e)),await Promise.all(e.map((e=>(this.peers.delete(e?.toString()),this.peerFailures.delete(e?.toString()),this.requestUnsubscribe(e,this.contentTopics))))),e.length>0&&(jl.info(`Replacing ${e.length} failed peers`),await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0}))})()}),this.config.keepAliveIntervalMs)}setupEventListeners(){this.peerManager.events.addEventListener($l.FilterConnect,this.onPeerConnected),this.peerManager.events.addEventListener($l.FilterDisconnect,this.onPeerDisconnected)}disposeIntervals(){this.subscribeIntervalId&&clearInterval(this.subscribeIntervalId),this.keepAliveIntervalId&&clearInterval(this.keepAliveIntervalId)}disposeHandlers(){for(const[e,t]of this.callbacks.entries())this.messageEmitter.removeEventListener(e.contentTopic,t);this.callbacks.clear()}async disposePeers(){await this.attemptUnsubscribe({useNewContentTopics:!1}),this.peers.clear(),this.peerFailures=new Map}disposeEventListeners(){this.peerManager.events.removeEventListener($l.FilterConnect,this.onPeerConnected),this.peerManager.events.removeEventListener($l.FilterDisconnect,this.onPeerDisconnected)}async onPeerConnected(e){const t=e.detail?.toString();jl.info("Peer connected: "+t),await this.peerManager.isPeerOnPubsub(e.detail,this.pubsubTopic)?this.peers.has(t)?jl.info(`Peer ${t} already subscribed, skipping`):await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0}):jl.info(`Peer ${t} doesn't support pubsubTopic:${this.pubsubTopic}`)}async onPeerDisconnected(e){const t=e.detail?.toString();jl.info("Peer disconnected: "+t),await this.peerManager.isPeerOnPubsub(e.detail,this.pubsubTopic)?this.peers.has(t)?(jl.info(`Active peer ${t} disconnected, removing from peers list`),this.peers.delete(t),this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0})):jl.info(`Disconnected peer ${t} not in use, ignoring`):jl.info(`Peer ${t} doesn't support pubsubTopic:${this.pubsubTopic}`)}async attemptSubscribe(e){const{useNewContentTopics:t,useOnlyNewPeers:r=!1}=e,n=t?Array.from(this.toSubscribeContentTopics):this.contentTopics;if(jl.info(`Attempting to subscribe: useNewContentTopics=${t}, useOnlyNewPeers=${r}, contentTopics=${n.length}`),!n.length)return jl.warn("Requested content topics is an empty array, skipping"),!1;const s=new Set(this.peers.keys()),i=await this.peerManager.getPeers({protocol:Ss.Filter,pubsubTopic:this.pubsubTopic});for(const e of i){if(this.peers.size>=this.config.numPeersToUse)break;this.peers.set(e.toString(),e)}const o=r?Array.from(this.peers.values()).filter((e=>!s.has(e.toString()))):Array.from(this.peers.values());if(jl.info(`Subscribing with ${o.length} peers for ${n.length} content topics`),r&&0===o.length)return jl.warn("Requested to use only new peers, but no peers found, skipping"),!1;const a=await Promise.all(o.map((e=>this.requestSubscribe(e,n)))),c=a.filter((e=>e)).length;return jl.info(`Subscribe attempts completed: ${c}/${a.length} successful`),t&&(this.toSubscribeContentTopics=new Set),a.some((e=>e))}async requestSubscribe(e,t){if(jl.info(`requestSubscribe: pubsubTopic:${this.pubsubTopic}\tcontentTopics:${t.join(",")}`),!t.length||!this.pubsubTopic)return jl.warn("requestSubscribe: no contentTopics or pubsubTopic provided, not sending subscribe request"),!1;const r=await this.protocol.subscribe(this.pubsubTopic,e,t);return r.failure?(jl.warn(`requestSubscribe: Failed to subscribe ${this.pubsubTopic} to ${e.toString()} with error:${r.failure.error} for contentTopics:${t}`),!1):(jl.info(`requestSubscribe: Subscribed ${this.pubsubTopic} to ${e.toString()} for contentTopics:${t}`),!0)}async attemptUnsubscribe(e){const{useNewContentTopics:t}=e,r=t?Array.from(this.toUnsubscribeContentTopics):this.contentTopics;if(jl.info(`Attempting to unsubscribe: useNewContentTopics=${t}, contentTopics=${r.length}`),!r.length)return jl.warn("Requested content topics is an empty array, skipping"),!1;const n=Array.from(this.peers.values()),s=await Promise.all(n.map((e=>this.requestUnsubscribe(e,t?r:void 0)))),i=s.filter((e=>e)).length;return jl.info(`Unsubscribe attempts completed: ${i}/${s.length} successful`),t&&(this.toUnsubscribeContentTopics=new Set),s.some((e=>e))}async requestUnsubscribe(e,t){const r=t?await this.protocol.unsubscribe(this.pubsubTopic,e,t):await this.protocol.unsubscribeAll(this.pubsubTopic,e);return r.failure?(jl.warn(`requestUnsubscribe: Failed to unsubscribe for pubsubTopic:${this.pubsubTopic} from peerId:${e.toString()} with error:${r.failure?.error} for contentTopics:${t}`),!1):(jl.info(`requestUnsubscribe: Unsubscribed pubsubTopic:${this.pubsubTopic} from peerId:${e.toString()} for contentTopics:${t}`),!0)}}const Vl=new fs("sdk:filter");class Hl{protocol;peerManager;config;subscriptions=new Map;constructor(e){this.config={numPeersToUse:2,pingsBeforePeerRenewed:3,keepAliveIntervalMs:6e4,...e.options},this.peerManager=e.peerManager,this.protocol=new _i(this.onIncomingMessage.bind(this),e.libp2p)}get multicodec(){return this.protocol.multicodec}async start(){await this.protocol.start()}async stop(){await this.protocol.stop()}unsubscribeAll(){for(const e of this.subscriptions.values())e.stop();this.subscriptions.clear()}async subscribe(e,t){const r=Array.isArray(e)?e:[e];if(0===r.length)throw Error("Cannot subscribe with 0 decoders.");const n=r.map((e=>e.pubsubTopic)),s=n[0],i=r.map((e=>e.contentTopic));Vl.info(`Subscribing to contentTopics: ${i}, pubsubTopic: ${s}`),this.throwIfTopicNotSame(n);let o=this.subscriptions.get(s);o||(o=new Kl({pubsubTopic:s,protocol:this.protocol,config:this.config,peerManager:this.peerManager}),o.start());const a=await o.add(r,t);return this.subscriptions.set(s,o),Vl.info(`Subscription ${a?"successful":"failed"} for content topic: ${i}`),a}async unsubscribe(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw Error("Cannot unsubscribe with 0 decoders.");const r=t.map((e=>e.pubsubTopic)),n=r[0],s=t.map((e=>e.contentTopic));Vl.info(`Unsubscribing from contentTopics: ${s}, pubsubTopic: ${n}`),this.throwIfTopicNotSame(r);const i=this.subscriptions.get(n);if(!i)return Vl.warn("No subscriptions associated with the decoder."),!1;const o=await i.remove(t);return i.isEmpty()&&(Vl.warn("Subscription has no decoders anymore, terminating it."),i.stop(),this.subscriptions.delete(n)),Vl.info(`Unsubscribing ${o?"successful":"failed"} for content topic: ${s}`),o}async onIncomingMessage(e,t,r){Vl.info(`Received message for pubsubTopic:${e}, contentTopic:${t.contentTopic}, peerId:${r.toString()}`);const n=this.subscriptions.get(e);n?n.invoke(t,r):Vl.error("No subscription locally registered for topic "+e)}throwIfTopicNotSame(e){const t=e[0];if(!e.every((e=>e===t)))throw Error("Cannot subscribe to more than one pubsub topic at the same time, got pubsubTopics:"+e)}}var Gl,Wl,Xl=function(){if(Wl)return Gl;Wl=1;var e=/^\s+|\s+$/g,t=/^[-+]0x[0-9a-f]+$/i,r=/^0b[01]+$/i,n=/^0o[0-7]+$/i,s=parseInt,i="object"==typeof ns&&ns&&ns.Object===Object&&ns,o="object"==typeof self&&self&&self.Object===Object&&self,a=i||o||Function("return this")(),c=Object.prototype.toString,l=Math.max,u=Math.min,h=()=>a.Date.now();function d(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function p(i){if("number"==typeof i)return i;if(function(e){return"symbol"==typeof e||(e=>!!e&&"object"==typeof e)(e)&&"[object Symbol]"==c.call(e)}(i))return NaN;if(d(i)){var o="function"==typeof i.valueOf?i.valueOf():i;i=d(o)?o+"":o}if("string"!=typeof i)return 0===i?i:+i;i=i.replace(e,"");var a=r.test(i);return a||n.test(i)?s(i.slice(2),a?2:8):t.test(i)?NaN:+i}return Gl=function(e,t,r){var n,s,i,o,a,c,f=0,g=!1,m=!1,y=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function b(t){var r=n,i=s;return n=s=void 0,f=t,o=e.apply(i,r)}function w(e){var r=e-c;return void 0===c||r>=t||r<0||m&&e-f>=i}function v(){var e=h();if(w(e))return E(e);a=setTimeout(v,function(e){var r=t-(e-c);return m?u(r,i-(e-f)):r}(e))}function E(e){return a=void 0,y&&n?b(e):(n=s=void 0,o)}function S(){var e=h(),r=w(e);if(n=arguments,s=this,c=e,r){if(void 0===a)return function(e){return f=e,a=setTimeout(v,t),g?b(e):o}(c);if(m)return a=setTimeout(v,t),b(c)}return void 0===a&&(a=setTimeout(v,t)),o}return t=p(t)||0,d(r)&&(g=!!r.leading,i=(m="maxWait"in r)?l(p(r.maxWait)||0,t):i,y="trailing"in r?!!r.trailing:y),S.cancel=function(){void 0!==a&&clearTimeout(a),f=0,n=c=s=a=void 0},S.flush=function(){return void 0===a?o:E(h())},S},Gl}(),Zl=ss(Xl);const Yl=new fs("health-indicator");class Ql{isStarted=!1;libp2p;events;value=Ps.Unhealthy;debouncedAssessHealth;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.onPeerIdentify=this.onPeerIdentify.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this),this.debouncedAssessHealth=Zl((()=>{this.assessHealth()}),100)}start(){this.isStarted||(this.isStarted=!0,Yl.info("start: adding listeners to libp2p"),this.libp2p.addEventListener("peer:identify",this.onPeerIdentify),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnected),this.debouncedAssessHealth())}stop(){this.isStarted&&(this.isStarted=!1,Yl.info("stop: removing listeners to libp2p"),this.libp2p.removeEventListener("peer:identify",this.onPeerIdentify),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnected),this.debouncedAssessHealth.cancel())}toValue(){return this.value}onPeerDisconnected(e){Yl.info("onPeerDisconnected: received libp2p event"),this.debouncedAssessHealth()}onPeerIdentify(e){Yl.info("onPeerIdentify: received libp2p event"),this.debouncedAssessHealth()}async assessHealth(){const e=this.libp2p.getConnections();if(0===e.length)return Yl.info("assessHealth: no connections, setting to Unhealthy"),void this.updateAndDispatchHealthEvent(Ps.Unhealthy);const t=await Promise.all(e.map((async e=>{try{return await this.libp2p.peerStore.get(e.remotePeer)}catch(t){return Yl.warn(`assessHealth: failed to get peer ${e.remotePeer}, skipping`),null}}))),r=t.filter((e=>e?.protocols.includes(Ai))).length,n=t.filter((e=>e?.protocols.includes(Ti))).length;let s;0===r||0===n?s=Ps.Unhealthy:r>=2&&n>=2?s=Ps.SufficientlyHealthy:1===r&&1===n?s=Ps.MinimallyHealthy:(Yl.error(`assessHealth: unexpected state, cannot identify health status of the node: Filter:${r}; LightPush:${n}`),s=this.value),Yl.info(`assessHealth: node identified as ${s} Filter:${r}; LightPush:${n}`),this.updateAndDispatchHealthEvent(s)}updateAndDispatchHealthEvent(e){this.value!==e&&(this.value=e,this.events.dispatchEvent(new CustomEvent(Cs.Health,{detail:this.value})))}}const Jl=e=>new Promise(((t,r)=>setTimeout((()=>r(Error("Task timeout"))),e))),eu=new fs("sdk:retry-manager");class tu{intervalID=null;retryIntervalMs;inProgress=0;queue=[];peerManager;constructor(e){this.peerManager=e.peerManager,this.retryIntervalMs=e.retryIntervalMs||1e3}start(){this.intervalID=setInterval((()=>{this.processQueue()}),this.retryIntervalMs)}stop(){this.intervalID&&(clearInterval(this.intervalID),this.intervalID=null)}push(e,t,r){this.queue.push({maxAttempts:t,callback:e,routingInfo:r})}processQueue(){if(0!==this.queue.length)for(;this.queue.length&&this.inProgress<5;){const e=this.queue.shift();e&&this.scheduleTask(e)}}scheduleTask(e){setTimeout((async()=>this.taskExecutor(e)),100)}async taskExecutor(e){if(e.maxAttempts<=0)return void eu.warn("scheduleTask: max attempts has reached, removing from queue");const t=(await this.peerManager.getPeers({protocol:Ss.LightPush,pubsubTopic:e.routingInfo.pubsubTopic}))[0];if(!t)return eu.warn("scheduleTask: no peers, putting back to queue"),void this.queue.push({...e,maxAttempts:e.maxAttempts-1});try{this.inProgress+=1;const r=await Promise.race([Jl(1e4),e.callback(t)]);if(void 0===r)throw Error("Task timeout");if(r.failure)throw Error(r.failure.error);if(eu.info("scheduleTask: executed successfully"),0===e.maxAttempts)return void eu.warn("scheduleTask: discarded a task due to limit of max attempts");this.queue.push({...e,maxAttempts:e.maxAttempts-1})}catch(n){const s=n;if(eu.error("scheduleTask: task execution failed with error:",s),((r=s.message)===As.REMOTE_PEER_REJECTED||r===As.NO_RESPONSE||r===As.RLN_PROOF_GENERATION||r===As.NO_PEER_AVAILABLE)&&await this.peerManager.renewPeer(t,{protocol:Ss.LightPush,pubsubTopic:e.routingInfo.pubsubTopic}),0===e.maxAttempts)return void eu.warn("scheduleTask: discarded a task due to limit of max attempts");this.queue.push({...e,maxAttempts:e.maxAttempts-1})}finally{this.inProgress-=1}var r}}const ru=new fs("sdk:light-push"),nu={autoRetry:!0,retryIntervalMs:1e3,maxAttempts:3,numPeersToUse:1};class su{config;retryManager;peerManager;protocol;constructor(e){this.config={...nu,...e.options||{}},this.peerManager=e.peerManager,this.protocol=new Ni(e.libp2p),this.retryManager=new tu({peerManager:e.peerManager,retryIntervalMs:this.config.retryIntervalMs})}get multicodec(){return this.protocol.multicodec}start(){this.retryManager.start()}stop(){this.retryManager.stop()}async send(e,t,r={}){r={useLegacy:!1,...this.config,...r};const{pubsubTopic:n}=e;ru.info("send: attempting to send a message to pubsubTopic:",n);const s=await this.peerManager.getPeers({protocol:r.useLegacy?"light-push-v2":Ss.LightPush,pubsubTopic:e.pubsubTopic}),i=s?.length>0?await Promise.all(s.map((n=>this.protocol.send(e,t,n,r.useLegacy).catch((()=>({success:null,failure:{error:As.GENERIC_FAIL}})))))):[],o=i.length?{successes:i.filter((e=>e.success)).map((e=>e.success)),failures:i.filter((e=>e.failure)).map((e=>e.failure))}:{successes:[],failures:[{error:As.NO_PEER_AVAILABLE}]};if(r.autoRetry&&0===o.successes.length){const n=n=>this.protocol.send(e,t,n,r.useLegacy);this.retryManager.push(n.bind(this),r.maxAttempts||3,e.routingInfo)}return o}}const iu=new fs("store-sdk");class ou{options;libp2p;peerManager;protocol;constructor(e){this.options=e.options||{},this.peerManager=e.peerManager,this.libp2p=e.libp2p,this.protocol=new ji(e.libp2p)}get multicodec(){return this.protocol.multicodec}async*queryGenerator(e,t){const{decodersAsMap:r,queryOptions:n}=this.buildQueryParams(e,t);for(const e of n){const n=t?.peerId??await this.getPeerToUse(e.pubsubTopic);if(!n)throw iu.error("No peers available to query"),Error("No peers available to query");iu.info("Querying store with options: "+JSON.stringify(e));const s=this.protocol.queryPerPage(e,r,n);for await(const e of s)yield e}}async queryWithOrderedCallback(e,t,r){iu.info("Querying store with ordered callback");for await(const n of this.queryGenerator(e,r))if(await this.processMessages(n,t))break}async queryWithPromiseCallback(e,t,r){iu.info("Querying store with promise callback");let n=!1;for await(const s of this.queryGenerator(e,r)){const e=s.map((async e=>{n||(n=!!await t(e))}));if(await Promise.all(e),n)break}}async processMessages(e,t){let r=!1;const n=(await Promise.all(e)).filter(Yt);return await Promise.all(n.map((async e=>{e&&!r&&(r=!!await t(e))}))),r}createCursor(e){return gs(e.pubsubTopic,e)}validateDecodersAndPubsubTopic(e){if(0===e.length)throw iu.error("No decoders provided"),Error("No decoders provided");const t=Array.from(new Set(e.map((e=>e.pubsubTopic))));if(t.length>1)throw iu.error("API does not support querying multiple pubsub topics at once"),Error("API does not support querying multiple pubsub topics at once");const r=t[0],n=new Map;e.forEach((e=>{if(n.has(e.contentTopic))throw iu.error("API does not support different decoder per content topic"),Error("API does not support different decoder per content topic");n.set(e.contentTopic,e)}));const s=e.filter((e=>e.pubsubTopic===r)).map((e=>e.contentTopic));if(0===s.length)throw iu.error("No decoders found for topic "+r),Error("No decoders found for topic "+r);return{pubsubTopic:r,contentTopics:s,decodersAsMap:n}}async getPeerToUse(e){const t=await this.peerManager.getPeers({protocol:Ss.Store,pubsubTopic:e});return this.options.peers?await this.getPeerFromConfigurationOrFirst(t,this.options.peers):t[0]}async getPeerFromConfigurationOrFirst(e,t){const r=t.map(bl),n=[];for(const t of r){const r=e.find((e=>e.toString()===t.getPeerId()?.toString()));if(r)return r;n.push(t)}for(;n.length;){const e=n.pop();if(!e)return;try{if(await this.libp2p.dial(e))return Pc(e.getPeerId())}catch(t){iu.warn(`Failed to dial peer from options.peers list for Store protocol. Peer:${e.getPeerId()}, error:${t}`)}}return iu.warn(`Passed node to use for Store not found: ${t.toString()}. Attempting to use first available peers.`),e[0]}buildQueryParams(e,t){let r,n,s;if(t?.messageHashes&&t.messageHashes.length>0)r=t.pubsubTopic||e[0]?.pubsubTopic||"",n=[],s=new Map,e.forEach((e=>{s.set(e.contentTopic,e)}));else{const t=this.validateDecodersAndPubsubTopic(e);r=t.pubsubTopic,n=t.contentTopics,s=t.decodersAsMap}const i=[];if(t?.timeStart&&t?.timeEnd){let e=t.timeStart;const r=t.timeEnd;for(;r.getTime()-e.getTime()>this.protocol.maxTimeLimit;){const t=new Date(e.getTime()+this.protocol.maxTimeLimit);i.push([e,t]),e=t}0===i.length&&(iu.info("Using single time range"),i.push([e,r]))}return 0===i.length?(iu.info("No sub time ranges"),{decodersAsMap:s,queryOptions:[{pubsubTopic:r,contentTopics:n,includeData:!0,paginationForward:!0,...t}]}):(iu.info(`Building ${i.length} sub time ranges`),{decodersAsMap:s,queryOptions:i.map((([e,s])=>({pubsubTopic:r,contentTopics:n,includeData:!0,paginationForward:!0,...t,timeStart:e,timeEnd:s})))})}}const au=new fs("wait-for-remote-peer");function cu(e,t){return e.map((e=>async function(e,t){au.info(`Waiting for ${e} peer.`),await new Promise((r=>{const n=async s=>{if(s.detail?.protocols?.includes(e)){const e=t.services.metadata;if(!e)return t.removeEventListener("peer:identify",n),void r();try{await e.confirmOrAttemptHandshake(s.detail.peerId),t.removeEventListener("peer:identify",n),r()}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&au.error("Connection closed. Some peers can be on different shard."),au.error("Error waiting for metadata: "+e)}}};t.addEventListener("peer:identify",n)}))}(e,t)))}async function lu(e,t){const r=[];if(e.relay&&t.includes(Ss.Relay)&&r.push(e.relay.waitForPeers()),e.store&&t.includes(Ss.Store)&&r.push(...cu([zi],e.libp2p)),e.lightPush&&t.includes(Ss.LightPush)){const t=cu([Ti,ki],e.libp2p);r.push(Promise.any(t))}return e.filter&&t.includes(Ss.Filter)&&r.push(...cu([Ai],e.libp2p)),Promise.all(r)}const uu=(e,t)=>new Promise(((r,n)=>setTimeout((()=>n(Error(t))),e))),hu=new fs("sdk:waku");class du{libp2p;relay;store;filter;lightPush;events=new Jn;networkConfig;_nodeStateLock=!1;_nodeStarted=!1;connectionManager;peerManager;healthIndicator;constructor(e,t,r,n){this.relay=n,this.libp2p=t,this.networkConfig=e.networkConfig||Ts,r={filter:!1,lightpush:!1,store:!1,...r};const s=this.libp2p.peerId.toString();this.connectionManager=new Ml({libp2p:t,relay:this.relay,events:this.events,networkConfig:this.networkConfig,config:e?.connectionManager}),this.peerManager=new ql({libp2p:t,config:{numPeersToUse:e.numPeersToUse},connectionManager:this.connectionManager}),this.healthIndicator=new Ql({libp2p:t,events:this.events}),r.store&&(this.store=new ou({libp2p:t,peerManager:this.peerManager,options:e?.store})),r.lightpush&&(this.lightPush=new su({libp2p:t,peerManager:this.peerManager,options:e?.lightPush})),r.filter&&(this.filter=new Hl({libp2p:t,peerManager:this.peerManager,options:e.filter})),hu.info("Waku node created",s,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}get peerId(){return this.libp2p.peerId}get protocols(){return this.libp2p.getProtocols()}get health(){return this.healthIndicator.toValue()}async dial(e,t){const r=t??[];void 0===t&&(this.relay&&r.push(Ss.Relay),this.store&&r.push(Ss.Store),this.filter&&r.push(Ss.Filter),this.lightPush&&r.push(Ss.LightPush));const n=[];return r.includes(Ss.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach((e=>n.push(e))):hu.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(Ss.Store)&&(this.store?n.push(this.store.multicodec):hu.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(Ss.LightPush)&&(this.lightPush?n.push(...this.lightPush.multicodec):hu.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(Ss.Filter)&&(this.filter?n.push(this.filter.multicodec):hu.error("Filter codec not included in dial codec: protocol not mounted locally")),hu.info(`Dialing to ${e?.toString()} with protocols ${r}`),await this.connectionManager.dial(e,n)}async hangUp(e){return hu.info(`Hanging up peer:${e?.toString()}.`),this.connectionManager.hangUp(e)}async start(){this._nodeStateLock||this.isStarted()||(this._nodeStateLock=!0,await this.libp2p.start(),await(this.filter?.start()),this.connectionManager.start(),this.peerManager.start(),this.healthIndicator.start(),this.lightPush?.start(),this._nodeStateLock=!1,this._nodeStarted=!0)}async stop(){!this._nodeStateLock&&this.isStarted()&&(this._nodeStateLock=!0,this.lightPush?.stop(),await(this.filter?.stop()),this.healthIndicator.stop(),this.peerManager.stop(),this.connectionManager.stop(),await this.libp2p.stop(),this._nodeStateLock=!1,this._nodeStarted=!1)}async getConnectedPeers(){return this.connectionManager.getConnectedPeers()}async waitForPeers(e,t){return async function(e,t,r){t=t?.length?t:function(e){const t=[];return e.relay&&t.push(Ss.Relay),e.filter&&t.push(Ss.Filter),e.store&&t.push(Ss.Store),e.lightPush&&t.push(Ss.LightPush),t}(e);const n=e.libp2p.getConnections();if(!e.isStarted())throw Error("Waku node is not started");for(const r of t)switch(r){case Ss.Relay:if(!e.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");break;case Ss.LightPush:if(!e.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");break;case Ss.Store:if(!e.store)throw Error("Cannot wait for Store peer: protocol not mounted");break;case Ss.Filter:if(!e.filter)throw Error("Cannot wait for Filter peer: protocol not mounted")}const s=[lu(e,t)];n.length>0&&!t.includes(Ss.Relay)&&s.push(async function(e,t){const r=e.libp2p.getPeers(),n=e.libp2p.services.metadata,s=function(e){const t=new Map,r={[Ss.Filter]:[Ai],[Ss.LightPush]:[Ti,ki],[Ss.Store]:[zi]};for(const n of e)r[n]&&r[n].forEach((e=>{t.set(e,!1)}));return t}(t);if(r.length&&n)for(const t of r)try{const r=await e.libp2p.peerStore.get(t);if(r.protocols.some((e=>s.has(e)))&&!(await n.confirmOrAttemptHandshake(t)).error&&(r.protocols.forEach((e=>{s.has(e)&&s.set(e,!0)})),Array.from(s.values()).every((e=>e))))return}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&au.error("Connection closed. Some peers can be on different shard."),au.error("Error while iterating through peers: "+e);continue}else au.info(`Skipping waitForMetadata due to missing connections:${r.length} or metadataService:${!!n}`)}(e,t)),r?await async function(e,t,r){await Promise.race([e,uu(t,"Timed out waiting for a remote peer.")])}(Promise.any(s),r):await Promise.any(s)}(this,e,t)}isStarted(){return this._nodeStarted&&"started"===this.libp2p.status}isConnected(){return this.connectionManager.isConnected()}createDecoder(e){const t=this.createRoutingInfo(e.contentTopic,e.shardId);return function(e,t){return new class{contentTopic;routingInfo;constructor(e,t){if(this.contentTopic=e,this.routingInfo=t,!e||""===e)throw Error("Content topic must be specified")}get pubsubTopic(){return this.routingInfo.pubsubTopic}fromWireToProtoObj(e){const t=ft.decode(e);return Promise.resolve({payload:t.payload,contentTopic:t.contentTopic,version:t.version??void 0,timestamp:t.timestamp??void 0,meta:t.meta??void 0,rateLimitProof:t.rateLimitProof??void 0,ephemeral:t.ephemeral??!1})}async fromProtoObj(e,t){return t.version?(ms.error("Failed to decode due to incorrect version, expected:",0,", actual:",t.version),Promise.resolve(void 0)):new bs(e,t)}}(e,t)}(e.contentTopic,t)}createEncoder(e){const t=this.createRoutingInfo(e.contentTopic,e.shardId);return vs({contentTopic:e.contentTopic,ephemeral:e.ephemeral,routingInfo:t})}createRoutingInfo(e,t){return gn(this.networkConfig,{contentTopic:e,shardId:t})}}const pu=4194304;let fu=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},gu=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},mu=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},yu=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function bu(e){return null!=e[Symbol.asyncIterator]}function wu(e,t){if(e.byteLength>t)throw new gu("Message length too long")}const vu=e=>{const t=f(e),r=a(t);return y(e,r),vu.bytes=t,r};function Eu(e,t){const r=(t=t??{}).lengthEncoder??vu,n=t?.maxDataLength??pu;function*s(e){wu(e,n);const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return bu(e)?async function*(){for await(const t of e)yield*s(t)}():function*(){for(const t of e)yield*s(t)}()}var Su;vu.bytes=0,Eu.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??vu;return wu(e,t?.maxDataLength??pu),new Us(r(e.byteLength),e)},(e=>{e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(Su||(Su={}));const Au=e=>{const t=b(e);return Au.bytes=f(t),t};function Iu(e,t){const r=new Us;let n=Su.LENGTH,s=-1;const i=t?.lengthDecoder??Au,o=t?.maxLengthLength??8,a=t?.maxDataLength??pu;function*c(){for(;r.byteLength>0;){if(n===Su.LENGTH)try{if(s=i(r),s<0)throw new fu("Invalid message length");if(s>a)throw new gu("Message length too long");const e=i.bytes;r.consume(e),null!=t?.onLength&&t.onLength(s),n=Su.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>o)throw new mu("Message length length too long");break}throw e}if(n===Su.DATA){if(r.byteLength<s)break;const e=r.sublist(0,s);r.consume(s),null!=t?.onData&&t.onData(e),yield e,n=Su.LENGTH}}}return bu(e)?async function*(){for await(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new yu("Unexpected end of input")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new yu("Unexpected end of input")}()}Au.bytes=0,Iu.fromReader=(e,t)=>{let r=1;return Iu(async function*(){for(;;)try{const{done:t,value:n}=await e.next(r);if(!0===t)return;null!=n&&(yield n)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{r=1}}(),{...t??{},onLength(e){r=e}})};class _u extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}function Cu(e,t){const r=ri();e.sink(r).catch((async e=>{await r.end(e)})),e.sink=async e=>{for await(const t of e)await r.push(t);await r.end()};let n=e.source;null!=e.source[Symbol.iterator]?n=e.source[Symbol.iterator]():null!=e.source[Symbol.asyncIterator]&&(n=e.source[Symbol.asyncIterator]());const s=new Us;return{async read(e){if(e?.signal?.throwIfAborted(),null==e?.bytes){const{done:t,value:r}=await ei(n.next(),e?.signal);return!0===t?null:r}for(;s.byteLength<e.bytes;){const{value:t,done:r}=await ei(n.next(),e?.signal);if(!0===r)throw new _u("unexpected end of input");s.append(t)}const t=s.sublist(0,e.bytes);return s.consume(e.bytes),t},async write(e,t){t?.signal?.throwIfAborted(),e instanceof Uint8Array?await r.push(e,t):await r.push(e.subarray(),t)},unwrap(){if(s.byteLength>0){const r=e.source;e.source=async function*(){!1===t?.yieldBytes?yield s:yield*s,yield*r}()}return e}}}class xu extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class ku extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class Tu extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function Pu(e,t={}){const r=Cu(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=f(t.maxDataLength));const n=t?.lengthDecoder??b,s=t?.lengthEncoder??y;return{async read(e){let s=-1;const i=new Us;for(;;){i.append(await r.read({...e,bytes:1}));try{s=n(i)}catch(e){if(e instanceof RangeError)continue;throw e}if(s<0)throw new xu("Invalid message length");if(null!=t?.maxLengthLength&&i.byteLength>t.maxLengthLength)throw new Tu("message length length too long");if(s>-1)break}if(null!=t?.maxDataLength&&s>t.maxDataLength)throw new ku("message length too long");return r.read({...e,bytes:s})},async write(e,t){await r.write(new Us(s(e.byteLength),e),t)},async writeV(e,t){const n=new Us(...e.flatMap((e=>[s(e.byteLength),e])));await r.write(n,t)},unwrap:()=>r.unwrap()}}function Ru(){const e=Ws();let t=!1;return{async sink(r){if(t)throw Error("already piped");t=!0,e.resolve(r)},source:async function*(){const t=await e.promise;yield*t}()}}const Lu=65535,Du=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function Mu(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Nu(e){if("boolean"!=typeof e)throw Error("boolean expected, not "+e)}function Ou(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function Uu(e,...t){if(!Mu(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function Fu(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Bu(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function $u(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const qu=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];function zu(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!Mu(e))throw Error("Uint8Array expected, got "+typeof e);e=Vu(e)}return e}function ju(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw Error("invalid output length, expected "+e+", got: "+t.length);if(r&&t.byteOffset%4!=0)throw Error("invalid output, must be aligned");return t}function Ku(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i);e.setUint32(t+4,o,n),e.setUint32(t+0,a,n)}function Vu(e){return Uint8Array.from(e)}const Hu=e=>Uint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),Gu=Hu("expand 16-byte k"),Wu=Hu("expand 32-byte k"),Xu=Bu(Gu),Zu=Bu(Wu);function Yu(e,t){return e<<t|e>>>32-t}function Qu(e){return e.byteOffset%4==0}const Ju=2**32-1,eh=new Uint32Array,th=(e,t)=>255&e[t++]|(255&e[t++])<<8;class rh{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,Uu(e=zu(e),32);const t=th(e,0),r=th(e,2),n=th(e,4),s=th(e,6),i=th(e,8),o=th(e,10),a=th(e,12),c=th(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|r<<3),this.r[2]=7939&(r>>>10|n<<6),this.r[3]=8191&(n>>>7|s<<9),this.r[4]=255&(s>>>4|i<<12),this.r[5]=i>>>1&8190,this.r[6]=8191&(i>>>14|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=th(e,16+2*t)}process(e,t,r=!1){const n=r?0:2048,{h:s,r:i}=this,o=i[0],a=i[1],c=i[2],l=i[3],u=i[4],h=i[5],d=i[6],p=i[7],f=i[8],g=i[9],m=th(e,t+0),y=th(e,t+2),b=th(e,t+4),w=th(e,t+6),v=th(e,t+8),E=th(e,t+10),S=th(e,t+12),A=th(e,t+14);let I=s[0]+(8191&m),_=s[1]+(8191&(m>>>13|y<<3)),C=s[2]+(8191&(y>>>10|b<<6)),x=s[3]+(8191&(b>>>7|w<<9)),k=s[4]+(8191&(w>>>4|v<<12)),T=s[5]+(v>>>1&8191),P=s[6]+(8191&(v>>>14|E<<2)),R=s[7]+(8191&(E>>>11|S<<5)),L=s[8]+(8191&(S>>>8|A<<8)),D=s[9]+(A>>>5|n),M=0,N=M+I*o+_*(5*g)+C*(5*f)+x*(5*p)+k*(5*d);M=N>>>13,N&=8191,N+=T*(5*h)+P*(5*u)+R*(5*l)+L*(5*c)+D*(5*a),M+=N>>>13,N&=8191;let O=M+I*a+_*o+C*(5*g)+x*(5*f)+k*(5*p);M=O>>>13,O&=8191,O+=T*(5*d)+P*(5*h)+R*(5*u)+L*(5*l)+D*(5*c),M+=O>>>13,O&=8191;let U=M+I*c+_*a+C*o+x*(5*g)+k*(5*f);M=U>>>13,U&=8191,U+=T*(5*p)+P*(5*d)+R*(5*h)+L*(5*u)+D*(5*l),M+=U>>>13,U&=8191;let F=M+I*l+_*c+C*a+x*o+k*(5*g);M=F>>>13,F&=8191,F+=T*(5*f)+P*(5*p)+R*(5*d)+L*(5*h)+D*(5*u),M+=F>>>13,F&=8191;let B=M+I*u+_*l+C*c+x*a+k*o;M=B>>>13,B&=8191,B+=T*(5*g)+P*(5*f)+R*(5*p)+L*(5*d)+D*(5*h),M+=B>>>13,B&=8191;let $=M+I*h+_*u+C*l+x*c+k*a;M=$>>>13,$&=8191,$+=T*o+P*(5*g)+R*(5*f)+L*(5*p)+D*(5*d),M+=$>>>13,$&=8191;let q=M+I*d+_*h+C*u+x*l+k*c;M=q>>>13,q&=8191,q+=T*a+P*o+R*(5*g)+L*(5*f)+D*(5*p),M+=q>>>13,q&=8191;let z=M+I*p+_*d+C*h+x*u+k*l;M=z>>>13,z&=8191,z+=T*c+P*a+R*o+L*(5*g)+D*(5*f),M+=z>>>13,z&=8191;let j=M+I*f+_*p+C*d+x*h+k*u;M=j>>>13,j&=8191,j+=T*l+P*c+R*a+L*o+D*(5*g),M+=j>>>13,j&=8191;let K=M+I*g+_*f+C*p+x*d+k*h;M=K>>>13,K&=8191,K+=T*u+P*l+R*c+L*a+D*o,M+=K>>>13,K&=8191,M=(M<<2)+M|0,M=M+N|0,N=8191&M,M>>>=13,O+=M,s[0]=N,s[1]=O,s[2]=U,s[3]=F,s[4]=B,s[5]=$,s[6]=q,s[7]=z,s[8]=j,s[9]=K}finalize(){const{h:e,pad:t}=this,r=new Uint16Array(10);let n=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=n,n=e[t]>>>13,e[t]&=8191;e[0]+=5*n,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+n,n=r[t]>>>13,r[t]&=8191;r[9]-=8192;let s=(1^n)-1;for(let e=0;e<10;e++)r[e]&=s;s=~s;for(let t=0;t<10;t++)e[t]=e[t]&s|r[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let i=e[0]+t[0];e[0]=65535&i;for(let r=1;r<8;r++)i=(e[r]+t[r]|0)+(i>>>16)|0,e[r]=65535&i;$u(r)}update(e){Fu(this),Uu(e=zu(e));const{buffer:t,blockLen:r}=this,n=e.length;for(let s=0;s<n;){const i=Math.min(r-this.pos,n-s);if(i!==r)t.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(t,0,!1),this.pos=0);else for(;r<=n-s;s+=r)this.process(e,s)}return this}destroy(){$u(this.h,this.r,this.buffer,this.pad)}digestInto(e){Fu(this),function(e,t){Uu(e);const r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,h:r}=this;let{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let t=0;t<8;t++)e[s++]=r[t]>>>0,e[s++]=r[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}}const nh=function(e){const t=(t,r)=>e(r).update(zu(t)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}((e=>new rh(e))),sh=function(e,t){const{allowShortKeys:r,extendNonceFn:n,counterLength:s,counterRight:i,rounds:o}=function(e,t){if(null==t||"object"!=typeof t)throw Error("options must be defined");return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t)}(0,{counterRight:!1,counterLength:4,allowShortKeys:!1});return Ou(s),Ou(o),Nu(i),Nu(r),(t,a,c,l,u=0)=>{Uu(t),Uu(a),Uu(c);const h=c.length;if(void 0===l&&(l=new Uint8Array(h)),Uu(l),Ou(u),u<0||u>=Ju)throw Error("arx: counter overflow");if(l.length<h)throw Error(`arx: output (${l.length}) is shorter than data (${h})`);const d=[];let p,f,g=t.length;if(32===g)d.push(p=Vu(t)),f=Zu;else{if(16!==g||!r)throw Error("arx: invalid 32-byte key, got length="+g);p=new Uint8Array(32),p.set(t),p.set(t,16),f=Xu,d.push(p)}Qu(a)||d.push(a=Vu(a));const m=Bu(p);if(n){if(24!==a.length)throw Error("arx: extended nonce must be 24 bytes");n(f,m,Bu(a.subarray(0,16)),m),a=a.subarray(16)}const y=16-s;if(y!==a.length)throw Error(`arx: nonce must be ${y} or 16 bytes`);if(12!==y){const e=new Uint8Array(12);e.set(a,i?0:12-a.length),a=e,d.push(a)}const b=Bu(a);return function(e,t,r,n,s,i,o,a){const c=s.length,l=new Uint8Array(64),u=Bu(l),h=Qu(s)&&Qu(i),d=h?Bu(s):eh,p=h?Bu(i):eh;for(let f=0;f<c;o++){if(e(t,r,n,u,o,a),o>=Ju)throw Error("arx: counter overflow");const g=Math.min(64,c-f);if(h&&64===g){const e=f/4;if(f%4!=0)throw Error("arx: invalid block position");for(let t,r=0;r<16;r++)t=e+r,p[t]=d[t]^u[r];f+=64}else{for(let e,t=0;t<g;t++)e=f+t,i[e]=s[e]^l[t];f+=g}}}(e,f,m,b,c,l,u,o),$u(...d),l}}((function(e,t,r,n,s,i=20){let o=e[0],a=e[1],c=e[2],l=e[3],u=t[0],h=t[1],d=t[2],p=t[3],f=t[4],g=t[5],m=t[6],y=t[7],b=s,w=r[0],v=r[1],E=r[2],S=o,A=a,I=c,_=l,C=u,x=h,k=d,T=p,P=f,R=g,L=m,D=y,M=b,N=w,O=v,U=E;for(let e=0;e<i;e+=2)S=S+C|0,M=Yu(M^S,16),P=P+M|0,C=Yu(C^P,12),S=S+C|0,M=Yu(M^S,8),P=P+M|0,C=Yu(C^P,7),A=A+x|0,N=Yu(N^A,16),R=R+N|0,x=Yu(x^R,12),A=A+x|0,N=Yu(N^A,8),R=R+N|0,x=Yu(x^R,7),I=I+k|0,O=Yu(O^I,16),L=L+O|0,k=Yu(k^L,12),I=I+k|0,O=Yu(O^I,8),L=L+O|0,k=Yu(k^L,7),_=_+T|0,U=Yu(U^_,16),D=D+U|0,T=Yu(T^D,12),_=_+T|0,U=Yu(U^_,8),D=D+U|0,T=Yu(T^D,7),S=S+x|0,U=Yu(U^S,16),L=L+U|0,x=Yu(x^L,12),S=S+x|0,U=Yu(U^S,8),L=L+U|0,x=Yu(x^L,7),A=A+k|0,M=Yu(M^A,16),D=D+M|0,k=Yu(k^D,12),A=A+k|0,M=Yu(M^A,8),D=D+M|0,k=Yu(k^D,7),I=I+T|0,N=Yu(N^I,16),P=P+N|0,T=Yu(T^P,12),I=I+T|0,N=Yu(N^I,8),P=P+N|0,T=Yu(T^P,7),_=_+C|0,O=Yu(O^_,16),R=R+O|0,C=Yu(C^R,12),_=_+C|0,O=Yu(O^_,8),R=R+O|0,C=Yu(C^R,7);let F=0;n[F++]=o+S|0,n[F++]=a+A|0,n[F++]=c+I|0,n[F++]=l+_|0,n[F++]=u+C|0,n[F++]=h+x|0,n[F++]=d+k|0,n[F++]=p+T|0,n[F++]=f+P|0,n[F++]=g+R|0,n[F++]=m+L|0,n[F++]=y+D|0,n[F++]=b+M|0,n[F++]=w+N|0,n[F++]=v+O|0,n[F++]=E+U|0})),ih=new Uint8Array(16),oh=(e,t)=>{e.update(t);const r=t.length%16;r&&e.update(ih.subarray(r))},ah=new Uint8Array(32);function ch(e,t,r,n,s){const i=e(t,r,ah),o=nh.create(i);s&&oh(o,s),oh(o,n);const a=function(e,t,r){Nu(r);const n=new Uint8Array(16),s=(i=n,new DataView(i.buffer,i.byteOffset,i.byteLength));var i;return Ku(s,0,BigInt(t),r),Ku(s,8,BigInt(e),r),n}(n.length,s?s.length:0,!0);o.update(a);const c=o.digest();return $u(i,a),c}const lh=((e,t)=>{function r(r,...n){if(Uu(r),!qu)throw Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){const t=n[0];if(!t)throw Error("nonce / iv required");e.varSizeNonce?Uu(t):Uu(t,e.nonceLength)}const s=e.tagLength;s&&void 0!==n[1]&&Uu(n[1]);const i=t(r,...n),o=(e,t)=>{if(void 0!==t){if(2!==e)throw Error("cipher output not supported");Uu(t)}};let a=!1;return{encrypt(e,t){if(a)throw Error("cannot encrypt() twice with same key + nonce");return a=!0,Uu(e),o(i.encrypt.length,t),i.encrypt(e,t)},decrypt(e,t){if(Uu(e),s&&e.length<s)throw Error("invalid ciphertext length: smaller than tagLength="+s);return o(i.decrypt.length,t),i.decrypt(e,t)}}}return Object.assign(r,e),r})({blockSize:64,nonceLength:12,tagLength:16},(uh=sh,(e,t,r)=>({encrypt(n,s){const i=n.length;(s=ju(i+16,s,!1)).set(n);const o=s.subarray(0,-16);uh(e,t,o,o,1);const a=ch(uh,e,t,o,r);return s.set(a,i),$u(a),s},decrypt(n,s){s=ju(n.length-16,s,!1);const i=n.subarray(0,-16),o=n.subarray(-16),a=ch(uh,e,t,i,r);if(!((e,t)=>{if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r})(o,a))throw Error("invalid tag");return s.set(n.subarray(0,-16)),uh(e,t,s,s,1),$u(a),s}})));var uh;const hh=Uint8Array.from([0]),dh=Uint8Array.of(),ph={hashSHA256:e=>en(e.subarray()),getHKDF(e,t){const r=function(e,t,r){return rr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),tc(e,br(r),br(t))}(en,t,e),n=function(e,t,r,n=32){rr(e),er(n);const s=e.outputLen;if(n>255*s)throw Error("Length should be <= 255*HashLen");const i=Math.ceil(n/s);void 0===r&&(r=dh);const o=new Uint8Array(i*s),a=tc.create(e,t),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let e=0;e<i;e++)hh[0]=e+1,c.update(0===e?dh:l).update(r).update(hh).digestInto(l),o.set(l,s*e),a._cloneInto(c);return a.destroy(),c.destroy(),sr(l,hh),o.slice(0,n)}(en,r,void 0,96),s=n;return[s.subarray(0,32),s.subarray(32,64),s.subarray(64,96)]},generateX25519KeyPair(){const e=Oa.utils.randomPrivateKey();return{publicKey:Oa.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:Oa.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>Oa.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>lh(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,s)=>lh(n,t,r).decrypt(e.subarray(),s)},fh=ph,gh=e=>{const t=a(2);return t[0]=e>>8,t[1]=e,t};gh.bytes=2;const mh=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};function yh(e,t){t.enabled&&Du&&(e?(t("LOCAL_STATIC_PUBLIC_KEY "+tn(e.publicKey,"hex")),t("LOCAL_STATIC_PRIVATE_KEY "+tn(e.privateKey,"hex"))):t("Missing local static keys."))}function bh(e,t){t.enabled&&Du&&(e?(t("LOCAL_PUBLIC_EPHEMERAL_KEY "+tn(e.publicKey,"hex")),t("LOCAL_PRIVATE_EPHEMERAL_KEY "+tn(e.privateKey,"hex"))):t("Missing local ephemeral keys."))}function wh(e,t){t.enabled&&Du&&t(e?"REMOTE_EPHEMERAL_PUBLIC_KEY "+tn(e.subarray(),"hex"):"Missing remote ephemeral keys.")}function vh(e,t,r){r.enabled&&Du&&(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&tn(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&tn(t.k,"hex")}`))}mh.bytes=2;class Eh extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=Eh.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}class Sh{n;bytes;view;constructor(e=0){this.n=e,this.bytes=o(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw Error("Cipherstate has reached maximum n, a new handshake must be performed")}}const Ah=o(0);class Ih{k;n;crypto;constructor(e,t,r=0){this.crypto=e,this.k=t,this.n=new Sh(r)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();const r=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,t,r){if(!this.hasKey())return t;this.n.assertValue();const n=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,r);return this.n.increment(),n}}class _h{cs;ck;h;crypto;constructor(e,t){this.crypto=e;const r=Ye(t,"utf-8");this.h=function(e,t){if(t.length<=32){const e=o(32);return e.set(t),e}return e.hash(t)}(e,r),this.ck=this.h,this.cs=new Ih(e)}mixKey(e){const[t,r]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new Ih(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new Us(this.h,e))}encryptAndHash(e){const t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){const t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){const[e,t]=this.crypto.hkdf(this.ck,Ah);return[new Ih(this.crypto,e),new Ih(this.crypto,t)]}}class Ch{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:t,protocolName:r,prologue:n,initiator:s,s:i,e:o,rs:a,re:c}=e;this.crypto=t,this.ss=new _h(t,r),this.ss.mixHash(n),this.initiator=s,this.s=i,this.e=o,this.rs=a,this.re=c}writeE(){if(this.e)throw Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw Error("ephemeral keypair is not set");if(!this.re)throw Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw Error("ephemeral keypair is not set");if(!this.rs)throw Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw Error("static keypair is not set");if(!this.re)throw Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw Error("static keypair is not set");if(!this.re)throw Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw Error("ephemeral keypair is not set");if(!this.rs)throw Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw Error("remote static public key is already set");const r=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+r)throw Error("message is not long enough");const n=e.sublist(t,t+r);return this.rs=this.ss.decryptAndHash(n),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class xh extends Ch{writeMessageA(e){return new Us(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const t=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new Us(t,r,this.ss.encryptAndHash(e))}writeMessageC(e){const t=this.writeS();return this.writeSE(),new Us(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new Eh("handshake stage 0 validation fail: "+e.message)}}readMessageB(e){try{this.readE(e),this.readEE();const t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(e){throw new Eh("handshake stage 1 validation fail: "+e.message)}}readMessageC(e){try{const t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(e){throw new Eh("handshake stage 2 validation fail: "+e.message)}}}var kh,Th;async function Ph(e,t,r){const n=await e.sign(Lh(t));return Th.encode({identityKey:Ac(e.publicKey),identitySig:n,extensions:r})}async function Rh(e,t,r){try{const n=Th.decode(e),s=Sc(n.identityKey);if(!1===r?.equals(s))throw Error(`Payload identity key ${s} does not match expected remote identity key ${r}`);if(!t)throw Error("Remote static does not exist");const i=Lh(t);if(!await s.verify(i,n.identitySig))throw Error("Invalid payload signature");return n}catch(e){throw new kn(e.message)}}function Lh(e){const t=Ye("noise-libp2p-static-key:");return e instanceof Uint8Array?Ls([t,e],t.length+e.length):(e.prepend(t),e)}(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(const r of e.webtransportCerthashes)t.uint32(10),t.bytes(r);if(null!=e.streamMuxers)for(const r of e.streamMuxers)t.uint32(18),t.string(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={webtransportCerthashes:[],streamMuxers:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:if(null!=r.limits?.webtransportCerthashes&&n.webtransportCerthashes.length===r.limits.webtransportCerthashes)throw new Xt('Decode error - map field "webtransportCerthashes" had too many elements');n.webtransportCerthashes.push(e.bytes());break;case 2:if(null!=r.limits?.streamMuxers&&n.streamMuxers.length===r.limits.streamMuxers)throw new Xt('Decode error - map field "streamMuxers" had too many elements');n.streamMuxers.push(e.string());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(kh||(kh={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.identityKey&&e.identityKey.byteLength>0&&(t.uint32(10),t.bytes(e.identityKey)),null!=e.identitySig&&e.identitySig.byteLength>0&&(t.uint32(18),t.bytes(e.identitySig)),null!=e.extensions&&(t.uint32(34),kh.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={identityKey:o(0),identitySig:o(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.identityKey=e.bytes();break;case 2:n.identitySig=e.bytes();break;case 4:n.extensions=kh.codec().decode(e,e.uint32(),{limits:r.limits?.extensions});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(Th||(Th={}));class Dh{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(e,t={}){const{staticNoiseKey:r,extensions:n,crypto:s,prologueBytes:i}=t,{metrics:a}=e;this.components=e;const c=s??fh;this.crypto=function(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}(c),this.extensions={webtransportCerthashes:[],...n},this.metrics=a?function(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(a):void 0,this.staticKey=r?c.generateX25519KeyPairFromSeed(r):c.generateX25519KeyPair(),this.prologue=i??o(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[ts]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){const r=Pu(e,{lengthEncoder:gh,lengthDecoder:mh,maxDataLength:Lu}),n=await this.performHandshakeInitiator(r,this.components.privateKey,t?.remotePeer?.publicKey,t),s=await this.createSecureConnection(r,n);e.source=s.source,e.sink=s.sink;const i=Sc(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:Rc(i),streamMuxer:!0===t?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(n.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(null==e||0===e.length)return;const t=this.components.upgrader.getStreamMuxers();if(null!=t)for(const r of e){const e=t.get(r);if(null!=e)return e}if(e.length)throw new Tn("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){const r=Pu(e,{lengthEncoder:gh,lengthDecoder:mh,maxDataLength:Lu}),n=await this.performHandshakeResponder(r,this.components.privateKey,t?.remotePeer?.publicKey,t),s=await this.createSecureConnection(r,n);e.source=s.source,e.sink=s.sink;const i=Sc(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:Rc(i),streamMuxer:!0===t?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(n.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,r,n){let s;const i=!0===n?.skipStreamMuxerNegotiation?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await async function(e,t){const{log:r,connection:n,crypto:s,privateKey:i,prologue:o,s:a,remoteIdentityKey:c,extensions:l}=e,u=await Ph(i,a.publicKey,l),h=new xh({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:o,s:a});yh(h.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(Ah),t),r.trace("Stage 0 - Initiator finished sending first message."),bh(h.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");const d=h.readMessageB(await n.read(t));var p,f;r.trace("Stage 1 - Initiator received the message."),wh(h.re,r),p=h.rs,(f=r).enabled&&Du&&f(p?"REMOTE_STATIC_PUBLIC_KEY "+tn(p.subarray(),"hex"):"Missing remote static public key."),r.trace("Initiator going to check remote's signature...");const g=await Rh(d,h.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(h.writeMessageC(u),t),r.trace("Stage 2 - Initiator sent message with signed payload.");const[m,y]=h.ss.split();return vh(m,y,r),{payload:g,encrypt:e=>m.encryptWithAd(Ah,e),decrypt:(e,t)=>y.decryptWithAd(Ah,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:i,webtransportCerthashes:[],...this.extensions}},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}async performHandshakeResponder(e,t,r,n){let s;const i=!0===n?.skipStreamMuxerNegotiation?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await async function(e,t){const{log:r,connection:n,crypto:s,privateKey:i,prologue:o,s:a,remoteIdentityKey:c,extensions:l}=e,u=await Ph(i,a.publicKey,l),h=new xh({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:o,s:a});yh(h.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),wh(h.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(h.writeMessageB(u),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),bh(h.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");const d=h.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");const p=await Rh(d,h.rs,c),[f,g]=h.ss.split();return vh(f,g,r),{payload:p,encrypt:e=>g.encryptWithAd(Ah,e),decrypt:(e,t)=>f.decryptWithAd(Ah,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:i,webtransportCerthashes:[],...this.extensions}},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}async createSecureConnection(e,t){const[r,n]=function(){const e=Ru(),t=Ru();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}(),s=e.unwrap();return await si(r,function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=65519){let s,i=r+65519;i>n.length&&(i=n.length),s=n instanceof Uint8Array?e.encrypt(n.subarray(r,i)):e.encrypt(n.sublist(r,i)),t?.encryptedPackets.increment(),yield new Us(gh(s.byteLength),s)}}}(t,this.metrics),s,(e=>Iu(e,{lengthDecoder:mh})),function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=Lu){let s=r+Lu;if(s>n.length&&(s=n.length),s-16<r)throw Error("Invalid chunk");const i=n.sublist(r,s),o=n.subarray(r,s-16);try{const r=e.decrypt(i,o);t?.decryptedPackets.increment(),yield r}catch(e){throw t?.decryptErrors.increment(),e}}}}(t,this.metrics),r),n}}function Mh(e={}){return t=>new Dh(t,e)}const Nh=dd("dns4"),Oh=dd("dns6"),Uh=dd("dnsaddr"),Fh=hd(dd("dns"),Uh,Nh,Oh),Bh=hd(dd("ip4"),dd("ip6")),$h=hd(ud(Bh,dd("tcp")),ud(Fh,dd("tcp"))),qh=ud(Bh,dd("udp")),zh=ud(qh,dd("utp")),jh=ud(qh,dd("quic")),Kh=ud(qh,dd("quic-v1")),Vh=hd(ud($h,dd("ws")),ud(Fh,dd("ws"))),Hh=hd(ud(Vh,dd("p2p")),Vh),Gh=hd(ud($h,dd("wss")),ud(Fh,dd("wss")),ud($h,dd("tls"),dd("ws")),ud(Fh,dd("tls"),dd("ws"))),Wh=hd(ud(Gh,dd("p2p")),Gh),Xh=hd(ud($h,dd("http")),ud(Bh,dd("http")),ud(Fh,dd("http"))),Zh=hd(ud($h,dd("https")),ud(Bh,dd("https")),ud(Fh,dd("https"))),Yh=ud(qh,dd("webrtc-direct"),dd("certhash")),Qh=hd(ud(Yh,dd("p2p")),Yh),Jh=ud(Kh,dd("webtransport"),dd("certhash"),dd("certhash")),ed=hd(ud(Jh,dd("p2p")),Jh),td=hd(ud(Hh,dd("p2p-webrtc-star"),dd("p2p")),ud(Wh,dd("p2p-webrtc-star"),dd("p2p")),ud(Hh,dd("p2p-webrtc-star")),ud(Wh,dd("p2p-webrtc-star")));hd(ud(Hh,dd("p2p-websocket-star"),dd("p2p")),ud(Wh,dd("p2p-websocket-star"),dd("p2p")),ud(Hh,dd("p2p-websocket-star")),ud(Wh,dd("p2p-websocket-star")));const rd=hd(ud(Xh,dd("p2p-webrtc-direct"),dd("p2p")),ud(Zh,dd("p2p-webrtc-direct"),dd("p2p")),ud(Xh,dd("p2p-webrtc-direct")),ud(Zh,dd("p2p-webrtc-direct"))),nd=hd(Vh,Gh,Xh,Zh,td,rd,$h,zh,jh,Fh,Qh,ed);hd(ud(nd,dd("p2p-stardust"),dd("p2p")),ud(nd,dd("p2p-stardust")));const sd=hd(ud(nd,dd("p2p")),td,rd,Qh,ed,dd("p2p")),id=hd(ud(sd,dd("p2p-circuit"),sd),ud(sd,dd("p2p-circuit")),ud(dd("p2p-circuit"),sd),ud(nd,dd("p2p-circuit")),ud(dd("p2p-circuit"),nd),dd("p2p-circuit")),od=()=>hd(ud(id,od),id),ad=od(),cd=hd(ud(ad,sd,ad),ud(sd,ad),ud(ad,sd),ad,sd);function ld(e){return function(t){let r;try{r=bl(t)}catch(e){return!1}const n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function ud(...e){function t(t){if(t.length<e.length)return null;let r=t;return e.some((e=>(r="function"==typeof e?e().partialMatch(t):e.partialMatch(t),Array.isArray(r)&&(t=r),null===r))),r}return{toString:()=>"{ "+e.join(" ")+" }",input:e,matches:ld(t),partialMatch:t}}function hd(...e){function t(t){let r=null;return e.some((e=>{const n="function"==typeof e?e().partialMatch(t):e.partialMatch(t);return null!=n&&(r=n,!0)})),r}return{toString:()=>"{ "+e.join(" ")+" }",input:e,matches:ld(t),partialMatch:t}}function dd(e){const t=e;return{toString:()=>t,matches(e){let r;try{r=bl(e)}catch(e){return!1}const n=r.protoNames();return 1===n.length&&n[0]===t},partialMatch:e=>0===e.length?null:e[0]===t?e.slice(1):null}}hd(ud(ad,dd("webrtc"),dd("p2p")),ud(ad,dd("webrtc")),ud(nd,dd("webrtc"),dd("p2p")),ud(nd,dd("webrtc")),dd("webrtc"));class pd extends Jn{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(null==t.list||0===t.list.length)throw Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??1e3,this.list=[];for(const e of t.list){if(!cd.matches(e)){this.log.error("Invalid multiaddr");continue}const t=bl(e),r=t.getPeerId();if(null==r){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const n={id:Pc(r),multiaddrs:[t]};this.list.push(n)}this._init=t}[vn]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[ts]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout((()=>{this._discoverBootstrapPeers().catch((e=>{this.log.error(e)}))}),this.timeout))}async _discoverBootstrapPeers(){if(null!=this.timer)for(const e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??"bootstrap"]:{value:this._init.tagValue??50,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),null==this.timer)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch((t=>{this.log.error("could not dial bootstrap peer %p",e.id,t)}))}}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}var fd;(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(26),t.bytes(e.payload)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={publicKey:o(0),payloadType:o(0),payload:o(0),signature:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.publicKey=e.bytes();break;case 2:r.payloadType=e.bytes();break;case 3:r.payload=e.bytes();break;case 5:r.signature=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(fd||(fd={}));class gd extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}}class md{static createFromProtobuf=e=>{const t=fd.decode(e),r=Sc(t.publicKey);return new md({publicKey:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,r)=>{if(null==t)throw Error("Missing private key");const n=e.domain,s=e.codec,i=e.marshal(),o=yd(n,s,i),a=await t.sign(o.subarray(),r);return new md({publicKey:t.publicKey,payloadType:s,payload:i,signature:a})};static openAndCertify=async(e,t,r)=>{const n=md.createFromProtobuf(e);if(!await n.validate(t,r))throw new gd("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){const{publicKey:t,payloadType:r,payload:n,signature:s}=e;this.publicKey=t,this.payloadType=r,this.payload=n,this.signature=s}marshal(){return null==this.marshaled&&(this.marshaled=fd.encode({publicKey:Ac(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return null!=e&&Ds(this.marshal(),e.marshal())}async validate(e,t){const r=yd(e,this.payloadType,this.payload);return this.publicKey.verify(r.subarray(),this.signature,t)}}const yd=(e,t,r)=>{const n=Ye(e),s=y(n.byteLength),i=y(t.length),o=y(r.length);return new Us(s,n,i,t,o,r)},bd=Uint8Array.from([3,1]);var wd;(e=>{let t;(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={multiaddr:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();t>>>3==1?r.multiaddr=e.bytes():e.skipType(7&t)}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==t&&(t=Wt(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.peerId&&t.peerId.byteLength>0&&(r.uint32(10),r.bytes(t.peerId)),null!=t.seq&&0n!==t.seq&&(r.uint32(16),r.uint64(t.seq)),null!=t.addresses)for(const n of t.addresses)r.uint32(26),e.AddressInfo.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={peerId:o(0),seq:0n,addresses:[]},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:s.peerId=t.bytes();break;case 2:s.seq=t.uint64();break;case 3:if(null!=n.limits?.addresses&&s.addresses.length===n.limits.addresses)throw new Xt('Decode error - map field "addresses" had too many elements');s.addresses.push(e.AddressInfo.codec().decode(t,t.uint32(),{limits:n.limits?.addresses$}));break;default:t.skipType(7&r)}}return s}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(wd||(wd={}));class vd{static createFromProtobuf=e=>{const t=wd.decode(e),r=Lc(Le(t.peerId)),n=(t.addresses??[]).map((e=>bl(e.multiaddr))),s=t.seq;return new vd({peerId:r,multiaddrs:n,seqNumber:s})};static DOMAIN="libp2p-peer-record";static CODEC=bd;peerId;multiaddrs;seqNumber;domain=vd.DOMAIN;codec=vd.CODEC;marshaled;constructor(e){const{peerId:t,multiaddrs:r,seqNumber:n}=e;this.peerId=t,this.multiaddrs=r??[],this.seqNumber=n??BigInt(Date.now())}marshal(){return null==this.marshaled&&(this.marshaled=wd.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map((e=>({multiaddr:e.bytes})))})),this.marshaled}equals(e){return e instanceof vd&&!!this.peerId.equals(e.peerId)&&this.seqNumber===e.seqNumber&&!!function(e,t){const r=(e,t)=>e.toString().localeCompare(t.toString());return e.length===t.length&&(t.sort(r),e.sort(r).every(((e,r)=>t[r].equals(e))))}(this.multiaddrs,e.multiaddrs)}}function Ed(e,t){let r;const n=()=>{clearTimeout(r),r=setTimeout((()=>{r=void 0,e()}),t)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}function Sd(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);}const Ad=globalThis.CustomEvent??Event;function Id(e,t){const r=Pu(e,t),n={async read(e,t){const n=await r.read(t);return e.decode(n)},async write(e,t,n){await r.write(t.encode(e),n)},async writeV(e,t,n){await r.writeV(e.map((e=>t.encode(e))),n)},pb:e=>({read:async t=>n.read(e,t),write:async(t,r)=>n.write(t,e,r),writeV:async(t,r)=>n.writeV(t,e,r),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var _d;(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.protocolVersion&&(t.uint32(42),t.string(e.protocolVersion)),null!=e.agentVersion&&(t.uint32(50),t.string(e.agentVersion)),null!=e.publicKey&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.listenAddrs)for(const r of e.listenAddrs)t.uint32(18),t.bytes(r);if(null!=e.observedAddr&&(t.uint32(34),t.bytes(e.observedAddr)),null!=e.protocols)for(const r of e.protocols)t.uint32(26),t.string(r);null!=e.signedPeerRecord&&(t.uint32(66),t.bytes(e.signedPeerRecord)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={listenAddrs:[],protocols:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 5:n.protocolVersion=e.string();break;case 6:n.agentVersion=e.string();break;case 1:n.publicKey=e.bytes();break;case 2:if(null!=r.limits?.listenAddrs&&n.listenAddrs.length===r.limits.listenAddrs)throw new Xt('Decode error - map field "listenAddrs" had too many elements');n.listenAddrs.push(e.bytes());break;case 4:n.observedAddr=e.bytes();break;case 3:if(null!=r.limits?.protocols&&n.protocols.length===r.limits.protocols)throw new Xt('Decode error - map field "protocols" had too many elements');n.protocols.push(e.string());break;case 8:n.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(_d||(_d={}));const Cd="ipfs";class xd{host;protocol;started;timeout;peerId;privateKey;peerStore;registrar;addressManager;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;events;runOnLimitedConnection;log;constructor(e,t){var r,n;this.protocol=t.protocol,this.started=!1,this.peerId=e.peerId,this.privateKey=e.privateKey,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.events=e.events,this.log=t.log,this.timeout=t.timeout??5e3,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.maxMessageSize=t.maxMessageSize??8192,this.maxObservedAddresses=t.maxObservedAddresses??10,this.runOnLimitedConnection=t.runOnLimitedConnection??true,this.host={protocolVersion:(t.protocolPrefix??Cd)+"/0.1.0",agentVersion:(r=e.nodeInfo,n=t.agentVersion,null!=n?n:r.userAgent)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:Ye(this.host.agentVersion),ProtocolVersion:Ye(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,(e=>{this.handleProtocol(e).catch((e=>{this.log.error(e)}))}),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}}var kd,Td={},Pd=(kd||(kd=1,function(){var e,t,r,n,s,i,o,a;a=e=>[(-16777216&e)>>>24,(16711680&e)>>>16,(65280&e)>>>8,255&e].join("."),o=e=>{var r,n,s,i,o,a;for(r=[],s=i=0;i<=3&&0!==e.length;s=++i){if(s>0){if("."!==e[0])throw Error("Invalid IP");e=e.substring(1)}o=(a=t(e))[0],n=a[1],e=e.substring(n),r.push(o)}if(0!==e.length)throw Error("Invalid IP");switch(r.length){case 1:if(r[0]>4294967295)throw Error("Invalid IP");return r[0]>>>0;case 2:if(r[0]>255||r[1]>16777215)throw Error("Invalid IP");return(r[0]<<24|r[1])>>>0;case 3:if(r[0]>255||r[1]>255||r[2]>65535)throw Error("Invalid IP");return(r[0]<<24|r[1]<<16|r[2])>>>0;case 4:if(r[0]>255||r[1]>255||r[2]>255||r[3]>255)throw Error("Invalid IP");return(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0;default:throw Error("Invalid IP")}},n=(r=e=>e.charCodeAt(0))("0"),i=r("a"),s=r("A"),t=e=>{var t,o,a,c,l;for(c=0,t=10,o="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,o="7")),l=a;a<e.length;){if("0"<=e[a]&&e[a]<=o)c=c*t+(r(e[a])-n)>>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")c=c*t+(10+r(e[a])-i)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+r(e[a])-s)>>>0}}if(c>4294967295)throw Error("too large");a++}if(a===l)throw Error("empty octet");return[c,a]},e=function(){function e(e,t){var r,n,s;if("string"!=typeof e)throw Error("Missing `net' parameter");if(t||(s=e.split("/",2),e=s[0],t=s[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=o(t)}catch(e){throw Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else{if(!t&&0!==t)throw Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(o(e)&this.maskLong)>>>0}catch(t){throw Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"==typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(o(t)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(a(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=o(this.first),r=o(this.last),t=0;n<=r;)e(a(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),Td.ip2long=o,Td.long2ip=a,Td.Netmask=e}()),Td);const Rd=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"].map((e=>new Pd.Netmask(e)));function Ld(e){for(const t of Rd)if(t.contains(e))return!0;return!1}function Dd(e){return zc(e)?Ld(e):/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(e)?function(e){const t=e.split(":");if(t.length<2)return!1;const r=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0");return Ld(`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(r.substring(0,2),16)}.${parseInt(r.substring(2),16)}`)}(e):function(e){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)}(e)?function(e){const t=e.split(":");return Ld(t[t.length-1])}(e):jc(e)?function(e){return/^::$/.test(e)||/^::1$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e)}(e):void 0}function Md(e){try{for(const{code:t}of e.getComponents())if(t!==Vc)return 4===t||t===Kc}catch{}return!1}function Nd(e){try{if(!Md(e))return!1;const[[,t]]=e.stringTuples();return null!=t&&(Dd(t)??!1)}catch{}return!0}const Od=e=>({match:t=>!(t.length<1)&&!!e(t[0])&&t.slice(1),pattern:"fn"}),Ud=e=>({match:t=>Od((t=>t===e)).match(t),pattern:e}),Fd=()=>({match:e=>Od((e=>"string"==typeof e)).match(e),pattern:"{string}"}),Bd=()=>({match:e=>Od((e=>!isNaN(parseInt(e)))).match(e),pattern:"{number}"}),$d=()=>({match(e){if(e.length<2)return!1;if("p2p"!==e[0]&&"ipfs"!==e[0])return!1;if(!e[1].startsWith("Q")&&!e[1].startsWith("1"))return!1;try{fe.decode("z"+e[1])}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),qd=()=>({match(e){if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{we.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),zd=e=>({match(t){const r=e.match(t);return!1===r?t:r},pattern:`optional(${e.pattern})`}),jd=(...e)=>({match(t){let r;for(const n of e){const e=n.match(t);!1!==e&&(null==r||e.length<r.length)&&(r=e)}return null!=r&&r},pattern:`or(${e.map((e=>e.pattern)).join(", ")})`}),Kd=(...e)=>({match(t){for(const r of e){const e=r.match(t);if(!1===e)return!1;t=e}return t},pattern:`and(${e.map((e=>e.pattern)).join(", ")})`});function Vd(...e){function t(t){let r=(e=>e.toString().split("/").slice(1))(t);for(const t of e){const e=t.match(r);if(!1===e)return!1;r=e}return r}return{matchers:e,matches:e=>!1!==t(e),exactMatch(e){const r=t(e);return!1!==r&&0===r.length}}}const Hd=Vd($d()),Gd=Kd(Ud("dns4"),Fd()),Wd=Kd(Ud("dns6"),Fd()),Xd=Kd(Ud("dnsaddr"),Fd()),Zd=Kd(Ud("dns"),Fd());Vd(Gd,zd($d())),Vd(Wd,zd($d())),Vd(Xd,zd($d())),Vd(jd(Zd,Xd,Gd,Wd),zd($d()));const Yd=Kd(Ud("ip4"),Od(zc)),Qd=Kd(Ud("ip6"),Od(jc)),Jd=jd(Yd,Qd),ep=jd(Jd,Zd,Gd,Wd,Xd),tp=Vd(jd(Jd,Kd(jd(Zd,Xd,Gd,Wd),zd($d())))),rp=Vd(Yd),np=Vd(Qd);Vd(Jd);const sp=Kd(ep,Ud("tcp"),Bd()),ip=Kd(ep,Ud("udp"),Bd()),op=Vd(Kd(sp,zd($d())));Vd(ip);const ap=Kd(ip,Ud("quic"),zd($d())),cp=Kd(ip,Ud("quic-v1"),zd($d())),lp=jd(ap,cp);Vd(ap);const up=Vd(cp),hp=jd(ep,sp,ip,ap,cp),dp=jd(Kd(hp,Ud("ws"),zd($d()))),pp=Vd(dp),fp=jd(Kd(hp,Ud("wss"),zd($d())),Kd(hp,Ud("tls"),zd(Kd(Ud("sni"),Fd())),Ud("ws"),zd($d()))),gp=Vd(fp),mp=Kd(ip,Ud("webrtc-direct"),zd(qd()),zd(qd()),zd($d())),yp=Vd(mp),bp=Kd(cp,Ud("webtransport"),zd(qd()),zd(qd()),zd($d())),wp=Vd(bp),vp=jd(dp,fp,Kd(sp,zd($d())),Kd(lp,zd($d())),Kd(ep,zd($d())),mp,bp,$d());Vd(vp);const Ep=Vd(Kd(vp,Ud("p2p-circuit"),$d())),Sp=Vd(jd(Kd(vp,Ud("p2p-circuit"),Ud("webrtc"),zd($d())),Kd(vp,Ud("webrtc"),zd($d())),Kd(Ud("webrtc"),zd($d()))));Vd(jd(Kd(ep,Ud("tcp"),Bd(),Ud("http"),zd($d())),Kd(ep,Ud("http"),zd($d())))),Vd(jd(Kd(ep,Ud("tcp"),jd(Kd(Ud("443"),Ud("http")),Kd(Bd(),Ud("https")),Kd(Bd(),Ud("tls"),Ud("http"))),zd($d())),Kd(ep,Ud("tls"),Ud("http"),zd($d())),Kd(ep,Ud("https"),zd($d())))),Vd(jd(Kd(Ud("memory"),Fd(),zd($d()))));class Ap extends xd{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??Cd}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??true)&&e.events.addEventListener("connection:open",(e=>{const t=e.detail;this.identify(t).catch((e=>{e.name!==jn.name&&this.log.error("error during identify trigged by connection:open",e)}))}))}[ts]=["@libp2p/identify"];async _identify(e,t={}){let r;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{r=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});const n=Id(r,{maxDataLength:this.maxMessageSize}).pb(_d),s=await n.read(t);return await r.close(t),s}catch(e){throw r?.abort(e),e}}async identify(e,t={}){const r=await this._identify(e,t),{publicKey:n,protocols:s,observedAddr:i}=r;if(null==n)throw new Kn("public key was missing from identify message");const o=Dc(Sc(n).toCID());if(!e.remotePeer.equals(o))throw new Kn("identified peer does not match the expected peer");if(this.peerId.equals(o))throw new Kn("identified peer is our own peer id?");return this.maybeAddObservedAddress(i),this.log("identify completed for peer %p and protocols %o",o,s),async function(e,t,r,n,s){if(r("received identify from %p",n.remotePeer),null==s)throw new Kn("message was null or undefined");const i={};if(s.listenAddrs.length>0&&(i.addresses=s.listenAddrs.map((e=>({isCertified:!1,multiaddr:bl(e)})))),s.protocols.length>0&&(i.protocols=s.protocols),null!=s.publicKey){const e=Sc(s.publicKey);if(!Rc(e).equals(n.remotePeer))throw new Kn("public key did not match remote PeerId");i.publicKey=e}let o;if(null!=s.signedPeerRecord){r.trace("received signedPeerRecord from %p",n.remotePeer);let t=s.signedPeerRecord;const a=await md.openAndCertify(t,vd.DOMAIN);let c=vd.createFromProtobuf(a.payload);const l=Dc(a.publicKey.toCID());if(!c.peerId.equals(l))throw new Kn("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(c.peerId))throw new Kn("signing key does not match remote PeerId");let u;try{u=await e.get(c.peerId)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=u&&(i.metadata=u.metadata,null!=u.peerRecordEnvelope)){const e=md.createFromProtobuf(u.peerRecordEnvelope),n=vd.createFromProtobuf(e.payload);n.seqNumber>=c.seqNumber&&(r("sequence number was lower or equal to existing sequence number - stored: %d received: %d",n.seqNumber,c.seqNumber),c=n,t=u.peerRecordEnvelope)}i.peerRecordEnvelope=t,i.addresses=c.multiaddrs.map((e=>({isCertified:!0,multiaddr:e}))),o={seq:c.seqNumber,addresses:c.multiaddrs}}else r("%p did not send a signed peer record",n.remotePeer);if(r.trace("patching %p with",n.remotePeer,i),await e.patch(n.remotePeer,i),null!=s.agentVersion||null!=s.protocolVersion){const t={};null!=s.agentVersion&&(t.AgentVersion=Ye(s.agentVersion)),null!=s.protocolVersion&&(t.ProtocolVersion=Ye(s.protocolVersion)),r.trace("merging %p metadata",n.remotePeer,t),await e.merge(n.remotePeer,{metadata:t})}const a={peerId:n.remotePeer,protocolVersion:s.protocolVersion,agentVersion:s.agentVersion,publicKey:s.publicKey,listenAddrs:s.listenAddrs.map((e=>bl(e))),observedAddr:null==s.observedAddr?void 0:bl(s.observedAddr),protocols:s.protocols,signedPeerRecord:o,connection:n};return t.safeDispatchEvent("peer:identify",{detail:a}),a}(this.peerStore,this.events,this.log,e,r)}maybeAddObservedAddress(e){const t=function(e){if(null!=e&&e.length>0)try{return bl(e)}catch{}}(e);if(null==t)return;if(this.log.trace("our observed address was %a",t),Nd(t))return void this.log.trace("our observed address was private");const r=t.getComponents();r[0].code!==Kc&&(r[0].code!==Vc||r[1].code!==Kc)||function(e){try{for(const{code:r,value:n}of e.getComponents())if(null!=n&&r===Kc)return t=n,new pl("2000::/3").contains(t)}catch{}var t;return!1}(t)?op.exactMatch(t)||(this.log.trace("storing the observed address"),this.addressManager.addObservedAddr(t)):this.log.trace("our observed address was IPv6 but not a global unicast address")}async handleProtocol(e){const{connection:t,stream:r}=e,n=AbortSignal.timeout(this.timeout);try{const e=await this.peerStore.get(this.peerId),s=this.addressManager.getAddresses().map((e=>e.decapsulateCode(wl("p2p").code)));let i=e.peerRecordEnvelope;if(s.length>0&&null==i){const e=new vd({peerId:this.peerId,multiaddrs:s});i=(await md.seal(e,this.privateKey)).marshal().subarray()}let o=t.remoteAddr.bytes;tp.matches(t.remoteAddr)||(o=void 0);const a=Id(r).pb(_d);await a.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Ac(this.privateKey.publicKey),listenAddrs:s.map((e=>e.bytes)),signedPeerRecord:i,observedAddr:o,protocols:e.protocols},{signal:n}),await r.close({signal:n})}catch(e){this.log.error("could not respond to identify request",e),r.abort(e)}}}function Ip(e={}){return t=>new Ap(t,e)}function _p(e,t){const r=function(e){if(null!=e){if("function"==typeof e[Symbol.iterator])return e[Symbol.iterator]();if("function"==typeof e[Symbol.asyncIterator])return e[Symbol.asyncIterator]();if("function"==typeof e.next)return e}throw Error("argument is not an iterator or iterable")}(e).return?.();var n;null!=(n=r)&&"function"==typeof n.then&&"function"==typeof n.catch&&"function"==typeof n.finally&&r.catch((e=>{t.error("could not cause iterator to return",e)}))}const Cp=()=>{const e=Error("Delay aborted");return e.name="AbortError",e},xp=new WeakMap,kp=function({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(Cp());let i,o,a;const c=e??clearTimeout,l=()=>{c(i),a(Cp())},u=new Promise(((e,c)=>{o=()=>{s&&s.removeEventListener("abort",l),e(n)},a=c,i=(t??setTimeout)(o,r)}));return s&&s.addEventListener("abort",l,{once:!0}),xp.set(u,(()=>{c(i),i=null,o()})),u}}();class Tp extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}}let Pp=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};class Rp{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??1e3*this.duration/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Lp}async consume(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r);let i=this.memoryStorage.incrby(n,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(n,i.consumedPoints,this.blockDuration)),new Tp("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let e=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));e<this.execEvenlyMinDelayMs&&(e=i.consumedPoints*this.execEvenlyMinDelayMs),await kp(e)}return i}penalty(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r),i=this.memoryStorage.incrby(n,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r),i=this.memoryStorage.incrby(n,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){const r=1e3*t,n=this.points+1;return this.memoryStorage.set(this.getKey(e),n,t),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:n,isFirstInDuration:!1}}set(e,t,r=0){const n=1e3*(r>=0?r:this.duration);return this.memoryStorage.set(this.getKey(e),t,r),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){const t=this.memoryStorage.get(this.getKey(e));return null!=t&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return null!=e?.customDuration&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}}class Lp{storage;constructor(){this.storage=new Map}incrby(e,t,r){const n=this.storage.get(e);if(null!=n){const s=null!=n.expiresAt?n.expiresAt.getTime()-(new Date).getTime():-1;return null==n.expiresAt||s>0?(n.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){const n=1e3*r,s=this.storage.get(e);null!=s&&clearTimeout(s.timeoutId);const i={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,i),n>0&&(i.timeoutId=setTimeout((()=>{this.storage.delete(e)}),n),null!=i.timeoutId.unref&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:i.value,isFirstInDuration:!0}}get(e){const t=this.storage.get(e);if(null!=t)return{remainingPoints:0,msBeforeNext:null!=t.expiresAt?t.expiresAt.getTime()-(new Date).getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){const t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}var Dp;(e=>{e[e.NEW_STREAM=0]="NEW_STREAM",e[e.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",e[e.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",e[e.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",e[e.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",e[e.RESET_RECEIVER=5]="RESET_RECEIVER",e[e.RESET_INITIATOR=6]="RESET_INITIATOR"})(Dp||(Dp={}));const Mp=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),Np=Object.freeze({NEW_STREAM:Dp.NEW_STREAM,MESSAGE:Dp.MESSAGE_INITIATOR,CLOSE:Dp.CLOSE_INITIATOR,RESET:Dp.RESET_INITIATOR}),Op=Object.freeze({MESSAGE:Dp.MESSAGE_RECEIVER,CLOSE:Dp.CLOSE_RECEIVER,RESET:Dp.RESET_RECEIVER}),Up=1048576;class Fp{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=Up,t=4194304){this._buffer=new Us,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(null==e||0===e.length)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new Kn("Unprocessed message queue size too large!");const t=[];for(;0!==this._buffer.length;){if(null==this._headerInfo)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(e){if("InvalidMessageError"===e.name)throw e;break}const{id:r,type:n,length:s,offset:i}=this._headerInfo;if(this._buffer.length-i<s)break;const o={id:r,type:n};n!==Dp.NEW_STREAM&&n!==Dp.MESSAGE_INITIATOR&&n!==Dp.MESSAGE_RECEIVER||(o.data=this._buffer.sublist(i,i+s)),t.push(o),this._buffer.consume(i+s),this._headerInfo=null}return t}_decodeHeader(e){const{value:t,offset:r}=qp(e),{value:n,offset:s}=qp(e,r),i=7&t;if(null==Mp[i])throw Error("Invalid type received: "+i);if(n>this._maxMessageSize)throw new Kn("Message size too large");return{id:t>>3,type:i,offset:r+s,length:n}}}const Bp=128,$p=127;function qp(e,t=0){let r,n=0,s=0,i=t;const o=e.length;do{if(i>=o||s>49)throw t=0,new RangeError("Could not decode varint");r=e.get(i++),n+=s<28?(r&$p)<<s:(r&$p)*Math.pow(2,s),s+=7}while(r>=Bp);return{value:n,offset:t=i-t}}const zp=10240,jp=new class{_pool;_poolOffset;constructor(){this._pool=a(zp),this._poolOffset=0}write(e,t){const r=this._pool;let n=this._poolOffset;y(e.id<<3|e.type,r,n),n+=f(e.id<<3|e.type),e.type!==Dp.NEW_STREAM&&e.type!==Dp.MESSAGE_INITIATOR&&e.type!==Dp.MESSAGE_RECEIVER||null==e.data?(y(0,r,n),n+=f(0)):(y(e.data.length,r,n),n+=f(e.data.length));const s=r.subarray(this._poolOffset,n);zp-n<100?(this._pool=a(zp),this._poolOffset=0):this._poolOffset=n,t.append(s),e.type!==Dp.NEW_STREAM&&e.type!==Dp.MESSAGE_INITIATOR&&e.type!==Dp.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}};class Kp extends Error{constructor(e="Stream input buffer error"){super(e),this.name="StreamInputBufferError"}}function Vp(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class Hp{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=Ws(),this.closed=Ws(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??5e3,this.onEnd=e.onEnd,this.onCloseRead=e.onCloseRead,this.onCloseWrite=e.onCloseWrite,this.onReset=e.onReset,this.onAbort=e.onAbort,this.source=this.streamSource=Qs({onEnd:e=>{null!=e?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(e){if("ready"!==this.writeStatus)throw new Un(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";const t={signal:this.sinkController.signal};if("outbound"===this.direction){const e=this.sendNewStream(t);Vp(e)&&await e}const r=()=>{_p(e,this.log)};try{this.sinkController.signal.addEventListener("abort",r),this.log.trace("sink reading from source");for await(let r of e){r=r instanceof Uint8Array?new Us(r):r;const e=this.sendData(r,t);Vp(e)&&(this.sendingData=Ws(),await e,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",r)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),"writing"===this.writeStatus&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){null==this.timeline.closeRead&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseRead?.(),null!=this.timeline.closeWrite?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){null==this.timeline.closeWrite&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseWrite?.(),null!=this.timeline.closeRead?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){"open"===this.status&&(this.log.trace("closing gracefully"),this.status="closing",await ei(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(e={}){if("closing"===this.readStatus||"closed"===this.readStatus)return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);const t=this.readStatus;this.readStatus="closing","reset"!==this.status&&"aborted"!==this.status&&null==this.timeline.closeRead&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),"ready"===t&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){"closing"!==this.writeStatus&&"closed"!==this.writeStatus&&(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),"ready"===this.writeStatus&&(this.log.trace("sink was never sunk, sink an empty array"),await ei(this.sink([]),e.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await ei(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await ei(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;this.log("abort with error",e),this.log("try to send reset to remote");const t=this.sendReset();Vp(t)&&t.catch((e=>{this.log.error("error sending reset message",e)})),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;const e=new On("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){"writing"===this.writeStatus&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){"closing"!==this.readStatus&&"closed"!==this.readStatus&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){"closing"!==this.readStatus&&"closed"!==this.readStatus?(this.log.trace("remote close write"),this._closeSource()):this.log("received remote close write but local source is already closed")}remoteCloseRead(){"closing"!==this.writeStatus&&"closed"!==this.writeStatus?(this.log.trace("remote close read"),this._closeSink()):this.log("received remote close read but local sink is already closed")}destroy(){"closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status?(this.log.trace("stream destroyed"),this._closeSinkAndSource()):this.log("received destroy but we are already closed")}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}}class Gp extends Hp{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types="outbound"===e.direction?Np:Op,this.send=e.send,this.name=e.name,this.streamId=e.streamId,this.maxDataSize=e.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:Np.NEW_STREAM,data:new Us(Ye(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){const t=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,t)}),e.consume(t)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}}function Wp(e){const t={...e,type:`${Mp[e.type]} (${e.type})`};return e.type===Dp.NEW_STREAM&&(t.data=tn(e.data instanceof Uint8Array?e.data:e.data.subarray())),e.type!==Dp.MESSAGE_INITIATOR&&e.type!==Dp.MESSAGE_RECEIVER||(t.data=tn(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class Xp{protocol="/mplex/6.7.0";sink;source;log;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;logger;constructor(e,t){t=t??{},this.log=e.logger.forComponent("libp2p:mplex"),this.logger=e.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=t,this.closeTimeout=t.closeTimeout??500,this.sink=this._createSink(),this._source=Qs({objectMode:!0,onEnd:()=>{for(const e of this._streams.initiators.values())e.destroy();for(const e of this._streams.receivers.values())e.destroy()}}),this.source=si(this._source,(e=>async function*(e){for await(const t of e){const e=new Us;jp.write(t,e),yield e}}(e))),this.closeController=new AbortController,this.rateLimiter=new Rp({points:t.disconnectThreshold??5,duration:1})}get streams(){const e=[];for(const t of this._streams.initiators.values())e.push(t);for(const t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new Nn("Muxer already closed");const t=this._streamId++;e=null==e?t.toString():e.toString();const r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}async close(e){if(this.closeController.signal.aborted)return;const t=e?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map((async e=>e.close({signal:t})))),this._source.end(),await this._source.onEmpty({signal:t}),this.closeController.abort()}catch(e){this.abort(e)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach((t=>{t.abort(e)})),this.closeController.abort(e))}_newReceiverStream(e){const{id:t,name:r}=e,n=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:n})}_newStream(e){const{id:t,name:r,type:n,registry:s}=e;if(this.log("new %s stream %s",n,t),"initiator"===n&&this._streams.initiators.size===(this._init.maxOutboundStreams??1024))throw new Yn("Too many outbound streams open");if(s.has(t))throw Error(`${n} stream ${t} already exists!`);const i=function(e){const{id:t,name:r,send:n,onEnd:s,type:i="initiator",maxMsgSize:o=Up}=e;return new Gp({id:"initiator"===i?"i"+t:"r"+t,streamId:t,name:""+(r??t),direction:"initiator"===i?"outbound":"inbound",maxDataSize:o,onEnd:s,send:n,log:e.logger.forComponent(`libp2p:mplex:stream:${i}:${t}`)})}({id:t,name:r,send:async e=>{this.log.enabled&&this.log.trace("%s stream %s send",n,t,Wp(e)),this._source.push(e)},type:n,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",n,t,i.protocol),s.delete(t),null!=this._init.onStreamEnd&&this._init.onStreamEnd(i)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return s.set(t,i),i}_createSink(){return async e=>{this.closeController.signal.addEventListener("abort",(()=>{_p(e,this.log)}));try{const t=new Fp(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const r of e)for(const e of t.write(r))await this._handleIncoming(e);this._source.end()}catch(e){this.log("error in sink",e),this._source.end(e)}finally{this.closeController.signal.removeEventListener("abort",t)}}}async _handleIncoming(e){const{id:t,type:r}=e;if(this.log.enabled&&this.log.trace("incoming message",Wp(e)),e.type===Dp.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024)){this.log("too many inbound streams open"),this._source.push({id:t,type:Dp.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{return this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),void this.abort(Error("Too many open streams"))}return}const r=this._newReceiverStream({id:t,name:tn(e.data instanceof Uint8Array?e.data:e.data.subarray())});return void(null!=this._init.onIncomingStream&&this._init.onIncomingStream(r))}const n=(1&~r?this._streams.receivers:this._streams.initiators).get(t);if(null==n){this.log("missing stream %s for message type %s",t,Mp[r]);try{await this.rateLimiter.consume("missing-stream",1)}catch{return this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),void this.abort(Error("Too many messages for missing streams"))}return}const s=this._init.maxStreamBufferSize??4194304;try{switch(r){case Dp.MESSAGE_INITIATOR:case Dp.MESSAGE_RECEIVER:if(n.sourceReadableLength()>s)throw this._source.push({id:e.id,type:r===Dp.MESSAGE_INITIATOR?Dp.RESET_RECEIVER:Dp.RESET_INITIATOR}),new Kp("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");n.sourcePush(e.data);break;case Dp.CLOSE_INITIATOR:case Dp.CLOSE_RECEIVER:n.remoteCloseWrite();break;case Dp.RESET_INITIATOR:case Dp.RESET_RECEIVER:n.reset();break;default:this.log("unknown message type %s",r)}}catch(e){this.log.error("error while processing message",e),n.abort(e)}}}class Zp{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}[Symbol.toStringTag]="@libp2p/mplex";[ts]=["@libp2p/stream-multiplexing"];createStreamMuxer(e={}){return new Xp(this.components,{...e,...this._init})}}function Yp(e={}){return t=>new Zp(t,e)}class Qp{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;log;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[ts]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(e){this.log("incoming ping from %p",e.connection.remotePeer);const{stream:t}=e,r=Date.now(),n=Cu(t);let s=!1;Promise.resolve().then((async()=>{for(;;){const e=AbortSignal.timeout(this.timeout);e.addEventListener("abort",(()=>{t?.abort(new Hn("ping timeout"))}));const r=await n.read({bytes:32,signal:e});await n.write(r,{signal:e}),s=!0}})).catch((r=>{s&&"UnexpectedEOFError"===r.name&&"ready"!==t.readStatus||(this.log.error("incoming ping from %p failed with error - %e",e.connection.remotePeer,r),t?.abort(r))})).finally((()=>{const n=Date.now()-r;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,n);const s=AbortSignal.timeout(this.timeout);t.close({signal:s}).catch((r=>{this.log.error("error closing ping stream from %p - %e",e.connection.remotePeer,r),t?.abort(r)}))}))}async ping(e,t={}){this.log("pinging %p",e);const r=Date.now(),n=Ya(32),s=await this.components.connectionManager.openConnection(e,t);let i;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{i=await s.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});const e=Cu(i),[,o]=await Promise.all([e.write(n,t),e.read({...t,bytes:32})]),a=Date.now()-r;if(!Ds(n,o.subarray()))throw new Vn(`Received wrong ping ack after ${a}ms`);return this.log("ping %p complete in %dms",s.remotePeer,a),a}catch(e){throw this.log.error("error while pinging %p",s.remotePeer,e),i?.abort(e),e}finally{null!=i&&await i.close(t)}}}function Jp(e={}){return t=>new Qp(t,e)}const ef=[6,53,56,54,55];function tf(e){return nf("sni",e)?.value}function rf(e){const t=nf("tcp",e)?.value;return null==t?"":":"+t}function nf(e,t){return t.find((t=>t.name===e))}function sf(e){return e.some((({code:e})=>448===e))}function of(e,t){const r=af[e.name];if(null==r)throw Error("Can't interpret protocol "+e.name);const n=r(e,t);return e.code===Kc?`[${n}]`:n}const af={ip4:e=>e.value,ip6:(e,t)=>0===t.length?e.value:`[${e.value}]`,tcp(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return`tcp://${of(r,t)}:${e.value}`},udp(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return`udp://${of(r,t)}:${e.value}`},dnsaddr:e=>e.value,dns4:e=>e.value,dns6:e=>e.value,dns:e=>e.value,ipfs(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return""+of(r,t)},p2p(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return""+of(r,t)},http(e,t){const r=sf(t),n=tf(t),s=rf(t);if(r&&null!=n)return`https://${n}${s}`;const i=r?"https://":"http://",o=t.pop();if(null==o)throw Error("Unexpected end of multiaddr");let a=of(o,t);return a=a?.replace("tcp://",""),`${i}${a}`},"http-path"(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return`${of(r,t)}${decodeURIComponent(e.value??"")}`},tls(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return of(r,t)},sni(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");return of(r,t)},https(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");let n=of(r,t);return n=n?.replace("tcp://",""),"https://"+n},ws(e,t){const r=sf(t),n=tf(t),s=rf(t);if(r&&null!=n)return`wss://${n}${s}`;const i=r?"wss://":"ws://",o=t.pop();if(null==o)throw Error("Unexpected end of multiaddr");let a=of(o,t);return a=a?.replace("tcp://",""),`${i}${a}`},wss(e,t){const r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");let n=of(r,t);return n=n?.replace("tcp://",""),"wss://"+n}};var cf,lf,uf=async e=>{if(e.readyState>=2)throw Error("socket closed");1!==e.readyState&&await new Promise(((t,r)=>{function n(){e.removeEventListener("open",s),e.removeEventListener("error",i)}function s(){n(),t()}function i(t){n(),r(t.error??Error("connect ECONNREFUSED "+e.url))}e.addEventListener("open",s),e.addEventListener("error",i)}))},hf=(e,t)=>((t=t??{}).closeOnEnd=!1!==t.closeOnEnd,async r=>{for await(const t of r){try{await uf(e)}catch(e){if("socket closed"===e.message)break;throw e}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(t)}null!=t.closeOnEnd&&e.readyState<=1&&await new Promise(((t,r)=>{e.addEventListener("close",(e=>{if(e.wasClean||1006===e.code)t();else{const t=Object.assign(Error("ws error"),{event:e});r(t)}})),setTimeout((()=>{e.close()}))}))}),df={},pf={},ff=function(){if(lf)return df;lf=1,Object.defineProperty(df,"__esModule",{value:!0});const e=function(){if(cf)return pf;cf=1,Object.defineProperty(pf,"__esModule",{value:!0});class e{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;const t={value:e,done:!1};if(this.pullQueue.length){const e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch((()=>{})),this.pushQueue.push(t)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:()=>{const e=this.pushQueue.shift();return e?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),e):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise(((e,t)=>{this.pullQueue.push({resolve:e,reject:t})}))},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class t{constructor(t,{highWaterMark:r=100,lowWaterMark:n=1}={}){const s=new e;s.highWaterMark=r,s.lowWaterMark=n,s.removeCallback=t({push:e=>s.push(e),stop:()=>s.stop(),fail:e=>s.fail(e),on(e,t){s.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>s[Symbol.asyncIterator](),Object.freeze(this)}}return pf.EventIterator=t,pf.default=t,pf}();return df.EventIterator=e.EventIterator,df.subscribe=function(t,r,n){return new e.EventIterator((({push:e})=>(this.addEventListener(t,e,r),()=>this.removeEventListener(t,e,r))),n)},df.default=e.EventIterator,df}();function gf(e){return e instanceof ArrayBuffer||"ArrayBuffer"===e?.constructor?.name&&"number"==typeof e?.byteLength}var mf=WebSocket;const yf={"http:":"ws:","https:":"wss:"};class bf extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}}function wf(e){return e.filter((e=>gp.exactMatch(e)||pp.exactMatch(e)))}function vf(e){return e.filter((e=>gp.exactMatch(e)))}class Ef{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,null!=e.metrics&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[_n]=!0;[Symbol.toStringTag]="@libp2p/websockets";[ts]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};const r=function(e,t,r){const n=r.logger.forComponent("libp2p:websockets:maconn"),s=r.metrics,i=r.metricPrefix??"",o={log:n,async sink(t){try{await e.sink(async function*(){for await(const e of t)e instanceof Uint8Array?yield e:yield e.subarray()}())}catch(e){"aborted"!==e.type&&n.error(e)}},source:e.source,remoteAddr:t,timeline:{open:Date.now()},async close(t={}){const r=Date.now();if(null==t.signal){const e=AbortSignal.timeout(500);t={...t,signal:e}}const s=()=>{const{host:e,port:t}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-r),this.abort(new xn("Socket close timeout"))};t.signal?.addEventListener("abort",s);try{await e.close()}catch(e){n.error("error closing WebSocket gracefully",e),this.abort(e)}finally{t.signal?.removeEventListener("abort",s),o.timeline.close=Date.now()}},abort(t){const{host:r,port:a}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",r,a,t),e.destroy(),o.timeline.close=Date.now(),s?.increment({[i+"error"]:!0})}};return e.socket.addEventListener("close",(()=>{s?.increment({[i+"close"]:!0}),null==o.timeline.close&&(o.timeline.close=Date.now())}),{once:!0}),o}(await this._connect(e,t),e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",r.remoteAddr);const n=await t.upgrader.upgradeOutbound(r,t);return this.log("outbound connection %s upgraded",r.remoteAddr),n}async _connect(e,t){t?.signal?.throwIfAborted();const r=e.toOptions();this.log("dialing %s:%s",r.host,r.port);const n=Ws(),s=function(e,t){t=t??{};const r=((e,t)=>{if(e.startsWith("//")&&(e=`${t?.protocol??"ws:"}${e}`),e.startsWith("/")&&null!=t){const r=t.protocol??"ws:",n=t.host,s=null!=t.port&&!0!==n?.endsWith(":"+t.port)?":"+t.port:"";e=`${r}//${n}${s}${e}`}const r=new URL(e);for(const[e,t]of Object.entries(yf))r.protocol===e&&(r.protocol=t);return r})(e,"undefined"==typeof window?void 0:window.location);return((e,t)=>{t=t??{};const r=(e=>{e.binaryType="arraybuffer";const t=async()=>{await new Promise(((t,r)=>{if(s)return void t();if(null!=n)return void r(n);const i=t=>{e.removeEventListener("open",o),e.removeEventListener("error",a),t()},o=()=>{i(t)},a=t=>{i((()=>{r(t.error??Error("connect ECONNREFUSED "+e.url))}))};e.addEventListener("open",o),e.addEventListener("error",a)}))},r=async function*(){const r=new ff.EventIterator((({push:t,stop:r,fail:n})=>{const s=e=>{let r=null;"string"==typeof e.data&&(r=Ye(e.data)),gf(e.data)&&(r=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(r=e.data),null!=r&&t(r)},i=e=>{n(e.error??Error("Socket error"))};return e.addEventListener("message",s),e.addEventListener("error",i),e.addEventListener("close",r),()=>{e.removeEventListener("message",s),e.removeEventListener("error",i),e.removeEventListener("close",r)}}),{highWaterMark:1/0});await t();for await(const e of r)yield gf(e)?new Uint8Array(e):e}();let n,s=1===e.readyState;return e.addEventListener("open",(()=>{s=!0,n=null})),e.addEventListener("close",(()=>{s=!1,n=null})),e.addEventListener("error",(t=>{s||(n=t.error??Error("connect ECONNREFUSED "+e.url))})),Object.assign(r,{connected:t})})(e);let n=t.remoteAddress,s=t.remotePort;if(null!=e.url)try{const t=new URL(e.url);n=t.hostname,s=parseInt(t.port,10)}catch{}if(null==n||null==s)throw Error("Remote connection did not have address and/or port");return{sink:hf(e,t),source:r,async connected(){await r.connected()},async close(){e.readyState!==e.CONNECTING&&e.readyState!==e.OPEN||await new Promise((t=>{e.addEventListener("close",(()=>{t()})),e.close()}))},destroy(){null!=e.terminate?e.terminate():e.close()},remoteAddress:n,remotePort:s,socket:e}})(new mf(r.toString(),t.websocket),t)}(function(e){const t=bl(e).getComponents(),r=t.pop();if(null==r)throw Error("Unexpected end of multiaddr");const n=af[r.name];if(null==n)throw Error("No interpreter found for "+r.name);let s=n(r,t)??"";return ef.includes(r.code)&&(s=s.replace(/^.*:\/\//,""),s="443"===r.value?"https://"+s:"http://"+s),(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("ws://")||s.startsWith("wss://"))&&(s=new URL(s).toString(),s.endsWith("/")&&(s=s.substring(0,s.length-1))),s}(e),this.init);s.socket.addEventListener("error",(()=>{const t=new Mn("Could not connect to "+e.toString());this.log.error("connection error:",t),this.metrics?.dialerEvents.increment({error:!0}),n.reject(t)}));try{t.onProgress?.(new bf("websockets:open-connection")),await ei(Promise.race([s.connected(),n.promise]),t.signal)}catch(e){throw t.signal?.aborted&&this.metrics?.dialerEvents.increment({abort:!0}),s.close().catch((e=>{this.log.error("error closing raw socket",e)})),e}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),s}createListener(e){return function(){throw Error("WebSocket Servers can not be created in the browser!")}((this.logger,this.components.events,this.components.metrics),this.init)}listenFilter(e){return e=Array.isArray(e)?e:[e],null!=this.init?.filter?this.init?.filter(e):wf(e)}dialFilter(e){return this.listenFilter(e)}}function Sf(e={}){return t=>new Ef(t,e)}function Af(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)}const{hasOwnProperty:If}=Object.prototype,{propertyIsEnumerable:_f}=Object,Cf=(e,t,r)=>{Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})},xf={concatArrays:!1,ignoreUndefined:!1},kf=e=>{const t=[];for(const r in e)If.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)_f.call(e,n)&&t.push(n)}return t};function Tf(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return kf(e).forEach((r=>{Cf(t,r,Tf(e[r]))})),t}(e):Af(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return kf(e).forEach((r=>{Cf(t,r,Tf(e[r]))})),t}(e):e}const Pf=(e,t,r,n)=>(r.forEach((r=>{void 0===t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?Cf(e,r,Lf(e[r],t[r],n)):Cf(e,r,Tf(t[r])))})),e),Rf=(e,t,r)=>{let n=e.slice(0,0),s=0;return[e,t].forEach((t=>{const i=[];for(let r=0;r<t.length;r++)If.call(t,r)&&(i.push(r+""),Cf(n,s++,t===e?t[r]:Tf(t[r])));n=Pf(n,t,kf(t).filter((e=>!i.includes(e))),r)})),n};function Lf(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?Rf(e,t,r):Af(t)&&Af(e)?Pf(e,t,kf(t),r):Tf(t)}function Df(...e){const t=Lf(Tf(xf),void 0!==this&&this||{},xf);let r={_:{}};for(const n of e)if(void 0!==n){if(!Af(n))throw new TypeError("`"+n+"` is not an Option Object");r=Lf(r,{_:n},t)}return r._}var Mf,Nf={exports:{}},Of=(Mf||(Mf=1,function(e){var t={}.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function i(e,t,n,i,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,o=Array(i);s<i;s++)o[s]=n[s].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,s,i,o){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,u=this._events[a],h=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),h){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,s),!0;case 5:return u.fn.call(u.context,t,n,s,i),!0;case 6:return u.fn.call(u.context,t,n,s,i,o),!0}for(l=1,c=Array(h-1);l<h;l++)c[l-1]=arguments[l];u.fn.apply(u.context,c)}else{var d,p=u.length;for(l=0;l<p;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),h){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,t);break;case 3:u[l].fn.call(u[l].context,t,n);break;case 4:u[l].fn.call(u[l].context,t,n,s);break;default:if(!c)for(d=1,c=Array(h-1);d<h;d++)c[d-1]=arguments[d];u[l].fn.apply(u[l].context,c)}}return!0},a.prototype.on=function(e,t,r){return i(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return i(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,s){var i=r?r+e:e;if(!this._events[i])return this;if(!t)return o(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||s&&!a.once||n&&a.context!==n||o(this,i);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||s&&!a[c].once||n&&a[c].context!==n)&&l.push(a[c]);l.length?this._events[i]=1===l.length?l[0]:l:o(this,i)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}(Nf)),Nf.exports),Uf=ss(Of);class Ff extends Error{constructor(e){super(e),this.name="TimeoutError"}}let Bf=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}};const $f=e=>void 0===globalThis.DOMException?new Bf(e):new DOMException(e),qf=e=>{const t=void 0===e.reason?$f("This operation was aborted."):e.reason;return t instanceof Error?t:$f(t)};let zf=class{#s=[];enqueue(e,t){const r={priority:(t={priority:0,...t}).priority,id:t.id,run:e};if(0===this.size||this.#s[this.size-1].priority>=t.priority)return void this.#s.push(r);const n=function(e,t,r){let n=0,s=e.length;for(;s>0;){const i=Math.trunc(s/2);let o=n+i;r(e[o],t)<=0?(n=++o,s-=i+1):s=i}return n}(this.#s,r,((e,t)=>t.priority-e.priority));this.#s.splice(n,0,r)}setPriority(e,t){const r=this.#s.findIndex((t=>t.id===e));if(-1===r)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);const[n]=this.#s.splice(r,1);this.enqueue(n.run,{priority:t,id:e})}dequeue(){return this.#s.shift()?.run}filter(e){return this.#s.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this.#s.length}};class jf extends Uf{#i;#o;#a=0;#c;#l;#u=0;#h;#d;#s;#p;#f=0;#g;#m;#y;#b=1n;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:zf,...e}).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#i=e.carryoverConcurrencyCount,this.#o=e.intervalCap===1/0||0===e.interval,this.#c=e.intervalCap,this.#l=e.interval,this.#s=new e.queueClass,this.#p=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#y=!0===e.throwOnTimeout,this.#m=!1===e.autoStart}get#w(){return this.#o||this.#a<this.#c}get#v(){return this.#f<this.#g}#E(){this.#f--,this.#S(),this.emit("next")}#A(){this.#I(),this.#_(),this.#d=void 0}get#C(){const e=Date.now();if(void 0===this.#h){const t=this.#u-e;if(!(t<0))return void 0===this.#d&&(this.#d=setTimeout((()=>{this.#A()}),t)),!0;this.#a=this.#i?this.#f:0}return!1}#S(){if(0===this.#s.size)return this.#h&&clearInterval(this.#h),this.#h=void 0,this.emit("empty"),0===this.#f&&this.emit("idle"),!1;if(!this.#m){const e=!this.#C;if(this.#w&&this.#v){const t=this.#s.dequeue();return!!t&&(this.emit("active"),t(),e&&this.#_(),!0)}}return!1}#_(){this.#o||void 0!==this.#h||(this.#h=setInterval((()=>{this.#I()}),this.#l),this.#u=Date.now()+this.#l)}#I(){0===this.#a&&0===this.#f&&this.#h&&(clearInterval(this.#h),this.#h=void 0),this.#a=this.#i?this.#f:0,this.#x()}#x(){for(;this.#S(););}get concurrency(){return this.#g}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#g=e,this.#x()}async#k(e){return new Promise(((t,r)=>{e.addEventListener("abort",(()=>{r(e.reason)}),{once:!0})}))}setPriority(e,t){this.#s.setPriority(e,t)}async add(e,t={}){return t.id??=""+this.#b++,t={timeout:this.timeout,throwOnTimeout:this.#y,...t},new Promise(((r,n)=>{this.#s.enqueue((async()=>{this.#f++,this.#a++;try{t.signal?.throwIfAborted();let n=e({signal:t.signal});t.timeout&&(n=function(e,t){const{milliseconds:r,fallback:n,message:s,customTimers:i={setTimeout:setTimeout,clearTimeout:clearTimeout}}=t;let o,a;const c=new Promise(((c,l)=>{if("number"!=typeof r||1!==Math.sign(r))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){const{signal:e}=t;e.aborted&&l(qf(e)),a=()=>{l(qf(e))},e.addEventListener("abort",a,{once:!0})}if(r===1/0)return void e.then(c,l);const u=new Ff;o=i.setTimeout.call(void 0,(()=>{if(n)try{c(n())}catch(e){l(e)}else"function"==typeof e.cancel&&e.cancel(),!1===s?c():s instanceof Error?l(s):(u.message=s??`Promise timed out after ${r} milliseconds`,l(u))}),r),(async()=>{try{c(await e)}catch(e){l(e)}})()})).finally((()=>{c.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)}));return c.clear=()=>{i.clearTimeout.call(void 0,o),o=void 0},c}(Promise.resolve(n),{milliseconds:t.timeout})),t.signal&&(n=Promise.race([n,this.#k(t.signal)]));const s=await n;r(s),this.emit("completed",s)}catch(e){if(e instanceof Ff&&!t.throwOnTimeout)return void r();n(e),this.emit("error",e)}finally{this.#E()}}),t),this.emit("add"),this.#S()}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this.#m?(this.#m=!1,this.#x(),this):this}pause(){this.#m=!0}clear(){this.#s=new this.#p}async onEmpty(){0!==this.#s.size&&await this.#T("empty")}async onSizeLessThan(e){this.#s.size<e||await this.#T("next",(()=>this.#s.size<e))}async onIdle(){0===this.#f&&0===this.#s.size||await this.#T("idle")}async#T(e,t){return new Promise((r=>{const n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)}))}get size(){return this.#s.size}sizeBy(e){return this.#s.filter(e).length}get pending(){return this.#f}get isPaused(){return this.#m}}function Kf(e){const t=[Xf.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function Vf(e){return{Status:e.Status??0,TC:e.TC??e.flag_tc??!1,RD:e.RD??e.flag_rd??!1,RA:e.RA??e.flag_ra??!1,AD:e.AD??e.flag_ad??!1,CD:e.CD??e.flag_cd??!1,Question:(e.Question??e.questions??[]).map((e=>({name:e.name,type:Xf[e.type]}))),Answer:(e.Answer??e.answers??[]).map((e=>({name:e.name,type:Xf[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?tn(e.data):e.data})))}}function Hf(e,t={}){const r=new jf({concurrency:t.queryConcurrency??4});return async(t,n={})=>{const s=new URLSearchParams;s.set("name",t),Kf(n.types).forEach((e=>{s.append("type",Xf[e])})),n.onProgress?.(new bf("dns:query",{detail:t}));const i=await r.add((async()=>{const t=await fetch(`${e}?${s}`,{headers:{accept:"application/dns-json"},signal:n?.signal});if(200!==t.status)throw Error(`Unexpected HTTP status: ${t.status} - ${t.statusText}`);const r=Vf(await t.json());return n.onProgress?.(new bf("dns:response",{detail:r})),r}),{signal:n.signal});if(null==i)throw Error("No DNS response received");return i}}var Gf,Wf,Xf,Zf=(Wf||(Wf=1,Gf=e=>{if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,r=Object.create(null),n=Object.create(null);function s(s,i){r[s]=i,++t>=e&&(t=0,n=r,r=Object.create(null))}return{has:e=>void 0!==r[e]||void 0!==n[e],remove(e){void 0!==r[e]&&(r[e]=void 0),void 0!==n[e]&&(n[e]=void 0)},get(e){var t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(s(e,t),t):void 0},set(e,t){void 0!==r[e]?r[e]=t:s(e,t)},clear(){r=Object.create(null),n=Object.create(null)}}}),Gf),Yf=ss(Zf);class Qf{lru;constructor(e){this.lru=Yf(e)}get(e,t){let r=!0;const n=[];for(const s of t){const t=this.getAnswers(e,s);if(0===t.length){r=!1;break}n.push(...t)}if(r)return Vf({answers:n})}getAnswers(e,t){const r=`${e.toLowerCase()}-${t}`,n=this.lru.get(r);if(null!=n){const e=n.filter((e=>e.expires>Date.now())).map((({expires:e,value:t})=>({...t,TTL:Math.round((e-Date.now())/1e3),type:Xf[t.type]})));return 0===e.length&&this.lru.remove(r),e}return[]}add(e,t){const r=`${e.toLowerCase()}-${t.type}`,n=this.lru.get(r)??[];n.push({expires:Date.now()+1e3*(t.TTL??60),value:t}),this.lru.set(r,n)}remove(e,t){const r=`${e.toLowerCase()}-${t}`;this.lru.remove(r)}clear(){this.lru.clear()}}class Jf{resolvers;cache;constructor(e){var t;this.resolvers={},this.cache=(t=e.cacheSize??1e3,new Qf(t)),Object.entries(e.resolvers??{}).forEach((([e,t])=>{Array.isArray(t)||(t=[t]),e.endsWith(".")||(e+="."),this.resolvers[e]=t})),null==this.resolvers["."]&&(this.resolvers["."]=[Hf("https://cloudflare-dns.com/dns-query"),Hf("https://dns.google/resolve")])}async query(e,t={}){const r=Kf(t.types),n=!1!==t.cached?this.cache.get(e,r):void 0;if(null!=n)return t.onProgress?.(new bf("dns:cache",{detail:n})),n;const s=e.split(".").pop()+".",i=(this.resolvers[s]??this.resolvers["."]).sort((()=>Math.random()>.5?-1:1)),o=[];for(const n of i){if(!0===t.signal?.aborted)break;try{const s=await n(e,{...t,types:r});for(const t of s.Answer)this.cache.add(e,t);return s}catch(e){o.push(e),t.onProgress?.(new bf("dns:error",{detail:e}))}}if(1===o.length)throw o[0];throw new AggregateError(o,`DNS lookup of ${e} ${r} failed`)}}(e=>{e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"})(Xf||(Xf={}));const eg=-1,tg={},rg={};[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,eg,"ip6zone"],[43,8,"ipcidr"],[53,eg,"dns",!0],[54,eg,"dns4",!0],[55,eg,"dns6",!0],[56,eg,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,eg,"unix",!1,!0],[421,eg,"ipfs"],[421,eg,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,eg,"garlic64"],[448,0,"tls"],[449,eg,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,eg,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,eg,"http-path"],[777,eg,"memory"]].forEach((e=>{const t=function(e,t,r,n,s){return{code:e,size:t,name:r,resolvable:!!n,path:!!s}}(...e);rg[t.code]=t,tg[t.name]=t}));const{code:ng}=function(e){if(null!=tg[e])return tg[e];throw Error("no protocol with name: "+e)}("dnsaddr");class sg extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}const ig=async function(e,t={}){const r=t.maxRecursiveDepth??32;if(0===r)throw new sg("Max recursive depth reached");const[,n]=e.stringTuples().find((([e])=>e===ng))??[],s=t?.dns??function(e={}){return new Jf(e)}(),i=await s.query("_dnsaddr."+n,{signal:t?.signal,types:[Xf.TXT]}),o=e.getPeerId(),a=[];for(const e of i.Answer){const n=e.data.replace(/["']/g,"").trim().split("=")[1];if(null==n)continue;if(null!=o&&!n.includes(o))continue;const s=bl(n);if(n.startsWith("/dnsaddr")){const e=await s.resolve({...t,maxRecursiveDepth:r-1});a.push(...e.map((e=>e.toString())))}else a.push(s.toString())}return a},og={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:ig}},transportManager:{faultTolerance:Cn.FATAL_ALL}};async function ag(e){const t=Df(og,e);if(null===t.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new Pn("Private network is enforced, but no protector was provided");return t}const cg=1e3,lg=6e4,ug=60*lg,hg=24*ug,dg=7*hg;function pg(e,t){try{if("string"==typeof e&&e.length>0)return function(e){if((e+="").length>100)throw Error("Value exceeds the maximum length of 100 characters.");const t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return NaN;const r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return r*dg;case"days":case"day":case"d":return r*hg;case"hours":case"hour":case"hrs":case"hr":case"h":return r*ug;case"minutes":case"minute":case"mins":case"min":case"m":return r*lg;case"seconds":case"second":case"secs":case"sec":case"s":return r*cg;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:throw Error(`The unit ${n} was matched, but no matching case exists.`)}}(e);if("number"==typeof e&&isFinite(e))return t?.long?function(e){const t=Math.abs(e);return t>=hg?fg(e,t,hg,"day"):t>=ug?fg(e,t,ug,"hour"):t>=lg?fg(e,t,lg,"minute"):t>=cg?fg(e,t,cg,"second"):e+" ms"}(e):function(e){const t=Math.abs(e);return t>=hg?Math.round(e/hg)+"d":t>=ug?Math.round(e/ug)+"h":t>=lg?Math.round(e/lg)+"m":t>=cg?Math.round(e/cg)+"s":e+"ms"}(e);throw Error("Value is not a string or number.")}catch(t){const r=function(e){return"object"==typeof e&&null!==e&&"message"in e}(t)?`${t.message}. value=${JSON.stringify(e)}`:"An unknown error has occured.";throw Error(r)}}function fg(e,t,r,n){const s=t>=1.5*r;return`${Math.round(e/r)} ${n}${s?"s":""}`}const gg=function(){try{return localStorage}catch(e){}}(),mg=console.debug??console.log??(()=>{});var yg=function(e){function t(e){let n,s,i,o=null;function a(...e){if(!a.enabled)return;const r=a,s=Number(new Date),i=s-(n||s);r.diff=i,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];n=i.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set(e){o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack??e.message:e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r<s;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(RegExp("^"+e.substr(1)+"$")):t.names.push(RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=pg,t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.setupFormatters(t.formatters),t.enable(t.load()),t}({formatArgs(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+pg(this.diff),!this.useColors)return;const t="color: "+this.color;e.splice(1,0,t,"color: inherit");let r=0,n=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(n=r))})),e.splice(n,0,t)},save(e){try{e?gg?.setItem("debug",e):gg?.removeItem("debug")}catch(e){}},load(){let e;try{e=gg?.getItem("debug")}catch(e){}return!e&&void 0!==globalThis.process&&"env"in globalThis.process&&(e=globalThis.process.env.DEBUG),e},useColors:()=>!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||null==navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement?.style?.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&null!=navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)),setupFormatters(e){e.j=e=>{try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},colors:["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],storage:gg,log:mg});function bg(){return{forComponent:e=>wg(e)}}function wg(e){let t=function(e){const t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}(e+":trace");return yg.enabled(e+":trace")&&null!=yg.names.map((e=>e.toString())).find((e=>e.includes(":trace")))&&(t=yg(e+":trace")),Object.assign(yg(e),{error:yg(e+":error"),trace:t,newScope:t=>wg(`${e}:${t}`)})}function vg(e){if(null!=e&&0!==(e=e.trim()).length)return e}function Eg(e,t){const r={[Symbol.iterator]:()=>r,next(){const r=e.next(),n=r.value;return!0===r.done||null==n?{done:!0,value:void 0}:{done:!1,value:t(n)}}};return r}function Sg(e){return Lc(Le(fe.decode("z"+e)))}yg.formatters.b=e=>null==e?"undefined":fe.baseEncode(e),yg.formatters.t=e=>null==e?"undefined":te.baseEncode(e),yg.formatters.m=e=>null==e?"undefined":ye.baseEncode(e),yg.formatters.p=e=>null==e?"undefined":e.toString(),yg.formatters.c=e=>null==e?"undefined":e.toString(),yg.formatters.k=e=>null==e?"undefined":e.toString(),yg.formatters.a=e=>null==e?"undefined":e.toString(),yg.formatters.e=e=>null==e?"undefined":vg(e.stack)??vg(e.message)??e.toString();class Ag{map;constructor(e){if(this.map=new Map,null!=e)for(const[t,r]of e.entries())this.map.set(t.toString(),{key:t,value:r})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Eg(this.map.entries(),(e=>[e[1].key,e[1].value]))}forEach(e){this.map.forEach((t=>{e(t.value,t.key,this)}))}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Eg(this.map.values(),(e=>e.key))}values(){return Eg(this.map.values(),(e=>e.value))}get size(){return this.map.size}}class Ig{set;constructor(e){if(this.set=new Set,null!=e)for(const t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Eg(this.set.entries(),(e=>{const t=Sg(e[0]);return[t,t]}))}forEach(e){this.set.forEach((t=>{const r=Sg(t);e(r,r,this)}))}has(e){return this.set.has(e.toString())}values(){return Eg(this.set.values(),(e=>Sg(e)))}intersection(e){const t=new Ig;for(const r of e)this.has(r)&&t.add(r);return t}difference(e){const t=new Ig;for(const r of this)e.has(r)||t.add(r);return t}union(e){const t=new Ig;for(const r of e)t.add(r);for(const e of this)t.add(e);return t}}const _g={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Cg={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},xg=new globalThis.TextEncoder,kg={hash:e=>Number(function(e,{size:t=32,utf8Buffer:r}={}){if(!_g[t])throw Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if("string"==typeof e){if(r)return function(e,t,r){if(0===r.length)throw Error("The `utf8Buffer` option must have a length greater than zero");const n=_g[t];let s=Cg[t],i=e;for(;i.length>0;){const e=xg.encodeInto(i,r);i=i.slice(e.read);for(let i=0;i<e.written;i++)s^=BigInt(r[i]),s=BigInt.asUintN(t,s*n)}return s}(e,t,r);e=xg.encode(e)}return function(e,t){const r=_g[t];let n=Cg[t];for(let s=0;s<e.length;s++)n^=BigInt(e[s]),n=BigInt.asUintN(t,n*r);return n}(e,t)}(e,{size:32})),hashV:(e,t)=>function(e){let t=e.toString(16);return t.length%2==1&&(t="0"+t),Ye(t,"base16")}(kg.hash(e,t))};class Tg{fp;h;seed;constructor(e,t,r,n=2){if(n>64)throw new TypeError("Invalid Fingerprint Size");const s=t.hashV(e,r),i=o(n);for(let e=0;e<i.length;e++)i[e]=s[e];0===i.length&&(i[0]=7),this.fp=i,this.h=t,this.seed=r}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array&&Ds(this.fp,e.fp)}}function Pg(e,t){return Math.floor(Math.random()*(t-e))+e}class Rg{contents;constructor(e){this.contents=Array(e).fill(null)}has(e){if(!(e instanceof Tg))throw new TypeError("Invalid Fingerprint");return this.contents.some((t=>e.equals(t)))}add(e){if(!(e instanceof Tg))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(null==this.contents[t])return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Tg))throw new TypeError("Invalid Fingerprint");const t=Pg(0,this.contents.length-1),r=this.contents[t];return this.contents[t]=e,r}remove(e){if(!(e instanceof Tg))throw new TypeError("Invalid Fingerprint");const t=this.contents.findIndex((t=>e.equals(t)));return t>-1&&(this.contents[t]=null,!0)}}class Lg{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??kg,this.seed=e.seed??Pg(0,1024)}add(e){"string"==typeof e&&(e=Ye(e));const t=new Tg(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=(r^t.hash())%this.filterSize;if(null==this.buckets[r]&&(this.buckets[r]=new Rg(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new Rg(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;const s=[r,n];let i=s[Pg(0,s.length-1)];null==this.buckets[i]&&(this.buckets[i]=new Rg(this.bucketSize));for(let e=0;e<500;e++){const e=this.buckets[i].swap(t);if(null!=e&&(i=(i^e.hash())%this.filterSize,null==this.buckets[i]&&(this.buckets[i]=new Rg(this.bucketSize)),this.buckets[i].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=Ye(e));const t=new Tg(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.has(t)??!1;if(n)return n;const s=(r^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){"string"==typeof e&&(e=Ye(e));const t=new Tg(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.remove(t)??!1;if(n)return this.count--,n;const s=(r^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}}const Dg={1:.5,2:.84,4:.95,8:.98};function Mg(e,t=.001){const r=function(e=.001){return e>.002?2:e>1e-5?4:8}(t);return{filterSize:Math.round(e/Dg[r]),bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*r)),64)}}class Ng{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??262144/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??kg,this.seed=e.seed??Pg(0,1024),this.filterSeries=[new Lg({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=Ye(e)),this.has(e))return!0;let t=this.filterSeries.find((e=>e.reliable));if(null==t){const e=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Lg({filterSize:e,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){"string"==typeof e&&(e=Ye(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){"string"==typeof e&&(e=Ye(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce(((e,t)=>e+t.count),0)}}function Og(e,t=.001){return new Ng({...Mg(e,t)})}class Ug extends Ag{metric;constructor(e){super();const{name:t,metrics:r}=e;this.metric=r.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}let Fg=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Bg(e,t,r,n){const s=new Fg(n?.errorMessage);null!=n?.errorCode&&(s.code=n.errorCode);const i=n?.errorEvent??"error";return!0===r?.aborted?Promise.reject(s):new Promise(((o,a)=>{function c(){qg(r,"abort",h),qg(e,t,l),qg(e,i,u)}const l=e=>{try{if(!1===n?.filter?.(e))return}catch(e){return c(),void a(e)}c(),o(e)},u=e=>{c(),a(e instanceof Error?e:e.detail??n?.error??Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},h=()=>{c(),a(s)};$g(r,"abort",h),$g(e,t,l),$g(e,i,u)}))}function $g(e,t,r){null!=e&&(zg(e)?e.addEventListener(t,r):e.addListener(t,r))}function qg(e,t,r){null!=e&&(zg(e)?e.removeEventListener(t,r):e.removeListener(t,r))}function zg(e){return"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener}class jg extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}function Kg(e,t){let r;const n=()=>{clearTimeout(r),r=setTimeout((()=>{r=void 0,e()}),t)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}let Vg=class extends Jn{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??1/0,this.maxSize=e.maxSize??1/0,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=Kg(this.emitEmpty.bind(this),1),this.emitIdle=Kg(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally((()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()})),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}start(){!1===this.autoStart&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new jg;const r=new class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(1e9*Math.random()+"",10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce(((e,t)=>e&&!0===t.signal?.aborted),!0)&&(this.controller.abort(new Fg),this.cleanup())}async join(e={}){const t=new class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Fg)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await ei(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach((t=>{t.deferred.resolve(e)})),this.status="complete"}catch(e){this.recipients.forEach((t=>{t.deferred.reject(e)})),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach((e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}))}}(e,t);return this.enqueue(r),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),r.join(t).then((e=>(this.safeDispatchEvent("success",{detail:{job:r,result:e}}),e))).catch((e=>{if("queued"===r.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===r){this.queue.splice(e,1);break}throw this.safeDispatchEvent("failure",{detail:{job:r,error:e}}),e}))}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new Fg)})),this.clear()}async onEmpty(e){0!==this.size&&await Bg(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Bg(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await Bg(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();const t=Qs({objectMode:!0}),r=e=>{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail.result)},s=e=>{r(e.detail.error)},i=()=>{r()},o=()=>{r(new Fg("Queue aborted"))};this.addEventListener("success",n),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("success",n),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",o),r()}}};const Hg="lock:worker:request-read",Gg="lock:worker:abort-read-request",Wg="lock:worker:release-read",Xg="lock:master:grant-read",Zg="lock:master:error-read",Yg="lock:worker:request-write",Qg="lock:worker:abort-write-request",Jg="lock:worker:release-write",em="lock:master:grant-write",tm="lock:master:error-write",rm="lock:worker:finalize",nm="mortice",sm={singleProcess:!1},im=(e,t,r,n,s,i,o,a,c)=>l=>{if(null==l.data)return;const u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===s&&e.safeDispatchEvent(r,{detail:{name:u.name,identifier:u.identifier,async handler(){t.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise((e=>{const r=n=>{if(null==n?.data)return;const s=n.data.type,i=(n.data.name,n.data.identifier);s===a&&i===u.identifier&&(t.removeEventListener("message",r),e())};t.addEventListener("message",r)}))},onError(e){t.postMessage({type:o,name:u.name,identifier:u.identifier,error:{message:e.message,name:e.name,stack:e.stack}})}}}),u.type===i&&e.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===rm&&e.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};class om{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(nm)}readLock(e){return this.sendRequest(Hg,Gg,Xg,Zg,Wg,e)}writeLock(e){return this.sendRequest(Yg,Qg,em,tm,Jg,e)}finalize(){this.channel.postMessage({type:rm,name:this.name}),this.channel.close()}async sendRequest(e,t,r,n,s,i){i?.signal?.throwIfAborted();const o=((e=10)=>Math.random().toString().substring(2,e+2))();return this.channel.postMessage({type:e,identifier:o,name:this.name}),new Promise(((e,a)=>{const c=()=>{this.channel.postMessage({type:t,identifier:o,name:this.name})};i?.signal?.addEventListener("abort",c,{once:!0});const l=t=>{if(t.data?.identifier===o&&(t.data?.type===r&&(this.channel.removeEventListener("message",l),i?.signal?.removeEventListener("abort",c),e((()=>{this.channel.postMessage({type:s,identifier:o,name:this.name})}))),t.data.type===n)){this.channel.removeEventListener("message",l),i?.signal?.removeEventListener("abort",c);const e=Error();null!=t.data.error&&(e.message=t.data.error.message,e.name=t.data.error.name,e.stack=t.data.error.stack),a(e)}};this.channel.addEventListener("message",l)}))}}const am=new Map;let cm;function lm(e){return"function"==typeof e?.readLock&&"function"==typeof e?.writeLock}async function um(e,t){let r,n;const s=new Promise(((e,t)=>{r=e,n=t})),i=()=>{n(new Fg)};return t?.signal?.addEventListener("abort",i,{once:!0}),e.add((async()=>{await new Promise((e=>{r((()=>{t?.signal?.removeEventListener("abort",i),e()}))}))}),{signal:t?.signal}).catch((e=>{n(e)})),s}const hm={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function dm(e){const t=Object.assign({},hm,e);return((e,t)=>{let r=am.get(e);if(null!=r)return r;const n=function(e){if(null==cm&&(cm=(e=>{if(e=Object.assign({},sm,e),globalThis.document||e.singleProcess){const e=new BroadcastChannel(nm),t=new Jn;return e.addEventListener("message",im(t,e,"requestReadLock","abortReadLockRequest",Hg,Gg,Zg,Wg,Xg)),e.addEventListener("message",im(t,e,"requestWriteLock","abortWriteLockRequest",Yg,Qg,tm,Jg,em)),t}return new om(e.name)})(e),!lm(cm))){const e=cm;e.addEventListener("requestReadLock",(t=>{const r=t.detail.name,n=t.detail.identifier,s=am.get(r);if(null==s)return;const i=new AbortController,o=e=>{e.detail.name===r&&e.detail.identifier===n&&i.abort()};e.addEventListener("abortReadLockRequest",o),s.readLock({signal:i.signal}).then((async e=>{await t.detail.handler().finally((()=>{e()}))})).catch((e=>{t.detail.onError(e)})).finally((()=>{e.removeEventListener("abortReadLockRequest",o)}))})),e.addEventListener("requestWriteLock",(t=>{const r=t.detail.name,n=t.detail.identifier,s=am.get(r);if(null==s)return;const i=new AbortController,o=e=>{e.detail.name===r&&e.detail.identifier===n&&i.abort()};e.addEventListener("abortWriteLockRequest",o),s.writeLock({signal:i.signal}).then((async e=>{await t.detail.handler().finally((()=>{e()}))})).catch((e=>{t.detail.onError(e)})).finally((()=>{e.removeEventListener("abortWriteLockRequest",o)}))})),e.addEventListener("finalizeRequest",(e=>{const t=e.detail.name,r=am.get(t);null!=r&&r.finalize()}))}return cm}(t);if(lm(n))return r=n,am.set(e,r),r;const s=new Vg({concurrency:1});let i;return r={async readLock(e){if(null!=i)return um(i,e);i=new Vg({concurrency:t.concurrency,autoStart:!1});const r=i,n=um(i,e);return s.add((async()=>{r.start(),await r.onIdle().then((()=>{i===r&&(i=null)}))})),n},writeLock:async e=>(i=null,um(s,e)),finalize(){am.delete(e)},queue:s},am.set(e,r),!0===t.autoFinalize&&s.addEventListener("idle",(()=>{r.finalize()}),{once:!0}),r})(t.name,t)}var pm,fm,gm;function mm(e,t){if(null!=e.publicKey||null==t.publicKey)return e;let r;return"RSA"===e.type&&(r=e.toMultihash()),Rc(Sc(t.publicKey,r))}function ym(e,t,r){const n=new Map,s=BigInt(Date.now());for(const[e,r]of t.tags.entries())null!=r.expiry&&r.expiry<s||n.set(e,r);return{...t,id:mm(e,t),addresses:t.addresses.filter((({observed:e})=>null!=e&&e>Date.now()-r)).map((({multiaddr:e,isCertified:t})=>({multiaddr:bl(e),isCertified:t??!1}))),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}function bm(e,t){return vm(e.addresses,t.addresses,((e,t)=>e.isCertified===t.isCertified&&!!Ds(e.multiaddr,t.multiaddr)))&&vm(e.protocols,t.protocols,((e,t)=>e===t))&&wm(e.publicKey,t.publicKey)&&wm(e.peerRecordEnvelope,t.peerRecordEnvelope)&&Em(e.metadata,t.metadata,((e,t)=>Ds(e,t)))&&function(e,t){return Em(e,t,((e,t)=>e.value===t.value&&e.expiry===t.expiry))}(e.tags,t.tags)}function wm(e,t){return null==e&&null==t||null!=e&&null!=t&&Ds(e,t)}function vm(e,t,r){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!r(e[n],t[n]))return!1;return!0}function Em(e,t,r){if(e.size!==t.size)return!1;for(const[n,s]of e.entries()){const e=t.get(n);if(null==e)return!1;if(!r(s,e))return!1}return!0}(e=>{let t;(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={key:"",value:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&(t.uint32(18),gm.codec().encode(e.value,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={key:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.key=e.string();break;case 2:n.value=gm.codec().decode(e,e.uint32(),{limits:r.limits?.value});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==t&&(t=Wt(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.addresses)for(const e of t.addresses)r.uint32(10),fm.codec().encode(e,r);if(null!=t.protocols)for(const e of t.protocols)r.uint32(18),r.string(e);if(null!=t.publicKey&&(r.uint32(34),r.bytes(t.publicKey)),null!=t.peerRecordEnvelope&&(r.uint32(42),r.bytes(t.peerRecordEnvelope)),null!=t.metadata&&0!==t.metadata.size)for(const[n,s]of t.metadata.entries())r.uint32(50),e.Peer$metadataEntry.codec().encode({key:n,value:s},r);if(null!=t.tags&&0!==t.tags.size)for(const[n,s]of t.tags.entries())r.uint32(58),e.Peer$tagsEntry.codec().encode({key:n,value:s},r);null!=t.updated&&(r.uint32(64),r.uint64Number(t.updated)),!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={addresses:[],protocols:[],metadata:new Map,tags:new Map},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:if(null!=n.limits?.addresses&&s.addresses.length===n.limits.addresses)throw new Xt('Decode error - map field "addresses" had too many elements');s.addresses.push(fm.codec().decode(t,t.uint32(),{limits:n.limits?.addresses$}));break;case 2:if(null!=n.limits?.protocols&&s.protocols.length===n.limits.protocols)throw new Xt('Decode error - map field "protocols" had too many elements');s.protocols.push(t.string());break;case 4:s.publicKey=t.bytes();break;case 5:s.peerRecordEnvelope=t.bytes();break;case 6:{if(null!=n.limits?.metadata&&s.metadata.size===n.limits.metadata)throw new Zt('Decode error - map field "metadata" had too many elements');const r=e.Peer$metadataEntry.codec().decode(t,t.uint32());s.metadata.set(r.key,r.value);break}case 7:{if(null!=n.limits?.tags&&s.tags.size===n.limits.tags)throw new Zt('Decode error - map field "tags" had too many elements');const r=e.Peer$tagsEntry.codec().decode(t,t.uint32(),{limits:{value:n.limits?.tags$value}});s.tags.set(r.key,r.value);break}case 8:s.updated=t.uint64Number();break;default:t.skipType(7&r)}}return s}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(pm||(pm={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),null!=e.isCertified&&(t.uint32(16),t.bool(e.isCertified)),null!=e.observed&&(t.uint32(24),t.uint64Number(e.observed)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={multiaddr:o(0)},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.multiaddr=e.bytes();break;case 2:r.isCertified=e.bool();break;case 3:r.observed=e.uint64Number();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(fm||(fm={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.value&&0!==e.value&&(t.uint32(8),t.uint32(e.value)),null!=e.expiry&&(t.uint32(16),t.uint64(e.expiry)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={value:0},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.value=e.uint32();break;case 2:r.expiry=e.uint64();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(gm||(gm={}));const Sm="/",Am=(new TextEncoder).encode(Sm),Im=Am[0];class _m{_buf;constructor(e,t){if("string"==typeof e)this._buf=Ye(e);else{if(!(e instanceof Uint8Array))throw Error("Invalid key, should be String of Uint8Array");this._buf=e}if(null==t&&(t=!0),t&&this.clean(),0===this._buf.byteLength||this._buf[0]!==Im)throw Error("Invalid key")}toString(e="utf8"){return tn(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new _m(e.join(Sm))}static random(){return new _m(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new _m(e):"function"==typeof e.uint8Array?new _m(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Am),this._buf[0]!==Im){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Im,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Im;)this._buf=this._buf.subarray(0,-1)}less(e){const t=this.list(),r=e.list();for(let e=0;e<t.length;e++){if(r.length<e+1)return!1;const n=t[e],s=r[e];if(n<s)return!0;if(n>s)return!1}return t.length<r.length}reverse(){return _m.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Sm).slice(1)}type(){return function(e){const t=e.split(":");return t.length<2?"":t.slice(0,-1).join(":")}(this.baseNamespace())}name(){return function(e){const t=e.split(":");return t[t.length-1]}(this.baseNamespace())}instance(e){return new _m(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Sm)||(e+=Sm),e+=this.type(),new _m(e)}parent(){const e=this.list();return 1===e.length?new _m(Sm):new _m(e.slice(0,-1).join(Sm))}child(e){return this.toString()===Sm?e:e.toString()===Sm?this:new _m(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()!==this.toString()&&e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()!==this.toString()&&this.toString().startsWith(e.toString())}isTopLevel(){return 1===this.list().length}concat(...e){var t;return _m.withNamespaces([...this.namespaces(),...(t=e.map((e=>e.namespaces())),[].concat(...t))])}}const Cm="/peers/";function xm(e){if(!Sn(e)||null==e.type)throw new Pn("Invalid PeerId");const t=e.toCID().toString();return new _m(`${Cm}${t}`)}async function km(e,t,r,n,s){const i=new Map;for(const n of r){if(null==n)continue;if(n.multiaddr instanceof Uint8Array&&(n.multiaddr=bl(n.multiaddr)),!yl(n.multiaddr))throw new Pn("Multiaddr was invalid");if(!await t(e,n.multiaddr,s))continue;const r=n.isCertified??!1,o=n.multiaddr.toString(),a=i.get(o);null!=a?n.isCertified=a.isCertified||r:i.set(o,{multiaddr:n.multiaddr,isCertified:r})}return[...i.values()].sort(((e,t)=>e.multiaddr.toString().localeCompare(t.multiaddr.toString()))).map((({isCertified:t,multiaddr:r})=>{const n=r.getPeerId();return e.equals(n)&&(r=r.decapsulate(bl("/p2p/"+e))),{isCertified:t,multiaddr:r.bytes}}))}async function Tm(e,t,r,n){if(null==t)throw new Pn("Invalid PeerData");if(null!=t.publicKey&&null!=e.publicKey&&!t.publicKey.equals(e.publicKey))throw new Pn("publicKey bytes do not match peer id publicKey bytes");const s=n.existingPeer?.peer;if(null!=s&&!e.equals(s.id))throw new Pn("peer id did not match existing peer id");let i,o=s?.addresses??[],a=new Set(s?.protocols??[]),c=s?.metadata??new Map,l=s?.tags??new Map,u=s?.peerRecordEnvelope;if("patch"===r&&(null==t.multiaddrs&&null==t.addresses||(o=[],null!=t.multiaddrs&&o.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&o.push(...t.addresses)),null!=t.protocols&&(a=new Set(t.protocols)),null!=t.metadata&&(c=Pm(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:Rm})),null!=t.tags&&(l=Pm(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:Lm,map:Dm})),null!=t.peerRecordEnvelope&&(u=t.peerRecordEnvelope)),"merge"===r){if(null!=t.multiaddrs&&o.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&o.push(...t.addresses),null!=t.protocols&&(a=new Set([...a,...t.protocols])),null!=t.metadata){const e=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(const[t,r]of e)null==r?c.delete(t):c.set(t,r);c=Pm([...c.entries()],{validate:Rm})}if(null!=t.tags){const e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),r=new Map(l);for(const[t,n]of e)null==n?r.delete(t):r.set(t,n);l=Pm([...r.entries()],{validate:Lm,map:Dm})}null!=t.peerRecordEnvelope&&(u=t.peerRecordEnvelope)}null!=s?.id.publicKey?i=Ac(s.id.publicKey):null!=t.publicKey?i=Ac(t.publicKey):null!=e.publicKey&&(i=Ac(e.publicKey));const h={addresses:await km(e,n.addressFilter??(async()=>!0),o,n.existingPeer?.peerPB.addresses,n),protocols:[...a.values()].sort(((e,t)=>e.localeCompare(t))),metadata:c,tags:l,publicKey:i,peerRecordEnvelope:u};return h.addresses.forEach((e=>{e.observed=n.existingPeer?.peerPB.addresses?.find((e=>Ds(e.multiaddr,e.multiaddr)))?.observed??Date.now()})),"RSA"!==e.type&&delete h.publicKey,h}function Pm(e,t){const r=new Map;for(const[r,n]of e)null!=n&&t.validate(r,n);for(const[n,s]of e.sort((([e],[t])=>e.localeCompare(t))))null!=s&&r.set(n,t.map?.(n,s)??s);return r}function Rm(e,t){if("string"!=typeof e)throw new Pn("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new Pn("Metadata value must be a Uint8Array")}function Lm(e,t){if("string"!=typeof e)throw new Pn("Tag name must be a string");if(null!=t.value){if(parseInt(""+t.value,10)!==t.value)throw new Pn("Tag value must be an integer");if(t.value<0||t.value>100)throw new Pn("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt(""+t.ttl,10)!==t.ttl)throw new Pn("Tag ttl must be an integer");if(t.ttl<0)throw new Pn("Tag ttl must be between greater than 0")}}function Dm(e,t){let r;null!=t.expiry&&(r=t.expiry),null!=t.ttl&&(r=BigInt(Date.now()+Number(t.ttl)));const n={value:t.value??0};return null!=r&&(n.expiry=r),n}function Mm(e){const t=e.toString().split("/")[2];return Dc(qe.parse(t,te))}function Nm(e,t,r){return function(e,t,r){return ym(e,pm.decode(t),r)}(Mm(e),t,r)}class Om{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=function(e){const{name:t,metrics:r}=e;let n;return n=null!=r?new Ug({name:t,metrics:r}):new Ag,n}({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return null==t&&(t={refs:0,lock:dm({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,0===t.refs&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){const r=this.getLock(e);try{const n=await r.lock.readLock(t);return()=>{n(),this.maybeRemoveLock(e,r)}}catch(t){throw this.maybeRemoveLock(e,r),t}}async getWriteLock(e,t){const r=this.getLock(e);try{const n=await r.lock.writeLock(t);return()=>{n(),this.maybeRemoveLock(e,r)}}catch(t){throw this.maybeRemoveLock(e,r),t}}async has(e,t){try{return await this.load(e,t),!0}catch(e){if("NotFoundError"!==e.name)throw e}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(xm(e),t)}async load(e,t){const r=xm(e),n=await this.datastore.get(r,t),s=pm.decode(n);if(this.#P(e,s))throw await this.datastore.delete(r,t),new Fn;return ym(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,r){const n=await this.#R(e,r),s=await Tm(e,t,"patch",{...r,addressFilter:this.addressFilter});return this.#L(e,s,n)}async patch(e,t,r){const n=await this.#R(e,r),s=await Tm(e,t,"patch",{...r,addressFilter:this.addressFilter,existingPeer:n});return this.#L(e,s,n)}async merge(e,t,r){const n=await this.#R(e,r),s=await Tm(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#L(e,s,n)}async*all(e){for await(const{key:t,value:r}of this.datastore.query(function(e,t){return{prefix:Cm,filters:(e.filters??[]).map((e=>({key:r,value:n})=>e(Nm(r,n,t)))),orders:(e.orders??[]).map((e=>(r,n)=>e(Nm(r.key,r.value,t),Nm(n.key,n.value,t))))}}(e??{},this.maxAddressAge),e)){const n=Mm(t);if(n.equals(this.peerId))continue;const s=pm.decode(r);this.#P(n,s)?await this.datastore.delete(t,e):yield ym(n,s,this.peerId.equals(n)?1/0:this.maxAddressAge)}}async#R(e,t){try{const r=xm(e),n=await this.datastore.get(r,t),s=pm.decode(n);if(this.#P(e,s))throw await this.datastore.delete(r,t),new Fn;return{peerPB:s,peer:ym(e,s,this.maxAddressAge)}}catch(e){"NotFoundError"!==e.name&&this.log.error("invalid peer data found in peer store - %e",e)}}async#L(e,t,r,n){t.updated=Date.now();const s=pm.encode(t);return await this.datastore.put(xm(e),s,n),{peer:ym(e,t,this.maxAddressAge),previous:r?.peer,updated:null==r||!bm(t,r.peerPB)}}#P(e,t){if(null==t.updated)return!0;if(this.peerId.equals(e))return!1;const r=t.updated<Date.now()-this.maxPeerAge,n=Date.now()-this.maxAddressAge,s=t.addresses.filter((e=>null!=e.observed&&e.observed>n));return r&&0===s.length}}class Um{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Om(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(const r of this.store.all(t))e(r)}async all(e){return Rs(this.store.all(e))}async delete(e,t){const r=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{r()}}async has(e,t){const r=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),r?.()}}async get(e,t){const r=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{r?.()}}async getInfo(e,t){const r=await this.get(e,t);return{id:r.id,multiaddrs:r.addresses.map((({multiaddr:e})=>e))}}async save(e,t,r){await this.store.getWriteLock(e,r);try{const n=await this.store.save(e,t,r);return this.#D(e,n),n.peer}finally{n?.()}}async patch(e,t,r){await this.store.getWriteLock(e,r);try{const n=await this.store.patch(e,t,r);return this.#D(e,n),n.peer}finally{n?.()}}async merge(e,t,r){await this.store.getWriteLock(e,r);try{const n=await this.store.merge(e,t,r);return this.#D(e,n),n.peer}finally{n?.()}}async consumePeerRecord(e,t,r){const n=Sn(t)?t:Sn(t?.expectedPeer)?t.expectedPeer:void 0,s=Sn(t)||void 0===t?r:t,i=await md.openAndCertify(e,vd.DOMAIN,s),o=Dc(i.publicKey.toCID());if(!1===n?.equals(o))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",n,o),!1;const a=vd.createFromProtobuf(i.payload);let c;try{c=await this.get(o,s)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=c?.peerRecordEnvelope){const e=md.createFromProtobuf(c.peerRecordEnvelope),t=vd.createFromProtobuf(e.payload);if(t.seqNumber>=a.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,a.seqNumber),!1}return await this.patch(a.peerId,{peerRecordEnvelope:e,addresses:a.multiaddrs.map((e=>({isCertified:!0,multiaddr:e})))},s),!0}#D(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}}class Fm extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=Fm.name;code=Fm.code;constructor(e="Not Found"){super(e)}}function Bm(e,t){let r=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(const n of e)await t(n,r++)&&(yield n)}();const n=function(e){const[t,r]=null!=e[Symbol.asyncIterator]?[e[Symbol.asyncIterator](),Symbol.asyncIterator]:[e[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push(e){n.push(e)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[r](){return this}}}(e),{value:s,done:i}=n.next();if(!0===i)return function*(){}();const o=t(s,r++);if("function"==typeof o.then)return async function*(){await o&&(yield s);for await(const e of n)await t(e,r++)&&(yield e)}();const a=t;return function*(){!0===o&&(yield s);for(const e of n)a(e,r++)&&(yield e)}()}function $m(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const r=await Rs(e);yield*r.sort(t)}():function*(){const r=Rs(e);yield*r.sort(t)}()}function qm(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let r=0;if(!(t<1))for await(const n of e)if(yield n,r++,r===t)return}():function*(){let r=0;if(!(t<1))for(const n of e)if(yield n,r++,r===t)return}()}class zm{put(e,t,r){return Promise.reject(Error(".put is not implemented"))}get(e,t){return Promise.reject(Error(".get is not implemented"))}has(e,t){return Promise.reject(Error(".has is not implemented"))}delete(e,t){return Promise.reject(Error(".delete is not implemented"))}async*putMany(e,t={}){for await(const{key:r,value:n}of e)await this.put(r,n,t),yield r}async*getMany(e,t={}){for await(const r of e)yield{key:r,value:await this.get(r,t)}}async*deleteMany(e,t={}){for await(const r of e)await this.delete(r,t),yield r}batch(){let e=[],t=[];return{put(t,r){e.push({key:t,value:r})},delete(e){t.push(e)},commit:async r=>{await Sd(this.putMany(e,r)),e=[],await Sd(this.deleteMany(t,r)),t=[]}}}async*_all(e,t){throw Error("._all is not implemented")}async*_allKeys(e,t){throw Error("._allKeys is not implemented")}query(e,t){let r=this._all(e,t);if(null!=e.prefix){const t=e.prefix;r=Bm(r,(e=>e.key.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>Bm(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>$m(e,t)),r)),null!=e.offset){let t=0;const n=e.offset;r=Bm(r,(()=>t++>=n))}return null!=e.limit&&(r=qm(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;r=Bm(r,(e=>e.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>Bm(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>$m(e,t)),r)),null!=e.offset){const t=e.offset;let n=0;r=Bm(r,(()=>n++>=t))}return null!=e.limit&&(r=qm(r,e.limit)),r}}class jm extends zm{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){const t=this.data.get(e.toString());if(null==t)throw new Fm;return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(const[e,t]of this.data.entries())yield{key:new _m(e),value:t}}*_allKeys(){for(const e of this.data.keys())yield new _m(e)}}class Km extends Map{metric;constructor(e){super();const{name:t,metrics:r}=e;this.metric=r.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function Vm(e){const{name:t,metrics:r}=e;let n;return n=null!=r?new Km({name:t,metrics:r}):new Map,n}const Hm=864e13;class Gm{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Vm({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){const t=this.findHost(e);for(const e of this.mappings.values())if(e.domain===t)return!0;return!1}add(e,t){t.forEach((t=>{this.log("add DNS mapping %s to %s",t,e);const r=!0===Dd(t);this.mappings.set(t,{domain:e,verified:r,expires:r?Hm-Date.now():0,lastVerified:r?Hm-Date.now():void 0})}))}remove(e){const t=this.findHost(e);let r=!1;for(const[e,n]of this.mappings.entries())n.domain===t&&(this.log("removing %s to %s DNS mapping %e",e,n.domain,Error("where")),this.mappings.delete(e),r=r||n.verified);return r}getAll(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r].multiaddr.stringTuples(),s=n[0][1];if(null!=s)for(const[i,o]of this.mappings.entries())s===i&&this.maybeAddSNITuple(n,o.domain)&&(e.splice(r,1),r--,t.push({multiaddr:bl("/"+n.map((e=>[wl(e[0]).name,e[1]].join("/"))).join("/")),verified:o.verified,type:"dns-mapping",expires:o.expires,lastVerified:o.lastVerified}))}return t}maybeAddSNITuple(e,t){for(let r=0;r<e.length;r++)if(448===e[r][0]&&449!==e[r+1]?.[0])return e.splice(r+1,0,[449,t]),!0;return!1}confirm(e,t){const r=this.findHost(e);let n=!1;for(const[e,s]of this.mappings.entries())s.domain===r&&(this.log("marking %s to %s DNS mapping as verified",e,s.domain),n=s.verified,s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now());return n}unconfirm(e,t){const r=this.findHost(e);let n=!1;for(const[e,s]of this.mappings.entries())s.domain===r&&(this.log("removing verification of %s to %s DNS mapping",e,s.domain),n=n||s.verified,s.verified=!1,s.expires=Date.now()+t);return n}findHost(e){for(const t of e.stringTuples()){if(449===t[0])return t[1];if(53===t[0]||54===t[0]||55===t[0]||56===t[0])return t[1]}}}class Wm{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Vm({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){const t=e.stringTuples();for(const e of this.mappings.values())for(const r of e)if(r.externalIp===t[0][1])return!0;return!1}add(e,t,r,n=t,s="tcp"){const i=`${e}-${t}-${s}`,o=this.mappings.get(i)??[],a={internalIp:e,internalPort:t,externalIp:r,externalPort:n,externalFamily:zc(r)?4:6,protocol:s,verified:!1,expires:0};o.push(a),this.mappings.set(i,o)}remove(e){const t=e.stringTuples(),r=t[0][1]??"",n=6===t[1][0]?"tcp":"udp",s=parseInt(t[1][1]??"0");let i=!1;for(const[e,t]of this.mappings.entries()){for(let e=0;e<t.length;e++){const o=t[e];o.externalIp===r&&o.externalPort===s&&o.protocol===n&&(this.log("removing %s:%s to %s:%s %s IP mapping",o.externalIp,o.externalPort,r,s,n),i=i||o.verified,t.splice(e,1),e--)}0===t.length&&this.mappings.delete(e)}return i}getAll(e){const t=[];for(const{multiaddr:r}of e){const e=r.stringTuples();let n;if(4!==e[0][0]&&41!==e[0][0]||6!==e[1][0]?4!==e[0][0]&&41!==e[0][0]||273!==e[1][0]||(n=`${e[0][1]}-${e[1][1]}-udp`):n=`${e[0][1]}-${e[1][1]}-tcp`,null==n)continue;const s=this.mappings.get(n);if(null!=s)for(const r of s)e[0][0]=4===r.externalFamily?4:41,e[0][1]=r.externalIp,e[1][1]=""+r.externalPort,t.push({multiaddr:bl("/"+e.map((e=>[wl(e[0]).name,e[1]].join("/"))).join("/")),verified:r.verified,type:"ip-mapping",expires:r.expires,lastVerified:r.lastVerified})}return t}confirm(e,t){const r=e.stringTuples()[0][1];let n=!1;for(const e of this.mappings.values())for(const s of e)s.externalIp===r&&(this.log("marking %s to %s IP mapping as verified",s.internalIp,s.externalIp),n=s.verified,s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now());return n}unconfirm(e,t){const r=e.stringTuples(),n=r[0][1]??"",s=6===r[1][0]?"tcp":"udp",i=parseInt(r[1][1]??"0");let o=!1;for(const e of this.mappings.values())for(let r=0;r<e.length;r++){const a=e[r];a.externalIp===n&&a.externalPort===i&&a.protocol===s&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n,i,s),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}}class Xm{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Vm({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(const t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Nd(e)||function(e){try{for(const{code:t,value:r}of e.getComponents())if(t!==Vc&&null!=r){if(4===t)return r.startsWith("169.254.");if(t===Kc)return r.toLowerCase().startsWith("fe80")}}catch{}return!1}(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map((([e,t])=>({multiaddr:bl(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified})))}remove(e){const t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){const r=e.toString(),n=this.addresses.get(r)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=n.verified;return n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now(),this.log("marking observed address %a as verified",r),this.addresses.set(r,n),s}}const Zm=[4,Kc,53,54,55,56];function Ym(e){try{for(const{code:t}of e.getComponents())if(t!==Vc)return Zm.includes(t)}catch{}return!1}class Qm{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Vm({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}get(e,t){if(Nd(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};const r=this.toKey(e);let n=this.addresses.get(r);return null==n&&(n={verified:!Ym(e),expires:0},this.addresses.set(r,n)),{multiaddr:e,verified:n.verified,type:"transport",expires:n.expires,lastVerified:n.lastVerified}}has(e){const t=this.toKey(e);return this.addresses.has(t)}remove(e){const t=this.toKey(e),r=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),r}confirm(e,t){const r=this.toKey(e),n=this.addresses.get(r)??{verified:!1,expires:0,lastVerified:0},s=n.verified;return n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now(),this.addresses.set(r,n),s}unconfirm(e,t){const r=this.toKey(e),n=this.addresses.get(r)??{verified:!1,expires:0},s=n.verified;return n.verified=!1,n.expires=Date.now()+t,this.addresses.set(r,n),s}toKey(e){if(Ym(e)){const t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}return e.toString()}}const Jm=e=>e;function ey(e,t){const r=e.getPeerId();return null!=r&&Pc(r).equals(t)&&(e=e.decapsulate(bl("/p2p/"+t.toString()))),e}class ty{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){const{listen:r=[],announce:n=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=r.map((e=>e.toString())),this.announce=new Set(n.map((e=>e.toString()))),this.appendAnnounce=new Set(s.map((e=>e.toString()))),this.observed=new Xm(e,t),this.dnsMappings=new Gm(e,t),this.ipMappings=new Wm(e,t),this.transportAddresses=new Qm(e,t),this.announceFilter=t.announceFilter??Jm,this.observedAddressFilter=Og(1024),this.addressVerificationTTL=t.addressVerificationTTL??6e5,this.addressVerificationRetry=t.addressVerificationRetry??3e5,this._updatePeerStoreAddresses=Ed(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",(()=>{this._updatePeerStoreAddresses()})),e.events.addEventListener("transport:close",(()=>{this._updatePeerStoreAddresses()}))}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){const e=this.getAddresses().map((e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate("/p2p/"+this.components.peerId.toString()):e));this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch((e=>{this.log.error("error updating addresses",e)}))}getListenAddrs(){return Array.from(this.listen).map((e=>bl(e)))}getAnnounceAddrs(){return Array.from(this.announce).map((e=>bl(e)))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map((e=>bl(e)))}getObservedAddrs(){return this.observed.getAll().map((e=>e.multiaddr))}addObservedAddr(e){const t=e.stringTuples(),r=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(r)||(this.observedAddressFilter.add(r),e=ey(e,this.components.peerId),this.ipMappings.has(e)||this.dnsMappings.has(e)||this.observed.add(e))}confirmObservedAddr(e,t){e=ey(e,this.components.peerId);let r=!0;("transport"===t?.type||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1),("dns-mapping"===t?.type||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1),("ip-mapping"===t?.type||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1),("observed"===t?.type||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),r=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1)),r||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=ey(e,this.components.peerId),this.observed.has(e)&&this.observed.remove(e),this.transportAddresses.has(e)&&this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry),this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry),this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)}getAddresses(){const e=new Set,t=this.getAddressesWithMetadata().filter((t=>{if(!t.verified)return!1;const r=t.multiaddr.toString();return!e.has(r)&&(e.add(r),!0)})).map((e=>e.multiaddr));return this.announceFilter(t.map((e=>{const t=bl(e);return t.getComponents().pop()?.value===this.components.peerId.toString()?t:t.encapsulate("/p2p/"+this.components.peerId.toString())})))}getAddressesWithMetadata(){const e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach((t=>{t.updateAnnounceAddrs(e)})),e.map((e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})));let t=[];t=t.concat(this.components.transportManager.getAddrs().map((e=>this.transportAddresses.get(e,this.addressVerificationTTL))));const r=this.getAppendAnnounceAddrs();return r.length>0&&(this.components.transportManager.getListeners().forEach((e=>{e.updateAnnounceAddrs(r)})),t=t.concat(r.map((e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}))))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(bl("/dns/"+e))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,r,n=t,s="tcp"){this.ipMappings.add(e,t,r,n,s),this.observed.removePrefixed(`/ip${zc(r)?4:6}/${r}/${s}/${n}`)}removePublicAddressMapping(e,t,r,n=t,s="tcp"){this.ipMappings.remove(bl(`/ip${zc(r)?4:6}/${r}/${s}/${n}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;const t=e.toOptions();if(6===t.family||"127.0.0.1"===t.host||!0===Dd(t.host))return!1;const r=this.components.transportManager.getListeners(),n=[e=>pp.exactMatch(e)||gp.exactMatch(e),e=>op.exactMatch(e),e=>up.exactMatch(e)];for(const s of n){if(!s(e))continue;const n=r.filter((e=>e.getAddrs().filter((e=>4===e.toOptions().family&&s(e))).length>0));if(1!==n.length)continue;const i=n[0].getAddrs().filter((e=>"127.0.0.1"!==e.toOptions().host)).pop();if(null==i)continue;const o=i.toOptions();return this.observed.remove(e),this.ipMappings.add(o.host,o.port,t.host,t.port,t.transport),!0}return!1}}var ry;(e=>{e.NOT_STARTED_YET="The libp2p node is not started yet",e.NOT_FOUND="Not found"})(ry||(ry={}));class ny extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}}class sy extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}}class iy extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}}class oy extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}}class ay extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}}class cy extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}}class ly extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}}class uy extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}}class hy extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}}class dy extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}}class py extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}}class fy extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}}class gy extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}}class my extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}}class yy extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}}class by extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}}class wy{components={};_started=!1;constructor(e={}){this.components={};for(const[t,r]of Object.entries(e))this.components[t]=r;null==this.components.logger&&(this.components.logger=bg())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter((e=>es(e))).map((async t=>{await(t[e]?.())})))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}}const vy=["metrics","connectionProtector","dns"],Ey=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Sy(e){return Array.isArray(e?.[ts])?e[ts]:[]}function Ay(e){return Array.isArray(e?.[rs])?e[rs]:[]}function Iy(e){return e?.[Symbol.toStringTag]??e?.toString()??"unknown"}function _y(e={}){return{denyDialPeer:async()=>!1,async denyDialMultiaddr(e){if(pp.matches(e))return!1;const t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&!!Dd(""+t[0][1])},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...e}}function Cy(e){if(Sn(e))return{peerId:e,multiaddrs:[]};let t,r=Array.isArray(e)?e:[e];if(r.length>0){const e=r[0].getPeerId();t=null==e?void 0:Pc(e),r.forEach((e=>{if(!yl(e))throw new $n("Invalid multiaddr");const r=e.getPeerId();if(null==r){if(null!=t)throw new Pn("Multiaddrs must all have the same peer id or have no peer id")}else{const e=Pc(r);if(!0!==t?.equals(e))throw new Pn("Multiaddrs must all have the same peer id or have no peer id")}}))}return r=r.filter((e=>!Hd.exactMatch(e))),{peerId:t,multiaddrs:r}}const xy=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function ky(e){try{let t;if(t="string"==typeof e?bl(e):e,!t.protoNames().includes("ipcidr")){const e=t.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(e)}return function(e){let t,r;if(e.getComponents().forEach((e=>{"ip4"!==e.name&&"ip6"!==e.name||(r=e.value),"ipcidr"===e.name&&(t=e.value)})),null==t||null==r)throw Error("Invalid multiaddr");return new pl(r,t)}(t)}catch(t){throw Error("Can't convert to IpNet, Invalid multiaddr format: "+e)}}class Ty{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map((e=>ky(e))),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch((e=>{this.log.error("error while pruning connections %e",e)}))}async _maybePruneConnections(){const e=this.connectionManager.getConnections(),t=e.length,r=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,r),t<=r)return;const n=new Ag;for(const t of e){const r=t.remotePeer;if(!n.has(r)){n.set(r,0);try{const e=await this.peerStore.get(r);n.set(r,[...e.tags.values()].reduce(((e,t)=>e+t.value),0))}catch(e){"NotFoundError"!==e.name&&this.log.error("error loading peer tags",e)}}}const s=this.sortConnections(e,n),i=Math.max(t-r,0),o=[];for(const e of s)if(this.log("too many connections open - closing a connection to %p",e.remotePeer),this.allow.some((t=>t.contains(e.remoteAddr.nodeAddress().address)))||o.push(e),o.length===i)break;await Promise.all(o.map((async e=>{await async function(e,t){const r=e?.streams?.map((e=>e.protocol))??[],n=t?.closableProtocols??xy;if(!(r.filter((e=>null!=e&&!n.includes(e))).length>0))try{await(e?.close(t))}catch(t){e?.abort(t)}}(e,{signal:AbortSignal.timeout(1e3)})}))),this.events.safeDispatchEvent("connection:prune",{detail:o})}sortConnections(e,t){return e.sort(((e,t)=>{const r=e.timeline.open,n=t.timeline.open;return r<n?1:r>n?-1:0})).sort(((e,t)=>"outbound"===e.direction&&"inbound"===t.direction?1:"inbound"===e.direction&&"outbound"===t.direction?-1:0)).sort(((e,t)=>e.streams.length>t.streams.length?1:e.streams.length<t.streams.length?-1:0)).sort(((e,r)=>{const n=t.get(e.remotePeer)??0,s=t.get(r.remotePeer)??0;return n>s?1:n<s?-1:0}))}}class Py{deferred;signal;constructor(e){this.signal=e,this.deferred=Ws(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new xn)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Ry{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(1e9*Math.random()+"",10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce(((e,t)=>e&&!0===t.signal?.aborted),!0)&&(this.controller.abort(new xn),this.cleanup())}async join(e={}){const t=new Py(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await ei(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach((t=>{t.deferred.resolve(e)})),this.status="complete"}catch(e){this.recipients.forEach((t=>{t.deferred.reject(e)})),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach((e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}))}}class Ly extends Jn{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??1/0,this.maxSize=e.maxSize??1/0,this.pending=0,null!=e.metricName&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Ed(this.emitEmpty.bind(this),1),this.emitIdle=Ed(this.emitIdle.bind(this),1)}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally((()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")})),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Pp;const r=new Ry(e,t);return this.enqueue(r),this.safeDispatchEvent("add"),this.tryToStartAnother(),r.join(t).then((e=>(this.safeDispatchEvent("completed",{detail:e}),this.safeDispatchEvent("success",{detail:{job:r,result:e}}),e))).catch((e=>{if("queued"===r.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===r){this.queue.splice(e,1);break}throw this.safeDispatchEvent("failure",{detail:{job:r,error:e}}),e}))}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new xn)})),this.clear()}async onEmpty(e){0!==this.size&&await Bg(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Bg(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await Bg(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();const t=Qs({objectMode:!0}),r=e=>{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail)},s=e=>{r(e.detail.error)},i=()=>{r()},o=()=>{r(new xn("Queue aborted"))};this.addEventListener("completed",n),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",o),r()}}}class Dy extends Ly{constructor(e={}){super({...e,sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0})}}function My(e){const t=new globalThis.AbortController;function r(){t.abort();for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",r)}for(const t of e){if(!0===t?.aborted){r();break}null!=t?.addEventListener&&t.addEventListener("abort",r)}const n=t.signal;return n.clear=function(){for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",r)},n}function Ny(e){if(!Md(e))return!1;const{address:t}=e.nodeAddress();var r;return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r=t)||/^::1$/.test(r)}function Oy(e,t){const r=op.exactMatch(e.multiaddr),n=op.exactMatch(t.multiaddr);if(r&&!n)return-1;if(!r&&n)return 1;const s=gp.exactMatch(e.multiaddr),i=gp.exactMatch(t.multiaddr);if(s&&!i)return-1;if(!s&&i)return 1;const o=pp.exactMatch(e.multiaddr),a=pp.exactMatch(t.multiaddr);if(o&&!a)return-1;if(!o&&a)return 1;const c=Sp.exactMatch(e.multiaddr),l=Sp.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;const u=yp.exactMatch(e.multiaddr),h=yp.exactMatch(t.multiaddr);if(u&&!h)return-1;if(!u&&h)return 1;const d=wp.exactMatch(e.multiaddr),p=wp.exactMatch(t.multiaddr);return d&&!p?-1:!d&&p?1:0}function Uy(e,t){const r=Ny(e.multiaddr),n=Ny(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function Fy(e,t){const r=Nd(e.multiaddr),n=Nd(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function By(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function $y(e,t){const r=Ep.exactMatch(e.multiaddr),n=Ep.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}class qy{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??25,this.maxDialQueueLength=t.maxDialQueueLength??500,this.dialTimeout=t.dialTimeout??1e4,this.connections=t.connections??new Ag,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,this.shutDownController.signal;for(const[e,r]of Object.entries(t.resolvers??{}))ml.set(e,r);this.queue=new Dy({concurrency:t.maxParallelDials??50,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",(e=>{e.detail?.name!==xn.name&&this.log.error("error in dial queue - %e",e.detail)}))}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){const{peerId:r,multiaddrs:n}=Cy(e),s=Array.from(this.connections.values()).flat().find((e=>!0!==t.force&&(!!e.remotePeer.equals(r)||n.find((t=>t.equals(e.remoteAddr))))));if("open"===s?.status)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new bf("dial-queue:already-connected")),s;const i=this.queue.queue.find((e=>{if(!0===r?.equals(e.options.peerId))return!0;const t=e.options.multiaddrs;if(null==t)return!1;for(const e of n)if(t.has(e.toString()))return!0;return!1}));if(null!=i){this.log("joining existing dial target for %p",r);for(const e of n)i.options.multiaddrs.add(e.toString());return t.onProgress?.(new bf("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Wn("Dial queue is full");return this.log("creating dial target for %p",r,n.map((e=>e.toString()))),t.onProgress?.(new bf("dial-queue:add-to-dial-queue")),this.queue.add((async e=>{e.onProgress?.(new bf("dial-queue:start-dial"));const t=My([this.shutDownController.signal,e.signal]);try{return await this.dialPeer(e,t)}finally{t.clear()}}),{peerId:r,priority:t.priority??rb,multiaddrs:new Set(n.map((e=>e.toString()))),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){const r=e.peerId,n=e.multiaddrs,s=new Set;let i=0===e.multiaddrs.size,o=0,a=0;const c=[];for(this.log("starting dial to %p",r);i||n.size>0;){a++,i=!1;const l=[],u=new Set(e.multiaddrs);n.clear(),this.log("calculating addrs to dial %p from %s",r,[...u]);const h=await this.calculateMultiaddrs(r,u,{...e,signal:t});for(const e of h)s.has(e.multiaddr.toString())?this.log.trace("skipping previously failed multiaddr %a while dialing %p",e.multiaddr,r):l.push(e);this.log("%s dial to %p with %s",1===a?"starting":"continuing",r,l.map((e=>e.multiaddr.toString()))),e?.onProgress?.(new bf("dial-queue:calculated-addresses",l));for(const n of l){if(o===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",o,e.peerId),new Wn("Peer had more than maxPeerAddrsToDial");o++;try{const s=await this.components.transportManager.dial(n.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",n.multiaddr);try{await this.components.peerStore.merge(s.remotePeer,{multiaddrs:[s.remoteAddr],metadata:{"last-dial-success":Ye(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}return s}catch(e){if(this.log.error("dial failed to %a",n.multiaddr,e),s.add(n.multiaddr.toString()),null!=r)try{await this.components.peerStore.merge(r,{metadata:{"last-dial-failure":Ye(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}if(t.aborted)throw new Hn(e.message);c.push(e)}}}if(1===c.length)throw c[0];throw new AggregateError(c,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,r={}){const n=[...t].map((e=>({multiaddr:bl(e),isCertified:!1})));if(null!=e){if(this.components.peerId.equals(e))throw new Wn("Tried to dial self");if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new uy("The dial request is blocked by gater.allowDialPeer");if(0===n.length){this.log("loading multiaddrs for %p",e);try{const t=await this.components.peerStore.get(e);n.push(...t.addresses),this.log("loaded multiaddrs for %p",e,n.map((({multiaddr:e})=>e.toString())))}catch(e){if("NotFoundError"!==e.name)throw e}}if(0===n.length){this.log("looking up multiaddrs for %p in the peer routing",e);try{const t=await this.components.peerRouting.findPeer(e,r);this.log("found multiaddrs for %p in the peer routing",e,n.map((({multiaddr:e})=>e.toString()))),n.push(...t.multiaddrs.map((e=>({multiaddr:e,isCertified:!1}))))}catch(t){"NoPeerRoutersError"===t.name?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,t)}}}let s=(await Promise.all(n.map((async e=>{const t=await async function(e,t){let r=!1;for(const t of ml.keys())if(r=e.protoNames().includes(t),r)break;if(!r)return[e];const n=await e.resolve(t);return t.log("resolved %s to",e,n.map((e=>e.toString()))),n}(e.multiaddr,{dns:this.components.dns,...r,log:this.log});return 1===t.length&&t[0].equals(e.multiaddr)?e:t.map((e=>({multiaddr:e,isCertified:!1})))})))).flat();if(null!=e){const t="/p2p/"+e.toString();s=s.map((e=>"p2p"!==e.multiaddr.getComponents().pop()?.name?{multiaddr:e.multiaddr.encapsulate(t),isCertified:e.isCertified}:e))}const i=s.filter((t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;const r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)})),o=new Map;for(const e of i){const t=e.multiaddr.toString(),r=o.get(t);null==r?o.set(t,e):r.isCertified=r.isCertified||e.isCertified||!1}const a=[...o.values()];if(0===a.length)throw new py("The dial request has no valid addresses");const c=[];for(const e of a)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||c.push(e);const l=null==this.addressSorter?c.sort(Oy).sort(By).sort($y).sort(Fy).sort(Uy):c.sort(this.addressSorter);if(0===l.length)throw new uy("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map((({multiaddr:e})=>e.toString()))),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map((({multiaddr:e})=>e.toString()))),l}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{const r=await this.calculateMultiaddrs(void 0,new Set(e.map((e=>e.toString()))),t);return!1!==t.runOnLimitedConnection||null!=r.find((e=>!Ep.matches(e.multiaddr)))}catch(e){this.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}}class zy extends Ly{has(e){return null!=this.find(e)}find(e){return this.queue.find((t=>e.equals(t.options.peerId)))}}var jy,Ky,Vy,Hy,Gy,Wy={},Xy=ss(Gy?Hy:(Gy=1,Hy=function(){var e,t;return Vy||(Vy=1,e=Wy,t=function(){if(Ky)return jy;function e(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return Ky=1,jy=e,e.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},e.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},e.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((()=>{n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((()=>{n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),r),this._options.unref&&this._timer.unref(),!0},e.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout((()=>{r._operationTimeoutCb()}),r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},e.prototype.try=function(e){this.attempt(e)},e.prototype.start=function(e){this.attempt(e)},e.prototype.start=e.prototype.try,e.prototype.errors=function(){return this._errors},e.prototype.attempts=function(){return this._attempts},e.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var s=this._errors[n],i=s.message,o=(e[i]||0)+1;e[i]=o,o>=r&&(t=s,r=o)}return t},jy}(),e.operation=r=>{var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw Error("minTimeout is greater than maxTimeout");for(var n=[],s=0;s<t.retries;s++)n.push(this.createTimeout(s,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(s,t)),n.sort(((e,t)=>e-t)),n},e.createTimeout=(e,t)=>{var r=t.randomize?Math.random()+1:1,n=Math.round(r*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return Math.min(n,t.maxTimeout)},e.wrap=function(t,r,n){if(r instanceof Array&&(n=r,r=null),!n)for(var s in n=[],t)"function"==typeof t[s]&&n.push(s);for(var i=0;i<n.length;i++){var o=n[i],a=t[o];t[o]=function(n){var s=e.operation(r),i=[].slice.call(arguments,1),o=i.pop();i.push((function(e){s.retry(e)||(e&&(arguments[0]=s.mainError()),o.apply(this,arguments))})),s.attempt((()=>{n.apply(t,i)}))}.bind(t,a),t[o].options=r}}),Wy}()));const Zy={}.toString,Yy=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);class Qy extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const Jy=(e,t,r)=>{const n=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=n,e};class eb{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new zy({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",(e=>{this.maybeReconnect(e.detail).catch((t=>{this.log.error("failed to maybe reconnect to %p - %e",e.detail,t)}))}))}async maybeReconnect(e){if(!this.started)return;const t=await this.peerStore.get(e);tb(t)&&(this.queue.has(e)||this.queue.add((async t=>{await async function(e,t){return new Promise(((r,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;const s=Xy.operation(t),i=()=>{s.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",i,{once:!0});const o=()=>{t.signal?.removeEventListener("abort",i),s.stop()};s.attempt((async i=>{try{const t=await e(i);o(),r(t)}catch(e){try{if(!(e instanceof Error))throw new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(e instanceof Qy)throw e.originalError;if(e instanceof TypeError&&!function(e){var t;return!(!e||(t=e,"[object Error]"!==Zy.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)&&("Load failed"===e.message?void 0===e.stack:Yy.has(e.message))}(e))throw e;if(Jy(e,i,t),await t.shouldRetry(e)||(s.stop(),n(e)),await t.onFailedAttempt(e),!s.retry(e))throw s.mainError()}catch(e){Jy(e,i,t),o(),n(e)}}}))}))}((async r=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:t?.signal})}catch(t){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,r,this.retries,t),t}}),{signal:t?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})}),{peerId:e}).catch((async r=>{this.log.error("failed to reconnect to %p - %e",e,r);const n={};[...t.tags.keys()].forEach((e=>{e.startsWith(In)&&(n[e]=void 0)})),await this.peerStore.merge(e,{tags:n}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})})).catch((async t=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,t)})))}start(){this.started=!0}async afterStart(){Promise.resolve().then((async()=>{const e=await this.peerStore.all({filters:[e=>tb(e)]});await Promise.all(e.map((async e=>{await this.connectionManager.openConnection(e.id).catch((e=>{this.log.error(e)}))})))})).catch((e=>{this.log.error(e)}))}stop(){this.started=!1,this.queue.abort()}}function tb(e){for(const t of e.tags.keys())if(t.startsWith(In))return!0;return!1}const rb=50;class nb{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??100,this.maxConnections<1)throw new Pn("Connection Manager maxConnections must be greater than 0");this.connections=new Ag,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map((e=>ky(e))),this.deny=(t.deny??[]).map((e=>ky(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??10,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Rp({points:t.inboundConnectionThreshold??5,duration:1}),this.connectionPruner=new Ty({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map((e=>bl(e)))}),this.dialQueue=new qy(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:ig},connections:this.connections}),this.reconnectQueue=new eb({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(const t of this.connections.values())for(const r of t)e[r.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t)for(const t of r.streams){const r=`${t.direction} ${t.protocol??"unnegotiated"}`;e[r]=(e[r]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t){const t={};for(const e of r.streams){const r=`${e.direction} ${e.protocol??"unnegotiated"}`;t[r]=(t[r]??0)+1}for(const[r,n]of Object.entries(t))e[r]=e[r]??[],e[r].push(n)}const t={};for(let[r,n]of Object.entries(e)){n=n.sort(((e,t)=>e-t));const e=Math.floor(.9*n.length);t[r]=n[e]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await async function(...e){const t=[];for(const r of e)es(r)&&t.push(r);await Promise.all(t.map((async e=>{null!=e.beforeStart&&await e.beforeStart()}))),await Promise.all(t.map((async e=>{await e.start()}))),await Promise.all(t.map((async e=>{null!=e.afterStart&&await e.afterStart()})))}(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await async function(...e){const t=[];for(const r of e)es(r)&&t.push(r);await Promise.all(t.map((async e=>{null!=e.beforeStop&&await e.beforeStop()}))),await Promise.all(t.map((async e=>{await e.stop()}))),await Promise.all(t.map((async e=>{null!=e.afterStop&&await e.afterStop()})))}(this.reconnectQueue,this.dialQueue,this.connectionPruner);const e=[];for(const t of this.connections.values())for(const r of t)e.push((async()=>{try{await r.close()}catch(e){this.log.error(e)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new Pn("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch((e=>{this.log.error(e)}))}async _onConnect(e){const{detail:t}=e;if(!this.started)return void await t.close();if("open"!==t.status)return;const r=t.remotePeer,n=!this.connections.has(r),s=this.connections.get(r)??[];s.push(t),this.connections.set(r,s),null!=r.publicKey&&"RSA"===r.type&&await this.peerStore.patch(r,{publicKey:r.publicKey}),n&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){const{detail:t}=e,r=t.remotePeer,n=(this.connections.get(r)??[]).filter((e=>e.id!==t.id));this.connections.set(r,n),0===n.length&&(this.log("onDisconnect remove all connections for peer %p",r),this.connections.delete(r),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(null!=e)return this.connections.get(e)??[];let t=[];for(const e of this.connections.values())t=t.concat(e);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Gn("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();const{peerId:r}=Cy(e);if(this.peerId.equals(r))throw new Bn("Can not dial self");if(null!=r&&!0!==t.force){this.log("dial %p",r);const e=this.getConnections(r).find((e=>null==e.limits));if(null!=e)return this.log("had an existing non-limited connection to %p",r),t.onProgress?.(new bf("dial-queue:already-connected")),e}const n=await this.dialQueue.dial(e,{...t,priority:t.priority??rb});if("open"!==n.status)throw new Dn("Remote closed connection during opening");let s=this.connections.get(n.remotePeer);null==s&&(s=[],this.connections.set(n.remotePeer,s));let i=!1;for(const e of s)if(e.id===n.id&&(i=!0),!0!==t.force&&e.id!==n.id&&e.remoteAddr.equals(n.remoteAddr))return n.abort(new $n("Duplicate multiaddr connection")),e;return i||s.push(n),n}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){const r=this.connections.get(e)??[];await Promise.all(r.map((async e=>{try{await e.close(t)}catch(t){e.abort(t)}})))}async acceptIncomingConnection(e){if(this.deny.some((t=>t.contains(e.remoteAddr.nodeAddress().address))))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some((t=>t.contains(e.remoteAddr.nodeAddress().address))))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){const t=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(t,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,t),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){const e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map((t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map((e=>bl(e)))})))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class sb{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(null!=this.previousTime){const r=this.alpha(t,this.previousTime),n=e-this.movingAverage,s=r*n;this.movingAverage=r*e+(1-r)*this.movingAverage,this.variance=(1-r)*(this.variance+n*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+r*n}else this.movingAverage=e;this.previousTime=t}}class ib{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){const t=e.interval??5e3;this.success=new sb(t),this.failure=new sb(t),this.next=new sb(t),this.failureMultiplier=e.failureMultiplier??2,this.timeoutMultiplier=e.timeoutMultiplier??1.2,this.minTimeout=e.minTimeout??5e3,this.maxTimeout=e.maxTimeout??6e4,null!=e.metricName&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);const r=AbortSignal.timeout(t),n=My([e.signal,r]);return n.start=Date.now(),n.timeout=t,n}cleanUp(e){const t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}}class ob{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??1e4,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??!0,this.timeout=new ib({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[ts]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval((()=>{this.components.connectionManager.getConnections().forEach((e=>{Promise.resolve().then((async()=>{let t=Date.now();try{const r=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),n=Cu(await e.newStream(this.protocol,{signal:r,runOnLimitedConnection:!0}));t=Date.now(),await Promise.all([n.write(Ya(32),{signal:r}),n.read({bytes:32,signal:r})]),e.rtt=Date.now()-t,await n.unwrap().close({signal:r})}catch(r){if("UnsupportedProtocolError"!==r.name)throw r;e.rtt=(Date.now()-t)/2}})).catch((t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")}))}))}),this.pingIntervalMs)}stop(){this.abortController?.abort(),null!=this.heartbeatInterval&&clearInterval(this.heartbeatInterval)}}class ab{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()}),getAttributesFromYieldedValue:(e,t)=>({...t,providers:[...Array.isArray(t.providers)?t.providers:[],e.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([e])=>({key:tn(e,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([e])=>({key:tn(e,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(0===this.routers.length)throw new iy("No content routers available");const r=this,n=new Ig;for await(const s of ni(...r.routers.filter((e=>e.findProviders instanceof Function)).map((r=>r.findProviders(e,t)))))null!=s&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),n.has(s.id)||(n.add(s.id),yield s))}async provide(e,t={}){if(0===this.routers.length)throw new iy("No content routers available");await Promise.all(this.routers.filter((e=>e.provide instanceof Function)).map((async r=>{await r.provide(e,t)})))}async cancelReprovide(e,t={}){if(0===this.routers.length)throw new iy("No content routers available");await Promise.all(this.routers.filter((e=>e.cancelReprovide instanceof Function)).map((async r=>{await r.cancelReprovide(e,t)})))}async put(e,t,r){if(!this.isStarted())throw new Gn;await Promise.all(this.routers.filter((e=>e.put instanceof Function)).map((async n=>{await n.put(e,t,r)})))}async get(e,t){if(!this.isStarted())throw new Gn;return Promise.any(this.routers.filter((e=>e.get instanceof Function)).map((async r=>r.get(e,t))))}}class cb{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,peer:e.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,key:tn(e,"base36")}),getAttributesFromYieldedValue:(e,t)=>({...t,peers:[...Array.isArray(t.peers)?t.peers:[],e.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(0===this.routers.length)throw new oy("No peer routers available");if(e.toString()===this.peerId.toString())throw new ay("Should not try to find self");const r=this,n=ni(...this.routers.filter((e=>e.findPeer instanceof Function)).map((n=>async function*(){try{yield await n.findPeer(e,t)}catch(e){r.log.error(e)}}())));for await(const e of n)if(null!=e)return e.multiaddrs.length>0&&await this.peerStore.merge(e.id,{multiaddrs:e.multiaddrs},t),e;throw new Fn}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new oy("No peer routers available");const r=this,n=Og(1024);for await(const s of async function*(e,t={}){let r=t.concurrency??1/0;r<1&&(r=1/0);const n=t.ordered??!1,s=new EventTarget,i=[];let o,a=Ws(),c=Ws(),l=!1,u=!1;function h(){return n?i[0]?.done:!!i.find((e=>e.done))}function*d(){for(;i.length>0&&i[0].done;){const e=i[0];if(i.shift(),!e.ok)throw u=!0,a.resolve(),e.err;yield e.value,a.resolve()}}function*p(){for(;h();)for(let e=0;e<i.length;e++)if(i[e].done){const t=i[e];if(i.splice(e,1),e--,!t.ok)throw u=!0,a.resolve(),t.err;yield t.value,a.resolve()}}for(s.addEventListener("task-complete",(()=>{c.resolve()})),Promise.resolve().then((async()=>{try{for await(const t of e){if(i.length===r&&(a=Ws(),await a.promise),u)break;const e={done:!1};i.push(e),t().then((t=>{e.done=!0,e.ok=!0,e.value=t,s.dispatchEvent(new Ad("task-complete"))}),(t=>{e.done=!0,e.err=t,s.dispatchEvent(new Ad("task-complete"))}))}l=!0,s.dispatchEvent(new Ad("task-complete"))}catch(e){o=e,s.dispatchEvent(new Ad("task-complete"))}}));;){if(h()||(c=Ws(),await c.promise),null!=o)throw o;if(n?yield*d():yield*p(),null!=o)throw o;if(l&&0===i.length)break}}(async function*(){const n=ni(...r.routers.filter((e=>e.getClosestPeers instanceof Function)).map((r=>r.getClosestPeers(e,t))));for await(let e of n)yield async()=>{if(0===e.multiaddrs.length)try{e=await r.findPeer(e.id,{...t,useCache:!1})}catch(e){return void r.log.error("could not find peer multiaddrs",e)}return e}}()))null!=s&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),n.has(s.id.toMultihash().bytes)||(n.add(s.id.toMultihash().bytes),yield s))}}class lb extends Jn{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;const t=My([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=Ws();const e=await Bg(this,"walk:peer",t,{errorEvent:"walk:error"});yield e.detail}}finally{t.clear(),this.walkers--,0===this.walkers&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;const e=My([this.walkController.signal,this.shutdownController.signal]),t=Date.now();let r=0;Promise.resolve().then((async()=>{for(this.log("start walk");this.walkers>0;)try{const t=Ya(32);let n=Date.now();for await(const s of this.peerRouting.getClosestPeers(t,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-n,this.walkers),r++,this.safeDispatchEvent("walk:peer",{detail:s}),1===this.walkers&&null!=this.needNext&&(this.log("wait for need next"),await ei(this.needNext.promise,e)),n=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",t,this.walkers,r)}catch(e){this.log.error("random walk errored",e),this.safeDispatchEvent("walk:error",{detail:e})}this.log("no walkers left, ended walk")})).catch((e=>{this.log.error("random walk errored",e)})).finally((()=>{this.log("finished walk, found %d peers after %dms",r,Date.now()-t),this.walking=!1}))}}class ub{log;topologies;handlers;components;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{const e={};for(const[t,r]of this.topologies)e[t]=r.size;return e}}),this.handlers=Vm({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){const t=this.handlers.get(e);if(null==t)throw new cy("No handler registered for protocol "+e);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,r){if(this.handlers.has(e)&&!0!==r?.force)throw new ly("Handler already registered for protocol "+e);const n=Df.bind({ignoreUndefined:!0})({maxInboundStreams:32,maxOutboundStreams:64},r);this.handlers.set(e,{handler:t,options:n}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},r)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach((e=>{this.handlers.delete(e)})),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(null==t)throw new Pn("invalid topology");const r=`${(1e9*Math.random()).toString(36)}${Date.now()}`;let n=this.topologies.get(e);return null==n&&(n=new Map,this.topologies.set(e,n)),n.set(r,t),r}unregister(e){for(const[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){const t=e.detail,r={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(t,r).then((e=>{for(const r of e.protocols){const e=this.topologies.get(r);if(null!=e)for(const r of e.values())!1!==r.filter?.has(t)&&(r.filter?.remove(t),r.onDisconnect?.(t))}})).catch((e=>{"NotFoundError"!==e.name&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)}))}_onPeerUpdate(e){const{peer:t,previous:r}=e.detail,n=(r?.protocols??[]).filter((e=>!t.protocols.includes(e)));for(const e of n){const r=this.topologies.get(e);if(null!=r)for(const e of r.values())!1!==e.filter?.has(t.id)&&(e.filter?.remove(t.id),e.onDisconnect?.(t.id))}}_onPeerIdentify(e){const t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(const e of t){const t=this.topologies.get(e);if(null!=t)for(const e of t.values())null!=r.limits&&!0!==e.notifyOnLimitedConnection||!0!==e.filter?.has(n)&&(e.filter?.add(n),e.onConnect?.(n,r))}}}class hb{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Vm({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Vm({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Cn.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){const t=e[Symbol.toStringTag];if(null==t)throw new Pn("Transport must have a valid tag");if(this.transports.has(t))throw new Pn("There is already a transport with the tag "+t);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){const e=[];for(const[t,r]of this.listeners)for(this.log("closing listeners for %s",t);r.length>0;){const t=r.pop();null!=t&&e.push(t.close())}await Promise.all(e),this.log("all listeners closed");for(const e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(e,t){const r=this.dialTransportForMultiaddr(e);if(null==r)throw new by("No transport available for address "+e);return t?.onProgress?.(new bf("transport-manager:selected-transport",r[Symbol.toStringTag])),r.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(const t of this.listeners.values())for(const r of t)e=[...e,...r.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(const t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(const t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Gn("Not started");if(null==e||0===e.length)return void this.log("no addresses were provided for listening, this node is dial only");const t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach((e=>{t.errors.set(e.toString(),new hy)}));const r=[];for(const[n,s]of this.transports.entries()){const i=s.listenFilter(e);for(const e of i){this.log("creating listener for %s on %a",n,e);const i=s.createListener({upgrader:this.components.upgrader});let o=this.listeners.get(n)??[];null==o&&(o=[],this.listeners.set(n,o)),o.push(i),i.addEventListener("listening",(()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:i})})),i.addEventListener("close",(()=>{const e=o.findIndex((e=>e===i));o.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:i})})),rp.matches(e)?t.ipv4.attempts++:np.matches(e)&&t.ipv6.attempts++,r.push(i.listen(e).then((()=>{t.errors.delete(e.toString()),rp.matches(e)&&t.ipv4.success++,np.matches(e)&&t.ipv6.success++}),(r=>{throw this.log.error("transport %s could not listen on address %a - %e",n,e,r),t.errors.set(e.toString(),r),r})))}}const n=await Promise.allSettled(r);if(!(n.length>0&&n.every((e=>"fulfilled"===e.status))))if(this.ipv6Unsupported(t))this.log("all IPv4 addresses succeed but all IPv6 failed");else{if(this.faultTolerance!==Cn.NO_FATAL)throw new dy("Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set `transportManager.faultTolerance` to NO_FATAL:\n"+[...t.errors.entries()].map((([e,t])=>`\n ${e}: ${(""+(t.stack??t)).split("\n").join("\n ")}\n`)).join(""));this.log("failed to listen on any address but fault tolerance allows this")}}ipv6Unsupported(e){if(0===e.ipv4.attempts||0===e.ipv6.attempts)return!1;const t=e.ipv4.attempts===e.ipv4.success,r=0===e.ipv6.success;return t&&r}async remove(e){const t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);const r=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){const e=t.pop();null!=e&&r.push(e.close())}await Promise.all(r),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){const e=[];for(const t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}}const db="/multistream/1.0.0",pb=1024,fb=Ye("\n");async function gb(e,t,r){await e.write(t,r)}async function mb(e,t){const r=await async function(e,t){const r=await e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==fb[0])throw t.log.error("Invalid mss message - missing newline",r),new Kn("Missing newline");return r.sublist(0,-1)}(e,t);return tn(r.subarray())}async function yb(e,t,r){if(1===(t=Array.isArray(t)?[...t]:[t]).length&&!1===r.negotiateFully)return function(e,t,r){const n=e.sink.bind(e),s=e.source;let i=!1,o=!1;const a=Ws();let c=!1,l=!1;const u=Ws();let h=!1,d=!1;const p=Ws(),f=Pu({sink:n,source:s},{...r,maxDataLength:pb});async function g(){if(o)return r.log.trace("optimistic: already negotiating %s stream",t),void await a.promise;o=!0;try{c||(r.log.trace("optimistic: doing send protocol for %s stream",t),await async function(){if(l)await u.promise;else{l=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',db,t),await f.writeV([Ye(db+"\n"),Ye(t+"\n")]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',db,t)}finally{c=!0,l=!1,u.resolve()}}}()),h||(r.log.trace("optimistic: doing read protocol for %s stream",t),await async function(){if(d)await p.promise;else{d=!0;try{r.log.trace("optimistic: reading multistream select header");let e=await mb(f,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===db&&(e=await mb(f,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new jn("protocol selection failed")}finally{h=!0,d=!1,p.resolve()}}}())}finally{o=!1,i=!0,a.resolve()}}if(e.sink=async e=>{const{sink:n}=f.unwrap();await n(async function*(){let n=!1;for await(const s of e){if(l&&await u.promise,c)yield s;else{l=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',db,t,s.byteLength);const e=t+"\n";yield new Us(Uint8Array.from([19]),Ye(db+"\n"),y(e.length),Ye(e),s).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',db,t,s.byteLength),c=!0,l=!1,u.resolve(),g().catch((e=>{r.log.error("could not finish optimistic protocol negotiation of %s",t,e)}))}n=!0}n||await g()}())},e.source=async function*(){await g(),r.log.trace('optimistic: reading data from "%s" stream',t),yield*f.unwrap().source}(),null!=e.closeRead){const t=e.closeRead.bind(e);e.closeRead=async e=>{i||await g().catch((e=>{r.log.error("could not negotiate protocol before close read",e)})),await t(e)}}if(null!=e.closeWrite){const t=e.closeWrite.bind(e);e.closeWrite=async e=>{i||await g().catch((e=>{r.log.error("could not negotiate protocol before close write",e)})),await t(e)}}if(null!=e.close){const t=e.close.bind(e);e.close=async e=>{const r=[];l&&r.push(u.promise),d&&r.push(p.promise),r.length>0?await ei(Promise.all(r),e?.signal):(i=!0,o=!1,a.resolve()),await t(e)}}return{stream:e,protocol:t}}(e,t[0],r);const n=Pu(e,{...r,maxDataLength:pb}),s=t.shift();if(null==s)throw Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',db,s);const i=Ye(db+"\n"),o=Ye(s+"\n");await async function(e,t,r){await e.writeV(t,r)}(n,[i,o],r),r.log.trace("select: reading multistream-select header");let a=await mb(n,r);if(r.log.trace('select: read "%s"',a),a===db&&(r.log.trace("select: reading protocol response"),a=await mb(n,r),r.log.trace('select: read "%s"',a)),a===s)return{stream:n.unwrap(),protocol:s};for(const e of t){r.log.trace('select: write "%s"',e),await gb(n,Ye(e+"\n"),r),r.log.trace("select: reading protocol response");const t=await mb(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new jn("protocol selection failed")}async function bb(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);const n=Pu(e,{...r,maxDataLength:pb,maxLengthLength:2});for(;;){r.log.trace("handle: reading incoming string");const e=await mb(n,r);if(r.log.trace('handle: read "%s"',e),e!==db){if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await gb(n,Ye(e+"\n"),r),r.log.trace('handle: responded with "%s" for "%s"',e,e),{stream:n.unwrap(),protocol:e};if("ls"!==e)r.log.trace('handle: respond with "na" for "%s"',e),await gb(n,Ye("na\n"),r),r.log('handle: responded with "na" for "%s"',e);else{const s=new Us(...t.map((e=>Eu.single(Ye(e+"\n")))),Ye("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await gb(n,s,r),r.log.trace('handle: responded with "%s" for %s',t,e)}}else r.log.trace('handle: respond with "%s" for "%s"',db,e),await gb(n,Ye(db+"\n"),r),r.log.trace('handle: responded with "%s" for "%s"',db,e)}}class wb{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){const{remoteAddr:t,remotePeer:r,newStream:n,close:s,abort:i,getStreams:o}=e;this.id=`${parseInt(1e9*Math.random()+"").toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=r,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),null==this.remoteAddr.getPeerId()&&(this.remoteAddr=this.remoteAddr.encapsulate("/p2p/"+this.remotePeer)),this._newStream=n,this._close=s,this._abort=i,this._getStreams=o,this.tags=[]}[Symbol.toStringTag]="Connection";[bn]=!0;get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new Ln("the connection is being closed");if("closed"===this.status)throw new Dn("the connection is closed");if(Array.isArray(e)||(e=[e]),null!=this.limits&&!0!==t?.runOnLimitedConnection)throw new Xn("Cannot open protocol stream on limited connection");const r=await this._newStream(e,t);return r.direction="outbound",r}async close(e={}){if("closed"!==this.status&&"closing"!==this.status){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",null==e.signal){const t=AbortSignal.timeout(500);e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(e){"closed"!==this.status&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}}function vb(e,t,r){let n=0;return r.streams.forEach((r=>{r.direction===t&&r.protocol===e&&n++})),n}class Eb{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=Vm({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach((e=>{this.connectionEncrypters.set(e.protocol,e)})),this.streamMuxers=Vm({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach((e=>{this.streamMuxers.set(e.protocol,e)})),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){const r=this.components.connectionGater[e];if(null!=r&&!0===await r.apply(this.components.connectionGater,t))throw new fy("The multiaddr connection is blocked by gater."+e)}createInboundAbortSignal(e){return My([AbortSignal.timeout(this.inboundUpgradeTimeout),e])}async upgradeInbound(e,t){let r=!1;const n=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),r=await ei(this.components.connectionManager.acceptIncomingConnection(e),n),!r)throw new gy("Connection denied");await ei(this.shouldBlockConnection("denyInboundConnection",e),n),await this._performUpgrade(e,"inbound",{...t,signal:n})}catch(e){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[e.name??"Error"]:!0}),e}finally{n.clear(),r&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});const r=e.remoteAddr.getPeerId();let n;null!=r&&(n=Pc(r),await ei(this.shouldBlockConnection("denyOutboundConnection",n,e),t.signal));let s="outbound";return!1===t.initiator&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(e){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[e.name??"Error"]:!0}),e}}async _performUpgrade(e,t,r){let n,s,i,o,a;this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let c=e;if(!0!==r?.skipProtection){const n=this.components.connectionProtector;null!=n&&(e.log("protecting the %s connection",t),c=await n.protect(e,r))}try{if(n=c,!0!==r?.skipEncryption){r?.onProgress?.(new bf(`upgrader:encrypt-${t}-connection`)),({conn:n,remotePeer:s,protocol:a,streamMuxer:o}=await("inbound"===t?this._encryptInbound(c,r):this._encryptOutbound(c,r)));const e={...c,...n};await this.shouldBlockConnection("inbound"===t?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e)}else{const r=e.remoteAddr.getPeerId();if(null==r)throw new $n(t+" connection that skipped encryption must have a peer id");const n=Pc(r);a="native",s=n}if(s.equals(this.components.peerId)){const t=new Bn("Can not dial self");throw e.abort(t),t}if(i=n,null!=r?.muxerFactory)o=r.muxerFactory;else if(null==o&&this.streamMuxers.size>0){r?.onProgress?.(new bf(`upgrader:multiplex-${t}-connection`));const e=await("inbound"===t?this._multiplexInbound({...c,...n},this.streamMuxers,r):this._multiplexOutbound({...c,...n},this.streamMuxers,r));o=e.muxerFactory,i=e.stream}}catch(r){throw e.log.error("failed to upgrade inbound connection %s %a - %e","inbound"===t?"from":"to",e.remoteAddr,r),r}return await this.shouldBlockConnection("inbound"===t?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:a,direction:t,maConn:e,upgradedConn:i,muxerFactory:o,remotePeer:s,limits:r?.limits})}_createConnection(e){const{cryptoProtocol:t,direction:r,maConn:n,upgradedConn:s,remotePeer:i,muxerFactory:o,limits:a}=e;let c,l,u;null!=o&&(c=o.createStreamMuxer({direction:r,onIncomingStream:e=>{if(null==u)return;const t=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then((async()=>{const r=this.components.registrar.getProtocols(),{stream:n,protocol:s}=await bb(e,r,{signal:t,log:e.log,yieldBytes:!1});if(null==u)return;u.log("incoming stream opened on %s",s);const o=function(e,t){try{const{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return 32}(s,this.components.registrar);if(vb(s,"inbound",u)===o){const t=new Zn(`Too many inbound protocol streams for protocol "${s}" - limit ${o}`);throw e.abort(t),t}e.source=n.source,e.sink=n.sink,e.protocol=s,null!=n.closeWrite&&(e.closeWrite=n.closeWrite),null!=n.closeRead&&(e.closeRead=n.closeRead),null!=n.close&&(e.close=n.close),await this.components.peerStore.merge(i,{protocols:[s]},{signal:t}),this.components.metrics?.trackProtocolStream(e,u),this._onStream({connection:u,stream:e,protocol:s})})).catch((async r=>{u.log.error("error handling incoming stream id %s - %e",e.id,r),null==e.timeline.close&&await e.close({signal:t}).catch((t=>e.abort(t)))}))}}),l=async(t,n={})=>{if(null==c)throw new my("Connection is not multiplexed");u.log.trace("starting new stream for protocols %s",t);const s=await c.newStream();u.log.trace("started new stream %s for protocols %s",s.id,t);try{if(null==n.signal){s.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",t);const e=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);n={...n,signal:e}}s.log.trace("selecting protocol from protocols %s",t);const{stream:e,protocol:r}=await yb(s,t,{...n,log:s.log,yieldBytes:!0});s.log.trace("selected protocol %s",r);const o=function(e,t,r={}){try{const{options:r}=t.getHandler(e);if(null!=r.maxOutboundStreams)return r.maxOutboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return r.maxOutboundStreams??64}(r,this.components.registrar,n),a=vb(r,"outbound",u);if(a>=o){const e=new Yn(`Too many outbound protocol streams for protocol "${r}" - ${a}/${o}`);throw s.abort(e),e}return await this.components.peerStore.merge(i,{protocols:[r]}),s.source=e.source,s.sink=e.sink,s.protocol=r,null!=e.closeWrite&&(s.closeWrite=e.closeWrite),null!=e.closeRead&&(s.closeRead=e.closeRead),null!=e.close&&(s.close=e.close),this.components.metrics?.trackProtocolStream(s,u),s}catch(n){throw u.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e","inbound"===r?"from":"to",e.maConn.remoteAddr,t,n),null==s.timeline.close&&s.abort(n),n}},Promise.all([c.sink(s.source),s.sink(c.source)]).catch((e=>{u.log.error("error piping data through muxer - %e",e)})));const h=n.timeline;var d;return n.timeline=new Proxy(h,{set:(...e)=>("close"===e[1]&&null!=e[2]&&null==h.close&&(async()=>{try{"open"===u.status&&await u.close()}catch(e){u.log.error("error closing connection after timeline close %e",e)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch((e=>{u.log.error("error thrown while dispatching connection:close event %e",e)})),Reflect.set(...e))}),n.timeline.upgraded=Date.now(),d={remoteAddr:n.remoteAddr,remotePeer:i,status:"open",direction:r,timeline:n.timeline,multiplexer:c?.protocol,encryption:t,limits:a,logger:this.components.logger,newStream:l??(()=>{throw new my("Connection is not multiplexed")}),getStreams:()=>c?.streams??[],async close(e){await(c?.close(e)),await n.close(e)},abort(e){n.abort(e),c?.abort(e)}},u=new wb(d),this.events.safeDispatchEvent("connection:open",{detail:u}),u.__maConnTimeline=h,u}_onStream(e){const{connection:t,stream:r,protocol:n}=e,{handler:s,options:i}=this.components.registrar.getHandler(n);if(null!=t.limits&&!0!==i.runOnLimitedConnection)throw new Xn("Cannot open protocol stream on limited connection");s({connection:t,stream:r})}async _encryptInbound(e,t){const r=Array.from(this.connectionEncrypters.keys());try{const{stream:n,protocol:s}=await bb(e,r,{...t,log:e.log}),i=this.connectionEncrypters.get(s);if(null==i)throw new yy("no crypto module found for "+s);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,s),{...await i.secureInbound(n,t),protocol:s}}catch(t){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,t),new yy(t.message)}}async _encryptOutbound(e,t){const r=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",r);const{stream:n,protocol:s}=await yb(e,r,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(null==i)throw new yy("no crypto module found for "+s);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,s),{...await i.secureOutbound(n,t),protocol:s}}catch(t){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,t),new yy(t.message)}}async _multiplexOutbound(e,t,r){const n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);const{stream:s,protocol:i}=await yb(e,n,{...r,log:e.log,yieldBytes:!0});return e.log("selected %s as muxer protocol",i),{stream:s,muxerFactory:t.get(i)}}catch(t){throw e.log.error("error multiplexing outbound connection",t),new my(t+"")}}async _multiplexInbound(e,t,r){const n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{const{stream:s,protocol:i}=await bb(e,n,{...r,log:e.log});return{stream:s,muxerFactory:t.get(i)}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new my(t+"")}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}}const Sb="2.8.11",Ab="js-libp2p";function Ib(e,t){return`${e??Ab}/${t??Sb} browser/${globalThis.navigator.userAgent}`}class _b extends Jn{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new Jn,r=t.dispatchEvent.bind(t);t.dispatchEvent=e=>{const t=r(e),n=this.dispatchEvent(new CustomEvent(e.type,{detail:e.detail}));return t||n},this.peerId=e.peerId,this.logger=e.logger??bg(),this.log=this.logger.forComponent("libp2p"),this.services={};const n=e.nodeInfo?.name??Ab,s=e.nodeInfo?.version??Sb,i=this.components=function(e={}){const t=new wy(e);return new Proxy(t,{get(e,r,n){if("string"==typeof r&&!Ey.includes(r)){const e=t.components[r];if(null==e&&!vy.includes(r))throw new ny(r+" not set");return e}return Reflect.get(e,r,n)},set:(e,r,n)=>("string"==typeof r?t.components[r]=n:Reflect.set(e,r,n),!0)})}({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:n,version:s,userAgent:e.nodeInfo?.userAgent??Ib(n,s)},logger:this.logger,events:t,datastore:e.datastore??new jm,connectionGater:_y(e.connectionGater),dns:e.dns});null!=e.metrics&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",function(e,t={}){return new Um(e,t)}(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",(e=>{if(null==e.detail.previous){const t={id:e.detail.peer.id,multiaddrs:e.detail.peer.addresses.map((e=>e.multiaddr))};i.events.safeDispatchEvent("peer:discovery",{detail:t})}})),null!=e.connectionProtector&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Eb(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map(((e,t)=>this.configureComponent("connection-encryption-"+t,e(this.components)))),streamMuxers:(e.streamMuxers??[]).map(((e,t)=>this.configureComponent("stream-muxers-"+t,e(this.components)))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new hb(this.components,e.transportManager)),this.configureComponent("connectionManager",new nb(this.components,e.connectionManager)),!1!==e.connectionMonitor?.enabled&&this.configureComponent("connectionMonitor",new ob(this.components,e.connectionMonitor)),this.configureComponent("registrar",new ub(this.components)),this.configureComponent("addressManager",new ty(this.components,e.addresses));const o=(e.peerRouters??[]).map(((e,t)=>this.configureComponent("peer-router-"+t,e(this.components))));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new cb(this.components,{routers:o}));const a=(e.contentRouters??[]).map(((e,t)=>this.configureComponent("content-router-"+t,e(this.components))));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new ab(this.components,{routers:a})),this.configureComponent("randomWalk",new lb(this.components)),(e.peerDiscovery??[]).forEach(((e,t)=>{this.configureComponent("peer-discovery-"+t,e(this.components)).addEventListener("peer",(e=>{this.#M(e)}))})),e.transports?.forEach(((e,t)=>{this.components.transportManager.add(this.configureComponent("transport-"+t,e(this.components)))})),null!=e.services)for(const t of Object.keys(e.services)){const r=(0,e.services[t])(this.components);null!=r?(this.services[t]=r,this.configureComponent(t,r),null!=r[wn]&&(this.log("registering service %s for content routing",t),a.push(r[wn])),null!=r[An]&&(this.log("registering service %s for peer routing",t),o.push(r[An])),null!=r[vn]&&(this.log("registering service %s for peer discovery",t),r[vn].addEventListener?.("peer",(e=>{this.#M(e)})))):this.log.error("service factory %s returned null or undefined instance",t)}!function(e){const t={};for(const r of Object.values(e.components))for(const e of Sy(r))t[e]=!0;for(const r of Object.values(e.components))for(const e of Ay(r))if(!0!==t[e])throw new sy(`Service "${Iy(r)}" required capability "${e}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}(i)}configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if("stopped"===this.status){this.status="starting",this.log("libp2p is starting");try{await(this.components.beforeStart?.()),await this.components.start(),await(this.components.afterStart?.()),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){"started"===this.status&&(this.log("libp2p is stopping"),this.status="stopping",await(this.components.beforeStop?.()),await this.components.stop(),await(this.components.afterStop?.()),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const e=new Ig;for(const t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,r={}){if(null==t)throw new Pn("no protocols were provided to open a stream");if(0===(t=Array.isArray(t)?t:[t]).length)throw new Pn("no protocols were provided to open a stream");return(await this.dial(e,r)).newStream(t,r)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){yl(e)&&(e=Pc(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),null!=e.publicKey)return e.publicKey;try{const r=await this.peerStore.get(e,t);if(null!=r.id.publicKey)return r.id.publicKey}catch(e){if("NotFoundError"!==e.name)throw e}const r=Ls([Ye("/pk/"),e.toMultihash().bytes]),n=Sc(await this.contentRouting.get(r,t));return await this.peerStore.patch(e,{publicKey:n},t),n}async handle(e,t,r){Array.isArray(e)||(e=[e]),await Promise.all(e.map((async e=>{await this.components.registrar.handle(e,t,r)})))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map((async e=>{await this.components.registrar.unhandle(e,t)})))}async register(e,t,r){return this.components.registrar.register(e,t,r)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#M(e){const{detail:t}=e;t.id.toString()!==this.peerId.toString()?this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch((e=>{this.log.error(e)})):this.log.error("peer discovery mechanism discovered self")}}function Cb(){try{return!1}catch(e){return!1}}const xb="enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im",kb="enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im",Tb=xs.BOOTSTRAP,Pb="Invalid record id";var Rb=Object.freeze({__proto__:null,default:{}});const Lb=BigInt(0),Db=BigInt(1),Mb=BigInt(2),Nb=BigInt(3),Ob=BigInt(8),Ub=Object.freeze({a:Lb,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:Db,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),Fb=(e,t)=>(e+t/Mb)/t,Bb={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){const{n:t}=Ub,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Db*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,o=BigInt("0x100000000000000000000000000000000"),a=Fb(i*e,t),c=Fb(-n*e,t);let l=gw(e-a*r-c*s,t),u=gw(-a*n-c*i,t);const h=l>o,d=u>o;if(h&&(l=t-l),d&&(u=t-u),l>o||u>o)throw Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}},$b=32,qb=32;function zb(e){const{a:t,b:r}=Ub,n=gw(e*e),s=gw(n*e);return gw(s+t*e+r)}const jb=Ub.a===Lb;class Kb extends Error{constructor(e){super(e)}}function Vb(e){if(!(e instanceof Hb))throw new TypeError("JacobianPoint expected")}class Hb{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof Xb))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(Xb.ZERO)?Hb.ZERO:new Hb(e.x,e.y,Db)}static toAffineBatch(e){const t=function(e,t=Ub.P){const r=Array(e.length),n=yw(e.reduce(((e,n,s)=>n===Lb?e:(r[s]=e,gw(e*n,t))),Db),t);return e.reduceRight(((e,n,s)=>n===Lb?e:(r[s]=gw(e*r[s],t),gw(e*n,t))),n),r}(e.map((e=>e.z)));return e.map(((e,r)=>e.toAffine(t[r])))}static normalizeZ(e){return Hb.toAffineBatch(e).map(Hb.fromAffine)}equals(e){Vb(e);const{x:t,y:r,z:n}=this,{x:s,y:i,z:o}=e,a=gw(n*n),c=gw(o*o),l=gw(t*c),u=gw(s*a),h=gw(gw(r*o)*c),d=gw(gw(i*n)*a);return l===u&&h===d}negate(){return new Hb(this.x,gw(-this.y),this.z)}double(){const{x:e,y:t,z:r}=this,n=gw(e*e),s=gw(t*t),i=gw(s*s),o=e+s,a=gw(Mb*(gw(o*o)-n-i)),c=gw(Nb*n),l=gw(c*c),u=gw(l-Mb*a),h=gw(c*(a-u)-Ob*i),d=gw(Mb*t*r);return new Hb(u,h,d)}add(e){Vb(e);const{x:t,y:r,z:n}=this,{x:s,y:i,z:o}=e;if(s===Lb||i===Lb)return this;if(t===Lb||r===Lb)return e;const a=gw(n*n),c=gw(o*o),l=gw(t*c),u=gw(s*a),h=gw(gw(r*o)*c),d=gw(gw(i*n)*a),p=gw(u-l),f=gw(d-h);if(p===Lb)return f===Lb?this.double():Hb.ZERO;const g=gw(p*p),m=gw(p*g),y=gw(l*g),b=gw(f*f-m-Mb*y),w=gw(f*(y-b)-h*m),v=gw(n*o*p);return new Hb(b,w,v)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){const t=Hb.ZERO;if("bigint"==typeof e&&e===Lb)return t;let r=fw(e);if(r===Db)return this;if(!jb){let e=t,n=this;for(;r>Lb;)r&Db&&(e=e.add(n)),n=n.double(),r>>=Db;return e}let{k1neg:n,k1:s,k2neg:i,k2:o}=Bb.splitScalar(r),a=t,c=t,l=this;for(;s>Lb||o>Lb;)s&Db&&(a=a.add(l)),o&Db&&(c=c.add(l)),l=l.double(),s>>=Db,o>>=Db;return n&&(a=a.negate()),i&&(c=c.negate()),c=new Hb(gw(c.x*Bb.beta),c.y,c.z),a.add(c)}precomputeWindow(e){const t=jb?128/e+1:256/e+1,r=[];let n=this,s=n;for(let i=0;i<t;i++){s=n,r.push(s);for(let t=1;t<2**(e-1);t++)s=s.add(n),r.push(s);n=s.double()}return r}wNAF(e,t){!t&&this.equals(Hb.BASE)&&(t=Xb.BASE);const r=t&&t._WINDOW_SIZE||1;if(256%r)throw Error("Point#wNAF: Invalid precomputation window, must be power of 2");let n=t&&Wb.get(t);n||(n=this.precomputeWindow(r),t&&1!==r&&(n=Hb.normalizeZ(n),Wb.set(t,n)));let s=Hb.ZERO,i=Hb.BASE;const o=1+(jb?128/r:256/r),a=2**(r-1),c=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let t=0;t<o;t++){const r=t*a;let o=Number(e&c);e>>=u,o>a&&(o-=l,e+=Db);const h=r,d=r+Math.abs(o)-1,p=t%2!=0,f=o<0;0===o?i=i.add(Gb(p,n[h])):s=s.add(Gb(f,n[d]))}return{p:s,f:i}}multiply(e,t){let r,n,s=fw(e);if(jb){const{k1neg:e,k1:i,k2neg:o,k2:a}=Bb.splitScalar(s);let{p:c,f:l}=this.wNAF(i,t),{p:u,f:h}=this.wNAF(a,t);c=Gb(e,c),u=Gb(o,u),u=new Hb(gw(u.x*Bb.beta),u.y,u.z),r=c.add(u),n=l.add(h)}else{const{p:e,f:i}=this.wNAF(s,t);r=e,n=i}return Hb.normalizeZ([r,n])[0]}toAffine(e){const{x:t,y:r,z:n}=this,s=this.equals(Hb.ZERO);null==e&&(e=s?Ob:yw(n));const i=e,o=gw(i*i),a=gw(o*i),c=gw(t*o),l=gw(r*a),u=gw(n*i);if(s)return Xb.ZERO;if(u!==Db)throw Error("invZ was invalid");return new Xb(c,l)}}function Gb(e,t){const r=t.negate();return e?r:t}Hb.BASE=new Hb(Ub.Gx,Ub.Gy,Db),Hb.ZERO=new Hb(Lb,Db,Lb);const Wb=new WeakMap;class Xb{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,Wb.delete(this)}hasEvenY(){return this.y%Mb===Lb}static fromCompressedHex(e){const t=32===e.length,r=dw(t?e:e.subarray(1));if(!Aw(r))throw Error("Point is not on curve");let n=function(e){const{P:t}=Ub,r=BigInt(6),n=BigInt(11),s=BigInt(22),i=BigInt(23),o=BigInt(44),a=BigInt(88),c=e*e*e%t,l=c*c*e%t,u=mw(l,Nb)*l%t,h=mw(u,Nb)*l%t,d=mw(h,Mb)*c%t,p=mw(d,n)*d%t,f=mw(p,s)*p%t,g=mw(f,o)*f%t,m=mw(g,a)*g%t,y=mw(m,o)*f%t,b=mw(y,Nb)*l%t,w=mw(b,i)*p%t,v=mw(w,r)*c%t,E=mw(v,Mb);if(E*E%t!==e)throw Error("Cannot find square root");return E}(zb(r));const s=(n&Db)===Db;t?s&&(n=gw(-n)):!(1&~e[0])!==s&&(n=gw(-n));const i=new Xb(r,n);return i.assertValidity(),i}static fromUncompressedHex(e){const t=dw(e.subarray(1,33)),r=dw(e.subarray(33,65)),n=new Xb(t,r);return n.assertValidity(),n}static fromHex(e){const t=pw(e),r=t.length,n=t[0];if(r===$b)return this.fromCompressedHex(t);if(33===r&&(2===n||3===n))return this.fromCompressedHex(t);if(65===r&&4===n)return this.fromUncompressedHex(t);throw Error("Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not "+r)}static fromPrivateKey(e){return Xb.BASE.multiply(_w(e))}static fromSignature(e,t,r){const{r:n,s:s}=Cw(t);if(![0,1,2,3].includes(r))throw Error("Cannot recover: invalid recovery bit");const i=bw(pw(e)),{n:o}=Ub,a=2===r||3===r?n+o:n,c=yw(a,o),l=gw(-i*c,o),u=gw(s*c,o),h=1&r?"03":"02",d=Xb.fromHex(h+cw(a)),p=Xb.BASE.multiplyAndAddUnsafe(d,l,u);if(!p)throw Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return ow(this.toHex(e))}toHex(e=!1){const t=cw(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${cw(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const e="Point is not on elliptic curve",{x:t,y:r}=this;if(!Aw(t)||!Aw(r))throw Error(e);const n=gw(r*r);if(gw(n-zb(t))!==Lb)throw Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Xb(this.x,gw(-this.y))}double(){return Hb.fromAffine(this).double().toAffine()}add(e){return Hb.fromAffine(this).add(Hb.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Hb.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,r){const n=Hb.fromAffine(this),s=t===Lb||t===Db||this!==Xb.BASE?n.multiplyUnsafe(t):n.multiply(t),i=Hb.fromAffine(e).multiplyUnsafe(r),o=s.add(i);return o.equals(Hb.ZERO)?void 0:o.toAffine()}}function Zb(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function Yb(e){if(e.length<2||2!==e[0])throw Error("Invalid signature integer tag: "+nw(e));const t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw Error("Invalid signature integer: wrong length");if(0===r[0]&&r[1]<=127)throw Error("Invalid signature integer: trailing length");return{data:dw(r),left:e.subarray(t+2)}}Xb.BASE=new Xb(Ub.Gx,Ub.Gy),Xb.ZERO=new Xb(Lb,Lb);class Qb{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){const t=Jb(e),r="Signature.fromCompact";if("string"!=typeof e&&!t)throw new TypeError(r+": Expected string or Uint8Array");const n=t?nw(e):e;if(128!==n.length)throw Error(r+": Expected 64-byte hex");return new Qb(hw(n.slice(0,64)),hw(n.slice(64,128)))}static fromDER(e){const t=Jb(e);if("string"!=typeof e&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r:r,s:n}=function(e){if(e.length<2||48!=e[0])throw Error("Invalid signature tag: "+nw(e));if(e[1]!==e.length-2)throw Error("Invalid signature: incorrect length");const{data:t,left:r}=Yb(e.subarray(2)),{data:n,left:s}=Yb(r);if(s.length)throw Error("Invalid signature: left bytes after parsing: "+nw(s));return{r:t,s:n}}(t?e:ow(e));return new Qb(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){const{r:e,s:t}=this;if(!Sw(e))throw Error("Invalid Signature: r must be 0 < r < n");if(!Sw(t))throw Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const e=Ub.n>>Db;return this.s>e}normalizeS(){return this.hasHighS()?new Qb(this.r,gw(-this.s,Ub.n)):this}toDERRawBytes(){return ow(this.toDERHex())}toDERHex(){const e=Zb(uw(this.s)),t=Zb(uw(this.r)),r=e.length/2,n=t.length/2,s=uw(r),i=uw(n);return`30${uw(n+r+4)}02${i}${t}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return ow(this.toCompactHex())}toCompactHex(){return cw(this.r)+cw(this.s)}}function Jb(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ew(e){if(!Jb(e))throw Error("Uint8Array expected")}function tw(...e){if(e.every(ew),1===e.length)return e[0];const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}const rw=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function nw(e){ew(e);let t="";for(let r=0;r<e.length;r++)t+=rw[e[r]];return t}const sw={_0:48,_9:57,A:65,F:70,a:97,f:102};function iw(e){return e>=sw._0&&e<=sw._9?e-sw._0:e>=sw.A&&e<=sw.F?e-(sw.A-10):e>=sw.a&&e<=sw.f?e-(sw.a-10):void 0}function ow(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,s=0;t<r;t++,s+=2){const r=iw(e.charCodeAt(s)),i=iw(e.charCodeAt(s+1));if(void 0===r||void 0===i){const t=e[s]+e[s+1];throw Error('hex string expected, got non-hex character "'+t+'" at index '+s)}n[t]=16*r+i}return n}const aw=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function cw(e){if("bigint"!=typeof e)throw Error("Expected bigint");if(!(Lb<=e&&e<aw))throw Error("Expected number 0 <= n < 2^256");return e.toString(16).padStart(64,"0")}function lw(e){const t=ow(cw(e));if(32!==t.length)throw Error("Error: expected 32 bytes");return t}function uw(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function hw(e){if("string"!=typeof e)throw new TypeError("hexToNumber: expected string, got "+typeof e);return BigInt("0x"+e)}function dw(e){return hw(nw(e))}function pw(e){return Jb(e)?Uint8Array.from(e):ow(e)}function fw(e){if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if("bigint"==typeof e&&Sw(e))return e;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function gw(e,t=Ub.P){const r=e%t;return r>=Lb?r:t+r}function mw(e,t){const{P:r}=Ub;let n=e;for(;t-- >Lb;)n*=n,n%=r;return n}function yw(e,t=Ub.P){if(e===Lb||t<=Lb)throw Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=gw(e,t),n=t,s=Lb,i=Db;for(;r!==Lb;){const e=n%r,t=s-i*(n/r);n=r,r=e,s=i,i=t}if(n!==Db)throw Error("invert: does not exist");return gw(s,t)}function bw(e,t=!1){const r=function(e){const t=8*e.length-256,r=dw(e);return t>0?r>>BigInt(t):r}(e);if(t)return r;const{n:n}=Ub;return r>=n?r-n:r}let ww,vw;class Ew{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,"number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");this.v=new Uint8Array(e).fill(1),this.k=new Uint8Array(e).fill(0),this.counter=0}hmac(...e){return Dw.hmacSha256(this.k,...e)}hmacSync(...e){return vw(this.k,...e)}checkSync(){if("function"!=typeof vw)throw new Kb("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),0!==e.length&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),0!==e.length&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0;const t=[];for(;e<this.qByteLen;){this.v=await this.hmac(this.v);const r=this.v.slice();t.push(r),e+=this.v.length}return tw(...t)}generateSync(){this.checkSync(),this.incr();let e=0;const t=[];for(;e<this.qByteLen;){this.v=this.hmacSync(this.v);const r=this.v.slice();t.push(r),e+=this.v.length}return tw(...t)}}function Sw(e){return Lb<e&&e<Ub.n}function Aw(e){return Lb<e&&e<Ub.P}function Iw(e,t,r,n=!0){const{n:s}=Ub,i=bw(e,!0);if(!Sw(i))return;const o=yw(i,s),a=Xb.BASE.multiply(i),c=gw(a.x,s);if(c===Lb)return;const l=gw(o*gw(t+r*c,s),s);if(l===Lb)return;let u=new Qb(c,l),h=(a.x===u.r?0:2)|Number(a.y&Db);return n&&u.hasHighS()&&(u=u.normalizeS(),h^=1),{sig:u,recovery:h}}function _w(e){let t;if("bigint"==typeof e)t=e;else if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)t=BigInt(e);else if("string"==typeof e){if(64!==e.length)throw Error("Expected 32 bytes of private key");t=hw(e)}else{if(!Jb(e))throw new TypeError("Expected valid private key");if(e.length!==qb)throw Error("Expected 32 bytes of private key");t=dw(e)}if(!Sw(t))throw Error("Expected private key: 0 < key < n");return t}function Cw(e){if(e instanceof Qb)return e.assertValidity(),e;try{return Qb.fromDER(e)}catch(t){return Qb.fromCompact(e)}}function xw(e){return dw(e.length>$b?e.slice(0,$b):e)}function kw(e){const t=xw(e),r=gw(t,Ub.n);return Tw(r<Lb?t:r)}function Tw(e){return lw(e)}const Pw={strict:!0};Xb.BASE._setWindowSize(8);const Rw={node:Rb,web:"object"==typeof self&&"crypto"in self?self.crypto:void 0},Lw={},Dw={bytesToHex:nw,hexToBytes:ow,concatBytes:tw,mod:gw,invert:yw,isValidPrivateKey(e){try{return _w(e),!0}catch(e){return!1}},_bigintTo32Bytes:lw,_normalizePrivateKey:_w,hashToPrivateKey(e){if((e=pw(e)).length<40||e.length>1024)throw Error("Expected valid bytes of private key as per FIPS 186");return lw(gw(dw(e),Ub.n-Db)+Db)},randomBytes(e=32){if(Rw.web)return Rw.web.getRandomValues(new Uint8Array(e));if(Rw.node){const{randomBytes:t}=Rw.node;return Uint8Array.from(t(e))}throw Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Dw.hashToPrivateKey(Dw.randomBytes(40)),precompute(e=8,t=Xb.BASE){const r=t===Xb.BASE?t:new Xb(t.x,t.y);return r._setWindowSize(e),r.multiply(Nb),r},async sha256(...e){if(Rw.web){const t=await Rw.web.subtle.digest("SHA-256",tw(...e));return new Uint8Array(t)}if(Rw.node){const{createHash:t}=Rw.node,r=t("sha256");return e.forEach((e=>r.update(e))),Uint8Array.from(r.digest())}throw Error("The environment doesn't have sha256 function")},async hmacSha256(e,...t){if(Rw.web){const r=await Rw.web.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=tw(...t),s=await Rw.web.subtle.sign("HMAC",r,n);return new Uint8Array(s)}if(Rw.node){const{createHmac:r}=Rw.node,n=r("sha256",e);return t.forEach((e=>n.update(e))),Uint8Array.from(n.digest())}throw Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,async taggedHash(e,...t){let r=Lw[e];if(void 0===r){const t=await Dw.sha256(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=tw(t,t),Lw[e]=r}return Dw.sha256(r,...t)},taggedHashSync(e,...t){if("function"!=typeof ww)throw new Kb("sha256Sync is undefined, you need to set it");let r=Lw[e];if(void 0===r){const t=ww(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=tw(t,t),Lw[e]=r}return ww(r,...t)},_JacobianPoint:Hb};Object.defineProperties(Dw,{sha256Sync:{configurable:!1,get:()=>ww,set(e){ww||(ww=e)}},hmacSha256Sync:{configurable:!1,get:()=>vw,set(e){vw||(vw=e)}}});var Mw,Nw,Ow={exports:{}},Uw=(Mw||(Mw=1,Nw=Ow,function(){var e="input is invalid type",t="object"==typeof window,r=t?window:{};r.JS_SHA3_NO_WINDOW&&(t=!1);var n=!t&&"object"==typeof self;!r.JS_SHA3_NO_NODE_JS&&"object"==typeof i&&i.versions&&i.versions.node?r=ns:n&&(r=self);for(var s=!r.JS_SHA3_NO_COMMON_JS&&Nw.exports,o=!r.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,a="0123456789abcdef".split(""),c=[4,1024,262144,67108864],l=[0,8,16,24],u=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],h=[224,256,384,512],d=[128,256],p=["hex","buffer","arrayBuffer","array","digest"],f={128:168,256:136},g=r.JS_SHA3_NO_NODE_JS||!Array.isArray?e=>"[object Array]"==={}.toString.call(e):Array.isArray,m=!o||!r.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView?ArrayBuffer.isView:e=>"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer,y=t=>{var r=typeof t;if("string"===r)return[t,!0];if("object"!==r||null===t)throw Error(e);if(o&&t.constructor===ArrayBuffer)return[new Uint8Array(t),!1];if(!g(t)&&!m(t))throw Error(e);return[t,!1]},b=e=>0===y(e)[0].length,w=e=>{for(var t=[],r=0;r<e.length;++r)t[r]=e[r];return t},v=(e,t,r)=>n=>new N(e,t,e).update(n)[r](),E=(e,t,r)=>(n,s)=>new N(e,t,s).update(n)[r](),S=(e,t,r)=>(t,n,s,i)=>x["cshake"+e].update(t,n,s,i)[r](),A=(e,t,r)=>(t,n,s,i)=>x["kmac"+e].update(t,n,s,i)[r](),I=(e,t,r,n)=>{for(var s=0;s<p.length;++s){var i=p[s];e[i]=t(r,n,i)}return e},_=(e,t)=>{var r=v(e,t,"hex");return r.create=()=>new N(e,t,e),r.update=e=>r.create().update(e),I(r,v,e,t)},C=[{name:"keccak",padding:[1,256,65536,16777216],bits:h,createMethod:_},{name:"sha3",padding:[6,1536,393216,100663296],bits:h,createMethod:_},{name:"shake",padding:[31,7936,2031616,520093696],bits:d,createMethod(e,t){var r=E(e,t,"hex");return r.create=r=>new N(e,t,r),r.update=(e,t)=>r.create(t).update(e),I(r,E,e,t)}},{name:"cshake",padding:c,bits:d,createMethod(e,t){var r=f[e],n=S(e,0,"hex");return n.create=(n,s,i)=>b(s)&&b(i)?x["shake"+e].create(n):new N(e,t,n).bytepad([s,i],r),n.update=(e,t,r,s)=>n.create(t,r,s).update(e),I(n,S,e,t)}},{name:"kmac",padding:c,bits:d,createMethod(e,t){var r=f[e],n=A(e,0,"hex");return n.create=(n,s,i)=>new O(e,t,s).bytepad(["KMAC",i],r).bytepad([n],r),n.update=(e,t,r,s)=>n.create(e,r,s).update(t),I(n,A,e,t)}}],x={},k=[],T=0;T<C.length;++T)for(var P=C[T],R=P.bits,L=0;L<R.length;++L){var D=P.name+"_"+R[L];if(k.push(D),x[D]=P.createMethod(R[L],P.padding),"sha3"!==P.name){var M=P.name+R[L];k.push(M),x[M]=x[D]}}function N(e,t,r){this.blocks=[],this.s=[],this.padding=t,this.outputBits=r,this.reset=!0,this.finalized=!1,this.block=0,this.start=0,this.blockCount=1600-(e<<1)>>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function O(e,t,r){N.call(this,e,t,r)}N.prototype.update=function(e){if(this.finalized)throw Error("finalize already called");var t=y(e);e=t[0];for(var r,n,s=t[1],i=this.blocks,o=this.byteCount,a=e.length,c=this.blockCount,u=0,h=this.s;u<a;){if(this.reset)for(this.reset=!1,i[0]=this.block,r=1;r<c+1;++r)i[r]=0;if(s)for(r=this.start;u<a&&r<o;++u)(n=e.charCodeAt(u))<128?i[r>>2]|=n<<l[3&r++]:n<2048?(i[r>>2]|=(192|n>>6)<<l[3&r++],i[r>>2]|=(128|63&n)<<l[3&r++]):n<55296||n>=57344?(i[r>>2]|=(224|n>>12)<<l[3&r++],i[r>>2]|=(128|n>>6&63)<<l[3&r++],i[r>>2]|=(128|63&n)<<l[3&r++]):(n=65536+((1023&n)<<10|1023&e.charCodeAt(++u)),i[r>>2]|=(240|n>>18)<<l[3&r++],i[r>>2]|=(128|n>>12&63)<<l[3&r++],i[r>>2]|=(128|n>>6&63)<<l[3&r++],i[r>>2]|=(128|63&n)<<l[3&r++]);else for(r=this.start;u<a&&r<o;++u)i[r>>2]|=e[u]<<l[3&r++];if(this.lastByteIndex=r,r>=o){for(this.start=r-o,this.block=i[c],r=0;r<c;++r)h[r]^=i[r];U(h),this.reset=!0}else this.start=r}return this},N.prototype.encode=function(e,t){var r=255&e,n=1,s=[r];for(r=255&(e>>=8);r>0;)s.unshift(r),r=255&(e>>=8),++n;return t?s.push(n):s.unshift(n),this.update(s),s.length},N.prototype.encodeString=function(e){var t=y(e);e=t[0];var r=t[1],n=0,s=e.length;if(r)for(var i=0;i<e.length;++i){var o=e.charCodeAt(i);o<128?n+=1:o<2048?n+=2:o<55296||o>=57344?n+=3:(o=65536+((1023&o)<<10|1023&e.charCodeAt(++i)),n+=4)}else n=s;return n+=this.encode(8*n),this.update(e),n},N.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n<e.length;++n)r+=this.encodeString(e[n]);var s=(t-r%t)%t,i=[];return i.length=s,this.update(i),this},N.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex,r=this.blockCount,n=this.s;if(e[t>>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t<r+1;++t)e[t]=0;for(e[r-1]|=2147483648,t=0;t<r;++t)n[t]^=e[t];U(n)}},N.prototype.toString=N.prototype.hex=function(){this.finalize();for(var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,i=0,o=0,c="";o<n;){for(i=0;i<t&&o<n;++i,++o)e=r[i],c+=a[e>>4&15]+a[15&e]+a[e>>12&15]+a[e>>8&15]+a[e>>20&15]+a[e>>16&15]+a[e>>28&15]+a[e>>24&15];o%t==0&&(r=w(r),U(r),i=0)}return s&&(e=r[i],c+=a[e>>4&15]+a[15&e],s>1&&(c+=a[e>>12&15]+a[e>>8&15]),s>2&&(c+=a[e>>20&15]+a[e>>16&15])),c},N.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,i=0,o=0,a=this.outputBits>>3;e=s?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);o<n;){for(i=0;i<t&&o<n;++i,++o)c[o]=r[i];o%t==0&&(r=w(r),U(r))}return s&&(c[o]=r[i],e=e.slice(0,a)),e},N.prototype.buffer=N.prototype.arrayBuffer,N.prototype.digest=N.prototype.array=function(){this.finalize();for(var e,t,r=this.blockCount,n=this.s,s=this.outputBlocks,i=this.extraBytes,o=0,a=0,c=[];a<s;){for(o=0;o<r&&a<s;++o,++a)e=a<<2,t=n[o],c[e]=255&t,c[e+1]=t>>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r==0&&(n=w(n),U(n))}return i&&(e=a<<2,t=n[o],c[e]=255&t,i>1&&(c[e+1]=t>>8&255),i>2&&(c[e+2]=t>>16&255)),c},O.prototype=new N,O.prototype.finalize=function(){return this.encode(this.outputBits,!0),N.prototype.finalize.call(this)};var U=e=>{var t,r,n,s,i,o,a,c,l,h,d,p,f,g,m,y,b,w,v,E,S,A,I,_,C,x,k,T,P,R,L,D,M,N,O,U,F,B,$,q,z,j,K,V,H,G,W,X,Z,Y,Q,J,ee,te,re,ne,se,ie,oe,ae,ce,le,ue;for(n=0;n<48;n+=2)s=e[0]^e[10]^e[20]^e[30]^e[40],i=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],l=e[5]^e[15]^e[25]^e[35]^e[45],h=e[6]^e[16]^e[26]^e[36]^e[46],d=e[7]^e[17]^e[27]^e[37]^e[47],t=(p=e[8]^e[18]^e[28]^e[38]^e[48])^(o<<1|a>>>31),r=(f=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|o>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=s^(c<<1|l>>>31),r=i^(l<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=o^(h<<1|d>>>31),r=a^(d<<1|h>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(p<<1|f>>>31),r=l^(f<<1|p>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=h^(s<<1|i>>>31),r=d^(i<<1|s>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],m=e[1],G=e[11]<<4|e[10]>>>28,W=e[10]<<4|e[11]>>>28,T=e[20]<<3|e[21]>>>29,P=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,j=e[40]<<18|e[41]>>>14,K=e[41]<<18|e[40]>>>14,N=e[2]<<1|e[3]>>>31,O=e[3]<<1|e[2]>>>31,y=e[13]<<12|e[12]>>>20,b=e[12]<<12|e[13]>>>20,X=e[22]<<10|e[23]>>>22,Z=e[23]<<10|e[22]>>>22,R=e[33]<<13|e[32]>>>19,L=e[32]<<13|e[33]>>>19,le=e[42]<<2|e[43]>>>30,ue=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,U=e[14]<<6|e[15]>>>26,F=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,v=e[24]<<11|e[25]>>>21,Y=e[34]<<15|e[35]>>>17,Q=e[35]<<15|e[34]>>>17,D=e[45]<<29|e[44]>>>3,M=e[44]<<29|e[45]>>>3,_=e[6]<<28|e[7]>>>4,C=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,se=e[16]<<23|e[17]>>>9,B=e[26]<<25|e[27]>>>7,$=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,J=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,V=e[8]<<27|e[9]>>>5,H=e[9]<<27|e[8]>>>5,x=e[18]<<20|e[19]>>>12,k=e[19]<<20|e[18]>>>12,ie=e[29]<<7|e[28]>>>25,oe=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,z=e[39]<<8|e[38]>>>24,A=e[48]<<14|e[49]>>>18,I=e[49]<<14|e[48]>>>18,e[0]=g^~y&w,e[1]=m^~b&v,e[10]=_^~x&T,e[11]=C^~k&P,e[20]=N^~U&B,e[21]=O^~F&$,e[30]=V^~G&X,e[31]=H^~W&Z,e[40]=te^~ne&ie,e[41]=re^~se&oe,e[2]=y^~w&E,e[3]=b^~v&S,e[12]=x^~T&R,e[13]=k^~P&L,e[22]=U^~B&q,e[23]=F^~$&z,e[32]=G^~X&Y,e[33]=W^~Z&Q,e[42]=ne^~ie&ae,e[43]=se^~oe&ce,e[4]=w^~E&A,e[5]=v^~S&I,e[14]=T^~R&D,e[15]=P^~L&M,e[24]=B^~q&j,e[25]=$^~z&K,e[34]=X^~Y&J,e[35]=Z^~Q&ee,e[44]=ie^~ae&le,e[45]=oe^~ce&ue,e[6]=E^~A&g,e[7]=S^~I&m,e[16]=R^~D&_,e[17]=L^~M&C,e[26]=q^~j&N,e[27]=z^~K&O,e[36]=Y^~J&V,e[37]=Q^~ee&H,e[46]=ae^~le&te,e[47]=ce^~ue&re,e[8]=A^~g&y,e[9]=I^~m&b,e[18]=D^~_&x,e[19]=M^~C&k,e[28]=j^~N&U,e[29]=K^~O&F,e[38]=J^~V&G,e[39]=ee^~H&W,e[48]=le^~te&ne,e[49]=ue^~re&se,e[0]^=u[n],e[1]^=u[n+1]};if(s)Nw.exports=x;else for(T=0;T<k.length;++T)r[k[T]]=x[k[T]]}()),Ow.exports),Fw=ss(Uw);function Bw(e){return new Uint8Array(Fw.keccak256.arrayBuffer(e))}function $w(e,t,r){try{return function(e,t,r,n=Pw){let s;try{s=Cw(e),t=pw(t)}catch(e){return!1}const{r:i,s:o}=s;if(n.strict&&s.hasHighS())return!1;const a=bw(t);let c;try{c=function(e){return e instanceof Xb?(e.assertValidity(),e):Xb.fromHex(e)}(r)}catch(e){return!1}const{n:l}=Ub,u=yw(o,l),h=gw(a*u,l),d=gw(i*u,l),p=Xb.BASE.multiplyAndAddUnsafe(c,h,d);return!!p&&gw(p.x,l)===i}(Qb.fromCompact(e.slice(0,64)),t,r)}catch{return!1}}function qw(e,t){switch(t){case"udp":return qw(e,"udp4")||qw(e,"udp6");case"tcp":return qw(e,"tcp4")||qw(e,"tcp6")}const r=t.endsWith("6"),n=e.get(r?"ip6":"ip");if(!n)return;const s=t.slice(0,3);let i;switch(s){case"udp":i=r?e.get("udp6"):e.get("udp");break;case"tcp":i=r?e.get("tcp6"):e.get("tcp");break;default:return}return i?function(e,t,r,n){let s=bl("/"+e+"/"+fl(e,r));return s=s.encapsulate(bl("/"+t+"/"+fl(t,n))),s}(r?"ip6":"ip4",s,n,i):void 0}const zw=parseInt("11111",2),jw=parseInt("10000000",2),Kw=parseInt("01111111",2),Vw={0:Ww,1:Ww,2(e,t){const r=Gw(e,t),n=t.offset,s=t.offset+r,i=[];for(let t=n;t<s;t++)t===n&&0===e[t]||i.push(e[t]);return t.offset+=r,Uint8Array.from(i)},3(e,t){const r=Gw(e,t),n=e[t.offset];t.offset++;const s=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,0!==n)throw Error("Unused bits in bit string is unimplemented");return s},4(e,t){const r=Gw(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n},5:(e,t)=>(t.offset++,null),6(e,t){const r=Gw(e,t),n=t.offset+r,s=e[t.offset];t.offset++;let i=0,o=0;s<40?(i=0,o=s):s<80?(i=1,o=s-40):(i=2,o=s-80);let a=`${i}.${o}`,c=[];for(;t.offset<n;){const r=e[t.offset];if(t.offset++,c.push(127&r),r<128){c.reverse();let e=0;for(let t=0;t<c.length;t++)e+=c[t]<<7*t;a+="."+e,c=[]}}return a},16:Ww,22:Ww,48:Ww};function Hw(e,t={offset:0}){const r=e[t.offset]&zw;if(t.offset++,null!=Vw[r])return Vw[r](e,t);throw Error("No decoder for tag "+r)}function Gw(e,t){let r=0;if((e[t.offset]&jw)===jw){const n=e[t.offset]&Kw;let s="0x";t.offset++;for(let r=0;r<n;r++,t.offset++)s+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(s,16)}else r=e[t.offset],t.offset++;return r}function Ww(e,t){Gw(e,t);const r=[];for(;!(t.offset>=e.byteLength);){const n=Hw(e,t);if(null===n)break;r.push(n)}return r}function Xw(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);const t=function(e){let t=e.toString(16);t.length%2==1&&(t="0"+t);const r=new Us;for(let e=0;e<t.length;e+=2)r.append(Uint8Array.from([parseInt(`${t[e]}${t[e+1]}`,16)]));return r}(e.byteLength);return new Us(Uint8Array.from([t.byteLength|jw]),t)}function Zw(e){const t=new Us;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new Us(Uint8Array.from([2]),Xw(t),t)}function Yw(e){const t=Uint8Array.from([0]),r=new Us(t,e);return new Us(Uint8Array.from([3]),Xw(r),r)}function Qw(e,t=48){const r=new Us;for(const t of e)r.append(t);return new Us(Uint8Array.from([t]),Xw(r),r)}const Jw=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),ev=Uint8Array.from([6,5,43,129,4,0,34]),tv=Uint8Array.from([6,5,43,129,4,0,35]),rv={ext:!0,kty:"EC",crv:"P-256"},nv={ext:!0,kty:"EC",crv:"P-384"},sv={ext:!0,kty:"EC",crv:"P-521"};function iv(e){if("P-256"===e)return Jw;if("P-384"===e)return ev;if("P-521"===e)return tv;throw new Pn("Invalid curve "+e)}class ov{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){var e;return null==this._raw&&(this._raw=(e=this.jwk,Qw([Zw(Uint8Array.from([1])),Qw([iv(e.crv)],160),Qw([Yw(new Us(Uint8Array.from([4]),Ye(e.x??"","base64url"),Ye(e.y??"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return Ne.digest(Sv(this))}toCID(){return qe.createV1(114,this.toMultihash())}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}async verify(e,t,r){return async function(e,t,r,n){const s=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();const i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}}class av extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class cv extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}var lv={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new cv("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};let uv;const hv=(async()=>{try{return await lv.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function dv(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class pv{type="Ed25519";raw;constructor(e){this.raw=fv(e,32)}toMultihash(){return Ne.digest(Sv(this))}toCID(){return qe.createV1(114,this.toMultihash())}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();const n=async function(e,t,r){return null==uv&&(uv=await hv),uv?async function(e,t,r){if(e.buffer instanceof ArrayBuffer){const n=await lv.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await lv.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(e,t,r):function(e,t,r){return Na.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(e,t,r)}(this.raw,t,e);return dv(n)?n.then((e=>(r?.signal?.throwIfAborted(),e))):n}}function fv(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Pn(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var gv,mv,yv,bv;(e=>{e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(gv||(gv={})),(e=>{e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(mv||(mv={})),(e=>{e.codec=()=>Gt(mv)})(gv||(gv={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),gv.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=gv.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(yv||(yv={})),(e=>{let t;e.codec=()=>(null==t&&(t=Wt(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),gv.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos<n;){const t=e.uint32();switch(t>>>3){case 1:r.Type=gv.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>ht(t,e.codec()),e.decode=(t,r)=>M(t,e.codec(),r)})(bv||(bv={}));class wv{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return null==this._raw&&(this._raw=function(e){if(null==e.n||null==e.e)throw new Pn("JWK was missing components");return Qw([vv,Yw(Qw([Zw(Ye(e.n,"base64url")),Zw(Ye(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return qe.createV1(114,this._multihash)}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}verify(e,t,r){return async function(e,t,r,n){const s=await lv.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();const i=await lv.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}}const vv=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);class Ev{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return wc.ProjectivePoint.fromHex(e),e}catch(e){throw new Rn(e+"")}}(e),this.raw=function(e){return wc.ProjectivePoint.fromHex(e).toRawBytes(!0)}(this._key)}toMultihash(){return Ne.digest(Sv(this))}toCID(){return qe.createV1(114,this.toMultihash())}toString(){return fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ds(this.raw,e.raw)}verify(e,t,r){return function(e,t,r,n){const s=Ue.digest(r instanceof Uint8Array?r:r.subarray());if(dv(s))return s.then((({digest:r})=>(n?.signal?.throwIfAborted(),wc.verify(t,r,e)))).catch((e=>{if("AbortError"===e.name)throw e;throw new av(e+"")}));try{return n?.signal?.throwIfAborted(),wc.verify(t,s.digest,e)}catch(e){throw new av(e+"")}}(this._key,t,e,r)}}function Sv(e){return yv.encode({Type:gv[e.type],Data:e.raw})}const Av=Symbol.for("nodejs.util.inspect.custom");class Iv{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[En]=!0;toString(){return null==this.string&&(this.string=fe.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return qe.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Ds(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return Ds(this.multihash.bytes,e.toMultihash().bytes);throw Error("not valid Id")}[Av](){return`PeerId(${this.toString()})`}}class _v extends Iv{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class Cv extends Iv{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class xv extends Iv{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}function kv(e){const t=e.reduce(((e,t)=>e+2+t.bytes.length),0),r=new Uint8Array(t),n=new DataView(r.buffer);let s=0;return e.forEach((e=>{if(e.getPeerId())throw Error("`multiaddr` field MUST not contain peer id");n.setUint16(s,e.bytes.length),s+=2,r.set(e.bytes,s),s+=e.bytes.length})),r}function Tv(e){let t=0;return e.lightPush&&(t+=1),t<<=1,e.filter&&(t+=1),t<<=1,e.store&&(t+=1),t<<=1,e.relay&&(t+=1),t}class Pv extends Map{seq;signature;constructor(e={},t=BigInt(1),r){super(Object.entries(e)),this.seq=t,this.signature=r}set(e,t){return this.signature=void 0,this.seq++,super.set(e,t)}get id(){const e=this.get("id");if(!e)throw Error("id not found.");return on(e)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw Error(Pb)}get rs(){const e=this.get("rs");if(e)return mn(e)}get rsv(){const e=this.get("rsv");if(e)return mn(e)}get ip(){return Rv(this,"ip","ip4")}set ip(e){Dv(this,"ip","ip4",e)}get tcp(){return Lv(this,"tcp","tcp")}set tcp(e){Mv(this,"tcp","tcp",e)}get udp(){return Lv(this,"udp","udp")}set udp(e){Mv(this,"udp","udp",e)}get ip6(){return Rv(this,"ip6","ip6")}set ip6(e){Dv(this,"ip6","ip6",e)}get tcp6(){return Lv(this,"tcp6","tcp")}set tcp6(e){Mv(this,"tcp6","tcp",e)}get udp6(){return Lv(this,"udp6","udp")}set udp6(e){Mv(this,"udp6","udp",e)}get multiaddrs(){const e=this.get("multiaddrs");if(e)return function(e){const t=[];let r=0;for(;r<e.length;){const n=new DataView(e.buffer,r,2).getUint16(0);r+=2;const s=e.slice(r,r+n);r+=n,t.push(bl(s))}return t}(e)}set multiaddrs(e){Nv(this,"multiaddrs",e,kv)}get waku2(){const e=this.get("waku2");if(e)return function(e){const t={relay:!1,store:!1,filter:!1,lightPush:!1};return e%2&&(t.relay=!0),(e>>=1)%2&&(t.store=!0),(e>>=1)%2&&(t.filter=!0),(e>>=1)%2&&(t.lightPush=!0),t}(e[0])}set waku2(e){Nv(this,"waku2",e,(e=>new Uint8Array([Tv(e)])))}}function Rv(e,t,r){const n=e.get(t);if(n)return fl(r,n)}function Lv(e,t,r){const n=e.get(t);if(n)return Number(fl(r,n))}function Dv(e,t,r,n){Nv(e,t,n,gl.bind({},r))}function Mv(e,t,r,n){Dv(e,t,r,n?.toString(10))}function Nv(e,t,r,n){void 0!==r?e.set(t,n(r)):e.delete(t)}const Ov=new fs("enr");var Uv,Fv;(e=>{e.TCP="tcp",e.UDP="udp"})(Uv||(Uv={})),(e=>{e.TCP4="tcp4",e.UDP4="udp4",e.TCP6="tcp6",e.UDP6="udp6"})(Fv||(Fv={}));class Bv extends Pv{static RECORD_PREFIX="enr:";peerId;static create(e={},t=BigInt(1),r){const n=new Bv(e,t,r);try{const e=n.publicKey;e&&(n.peerId=function(e){const t=function(e){if(32===e.byteLength)return t=fv(t=e,32),new pv(t);if(33===e.byteLength)return function(e){return new Ev(e)}(e);var t;const r=Hw(e),n=r[1]?.[0];if("1.2.840.10045.3.1.7"===n||"1.3.132.0.34"===n||"1.3.132.0.35"===n)return function(e){const t=e[1][1][0];let r,n;if(65===t.byteLength)return r=tn(t.subarray(1,33),"base64url"),n=tn(t.subarray(33),"base64url"),new ov({...rv,key_ops:["verify"],x:r,y:n});if(97===t.byteLength)return r=tn(t.subarray(1,49),"base64url"),n=tn(t.subarray(49),"base64url"),new ov({...nv,key_ops:["verify"],x:r,y:n});if(133===t.byteLength)return r=tn(t.subarray(1,67),"base64url"),n=tn(t.subarray(67),"base64url"),new ov({...sv,key_ops:["verify"],x:r,y:n});throw new Pn(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}(r);if("1.2.840.113549.1.1.1"===r[0]?.[0])return function(e,t,r){const n=function(e){const t=Hw(e[1],{offset:0});return{kty:"RSA",n:tn(t[0],"base64url"),e:tn(t[1],"base64url")}}(e);return null==r&&(r=Re(18,en(yv.encode({Type:gv.RSA,Data:t})))),new wv(n,r)}(r,e);throw new Pn("Could not extract public key from raw bytes")}(e);if("secp256k1"!==t.type)throw Error("Keypair type not implemented");return function(e){if("Ed25519"===e.type)return new Cv({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new xv({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new _v({multihash:e.toCID().multihash,publicKey:e});throw new Qn}(t)}(e))}catch(e){Ov.error("Could not calculate peer id for ENR",e)}return n}get nodeId(){if("v4"===this.id)return this.publicKey?function(e){const t=Xb.fromHex(e).toRawBytes(!1);return sn(Bw(t.slice(1)))}(this.publicKey):void 0;throw Error(Pb)}getLocationMultiaddr=qw.bind({},this);get shardInfo(){return this.rs&&this.rsv&&Ov.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(e){const t=e.protoNames();if(2!==t.length&&"udp"!==t[1]&&"tcp"!==t[1])throw Error("Invalid multiaddr");const r=e.tuples();if(!r[0][1]||!r[1][1])throw Error("Invalid multiaddr");4===r[0][0]?(this.set("ip",r[0][1]),this.set(t[1],r[1][1])):(this.set("ip6",r[0][1]),this.set(t[1]+"6",r[1][1]))}getAllLocationMultiaddrs(){const e=[];for(const t of Object.values(Fv)){const r=this.getLocationMultiaddr(t);r&&e.push(r)}const t=this.multiaddrs??[];return e.concat(t).map((e=>this.peerId?e.encapsulate("/p2p/"+this.peerId.toString()):e))}get peerInfo(){const e=this.peerId;if(e)return{id:e,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(e){if(this.peerId){const t=this.getLocationMultiaddr(e);if(t)return t.encapsulate("/p2p/"+this.peerId.toString())}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){const e=this.peerId;return this.multiaddrs.map((t=>t.encapsulate("/p2p/"+e.toString())))}return[]}verify(e,t){if(!this.get("id")||"v4"!==this.id)throw Error(Pb);if(!this.publicKey)throw Error("Failed to verify ENR: No public key");return $w(t,Bw(e),this.publicKey)}async sign(e,t){if("v4"!==this.id)throw Error(Pb);return this.signature=await async function(e,t){return async function(e,t,r={}){const{seed:n,m:s,d:i}=function(e,t,r){if(null==e)throw Error(`sign: expected valid message hash, not "${e}"`);const n=pw(e),s=_w(t),i=[Tw(s),kw(n)];if(null!=r){!0===r&&(r=Dw.randomBytes($b));const e=pw(r);if(e.length!==$b)throw Error("sign: Expected 32 bytes of extra data");i.push(e)}return{seed:tw(...i),m:xw(n),d:s}}(e,t,r.extraEntropy),o=new Ew(32,qb);let a;for(await o.reseed(n);!(a=Iw(await o.generate(),s,i,r.canonical));)await o.reseed();return function(e,t){const{sig:r,recovery:n}=e,{der:s,recovered:i}=Object.assign({canonical:!0,der:!0},t),o=s?r.toDERRawBytes():r.toCompactRawBytes();return i?[o,n]:o}(a,r)}(Bw(t),e,{der:!1})}(t,e),this.signature}}let $v=!1,qv=!1;const zv={debug:1,default:2,info:2,warning:3,error:4,off:5};let jv=zv.default,Kv=null;const Vv=function(){try{const e=[];if(["NFD","NFC","NFKD","NFKC"].forEach((t=>{try{if("test"!=="test".normalize(t))throw Error("bad normalize")}catch(r){e.push(t)}})),e.length)throw Error("missing "+e.join(", "))}catch(e){return e.message}return null}();var Hv,Gv;(e=>{e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR",e.OFF="OFF"})(Hv||(Hv={})),(e=>{e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.TIMEOUT="TIMEOUT",e.BUFFER_OVERRUN="BUFFER_OVERRUN",e.NUMERIC_FAULT="NUMERIC_FAULT",e.MISSING_NEW="MISSING_NEW",e.INVALID_ARGUMENT="INVALID_ARGUMENT",e.MISSING_ARGUMENT="MISSING_ARGUMENT",e.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",e.CALL_EXCEPTION="CALL_EXCEPTION",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.NONCE_EXPIRED="NONCE_EXPIRED",e.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",e.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",e.TRANSACTION_REPLACED="TRANSACTION_REPLACED",e.ACTION_REJECTED="ACTION_REJECTED"})(Gv||(Gv={}));const Wv="0123456789abcdef";class Xv{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const r=e.toLowerCase();null==zv[r]&&this.throwArgumentError("invalid log level name","logLevel",e)}debug(...e){this._log(Xv.levels.DEBUG,e)}info(...e){this._log(Xv.levels.INFO,e)}warn(...e){this._log(Xv.levels.WARNING,e)}makeError(e,t,r){if(qv)return this.makeError("censored error",t,{});t||(t=Xv.errors.UNKNOWN_ERROR),r||(r={});const n=[];Object.keys(r).forEach((e=>{const t=r[e];try{if(t instanceof Uint8Array){let r="";for(let e=0;e<t.length;e++)r+=Wv[t[e]>>4],r+=Wv[15&t[e]];n.push(e+"=Uint8Array(0x"+r+")")}else n.push(e+"="+JSON.stringify(t))}catch(t){n.push(e+"="+JSON.stringify(r[e].toString()))}})),n.push("code="+t),n.push("version="+this.version);const s=e;let i="";switch(t){case Gv.NUMERIC_FAULT:{i="NUMERIC_FAULT";const t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":i+="-"+t;break;case"negative-power":case"negative-width":i+="-unsupported";break;case"unbound-bitwise-result":i+="-unbound-result"}break}case Gv.CALL_EXCEPTION:case Gv.INSUFFICIENT_FUNDS:case Gv.MISSING_NEW:case Gv.NONCE_EXPIRED:case Gv.REPLACEMENT_UNDERPRICED:case Gv.TRANSACTION_REPLACED:case Gv.UNPREDICTABLE_GAS_LIMIT:i=t}i&&(e+=" [ See: https://links.ethers.org/v5-errors-"+i+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const o=Error(e);return o.reason=s,o.code=t,Object.keys(r).forEach((e=>{o[e]=r[e]})),o}throwError(e,t,r){throw this.makeError(e,t,r)}throwArgumentError(e,t,r){return this.throwError(e,Xv.errors.INVALID_ARGUMENT,{argument:t,value:r})}assert(e,t,r,n){e||this.throwError(t,r,n)}assertArgument(e,t,r,n){e||this.throwArgumentError(t,r,n)}checkNormalize(e){Vv&&this.throwError("platform missing String.prototype.normalize",Xv.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:Vv})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,Xv.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,Xv.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",e<t&&this.throwError("missing argument"+r,Xv.errors.MISSING_ARGUMENT,{count:e,expectedCount:t}),e>t&&this.throwError("too many arguments"+r,Xv.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){e!==Object&&null!=e||this.throwError("missing new",Xv.errors.MISSING_NEW,{name:t.name})}checkAbstract(e,t){e===t?this.throwError("cannot instantiate abstract class "+JSON.stringify(t.name)+" directly; use a sub-class",Xv.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):e!==Object&&null!=e||this.throwError("missing new",Xv.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return Kv||(Kv=new Xv("logger/5.8.0")),Kv}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",Xv.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),$v){if(!e)return;this.globalLogger().throwError("error censorship permanent",Xv.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}qv=!!e,$v=!!t}static setLogLevel(e){const t=zv[e.toLowerCase()];null!=t?jv=t:Xv.globalLogger().warn("invalid log level - "+e)}static from(e){return new Xv(e)}}Xv.errors=Gv,Xv.levels=Hv;const Zv=new Xv("bytes/5.8.0");function Yv(e){return!!e.toHexString}function Qv(e){return e.slice||(e.slice=function(){const t=[].slice.call(arguments);return Qv(new Uint8Array([].slice.apply(e,t)))}),e}function Jv(e){return"number"==typeof e&&e==e&&e%1==0}function eE(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e)return!1;if(!Jv(e.length)||e.length<0)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(!Jv(r)||r<0||r>=256)return!1}return!0}function tE(e,t){if(t||(t={}),"number"==typeof e){Zv.checkSafeUint53(e,"invalid arrayify value");const t=[];for(;e;)t.unshift(255&e),e=parseInt(e/256+"");return 0===t.length&&t.push(0),Qv(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),Yv(e)&&(e=e.toHexString()),rE(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":Zv.throwArgumentError("hex data is odd-length","value",e));const n=[];for(let e=0;e<r.length;e+=2)n.push(parseInt(r.substring(e,e+2),16));return Qv(new Uint8Array(n))}return eE(e)?Qv(new Uint8Array(e)):Zv.throwArgumentError("invalid arrayify value","value",e)}function rE(e){return!("string"!=typeof e||!e.match(/^0x[0-9A-Fa-f]*$/))}const nE="0123456789abcdef";function sE(e,t){if(t||(t={}),"number"==typeof e){Zv.checkSafeUint53(e,"invalid hexlify value");let t="";for(;e;)t=nE[15&e]+t,e=Math.floor(e/16);return t.length?(t.length%2&&(t="0"+t),"0x"+t):"0x00"}if("bigint"==typeof e)return(e=e.toString(16)).length%2?"0x0"+e:"0x"+e;if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),Yv(e))return e.toHexString();if(rE(e))return e.length%2&&("left"===t.hexPad?e="0x0"+e.substring(2):"right"===t.hexPad?e+="0":Zv.throwArgumentError("hex data is odd-length","value",e)),e.toLowerCase();if(eE(e)){let t="0x";for(let r=0;r<e.length;r++){let n=e[r];t+=nE[(240&n)>>4]+nE[15&n]}return t}return Zv.throwArgumentError("invalid hexlify value","value",e)}const iE=new Xv("rlp/5.8.0");function oE(e){const t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function aE(e,t,r){let n=0;for(let s=0;s<r;s++)n=256*n+e[t+s];return n}function cE(e){if(Array.isArray(e)){let t=[];if(e.forEach((e=>{t=t.concat(cE(e))})),t.length<=55)return t.unshift(192+t.length),t;const r=oE(t.length);return r.unshift(247+r.length),r.concat(t)}var t;rE(t=e)&&!(t.length%2)||eE(t)||iE.throwArgumentError("RLP object must be BytesLike","object",e);const r=[].slice.call(tE(e));if(1===r.length&&r[0]<=127)return r;if(r.length<=55)return r.unshift(128+r.length),r;const n=oE(r.length);return n.unshift(183+n.length),n.concat(r)}function lE(e,t,r,n){const s=[];for(;r<t+1+n;){const i=uE(e,r);s.push(i.result),(r+=i.consumed)>t+1+n&&iE.throwError("child data too short",Xv.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:s}}function uE(e,t){if(0===e.length&&iE.throwError("data too short",Xv.errors.BUFFER_OVERRUN,{}),e[t]>=248){const r=e[t]-247;t+1+r>e.length&&iE.throwError("data short segment too short",Xv.errors.BUFFER_OVERRUN,{});const n=aE(e,t+1,r);return t+1+r+n>e.length&&iE.throwError("data long segment too short",Xv.errors.BUFFER_OVERRUN,{}),lE(e,t,t+1+r,r+n)}if(e[t]>=192){const r=e[t]-192;return t+1+r>e.length&&iE.throwError("data array too short",Xv.errors.BUFFER_OVERRUN,{}),lE(e,t,t+1,r)}if(e[t]>=184){const r=e[t]-183;t+1+r>e.length&&iE.throwError("data array too short",Xv.errors.BUFFER_OVERRUN,{});const n=aE(e,t+1,r);return t+1+r+n>e.length&&iE.throwError("data array too short",Xv.errors.BUFFER_OVERRUN,{}),{consumed:1+r+n,result:sE(e.slice(t+1+r,t+1+r+n))}}if(e[t]>=128){const r=e[t]-128;return t+1+r>e.length&&iE.throwError("data too short",Xv.errors.BUFFER_OVERRUN,{}),{consumed:1+r,result:sE(e.slice(t+1,t+1+r))}}return{consumed:1,result:sE(e[t])}}const hE=new fs("enr:decoder");class dE{static fromString(e){if(!e.startsWith(Bv.RECORD_PREFIX))throw Error(`"string encoded ENR must start with '${Bv.RECORD_PREFIX}'`);return dE.fromRLP(Ye(e.slice(4),"base64url"))}static fromRLP(e){return async function(e){const{signature:t,seq:r,kvs:n}=function(e){if(!Array.isArray(e))throw Error("Decoded ENR must be an array");if(e.length%2!=0)throw Error("Decoded ENR must have an even number of elements");const[t,r,...n]=e;if(!t||Array.isArray(t))throw Error("Decoded ENR invalid signature: must be a byte array");if(!r||Array.isArray(r))throw Error("Decoded ENR invalid sequence number: must be a byte array");return{signature:t,seq:r,kvs:n}}(e),s={};for(let e=0;e<n.length;e+=2)try{s[on(n[e])]=n[e+1]}catch(t){hE.error("Failed to decode ENR key to UTF-8, skipping it",n[e],t)}const i=function(e){return e.length?BigInt("0x"+sn(e)):BigInt(0)}(r),o=Bv.create(s,i,t);return function(e,t,r,n){const s=rn(sE(cE([e,...t])));if(!r.verify(s,n))throw Error("Unable to verify ENR signature")}(r,n,o,t),o}(function(e){const t=tE(e),r=uE(t,0);return r.consumed!==t.length&&iE.throwArgumentError("invalid rlp data","data",e),r.result}(e).map(rn))}}class pE extends Map{#N=0;#O=new Map;#U=new Map;#F;#B;#$;constructor(e={}){if(super(),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if("number"==typeof e.maxAge&&0===e.maxAge)throw new TypeError("`maxAge` must be a number greater than 0");this.#F=e.maxSize,this.#B=e.maxAge||1/0,this.#$=e.onEviction}get __oldCache(){return this.#U}#q(e){if("function"==typeof this.#$)for(const[t,r]of e)this.#$(t,r.value)}#z(e,t){return"number"==typeof t.expiry&&t.expiry<=Date.now()&&("function"==typeof this.#$&&this.#$(e,t.value),this.delete(e))}#j(e,t){if(!1===this.#z(e,t))return t.value}#K(e,t){return t.expiry?this.#j(e,t):t.value}#V(e,t){const r=t.get(e);return this.#K(e,r)}#H(e,t){this.#O.set(e,t),this.#N++,this.#N>=this.#F&&(this.#N=0,this.#q(this.#U),this.#U=this.#O,this.#O=new Map)}#G(e,t){this.#U.delete(e),this.#H(e,t)}*#W(){for(const e of this.#U){const[t,r]=e;this.#O.has(t)||!1===this.#z(t,r)&&(yield e)}for(const e of this.#O){const[t,r]=e;!1===this.#z(t,r)&&(yield e)}}get(e){if(this.#O.has(e)){const t=this.#O.get(e);return this.#K(e,t)}if(this.#U.has(e)){const t=this.#U.get(e);if(!1===this.#z(e,t))return this.#G(e,t),t.value}}set(e,t,{maxAge:r=this.#B}={}){const n="number"==typeof r&&r!==1/0?Date.now()+r:void 0;return this.#O.has(e)?this.#O.set(e,{value:t,expiry:n}):this.#H(e,{value:t,expiry:n}),this}has(e){return this.#O.has(e)?!this.#z(e,this.#O.get(e)):!!this.#U.has(e)&&!this.#z(e,this.#U.get(e))}peek(e){return this.#O.has(e)?this.#V(e,this.#O):this.#U.has(e)?this.#V(e,this.#U):void 0}expiresIn(e){const t=this.#O.get(e)??this.#U.get(e);if(t)return t.expiry?t.expiry-Date.now():1/0}delete(e){const t=this.#O.delete(e);return t&&this.#N--,this.#U.delete(e)||t}clear(){this.#O.clear(),this.#U.clear(),this.#N=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");const t=[...this.#W()],r=t.length-e;r<0?(this.#O=new Map(t),this.#U=new Map,this.#N=t.length):(r>0&&this.#q(t.slice(0,r)),this.#U=new Map(t.slice(r)),this.#O=new Map,this.#N=0),this.#F=e}evict(e=1){const t=Number(e);if(!t||t<=0)return;const r=[...this.#W()],n=Math.trunc(Math.min(t,Math.max(r.length-1,0)));n<=0||(this.#q(r.slice(0,n)),this.#U=new Map(r.slice(n)),this.#O=new Map,this.#N=0)}*keys(){for(const[e]of this)yield e}*values(){for(const[,e]of this)yield e}*[Symbol.iterator](){for(const e of this.#O){const[t,r]=e;!1===this.#z(t,r)&&(yield[t,r.value])}for(const e of this.#U){const[t,r]=e;this.#O.has(t)||!1===this.#z(t,r)&&(yield[t,r.value])}}*entriesDescending(){let e=[...this.#O];for(let t=e.length-1;t>=0;--t){const r=e[t],[n,s]=r;!1===this.#z(n,s)&&(yield[n,s.value])}e=[...this.#U];for(let t=e.length-1;t>=0;--t){const r=e[t],[n,s]=r;this.#O.has(n)||!1===this.#z(n,s)&&(yield[n,s.value])}}*entriesAscending(){for(const[e,t]of this.#W())yield[e,t.value]}get size(){if(!this.#N)return this.#U.size;let e=0;for(const t of this.#U.keys())this.#O.has(t)||e++;return Math.min(this.#N+e,this.#F)}get maxSize(){return this.#F}get maxAge(){return this.#B}entries(){return this.entriesAscending()}forEach(e,t=this){for(const[r,n]of this.entriesAscending())e.call(t,n,r,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}function fE(e,t,r){return`${e}?name=${t}&type=${r}`}async function gE(e,t){const r=await fetch(e,{headers:new Headers({accept:"application/dns-json"}),signal:t});return await r.json()}function mE(e,t){return`${t}_${e}`}const yE=Object.assign(yg("dns-over-http-resolver"),{error:yg("dns-over-http-resolver:error")});class bE{_cache;_TXTcache;_servers;_request;_abortControllers;constructor(e={}){this._cache=new pE({maxSize:e?.maxCache??100}),this._TXTcache=new pE({maxSize:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??gE,this._abortControllers=[]}cancel(){this._abortControllers.forEach((e=>{e.abort()}))}getServers(){return this._servers}_getShuffledServers(){const e=[...this._servers];for(let t=e.length-1;t>0;t--){const r=Math.floor(Math.random()*t),n=e[t];e[t]=e[r],e[r]=n}return e}setServers(e){this._servers=e}async resolve(e,t="A"){switch(t){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw Error(t+" is not supported")}}async resolve4(e){const t="A",r=this._cache.get(mE(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const s=new AbortController;this._abortControllers.push(s);try{const n=await this._request(fE(r,e,t),s.signal),i=n.Answer.map((e=>e.data)),o=Math.min(...n.Answer.map((e=>e.TTL)));return this._cache.set(mE(e,t),i,{maxAge:o}),i}catch(i){s.signal.aborted&&(n=!0),yE.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter((e=>e!==s))}}if(n)throw Object.assign(Error("queryA ECANCELLED"),{code:"ECANCELLED"});throw Error(`Could not resolve ${e} record ${t}`)}async resolve6(e){const t="AAAA",r=this._cache.get(mE(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const s=new AbortController;this._abortControllers.push(s);try{const n=await this._request(fE(r,e,t),s.signal),i=n.Answer.map((e=>e.data)),o=Math.min(...n.Answer.map((e=>e.TTL)));return this._cache.set(mE(e,t),i,{maxAge:o}),i}catch(i){s.signal.aborted&&(n=!0),yE.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter((e=>e!==s))}}if(n)throw Object.assign(Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"});throw Error(`Could not resolve ${e} record ${t}`)}async resolveTxt(e){const t="TXT",r=this._TXTcache.get(mE(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const s=new AbortController;this._abortControllers.push(s);try{const n=await this._request(fE(r,e,t),s.signal),i=n.Answer.map((e=>[e.data.replace(/['"]+/g,"")])),o=Math.min(...n.Answer.map((e=>e.TTL)));return this._TXTcache.set(mE(e,t),i,{maxAge:o}),i}catch(i){s.signal.aborted&&(n=!0),yE.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter((e=>e!==s))}}if(n)throw Object.assign(Error("queryTxt ECANCELLED"),{code:"ECANCELLED"});throw Error(`Could not resolve ${e} record ${t}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}}const wE=new fs("dns-over-https");class vE{resolver;static async create(){return new vE}constructor(e=new bE){this.resolver=e}async resolveTXT(e){let t;try{t=await this.resolver.resolveTxt(e)}catch(e){throw wE.error("query failed: ",e),Error("DNS query failed")}if(!t)throw Error("Could not resolve "+e);const r=[];return t.forEach((e=>{"string"==typeof e?r.push(e):Array.isArray(e)?e.forEach((e=>{"string"==typeof e?r.push(e):r.push(on(e))})):r.push(on(e))})),r}}var EE,SE={exports:{}},AE=(EE||(EE=1,(e=>{(()=>{var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof i&&i.versions&&i.versions.node&&(t=ns);var r=!t.HI_BASE32_NO_COMMON_JS&&e.exports,n="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),s={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},o=[0,0,0,0,0,0,0,0],a=(e,t)=>{t.length>10&&(t="..."+t.substr(-10));var r=Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw r.position=e,r},c=e=>{if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw Error("Invalid base32 characters");for(var t,r,n,i,o,a,c,l,u=[],h=0,d=(e=e.replace(/=/g,"")).length,p=0,f=d>>3<<3;p<f;)t=s[e.charAt(p++)],r=s[e.charAt(p++)],n=s[e.charAt(p++)],i=s[e.charAt(p++)],o=s[e.charAt(p++)],a=s[e.charAt(p++)],c=s[e.charAt(p++)],l=s[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|i>>>4),u[h++]=255&(i<<4|o>>>1),u[h++]=255&(o<<7|a<<2|c>>>3),u[h++]=255&(c<<5|l);var g=d-f;return 2===g?(t=s[e.charAt(p++)],r=s[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2)):4===g?(t=s[e.charAt(p++)],r=s[e.charAt(p++)],n=s[e.charAt(p++)],i=s[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|i>>>4)):5===g?(t=s[e.charAt(p++)],r=s[e.charAt(p++)],n=s[e.charAt(p++)],i=s[e.charAt(p++)],o=s[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|i>>>4),u[h++]=255&(i<<4|o>>>1)):7===g&&(t=s[e.charAt(p++)],r=s[e.charAt(p++)],n=s[e.charAt(p++)],i=s[e.charAt(p++)],o=s[e.charAt(p++)],a=s[e.charAt(p++)],c=s[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|i>>>4),u[h++]=255&(i<<4|o>>>1),u[h++]=255&(o<<7|a<<2|c>>>3)),u},l=(e,t)=>{if(!t)return(e=>{for(var t,r,n="",s=e.length,i=0,o=0;i<s;)if((t=e[i++])<=127)n+=String.fromCharCode(t);else{t>191&&t<=223?(r=31&t,o=1):t<=239?(r=15&t,o=2):t<=247?(r=7&t,o=3):a(i,n);for(var c=0;c<o;++c)((t=e[i++])<128||t>191)&&a(i,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&a(i,n),r>1114111&&a(i,n),r<=65535?n+=String.fromCharCode(r):(n+=String.fromCharCode(55296+((r-=65536)>>10)),n+=String.fromCharCode(56320+(1023&r)))}return n})(c(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw Error("Invalid base32 characters");var r,n,i,o,l,u,h,d,p="",f=e.indexOf("=");-1===f&&(f=e.length);for(var g=0,m=f>>3<<3;g<m;)r=s[e.charAt(g++)],n=s[e.charAt(g++)],i=s[e.charAt(g++)],o=s[e.charAt(g++)],l=s[e.charAt(g++)],u=s[e.charAt(g++)],h=s[e.charAt(g++)],d=s[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|i<<1|o>>>4))+String.fromCharCode(255&(o<<4|l>>>1))+String.fromCharCode(255&(l<<7|u<<2|h>>>3))+String.fromCharCode(255&(h<<5|d));var y=f-m;return 2===y?(r=s[e.charAt(g++)],n=s[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))):4===y?(r=s[e.charAt(g++)],n=s[e.charAt(g++)],i=s[e.charAt(g++)],o=s[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|i<<1|o>>>4))):5===y?(r=s[e.charAt(g++)],n=s[e.charAt(g++)],i=s[e.charAt(g++)],o=s[e.charAt(g++)],l=s[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|i<<1|o>>>4))+String.fromCharCode(255&(o<<4|l>>>1))):7===y&&(r=s[e.charAt(g++)],n=s[e.charAt(g++)],i=s[e.charAt(g++)],o=s[e.charAt(g++)],l=s[e.charAt(g++)],u=s[e.charAt(g++)],h=s[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|i<<1|o>>>4))+String.fromCharCode(255&(o<<4|l>>>1))+String.fromCharCode(255&(l<<7|u<<2|h>>>3))),p},u={encode(e,t){var r="string"!=typeof e;return r&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),r?(e=>{for(var t,r,s,i,o,a="",c=e.length,l=0,u=5*parseInt(c/5);l<u;)t=e[l++],r=e[l++],s=e[l++],i=e[l++],o=e[l++],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[31&(i<<3|o>>>5)]+n[31&o];var h=c-u;return 1===h?(t=e[l],a+=n[t>>>3]+n[t<<2&31]+"======"):2===h?(t=e[l++],r=e[l],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[r<<4&31]+"===="):3===h?(t=e[l++],r=e[l++],s=e[l],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[s<<1&31]+"==="):4===h&&(t=e[l++],r=e[l++],s=e[l++],i=e[l],a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[i<<3&31]+"="),a})(e):t?(e=>{for(var t,r,s,i,o,a="",c=e.length,l=0,u=5*parseInt(c/5);l<u;)t=e.charCodeAt(l++),r=e.charCodeAt(l++),s=e.charCodeAt(l++),i=e.charCodeAt(l++),o=e.charCodeAt(l++),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[31&(i<<3|o>>>5)]+n[31&o];var h=c-u;return 1===h?(t=e.charCodeAt(l),a+=n[t>>>3]+n[t<<2&31]+"======"):2===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[r<<4&31]+"===="):3===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l++),s=e.charCodeAt(l),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[s<<1&31]+"==="):4===h&&(t=e.charCodeAt(l++),r=e.charCodeAt(l++),s=e.charCodeAt(l++),i=e.charCodeAt(l),a+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[i<<3&31]+"="),a})(e):(e=>{var t,r,s,i,a,c,l,u=!1,h="",d=0,p=0,f=e.length;if(""===e)return h;do{for(o[0]=o[5],o[1]=o[6],o[2]=o[7],l=p;d<f&&l<5;++d)(c=e.charCodeAt(d))<128?o[l++]=c:c<2048?(o[l++]=192|c>>6,o[l++]=128|63&c):c<55296||c>=57344?(o[l++]=224|c>>12,o[l++]=128|c>>6&63,o[l++]=128|63&c):(c=65536+((1023&c)<<10|1023&e.charCodeAt(++d)),o[l++]=240|c>>18,o[l++]=128|c>>12&63,o[l++]=128|c>>6&63,o[l++]=128|63&c);p=l-5,d===f&&++d,d>f&&l<6&&(u=!0),t=o[0],l>4?(r=o[1],s=o[2],i=o[3],a=o[4],h+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[31&(i<<3|a>>>5)]+n[31&a]):1===l?h+=n[t>>>3]+n[t<<2&31]+"======":2===l?(r=o[1],h+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[r<<4&31]+"===="):3===l?(r=o[1],s=o[2],h+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[s<<1&31]+"==="):(r=o[1],s=o[2],i=o[3],h+=n[t>>>3]+n[31&(t<<2|r>>>6)]+n[r>>>1&31]+n[31&(r<<4|s>>>4)]+n[31&(s<<1|i>>>7)]+n[i>>>2&31]+n[i<<3&31]+"=")}while(!u);return h})(e)},decode:l};l.asBytes=c,r?e.exports=u:t.base32=u})()})(SE)),SE.exports),IE=ss(AE);class _E{static RECORD_PREFIX=Bv.RECORD_PREFIX;static TREE_PREFIX="enrtree:";static BRANCH_PREFIX="enrtree-branch:";static ROOT_PREFIX="enrtree-root:";static parseAndVerifyRoot(e,t){if(!e.startsWith(this.ROOT_PREFIX))throw Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);const r=_E.parseRootValues(e),n=IE.decode.asBytes(t),s=e.split(" sig")[0],i=an(s);if(!$w(Ye(r.signature,"base64url").slice(0,64),Bw(i),new Uint8Array(n)))throw Error("Unable to verify ENRTree root signature");return r.eRoot}static parseRootValues(e){const t=e.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/);if(!Array.isArray(t))throw Error("Could not parse ENRTree root entry");t.shift();const[r,n,s,i]=t;if(!r)throw Error("Could not parse 'e' value from ENRTree root entry");if(!n)throw Error("Could not parse 'l' value from ENRTree root entry");if(!s)throw Error("Could not parse 'seq' value from ENRTree root entry");if(!i)throw Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:r,lRoot:n,seq:Number(s),signature:i}}static parseTree(e){if(!e.startsWith(this.TREE_PREFIX))throw Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);const t=e.match(/^enrtree:\/\/([^@]+)@(.+)$/);if(!Array.isArray(t))throw Error("Could not parse ENRTree tree entry");t.shift();const[r,n]=t;if(!r)throw Error("Could not parse public key from ENRTree tree entry");if(!n)throw Error("Could not parse domain from ENRTree tree entry");return{publicKey:r,domain:n}}static parseBranch(e){if(!e.startsWith(this.BRANCH_PREFIX))throw Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);return e.split(this.BRANCH_PREFIX)[1].split(",")}}const CE=new fs("discovery:fetch_nodes");async function*xE(e,t=10,r=3){const n=new Set;let s=0,i=0;for(;s<t&&i<r;){s++;const t=await e();t&&t.nodeId?n.has(t.nodeId)||(n.add(t.nodeId),t.waku2&&(yield t),CE.info(`got new peer candidate from DNS address=${t.nodeId}@${t.ip}`)):i++}}const kE=new fs("discovery:dns");class TE{dns;_DNSTreeCache;static async dnsOverHttp(e){return e||(e=await vE.create()),new TE(e)}constructor(e){this._DNSTreeCache={},this.dns=e}async*getNextPeer(e){for(const t of function(e){if(e.length<=1)return e;for(let t=0;t<e.length;t++){const r=Math.floor(Math.random()*Math.floor(e.length)),n=e[t];e[t]=e[r],e[r]=n}return e}(e)){const{publicKey:e,domain:r}=_E.parseTree(t),n={domain:r,publicKey:e,visits:{}};for await(const e of xE((()=>this._search(r,n))))yield e}}async _search(e,t){try{const r=await this._getTXTRecord(e,t);let n,s;t.visits[e]=!0;const i=function(e){return e.startsWith(_E.ROOT_PREFIX)?_E.ROOT_PREFIX:e.startsWith(_E.BRANCH_PREFIX)?_E.BRANCH_PREFIX:e.startsWith(_E.RECORD_PREFIX)?_E.RECORD_PREFIX:""}(r);try{switch(i){case _E.ROOT_PREFIX:return n=_E.parseAndVerifyRoot(r,t.publicKey),await this._search(n,t);case _E.BRANCH_PREFIX:return s=_E.parseBranch(r),n=function(e,t){const r={};for(const[n,s]of e.entries())t.visits[s]&&(r[n]=!0);if(Object.keys(r).length===e.length)throw Error("Unresolvable circular path detected");let n;do{n=Math.floor(Math.random()*e.length)}while(r[n]);return e[n]}(s,t),await this._search(n,t);case _E.RECORD_PREFIX:return dE.fromString(r);default:return null}}catch(t){return kE.error(`Failed to search DNS tree ${i} at subdomain ${e}: ${t}`),null}}catch(t){return kE.error(`Failed to retrieve TXT record at subdomain ${e}: ${t}`),null}}async _getTXTRecord(e,t){if(this._DNSTreeCache[e])return this._DNSTreeCache[e];const r=e!==t.domain?`${e}.${t.domain}`:t.domain,n=await this.dns.resolveTXT(r);if(!n.length)throw Error("Received empty result array while fetching TXT record");if(!n[0].length)throw Error("Received empty TXT record");const s=n.join("");return this._DNSTreeCache[e]=s,s}}const PE=new fs("peer-discovery-dns");class RE extends Jn{nextPeer;_started;_components;_options;constructor(e,t){super(),this._started=!1,this._components=e,this._options=t;const{enrUrls:r}=t;PE.info("Use following EIP-1459 ENR Tree URLs: ",r)}async start(){PE.info("Starting peer discovery via dns"),this._started=!0,await this.findPeers()}async findPeers(){if(!this.nextPeer){let{enrUrls:e}=this._options;Array.isArray(e)||(e=[e]);const t=await TE.dnsOverHttp();this.nextPeer=t.getNextPeer.bind(t,e)}for await(const e of this.nextPeer()){if(!this._started)return;const{peerInfo:t,shardInfo:r}=e;if(!t)continue;const n={[Tb]:{value:this._options.tagValue??50,ttl:this._options.tagTTL??1e8}};let s=!1;await this._components.peerStore.has(t.id)?(await this._components.peerStore.get(t.id)).tags.has(Tb)||(s=!0,await this._components.peerStore.merge(t.id,{tags:n})):(s=!0,await this._components.peerStore.save(t.id,{tags:n,...r&&{metadata:{shardInfo:yn(r)}}})),s&&this.dispatchEvent(new CustomEvent("peer",{detail:t}))}}stop(){this._started=!1}get[vn](){return!0}get[Symbol.toStringTag](){return"@waku/bootstrap"}}const LE=xs.PEER_EXCHANGE,DE="/vac/waku/peer-exchange/2.0.0-alpha1";class ME{proto;constructor(e){this.proto=e}static createRequest(e){const{numPeers:t}=e;return new ME({query:{numPeers:t},response:void 0})}encode(){return qt.encode(this.proto)}static decode(e){const t=qt.decode(e);return new ME(t)}get query(){return this.proto.query}get response(){return this.proto.response}}const NE=new fs("peer-exchange");class OE{components;streamManager;constructor(e){this.components=e,this.streamManager=new di(DE,e)}async query(e){const{numPeers:t,peerId:r}=e,n=ME.createRequest({numPeers:BigInt(t)});if(!await this.components.peerStore.has(r))return{peerInfos:null,error:_s.NO_PEER_AVAILABLE};const s=await this.streamManager.getStream(r);if(!s)return NE.error("Failed to get a stream for remote peer:"+r?.toString?.()),{peerInfos:null,error:_s.NO_STREAM_AVAILABLE};const i=await si([n.encode()],Eu,s,Iu,(async e=>await Rs(e)));try{const e=new Us;i.forEach((t=>{e.append(t)}));const{response:t}=ME.decode(e);return t?{peerInfos:await Promise.all(t.peerInfos.map((e=>e.enr)).filter(Yt).map((async e=>({ENR:await dE.fromRLP(e)})))),error:null}:(NE.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:_s.EMPTY_PAYLOAD})}catch(e){return NE.error("Failed to decode push reply",e),{peerInfos:null,error:_s.DECODE_FAILED}}}}const UE=new fs("peer-exchange-discovery");class FE extends Jn{components;peerExchange;options;isStarted=!1;queryingPeers=new Set;peerExpirationRecords=new Map;continuousDiscoveryInterval=null;constructor(e,t={}){super(),this.components=e,this.peerExchange=new OE(e),this.options={...t,TTL:t.TTL??3e4},this.handleDiscoveredPeer=this.handleDiscoveredPeer.bind(this)}start(){this.isStarted||(UE.info("Starting peer exchange node discovery, discovering peers"),this.isStarted=!0,this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer),this.continuousDiscoveryInterval=setInterval((()=>{this.handlePeriodicDiscovery()}),this.options.TTL))}stop(){this.isStarted&&(UE.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.peerExpirationRecords.clear(),this.continuousDiscoveryInterval&&clearInterval(this.continuousDiscoveryInterval),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[vn](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}async handleDiscoveredPeer(e){this.runQuery(e.detail.peerId,e.detail.protocols)}async handlePeriodicDiscovery(){const e=this.components.connectionManager.getConnections();await Promise.all(e.map((async e=>{try{const t=e.remotePeer.toString();if(this.peerExpirationRecords.has(t)&&!(this.peerExpirationRecords.get(t)<=Date.now()))return null;const r=await this.components.peerStore.get(e.remotePeer);return this.runQuery(e.remotePeer,r.protocols)}catch(e){return UE.warn("Error getting peer info",e),null}})))}async runQuery(e,t){if(t.includes(DE)&&!this.queryingPeers.has(e.toString())){try{this.queryingPeers.add(e.toString()),await this.query(e)}catch(e){UE.error("Error querying peer",e)}this.peerExpirationRecords.set(e.toString(),Date.now()+this.options.TTL),this.queryingPeers.delete(e.toString())}else UE.info(`Skipping peer ${e} as it is already querying or does not support peer exchange`)}async query(e){const t=e.toString();UE.info("Querying peer exchange for "+t);const{error:r,peerInfos:n}=await this.peerExchange.query({numPeers:60,peerId:e});if(r)UE.error(`Peer exchange query to ${t} failed`,r);else for(const{ENR:e}of n){if(!e){UE.warn(`No ENR in peerInfo object from ${t}, skipping`);continue}const{peerInfo:r,shardInfo:n}=e;if(!r){UE.warn(`No peerInfo in ENR from ${t}, skipping`);continue}const s=!await this.hasShardInfo(r.id)&&n?{metadata:{shardInfo:yn(n)}}:void 0;await this.components.peerStore.merge(r.id,{tags:{[LE]:{value:50}},...s,...r.multiaddrs&&{multiaddrs:r.multiaddrs}}),UE.info("Discovered peer: "+r.id.toString()),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r.id,multiaddrs:r.multiaddrs}}))}}async hasShardInfo(e){try{const t=await this.components.peerStore.get(e);return!!t&&t.metadata.has("shardInfo")}catch(t){UE.warn("Error getting shard info for "+e.toString(),t)}return!1}}const BE=xs.PEER_CACHE,$E=e=>!!e&&"object"==typeof e&&"id"in e&&"string"==typeof e.id&&"multiaddrs"in e&&Array.isArray(e.multiaddrs);class qE{get(){return[]}set(e){}remove(){}}class zE{get(){try{const e=localStorage.getItem("waku:peers");return(e?JSON.parse(e):[]).filter($E)}catch(e){return[]}}set(e){try{localStorage.setItem("waku:peers",JSON.stringify(e))}catch(e){}}remove(){try{localStorage.removeItem("waku:peers")}catch(e){}}}const jE=new fs("peer-cache");class KE extends Jn{components;isStarted=!1;cache;constructor(e,t){super(),this.components=e,this.cache=t?.cache??(()=>{try{if("undefined"!=typeof localStorage)return new zE}catch(e){}return new qE})()}get[Symbol.toStringTag](){return"@waku/"+BE}async start(){this.isStarted||(jE.info("Starting Peer Cache Discovery"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer),await this.discoverPeers(),this.isStarted=!0)}stop(){this.isStarted&&(jE.info("Stopping Peer Cache Discovery"),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer),this.isStarted=!1)}handleDiscoveredPeer=e=>{const{peerId:t,listenAddrs:r}=e.detail,n=r.map((e=>e.toString())),s=t.toString(),i=this.readPeerInfoFromCache(),o=i.findIndex((e=>e.id===s));-1!==o?i[o].multiaddrs=n:i.push({id:s,multiaddrs:n}),this.writePeerInfoToCache(i)};async discoverPeers(){const e=this.readPeerInfoFromCache();for(const t of e){const e=Pc(t.id),r=t.multiaddrs.map((e=>bl(e)));await this.components.peerStore.has(e)||(await this.components.peerStore.save(e,{multiaddrs:r,tags:{[BE]:{value:50}}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:e,multiaddrs:r}})))}}readPeerInfoFromCache(){try{return this.cache.get()}catch(e){return jE.error("Error parsing peers from cache:",e),[]}}writePeerInfoToCache(e){try{this.cache.set(e)}catch(e){jE.error("Error saving peers to cache:",e)}}}function VE(e,t){const r=[xb,kb],n=[];var s;return e?.dns&&n.push((s=r,e=>new RE(e,{enrUrls:s}))),(e?.peerCache||t)&&n.push(function(e={}){return t=>new KE(t,e)}({cache:t})),e?.peerExchange&&n.push(function(e={}){return t=>new FE(t,e)}()),n}const HE=new fs("sdk:create");async function GE(e){const t=(e.networkConfig??Ts).clusterId??1;HE.info("Creating Waku node with cluster id: ",t);const r=e?.libp2p??{},n=r.peerDiscovery??[];e?.defaultBootstrap?n.push(...VE({dns:!0,peerExchange:!0,peerCache:!0,...e.discovery},e.peerCache)):n.push(...VE(e.discovery,e.peerCache));const s=[...e.bootstrapPeers||[],...e.store?.peers||[]];var i;return s.length&&n.push((i={list:s},e=>new pd(e,i))),r.peerDiscovery=n,async function(e,t,r){return!t?.hideWebSocketInfo&&Cb(),async function(e={}){e.privateKey??=await async function(){return async function(){const{privateKey:e,publicKey:t}=function(){const e=Na.utils.randomPrivateKey(),t=Na.getPublicKey(e),r=function(e,t){const r=new Uint8Array(64);for(let n=0;n<32;n++)r[n]=e[n],r[32+n]=t[n];return r}(e,t);return{privateKey:r,publicKey:t}}();return new Ka(e,t)}()}();const t=new _b({...await ag(e),peerId:(r=e.privateKey,Rc(r.publicKey))});var r;return!1!==e.start&&await t.start(),t}({transports:[Sf({filter:!1===t?.filterMultiaddrs||Cb()?wf:vf})],streamMuxers:[Yp()],connectionEncrypters:[Mh()],...t,services:{identify:Ip({agentVersion:r??"js-waku"}),ping:Jp({maxInboundStreams:t?.pingMaxInboundStreams??10}),metadata:Fl(e),...t?.services}})}(t,r,e?.userAgent)}var WE=0,XE={size:0,kind:17,base:null,node:null,finalizer:null},ZE={size:0,kind:17,base:null,node:null,finalizer:null},YE={size:0,kind:17,base:null,node:null,finalizer:null},QE={size:0,kind:17,base:null,node:null,finalizer:null},JE={size:0,kind:17,base:null,node:null,finalizer:null},eS={size:0,kind:22,base:null,node:null,finalizer:null},tS={size:0,kind:28,base:null,node:null,finalizer:null},rS={size:0,kind:22,base:null,node:null,finalizer:null},nS={size:0,kind:17,base:null,node:null,finalizer:null},sS={size:0,kind:17,base:null,node:null,finalizer:null},iS={size:0,kind:17,base:null,node:null,finalizer:null},oS={size:0,kind:17,base:null,node:{kind:2,len:0,offset:0,typ:null,name:null,sons:[]},finalizer:null};iS.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},sS.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},rS.base=nS,eS.base=nS;var aS={kind:2,len:5,offset:0,typ:null,name:null,sons:[{kind:1,offset:"parent",len:0,typ:rS,name:"parent",sons:null},{kind:1,offset:"name",len:0,typ:{size:0,kind:29,base:null,node:null,finalizer:null},name:"name",sons:null},{kind:1,offset:"message",len:0,typ:tS,name:"msg",sons:null},{kind:1,offset:"trace",len:0,typ:tS,name:"trace",sons:null},{kind:1,offset:"up",len:0,typ:eS,name:"up",sons:null}]};function cS(e,t){throw e.name=t,0==WE&&function(e){var t=[[]];0!=e.message.length?(t[0].push.call(t[0],69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110,58,32),t[0].push.apply(t[0],e.message)):t[0].push.call(t[0],69,114,114,111,114,58,32,117,110,104,97,110,100,108,101,100,32,101,120,99,101,112,116,105,111,110),t[0].push.call(t[0],32,91),function(e,t,r){null===e[0]&&(e[0]=[]);var n=e[0].length;e[0].length+=r.length;for(var s=0;s<r.length;++s)e[0][n+s]=r.charCodeAt(s)}(t,0,e.name),t[0].push.call(t[0],93,10);var r=function(e){for(var t=SS(e.length),r=0,n=0;r<e.length;){var s=e[r];if(s<128)t[n]=String.fromCharCode(s),r+=1;else{var i=SS(0);e:for(;;){var o=s.toString(16);if(1==(null==o?0:o.length)?i.push("%0"):i.push("%"),i.push(o),r+=1,e.length<=r||e[r]<128)break e;s=e[r]}++WE;try{t[n]=decodeURIComponent(i.join("")),--WE}catch(e){--WE,t[n]=i.join("")}}n+=1}if(t.length<n)for(var a=t.length;a<n;++a)t.push(null);else t.length=n;return t.join("")}(t[0]);throw void 0!==Error?Error(r):r}(e),e}function lS(e,t){return 0==t&&cS({message:[100,105,118,105,115,105,111,110,32,98,121,32,122,101,114,111],parent:null,m_type:oS,name:null,trace:[],up:null},"DivByZeroDefect"),-1==t&&2147483647==e&&AS(),Math.trunc(e%t)}function uS(e){return e<0?-1*e:e}function hS(e,t){var r=e*t;return IS(r),r}function dS(e,t){var r=e-t;return IS(r),r}function pS(e,t){var r=e+t;return IS(r),r}nS.node=aS,JE.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},nS.base=JE,sS.base=nS,iS.base=sS,oS.base=iS,QE.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},QE.base=iS,YE.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},YE.base=sS,ZE.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},ZE.base=sS,XE.node={kind:2,len:0,offset:0,typ:null,name:null,sons:[]},XE.base=sS;var fS,gS,mS,yS,bS,wS=function(){for(var e={},t=0;t<arguments.length;++t){var r=arguments[t];if("object"==typeof r)for(var n=r[0];n<=r[1];++n)e[n]=!0;else e[r]=!0}return e}(17,16,4,18,27,19,23,22,21);function vS(e,t,r){var n=null;switch(r.kind){case 21:case 22:case 23:case 5:n=function(e){return!(null!=wS[e.base.kind])}(r)?[t[0],t[1]]:t;break;case 19:if(null==e)e={};else for(var s in e)delete e[s];for(var s in t)e[s]=t[s];n=e;break;case 18:case 17:CS(n=null!=r.base?vS(e,t,r.base):17==r.kind?null==e?{m_type:r}:e:null==e?{}:e,t,r.node);break;case 4:case 16:if(ArrayBuffer.isView(t))null==e||e.length!=t.length?e=new t.constructor(t):e.set(t,0),n=e;else if(null===t)n=null;else{null!=e&&e.length==t.length||(e=Array(t.length)),n=e;for(var i=0;i<t.length;++i)n[i]=vS(n[i],t[i],r.base)}break;case 24:case 27:if(null===t)n=null;else for(null!=e&&e.length==t.length||(e=Array(t.length)),n=e,i=0;i<t.length;++i)n[i]=vS(n[i],t[i],r.base);break;case 28:null!==t&&(n=t.slice(0));break;default:n=t}return n}function ES(e,t,r){var n=0;return t<=e&&e<=r?n=e:function(e,t,r){cS({message:vS(null,r<t?[105,110,100,101,120,32,111,117,116,32,111,102,32,98,111,117,110,100,115,44,32,116,104,101,32,99,111,110,116,97,105,110,101,114,32,105,115,32,101,109,112,116,121]:[105,110,100,101,120,32].concat(_S(e),[32,110,111,116,32,105,110,32],_S(t),[32,46,46,32],_S(r)),tS),parent:null,m_type:ZE,name:null,trace:[],up:null},"IndexDefect")}(e,t,r),n}function SS(e){var t=[];t=Array(e);for(var r=0;r<e;++r)t[r]=null;return t}function AS(){cS({message:[111,118,101,114,45,32,111,114,32,117,110,100,101,114,102,108,111,119],parent:null,m_type:QE,name:null,trace:[],up:null},"OverflowDefect")}function IS(e){(e>2147483647||e<-2147483648)&&AS()}function _S(e){var t=[[]];return function(e,t,r){!function(e,t,r){!function(e,t,r){!function(e,t,r,n,s){var i,o=e[t].length;if(e[t].length<(i=function(e,t,r){var n=0;return 0<=e&&e<=2147483647?n=e:cS({message:[118,97,108,117,101,32,111,117,116,32,111,102,32,114,97,110,103,101],parent:null,m_type:YE,name:null,trace:[],up:null},"RangeDefect"),n}(pS(o,s))))for(var a=e[t].length;a<i;++a)e[t].push(0);else e[t].length=i;for(var c=0,l=0;l<s;)c=l,e[t][ES(pS(o,c),0,e[t].length-1)]=r.charCodeAt(ES(pS(0,c),0,r.length-1)),l=pS(l,1)}(e,t,r,0,null==r?0:r.length)}(e,0,r+"")}(e,0,r)}(t,0,e),t[0]}function CS(e,t,r){switch(r.kind){case 0:break;case 1:e[r.offset]=vS(e[r.offset],t[r.offset],r.typ);break;case 2:for(var n=0;n<r.sons.length;n++)CS(e,t,r.sons[n]);break;case 3:for(e[r.offset]=vS(e[r.offset],t[r.offset],r.typ),n=0;n<r.sons.length;++n)CS(e,t,r.sons[n][1])}}function xS(e,t){var r=65535,n=(e&r)>>>0,s=(t&r)>>>0;return(n*s>>>0)+((((e>>>16&r)>>>0)*s>>>0)+(n*((t>>>16&r)>>>0)>>>0)>>>0<<16>>>0)>>>0}function kS(e,t){return(e<<t>>>0|e>>>dS(32,t))>>>0}function TS(e){return function(e){for(var t=e.length,r=(a=t,Math.trunc(a/4)),n=0,s=0;s<hS(r,4);){for(var i=0,o=4;0<o;)o=dS(o,1),i=(i<<8>>>0|Number(BigInt.asUintN(32,BigInt(e[ES(pS(s,o),0,e.length-1)]))))>>>0;s=pS(s,4),i=kS(i=xS(i,3432918353),15),n=3864292196+(5*(n=kS(n=(n^(i=xS(i,461845907)))>>>0,13))>>>0)>>>0}for(var a,c=0,l=lS(t,4);0<l;)l=dS(l,1),c=(c<<8>>>0|Number(BigInt.asUintN(32,BigInt(e[ES(pS(s,l),0,e.length-1)]))))>>>0;return c=xS(c,3432918353),c=xS(c=kS(c,15),461845907),n=xS(n=((n=((n=(n^c)>>>0)^Number(BigInt.asUintN(32,BigInt(t))))>>>0)^n>>>16)>>>0,2246822507),n=((n=xS(n=(n^n>>>13)>>>0,3266489909))^n>>>16)>>>0,Number(BigInt.asIntN(32,BigInt(n)))}(e.slice(0,e.length-1+1))}0!=(gS=lS(uS(TS(fS=[100,117,109,109,121])),1),mS=lS(uS(TS(fS.concat([32,98]))),1),lS(uS(pS(gS,hS(0,mS))),1))&&cS({message:vS(null,[110,105,109,95,104,97,115,104,46,110,105,109,40,50,54,44,32,51,41,32,96,104,97,115,104,78,40,34,100,117,109,109,121,34,44,32,48,44,32,49,41,32,61,61,32,48,96,32],tS),m_type:XE,parent:null,name:null,trace:[],up:null},"AssertionDefect"),(e=>{e.Send="send",e.Receive="receive",e.SendEphemeral="sendEphemeral"})(yS||(yS={})),(e=>{e.OutMessageSent="sds:out:message-sent",e.InMessageDelivered="sds:in:message-delivered",e.InMessageReceived="sds:in:message-received",e.OutMessageAcknowledged="sds:out:message-acknowledged",e.OutMessagePossiblyAcknowledged="sds:out:message-possibly-acknowledged",e.InMessageMissing="sds:in:message-missing",e.OutSyncSent="sds:out:sync-sent",e.InSyncReceived="sds:in:sync-received",e.InMessageLost="sds:in:message-irretrievably-lost",e.ErrorTask="sds:error-task"})(bS||(bS={}));var PS,RS,LS={exports:{}};PS||(PS=1,function(e,t){!function(){var r,n="Expected a function",s="__lodash_hash_undefined__",i="__lodash_placeholder__",o=32,a=128,c=1/0,l=9007199254740991,u=NaN,h=4294967295,d=[["ary",a],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",o],["partialRight",64],["rearg",256]],p="[object Arguments]",f="[object Array]",g="[object Boolean]",m="[object Date]",y="[object Error]",b="[object Function]",w="[object GeneratorFunction]",v="[object Map]",E="[object Number]",S="[object Object]",A="[object Promise]",I="[object RegExp]",_="[object Set]",C="[object String]",x="[object Symbol]",k="[object WeakMap]",T="[object ArrayBuffer]",P="[object DataView]",R="[object Float32Array]",L="[object Float64Array]",D="[object Int8Array]",M="[object Int16Array]",N="[object Int32Array]",O="[object Uint8Array]",U="[object Uint8ClampedArray]",F="[object Uint16Array]",B="[object Uint32Array]",$=/\b__p \+= '';/g,q=/\b(__p \+=) '' \+/g,z=/(__e\(.*?\)|\b__t\)) \+\n'';/g,j=/&(?:amp|lt|gt|quot|#39);/g,K=/[&<>"']/g,V=RegExp(j.source),H=RegExp(K.source),G=/<%-([\s\S]+?)%>/g,W=/<%([\s\S]+?)%>/g,X=/<%=([\s\S]+?)%>/g,Z=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Y=/^\w*$/,Q=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,J=/[\\^$.*+?()[\]{}|]/g,ee=RegExp(J.source),te=/^\s+/,re=/\s/,ne=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,se=/\{\n\/\* \[wrapped with (.+)\] \*/,ie=/,? & /,oe=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,ae=/[()=,{}\[\]\/\s]/,ce=/\\(\\)?/g,le=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,ue=/\w*$/,he=/^[-+]0x[0-9a-f]+$/i,de=/^0b[01]+$/i,pe=/^\[object .+?Constructor\]$/,fe=/^0o[0-7]+$/i,ge=/^(?:0|[1-9]\d*)$/,me=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,ye=/($^)/,be=/['\n\r\u2028\u2029\\]/g,we="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",ve="\\u2700-\\u27bf",Ee="a-z\\xdf-\\xf6\\xf8-\\xff",Se="A-Z\\xc0-\\xd6\\xd8-\\xde",Ae="\\ufe0e\\ufe0f",Ie="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",_e="["+Ie+"]",Ce="["+we+"]",xe="\\d+",ke="["+ve+"]",Te="["+Ee+"]",Pe="[^\ud800-\udfff"+Ie+xe+ve+Ee+Se+"]",Re="\ud83c[\udffb-\udfff]",Le="[^\ud800-\udfff]",De="(?:\ud83c[\udde6-\uddff]){2}",Me="[\ud800-\udbff][\udc00-\udfff]",Ne="["+Se+"]",Oe="\\u200d",Ue="(?:"+Te+"|"+Pe+")",Fe="(?:"+Ne+"|"+Pe+")",Be="(?:['’](?:d|ll|m|re|s|t|ve))?",$e="(?:['’](?:D|LL|M|RE|S|T|VE))?",qe="(?:"+Ce+"|"+Re+")?",ze="["+Ae+"]?",je=ze+qe+"(?:"+Oe+"(?:"+[Le,De,Me].join("|")+")"+ze+qe+")*",Ke="(?:"+[ke,De,Me].join("|")+")"+je,Ve="(?:"+[Le+Ce+"?",Ce,De,Me,"[\ud800-\udfff]"].join("|")+")",He=RegExp("['’]","g"),Ge=RegExp(Ce,"g"),We=RegExp(Re+"(?="+Re+")|"+Ve+je,"g"),Xe=RegExp([Ne+"?"+Te+"+"+Be+"(?="+[_e,Ne,"$"].join("|")+")",Fe+"+"+$e+"(?="+[_e,Ne+Ue,"$"].join("|")+")",Ne+"?"+Ue+"+"+Be,Ne+"+"+$e,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])|\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",xe,Ke].join("|"),"g"),Ze=RegExp("["+Oe+"\ud800-\udfff"+we+Ae+"]"),Ye=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Qe=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Je=-1,et={};et[R]=et[L]=et[D]=et[M]=et[N]=et[O]=et[U]=et[F]=et[B]=!0,et[p]=et[f]=et[T]=et[g]=et[P]=et[m]=et[y]=et[b]=et[v]=et[E]=et[S]=et[I]=et[_]=et[C]=et[k]=!1;var tt={};tt[p]=tt[f]=tt[T]=tt[P]=tt[g]=tt[m]=tt[R]=tt[L]=tt[D]=tt[M]=tt[N]=tt[v]=tt[E]=tt[S]=tt[I]=tt[_]=tt[C]=tt[x]=tt[O]=tt[U]=tt[F]=tt[B]=!0,tt[y]=tt[b]=tt[k]=!1;var rt={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},nt=parseFloat,st=parseInt,it="object"==typeof ns&&ns&&ns.Object===Object&&ns,ot="object"==typeof self&&self&&self.Object===Object&&self,at=it||ot||Function("return this")(),ct=t&&!t.nodeType&&t,lt=ct&&e&&!e.nodeType&&e,ut=lt&&lt.exports===ct,ht=ut&&it.process,dt=(()=>{try{return lt&&lt.require&&lt.require("util").types||ht&&ht.binding&&ht.binding("util")}catch(e){}})(),pt=dt&&dt.isArrayBuffer,ft=dt&&dt.isDate,gt=dt&&dt.isMap,mt=dt&&dt.isRegExp,yt=dt&&dt.isSet,bt=dt&&dt.isTypedArray;function wt(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}function vt(e,t,r,n){for(var s=-1,i=null==e?0:e.length;++s<i;){var o=e[s];t(n,o,r(o),e)}return n}function Et(e,t){for(var r=-1,n=null==e?0:e.length;++r<n&&!1!==t(e[r],r,e););return e}function St(e,t){for(var r=null==e?0:e.length;r--&&!1!==t(e[r],r,e););return e}function At(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(!t(e[r],r,e))return!1;return!0}function It(e,t){for(var r=-1,n=null==e?0:e.length,s=0,i=[];++r<n;){var o=e[r];t(o,r,e)&&(i[s++]=o)}return i}function _t(e,t){return!(null==e||!e.length)&&Nt(e,t,0)>-1}function Ct(e,t,r){for(var n=-1,s=null==e?0:e.length;++n<s;)if(r(t,e[n]))return!0;return!1}function xt(e,t){for(var r=-1,n=null==e?0:e.length,s=Array(n);++r<n;)s[r]=t(e[r],r,e);return s}function kt(e,t){for(var r=-1,n=t.length,s=e.length;++r<n;)e[s+r]=t[r];return e}function Tt(e,t,r,n){var s=-1,i=null==e?0:e.length;for(n&&i&&(r=e[++s]);++s<i;)r=t(r,e[s],s,e);return r}function Pt(e,t,r,n){var s=null==e?0:e.length;for(n&&s&&(r=e[--s]);s--;)r=t(r,e[s],s,e);return r}function Rt(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}var Lt=Bt("length");function Dt(e,t,r){var n;return r(e,((e,r,s)=>{if(t(e,r,s))return n=r,!1})),n}function Mt(e,t,r,n){for(var s=e.length,i=r+(n?1:-1);n?i--:++i<s;)if(t(e[i],i,e))return i;return-1}function Nt(e,t,r){return t==t?((e,t,r)=>{for(var n=r-1,s=e.length;++n<s;)if(e[n]===t)return n;return-1})(e,t,r):Mt(e,Ut,r)}function Ot(e,t,r,n){for(var s=r-1,i=e.length;++s<i;)if(n(e[s],t))return s;return-1}function Ut(e){return e!=e}function Ft(e,t){var r=null==e?0:e.length;return r?zt(e,t)/r:u}function Bt(e){return t=>null==t?r:t[e]}function $t(e){return t=>null==e?r:e[t]}function qt(e,t,r,n,s){return s(e,((e,s,i)=>{r=n?(n=!1,e):t(r,e,s,i)})),r}function zt(e,t){for(var n,s=-1,i=e.length;++s<i;){var o=t(e[s]);o!==r&&(n=n===r?o:n+o)}return n}function jt(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}function Kt(e){return e?e.slice(0,or(e)+1).replace(te,""):e}function Vt(e){return t=>e(t)}function Ht(e,t){return xt(t,(t=>e[t]))}function Gt(e,t){return e.has(t)}function Wt(e,t){for(var r=-1,n=e.length;++r<n&&Nt(t,e[r],0)>-1;);return r}function Xt(e,t){for(var r=e.length;r--&&Nt(t,e[r],0)>-1;);return r}var Zt=$t({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),Yt=$t({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"});function Qt(e){return"\\"+rt[e]}function Jt(e){return Ze.test(e)}function er(e){var t=-1,r=Array(e.size);return e.forEach(((e,n)=>{r[++t]=[n,e]})),r}function tr(e,t){return r=>e(t(r))}function rr(e,t){for(var r=-1,n=e.length,s=0,o=[];++r<n;){var a=e[r];a!==t&&a!==i||(e[r]=i,o[s++]=r)}return o}function nr(e){var t=-1,r=Array(e.size);return e.forEach((e=>{r[++t]=e})),r}function sr(e){return Jt(e)?(e=>{for(var t=We.lastIndex=0;We.test(e);)++t;return t})(e):Lt(e)}function ir(e){return Jt(e)?(e=>e.match(We)||[])(e):(e=>e.split(""))(e)}function or(e){for(var t=e.length;t--&&re.test(e.charAt(t)););return t}var ar=$t({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"}),cr=function e(t){var re,we=(t=null==t?at:cr.defaults(at.Object(),t,cr.pick(at,Qe))).Array,ve=t.Date,Ee=t.Error,Se=t.Function,Ae=t.Math,Ie=t.Object,_e=t.RegExp,Ce=t.String,xe=t.TypeError,ke=we.prototype,Te=Se.prototype,Pe=Ie.prototype,Re=t["__core-js_shared__"],Le=Te.toString,De=Pe.hasOwnProperty,Me=0,Ne=(re=/[^.]+$/.exec(Re&&Re.keys&&Re.keys.IE_PROTO||""))?"Symbol(src)_1."+re:"",Oe=Pe.toString,Ue=Le.call(Ie),Fe=at._,Be=_e("^"+Le.call(De).replace(J,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),$e=ut?t.Buffer:r,qe=t.Symbol,ze=t.Uint8Array,je=$e?$e.allocUnsafe:r,Ke=tr(Ie.getPrototypeOf,Ie),Ve=Ie.create,We=Pe.propertyIsEnumerable,Ze=ke.splice,rt=qe?qe.isConcatSpreadable:r,it=qe?qe.iterator:r,ot=qe?qe.toStringTag:r,ct=(()=>{try{var e=ai(Ie,"defineProperty");return e({},"",{}),e}catch(e){}})(),lt=t.clearTimeout!==at.clearTimeout&&t.clearTimeout,ht=ve&&ve.now!==at.Date.now&&ve.now,dt=t.setTimeout!==at.setTimeout&&t.setTimeout,Lt=Ae.ceil,$t=Ae.floor,lr=Ie.getOwnPropertySymbols,ur=$e?$e.isBuffer:r,hr=t.isFinite,dr=ke.join,pr=tr(Ie.keys,Ie),fr=Ae.max,gr=Ae.min,mr=ve.now,yr=t.parseInt,br=Ae.random,wr=ke.reverse,vr=ai(t,"DataView"),Er=ai(t,"Map"),Sr=ai(t,"Promise"),Ar=ai(t,"Set"),Ir=ai(t,"WeakMap"),_r=ai(Ie,"create"),Cr=Ir&&new Ir,xr={},kr=Di(vr),Tr=Di(Er),Pr=Di(Sr),Rr=Di(Ar),Lr=Di(Ir),Dr=qe?qe.prototype:r,Mr=Dr?Dr.valueOf:r,Nr=Dr?Dr.toString:r;function Or(e){if(Yo(e)&&!$o(e)&&!(e instanceof $r)){if(e instanceof Br)return e;if(De.call(e,"__wrapped__"))return Mi(e)}return new Br(e)}var Ur=(()=>{function e(){}return t=>{if(!Zo(t))return{};if(Ve)return Ve(t);e.prototype=t;var n=new e;return e.prototype=r,n}})();function Fr(){}function Br(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=r}function $r(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=h,this.__views__=[]}function qr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function zr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function jr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Kr(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new jr;++t<r;)this.add(e[t])}function Vr(e){var t=this.__data__=new zr(e);this.size=t.size}function Hr(e,t){var r=$o(e),n=!r&&Bo(e),s=!r&&!n&&Ko(e),i=!r&&!n&&!s&&ia(e),o=r||n||s||i,a=o?jt(e.length,Ce):[],c=a.length;for(var l in e)!t&&!De.call(e,l)||o&&("length"==l||s&&("offset"==l||"parent"==l)||i&&("buffer"==l||"byteLength"==l||"byteOffset"==l)||fi(l,c))||a.push(l);return a}function Gr(e){var t=e.length;return t?e[Kn(0,t-1)]:r}function Wr(e,t){return Pi(_s(e),nn(t,0,e.length))}function Xr(e){return Pi(_s(e))}function Zr(e,t,n){(n!==r&&!Oo(e[t],n)||n===r&&!(t in e))&&tn(e,t,n)}function Yr(e,t,n){var s=e[t];De.call(e,t)&&Oo(s,n)&&(n!==r||t in e)||tn(e,t,n)}function Qr(e,t){for(var r=e.length;r--;)if(Oo(e[r][0],t))return r;return-1}function Jr(e,t,r,n){return ln(e,((e,s,i)=>{t(n,e,r(e),i)})),n}function en(e,t){return e&&Cs(t,xa(t),e)}function tn(e,t,r){"__proto__"==t&&ct?ct(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}function rn(e,t){for(var n=-1,s=t.length,i=we(s),o=null==e;++n<s;)i[n]=o?r:Sa(e,t[n]);return i}function nn(e,t,n){return e==e&&(n!==r&&(e=e<=n?e:n),t!==r&&(e=e>=t?e:t)),e}function sn(e,t,n,s,i,o){var a,c=1&t,l=2&t,u=4&t;if(n&&(a=i?n(e,s,i,o):n(e)),a!==r)return a;if(!Zo(e))return e;var h=$o(e);if(h){if(a=(e=>{var t=e.length,r=new e.constructor(t);return t&&"string"==typeof e[0]&&De.call(e,"index")&&(r.index=e.index,r.input=e.input),r})(e),!c)return _s(e,a)}else{var d=ui(e),f=d==b||d==w;if(Ko(e))return ws(e,c);if(d==S||d==p||f&&!i){if(a=l||f?{}:di(e),!c)return l?((e,t)=>Cs(e,li(e),t))(e,((e,t)=>e&&Cs(t,ka(t),e))(a,e)):((e,t)=>Cs(e,ci(e),t))(e,en(a,e))}else{if(!tt[d])return i?e:{};a=((e,t,r)=>{var n=e.constructor;switch(t){case T:return vs(e);case g:case m:return new n(+e);case P:return((e,t)=>{var r=t?vs(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)})(e,r);case R:case L:case D:case M:case N:case O:case U:case F:case B:return Es(e,r);case v:return new n;case E:case C:return new n(e);case I:return(e=>{var t=new e.constructor(e.source,ue.exec(e));return t.lastIndex=e.lastIndex,t})(e);case _:return new n;case x:return(e=>Mr?Ie(Mr.call(e)):{})(e)}})(e,d,c)}}o||(o=new Vr);var y=o.get(e);if(y)return y;o.set(e,a),ra(e)?e.forEach((r=>{a.add(sn(r,t,n,r,e,o))})):Qo(e)&&e.forEach(((r,s)=>{a.set(s,sn(r,t,n,s,e,o))}));var A=h?r:(u?l?ei:Js:l?ka:xa)(e);return Et(A||e,((r,s)=>{A&&(r=e[s=r]),Yr(a,s,sn(r,t,n,s,e,o))})),a}function on(e,t,n){var s=n.length;if(null==e)return!s;for(e=Ie(e);s--;){var i=n[s],o=t[i],a=e[i];if(a===r&&!(i in e)||!o(a))return!1}return!0}function an(e,t,s){if("function"!=typeof e)throw new xe(n);return Ci((()=>{e.apply(r,s)}),t)}function cn(e,t,r,n){var s=-1,i=_t,o=!0,a=e.length,c=[],l=t.length;if(!a)return c;r&&(t=xt(t,Vt(r))),n?(i=Ct,o=!1):t.length>=200&&(i=Gt,o=!1,t=new Kr(t));e:for(;++s<a;){var u=e[s],h=null==r?u:r(u);if(u=n||0!==u?u:0,o&&h==h){for(var d=l;d--;)if(t[d]===h)continue e;c.push(u)}else i(t,h,n)||c.push(u)}return c}Or.templateSettings={escape:G,evaluate:W,interpolate:X,variable:"",imports:{_:Or}},Or.prototype=Fr.prototype,Or.prototype.constructor=Or,Br.prototype=Ur(Fr.prototype),Br.prototype.constructor=Br,$r.prototype=Ur(Fr.prototype),$r.prototype.constructor=$r,qr.prototype.clear=function(){this.__data__=_r?_r(null):{},this.size=0},qr.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},qr.prototype.get=function(e){var t=this.__data__;if(_r){var n=t[e];return n===s?r:n}return De.call(t,e)?t[e]:r},qr.prototype.has=function(e){var t=this.__data__;return _r?t[e]!==r:De.call(t,e)},qr.prototype.set=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=_r&&t===r?s:t,this},zr.prototype.clear=function(){this.__data__=[],this.size=0},zr.prototype.delete=function(e){var t=this.__data__,r=Qr(t,e);return!(r<0||(r==t.length-1?t.pop():Ze.call(t,r,1),--this.size,0))},zr.prototype.get=function(e){var t=this.__data__,n=Qr(t,e);return n<0?r:t[n][1]},zr.prototype.has=function(e){return Qr(this.__data__,e)>-1},zr.prototype.set=function(e,t){var r=this.__data__,n=Qr(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this},jr.prototype.clear=function(){this.size=0,this.__data__={hash:new qr,map:new(Er||zr),string:new qr}},jr.prototype.delete=function(e){var t=ii(this,e).delete(e);return this.size-=t?1:0,t},jr.prototype.get=function(e){return ii(this,e).get(e)},jr.prototype.has=function(e){return ii(this,e).has(e)},jr.prototype.set=function(e,t){var r=ii(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this},Kr.prototype.add=Kr.prototype.push=function(e){return this.__data__.set(e,s),this},Kr.prototype.has=function(e){return this.__data__.has(e)},Vr.prototype.clear=function(){this.__data__=new zr,this.size=0},Vr.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},Vr.prototype.get=function(e){return this.__data__.get(e)},Vr.prototype.has=function(e){return this.__data__.has(e)},Vr.prototype.set=function(e,t){var r=this.__data__;if(r instanceof zr){var n=r.__data__;if(!Er||n.length<199)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new jr(n)}return r.set(e,t),this.size=r.size,this};var ln=Ts(yn),un=Ts(bn,!0);function hn(e,t){var r=!0;return ln(e,((e,n,s)=>r=!!t(e,n,s))),r}function dn(e,t,n){for(var s=-1,i=e.length;++s<i;){var o=e[s],a=t(o);if(null!=a&&(c===r?a==a&&!sa(a):n(a,c)))var c=a,l=o}return l}function pn(e,t){var r=[];return ln(e,((e,n,s)=>{t(e,n,s)&&r.push(e)})),r}function fn(e,t,r,n,s){var i=-1,o=e.length;for(r||(r=pi),s||(s=[]);++i<o;){var a=e[i];t>0&&r(a)?t>1?fn(a,t-1,r,n,s):kt(s,a):n||(s[s.length]=a)}return s}var gn=Ps(),mn=Ps(!0);function yn(e,t){return e&&gn(e,t,xa)}function bn(e,t){return e&&mn(e,t,xa)}function wn(e,t){return It(t,(t=>Go(e[t])))}function vn(e,t){for(var n=0,s=(t=gs(t,e)).length;null!=e&&n<s;)e=e[Li(t[n++])];return n&&n==s?e:r}function En(e,t,r){var n=t(e);return $o(e)?n:kt(n,r(e))}function Sn(e){return null==e?e===r?"[object Undefined]":"[object Null]":ot&&ot in Ie(e)?(e=>{var t=De.call(e,ot),n=e[ot];try{e[ot]=r;var s=!0}catch(e){}var i=Oe.call(e);return s&&(t?e[ot]=n:delete e[ot]),i})(e):(e=>Oe.call(e))(e)}function An(e,t){return e>t}function In(e,t){return null!=e&&De.call(e,t)}function _n(e,t){return null!=e&&t in Ie(e)}function Cn(e,t,n){for(var s=n?Ct:_t,i=e[0].length,o=e.length,a=o,c=we(o),l=1/0,u=[];a--;){var h=e[a];a&&t&&(h=xt(h,Vt(t))),l=gr(h.length,l),c[a]=!n&&(t||i>=120&&h.length>=120)?new Kr(a&&h):r}h=e[0];var d=-1,p=c[0];e:for(;++d<i&&u.length<l;){var f=h[d],g=t?t(f):f;if(f=n||0!==f?f:0,!(p?Gt(p,g):s(u,g,n))){for(a=o;--a;){var m=c[a];if(!(m?Gt(m,g):s(e[a],g,n)))continue e}p&&p.push(g),u.push(f)}}return u}function xn(e,t,n){var s=null==(e=Ai(e,t=gs(t,e)))?e:e[Li(Vi(t))];return null==s?r:wt(s,e,n)}function kn(e){return Yo(e)&&Sn(e)==p}function Tn(e,t,n,s,i){return e===t||(null==e||null==t||!Yo(e)&&!Yo(t)?e!=e&&t!=t:((e,t,n,s,i,o)=>{var a=$o(e),c=$o(t),l=a?f:ui(e),u=c?f:ui(t),h=(l=l==p?S:l)==S,d=(u=u==p?S:u)==S,b=l==u;if(b&&Ko(e)){if(!Ko(t))return!1;a=!0,h=!1}if(b&&!h)return o||(o=new Vr),a||ia(e)?Ys(e,t,n,s,i,o):((e,t,r,n,s,i,o)=>{switch(r){case P:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case T:return!(e.byteLength!=t.byteLength||!i(new ze(e),new ze(t)));case g:case m:case E:return Oo(+e,+t);case y:return e.name==t.name&&e.message==t.message;case I:case C:return e==t+"";case v:var a=er;case _:var c=1&n;if(a||(a=nr),e.size!=t.size&&!c)return!1;var l=o.get(e);if(l)return l==t;n|=2,o.set(e,t);var u=Ys(a(e),a(t),n,s,i,o);return o.delete(e),u;case x:if(Mr)return Mr.call(e)==Mr.call(t)}return!1})(e,t,l,n,s,i,o);if(!(1&n)){var w=h&&De.call(e,"__wrapped__"),A=d&&De.call(t,"__wrapped__");if(w||A){var k=w?e.value():e,R=A?t.value():t;return o||(o=new Vr),i(k,R,n,s,o)}}return!!b&&(o||(o=new Vr),((e,t,n,s,i,o)=>{var a=1&n,c=Js(e),l=c.length;if(l!=Js(t).length&&!a)return!1;for(var u=l;u--;){var h=c[u];if(!(a?h in t:De.call(t,h)))return!1}var d=o.get(e),p=o.get(t);if(d&&p)return d==t&&p==e;var f=!0;o.set(e,t),o.set(t,e);for(var g=a;++u<l;){var m=e[h=c[u]],y=t[h];if(s)var b=a?s(y,m,h,t,e,o):s(m,y,h,e,t,o);if(!(b===r?m===y||i(m,y,n,s,o):b)){f=!1;break}g||(g="constructor"==h)}if(f&&!g){var w=e.constructor,v=t.constructor;w==v||!("constructor"in e)||!("constructor"in t)||"function"==typeof w&&w instanceof w&&"function"==typeof v&&v instanceof v||(f=!1)}return o.delete(e),o.delete(t),f})(e,t,n,s,i,o))})(e,t,n,s,Tn,i))}function Pn(e,t,n,s){var i=n.length,o=i,a=!s;if(null==e)return!o;for(e=Ie(e);i--;){var c=n[i];if(a&&c[2]?c[1]!==e[c[0]]:!(c[0]in e))return!1}for(;++i<o;){var l=(c=n[i])[0],u=e[l],h=c[1];if(a&&c[2]){if(u===r&&!(l in e))return!1}else{var d=new Vr;if(s)var p=s(u,h,l,e,t,d);if(!(p===r?Tn(h,u,3,s,d):p))return!1}}return!0}function Rn(e){return!(!Zo(e)||(e=>!!Ne&&Ne in e)(e))&&(Go(e)?Be:pe).test(Di(e))}function Ln(e){return"function"==typeof e?e:null==e?Ja:"object"==typeof e?$o(e)?Un(e[0],e[1]):On(e):cc(e)}function Dn(e){if(!wi(e))return pr(e);var t=[];for(var r in Ie(e))De.call(e,r)&&"constructor"!=r&&t.push(r);return t}function Mn(e,t){return e<t}function Nn(e,t){var r=-1,n=zo(e)?we(e.length):[];return ln(e,((e,s,i)=>{n[++r]=t(e,s,i)})),n}function On(e){var t=oi(e);return 1==t.length&&t[0][2]?Ei(t[0][0],t[0][1]):r=>r===e||Pn(r,e,t)}function Un(e,t){return mi(e)&&vi(t)?Ei(Li(e),t):n=>{var s=Sa(n,e);return s===r&&s===t?Aa(n,e):Tn(t,s,3)}}function Fn(e,t,n,s,i){e!==t&&gn(t,((o,a)=>{if(i||(i=new Vr),Zo(o))((e,t,n,s,i,o,a)=>{var c=Ii(e,n),l=Ii(t,n),u=a.get(l);if(u)Zr(e,n,u);else{var h=o?o(c,l,n+"",e,t,a):r,d=h===r;if(d){var p=$o(l),f=!p&&Ko(l),g=!p&&!f&&ia(l);h=l,p||f||g?$o(c)?h=c:jo(c)?h=_s(c):f?(d=!1,h=ws(l,!0)):g?(d=!1,h=Es(l,!0)):h=[]:ea(l)||Bo(l)?(h=c,Bo(c)?h=pa(c):Zo(c)&&!Go(c)||(h=di(l))):d=!1}d&&(a.set(l,h),i(h,l,s,o,a),a.delete(l)),Zr(e,n,h)}})(e,t,a,n,Fn,s,i);else{var c=s?s(Ii(e,a),o,a+"",e,t,i):r;c===r&&(c=o),Zr(e,a,c)}}),ka)}function Bn(e,t){var n=e.length;if(n)return fi(t+=t<0?n:0,n)?e[t]:r}function $n(e,t,r){t=t.length?xt(t,(e=>$o(e)?t=>vn(t,1===e.length?e[0]:e):e)):[Ja];var n=-1;t=xt(t,Vt(si()));var s=Nn(e,(e=>{var r=xt(t,(t=>t(e)));return{criteria:r,index:++n,value:e}}));return((e,t)=>{var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e})(s,((e,t)=>((e,t,r)=>{for(var n=-1,s=e.criteria,i=t.criteria,o=s.length,a=r.length;++n<o;){var c=Ss(s[n],i[n]);if(c)return n>=a?c:c*("desc"==r[n]?-1:1)}return e.index-t.index})(e,t,r)))}function qn(e,t,r){for(var n=-1,s=t.length,i={};++n<s;){var o=t[n],a=vn(e,o);r(a,o)&&Xn(i,gs(o,e),a)}return i}function zn(e,t,r,n){var s=n?Ot:Nt,i=-1,o=t.length,a=e;for(e===t&&(t=_s(t)),r&&(a=xt(e,Vt(r)));++i<o;)for(var c=0,l=t[i],u=r?r(l):l;(c=s(a,u,c,n))>-1;)a!==e&&Ze.call(a,c,1),Ze.call(e,c,1);return e}function jn(e,t){for(var r=e?t.length:0,n=r-1;r--;){var s=t[r];if(r==n||s!==i){var i=s;fi(s)?Ze.call(e,s,1):as(e,s)}}return e}function Kn(e,t){return e+$t(br()*(t-e+1))}function Vn(e,t){var r="";if(!e||t<1||t>l)return r;do{t%2&&(r+=e),(t=$t(t/2))&&(e+=e)}while(t);return r}function Hn(e,t){return xi(Si(e,t,Ja),e+"")}function Gn(e){return Gr(Oa(e))}function Wn(e,t){var r=Oa(e);return Pi(r,nn(t,0,r.length))}function Xn(e,t,n,s){if(!Zo(e))return e;for(var i=-1,o=(t=gs(t,e)).length,a=o-1,c=e;null!=c&&++i<o;){var l=Li(t[i]),u=n;if("__proto__"===l||"constructor"===l||"prototype"===l)return e;if(i!=a){var h=c[l];(u=s?s(h,l,c):r)===r&&(u=Zo(h)?h:fi(t[i+1])?[]:{})}Yr(c,l,u),c=c[l]}return e}var Zn=Cr?(e,t)=>(Cr.set(e,t),e):Ja,Yn=ct?(e,t)=>ct(e,"toString",{configurable:!0,enumerable:!1,value:Za(t),writable:!0}):Ja;function Qn(e){return Pi(Oa(e))}function Jn(e,t,r){var n=-1,s=e.length;t<0&&(t=-t>s?0:s+t),(r=r>s?s:r)<0&&(r+=s),s=t>r?0:r-t>>>0,t>>>=0;for(var i=we(s);++n<s;)i[n]=e[n+t];return i}function es(e,t){var r;return ln(e,((e,n,s)=>!(r=t(e,n,s)))),!!r}function ts(e,t,r){var n=0,s=null==e?n:e.length;if("number"==typeof t&&t==t&&s<=2147483647){for(;n<s;){var i=n+s>>>1,o=e[i];null!==o&&!sa(o)&&(r?o<=t:o<t)?n=i+1:s=i}return s}return rs(e,t,Ja,r)}function rs(e,t,n,s){var i=0,o=null==e?0:e.length;if(0===o)return 0;for(var a=(t=n(t))!=t,c=null===t,l=sa(t),u=t===r;i<o;){var h=$t((i+o)/2),d=n(e[h]),p=d!==r,f=null===d,g=d==d,m=sa(d);if(a)var y=s||g;else y=u?g&&(s||p):c?g&&p&&(s||!f):l?g&&p&&!f&&(s||!m):!f&&!m&&(s?d<=t:d<t);y?i=h+1:o=h}return gr(o,4294967294)}function ns(e,t){for(var r=-1,n=e.length,s=0,i=[];++r<n;){var o=e[r],a=t?t(o):o;if(!r||!Oo(a,c)){var c=a;i[s++]=0===o?0:o}}return i}function ss(e){return"number"==typeof e?e:sa(e)?u:+e}function is(e){if("string"==typeof e)return e;if($o(e))return xt(e,is)+"";if(sa(e))return Nr?Nr.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function os(e,t,r){var n=-1,s=_t,i=e.length,o=!0,a=[],c=a;if(r)o=!1,s=Ct;else if(i>=200){var l=t?null:Vs(e);if(l)return nr(l);o=!1,s=Gt,c=new Kr}else c=t?[]:a;e:for(;++n<i;){var u=e[n],h=t?t(u):u;if(u=r||0!==u?u:0,o&&h==h){for(var d=c.length;d--;)if(c[d]===h)continue e;t&&c.push(h),a.push(u)}else s(c,h,r)||(c!==a&&c.push(h),a.push(u))}return a}function as(e,t){return null==(e=Ai(e,t=gs(t,e)))||delete e[Li(Vi(t))]}function cs(e,t,r,n){return Xn(e,t,r(vn(e,t)),n)}function ls(e,t,r,n){for(var s=e.length,i=n?s:-1;(n?i--:++i<s)&&t(e[i],i,e););return r?Jn(e,n?0:i,n?i+1:s):Jn(e,n?i+1:0,n?s:i)}function us(e,t){var r=e;return r instanceof $r&&(r=r.value()),Tt(t,((e,t)=>t.func.apply(t.thisArg,kt([e],t.args))),r)}function hs(e,t,r){var n=e.length;if(n<2)return n?os(e[0]):[];for(var s=-1,i=we(n);++s<n;)for(var o=e[s],a=-1;++a<n;)a!=s&&(i[s]=cn(i[s]||o,e[a],t,r));return os(fn(i,1),t,r)}function ds(e,t,n){for(var s=-1,i=e.length,o=t.length,a={};++s<i;){var c=s<o?t[s]:r;n(a,e[s],c)}return a}function ps(e){return jo(e)?e:[]}function fs(e){return"function"==typeof e?e:Ja}function gs(e,t){return $o(e)?e:mi(e,t)?[e]:Ri(fa(e))}var ms=Hn;function ys(e,t,n){var s=e.length;return n=n===r?s:n,!t&&n>=s?e:Jn(e,t,n)}var bs=lt||(e=>at.clearTimeout(e));function ws(e,t){if(t)return e.slice();var r=e.length,n=je?je(r):new e.constructor(r);return e.copy(n),n}function vs(e){var t=new e.constructor(e.byteLength);return new ze(t).set(new ze(e)),t}function Es(e,t){var r=t?vs(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}function Ss(e,t){if(e!==t){var n=e!==r,s=null===e,i=e==e,o=sa(e),a=t!==r,c=null===t,l=t==t,u=sa(t);if(!c&&!u&&!o&&e>t||o&&a&&l&&!c&&!u||s&&a&&l||!n&&l||!i)return 1;if(!s&&!o&&!u&&e<t||u&&n&&i&&!s&&!o||c&&n&&i||!a&&i||!l)return-1}return 0}function As(e,t,r,n){for(var s=-1,i=e.length,o=r.length,a=-1,c=t.length,l=fr(i-o,0),u=we(c+l),h=!n;++a<c;)u[a]=t[a];for(;++s<o;)(h||s<i)&&(u[r[s]]=e[s]);for(;l--;)u[a++]=e[s++];return u}function Is(e,t,r,n){for(var s=-1,i=e.length,o=-1,a=r.length,c=-1,l=t.length,u=fr(i-a,0),h=we(u+l),d=!n;++s<u;)h[s]=e[s];for(var p=s;++c<l;)h[p+c]=t[c];for(;++o<a;)(d||s<i)&&(h[p+r[o]]=e[s++]);return h}function _s(e,t){var r=-1,n=e.length;for(t||(t=we(n));++r<n;)t[r]=e[r];return t}function Cs(e,t,n,s){var i=!n;n||(n={});for(var o=-1,a=t.length;++o<a;){var c=t[o],l=s?s(n[c],e[c],c,n,e):r;l===r&&(l=e[c]),i?tn(n,c,l):Yr(n,c,l)}return n}function xs(e,t){return(r,n)=>{var s=$o(r)?vt:Jr,i=t?t():{};return s(r,e,si(n,2),i)}}function ks(e){return Hn(((t,n)=>{var s=-1,i=n.length,o=i>1?n[i-1]:r,a=i>2?n[2]:r;for(o=e.length>3&&"function"==typeof o?(i--,o):r,a&&gi(n[0],n[1],a)&&(o=i<3?r:o,i=1),t=Ie(t);++s<i;){var c=n[s];c&&e(t,c,s,o)}return t}))}function Ts(e,t){return(r,n)=>{if(null==r)return r;if(!zo(r))return e(r,n);for(var s=r.length,i=t?s:-1,o=Ie(r);(t?i--:++i<s)&&!1!==n(o[i],i,o););return r}}function Ps(e){return(t,r,n)=>{for(var s=-1,i=Ie(t),o=n(t),a=o.length;a--;){var c=o[e?a:++s];if(!1===r(i[c],c,i))break}return t}}function Rs(e){return t=>{var n=Jt(t=fa(t))?ir(t):r,s=n?n[0]:t.charAt(0),i=n?ys(n,1).join(""):t.slice(1);return s[e]()+i}}function Ls(e){return t=>Tt(Ga(Ba(t).replace(He,"")),e,"")}function Ds(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var r=Ur(e.prototype),n=e.apply(r,t);return Zo(n)?n:r}}function Ms(e){return(t,n,s)=>{var i=Ie(t);if(!zo(t)){var o=si(n,3);t=xa(t),n=e=>o(i[e],e,i)}var a=e(t,n,s);return a>-1?i[o?t[a]:a]:r}}function Ns(e){return Qs((function(t){var s=t.length,i=s,o=Br.prototype.thru;for(e&&t.reverse();i--;){var a=t[i];if("function"!=typeof a)throw new xe(n);if(o&&!c&&"wrapper"==ri(a))var c=new Br([],!0)}for(i=c?i:s;++i<s;){var l=ri(a=t[i]),u="wrapper"==l?ti(a):r;c=u&&yi(u[0])&&424==u[1]&&!u[4].length&&1==u[9]?c[ri(u[0])].apply(c,u[3]):1==a.length&&yi(a)?c[l]():c.thru(a)}return function(){var e=arguments,r=e[0];if(c&&1==e.length&&$o(r))return c.plant(r).value();for(var n=0,i=s?t[n].apply(this,e):r;++n<s;)i=t[n].call(this,i);return i}}))}function Os(e,t,n,s,i,o,c,l,u,h){var d=t&a,p=1&t,f=2&t,g=24&t,m=512&t,y=f?r:Ds(e);return function a(){for(var b=arguments.length,w=we(b),v=b;v--;)w[v]=arguments[v];if(g)var E=ni(a),S=((e,t)=>{for(var r=e.length,n=0;r--;)e[r]===t&&++n;return n})(w,E);if(s&&(w=As(w,s,i,g)),o&&(w=Is(w,o,c,g)),b-=S,g&&b<h){var A=rr(w,E);return js(e,t,Os,a.placeholder,n,w,A,l,u,h-b)}var I=p?n:this,_=f?I[e]:e;return b=w.length,l?w=((e,t)=>{for(var n=e.length,s=gr(t.length,n),i=_s(e);s--;){var o=t[s];e[s]=fi(o,n)?i[o]:r}return e})(w,l):m&&b>1&&w.reverse(),d&&u<b&&(w.length=u),this&&this!==at&&this instanceof a&&(_=y||Ds(_)),_.apply(I,w)}}function Us(e,t){return(r,n)=>((e,t,r,n)=>(yn(e,((e,s,i)=>{t(n,r(e),s,i)})),n))(r,e,t(n),{})}function Fs(e,t){return(n,s)=>{var i;if(n===r&&s===r)return t;if(n!==r&&(i=n),s!==r){if(i===r)return s;"string"==typeof n||"string"==typeof s?(n=is(n),s=is(s)):(n=ss(n),s=ss(s)),i=e(n,s)}return i}}function Bs(e){return Qs((function(t){return t=xt(t,Vt(si())),Hn((function(r){var n=this;return e(t,(e=>wt(e,n,r)))}))}))}function $s(e,t){var n=(t=t===r?" ":is(t)).length;if(n<2)return n?Vn(t,e):t;var s=Vn(t,Lt(e/sr(t)));return Jt(t)?ys(ir(s),0,e).join(""):s.slice(0,e)}function qs(e){return(t,n,s)=>(s&&"number"!=typeof s&&gi(t,n,s)&&(n=s=r),t=la(t),n===r?(n=t,t=0):n=la(n),((e,t,r,n)=>{for(var s=-1,i=fr(Lt((t-e)/(r||1)),0),o=we(i);i--;)o[n?i:++s]=e,e+=r;return o})(t,n,s=s===r?t<n?1:-1:la(s),e))}function zs(e){return(t,r)=>("string"==typeof t&&"string"==typeof r||(t=da(t),r=da(r)),e(t,r))}function js(e,t,n,s,i,a,c,l,u,h){var d=8&t;t|=d?o:64,4&(t&=~(d?64:o))||(t&=-4);var p=[e,t,i,d?a:r,d?c:r,d?r:a,d?r:c,l,u,h],f=n.apply(r,p);return yi(e)&&_i(f,p),f.placeholder=s,ki(f,e,t)}function Ks(e){var t=Ae[e];return(e,r)=>{if(e=da(e),(r=null==r?0:gr(ua(r),292))&&hr(e)){var n=(fa(e)+"e").split("e");return+((n=(fa(t(n[0]+"e"+(+n[1]+r)))+"e").split("e"))[0]+"e"+(+n[1]-r))}return t(e)}}var Vs=Ar&&1/nr(new Ar([,-0]))[1]==c?e=>new Ar(e):sc;function Hs(e){return t=>{var r=ui(t);return r==v?er(t):r==_?function(e){var t=-1,r=Array(e.size);return e.forEach((e=>{r[++t]=[e,e]})),r}(t):((e,t)=>xt(t,(t=>[t,e[t]])))(t,e(t))}}function Gs(e,t,s,c,l,u,h,d){var p=2&t;if(!p&&"function"!=typeof e)throw new xe(n);var f=c?c.length:0;if(f||(t&=-97,c=l=r),h=h===r?h:fr(ua(h),0),d=d===r?d:ua(d),f-=l?l.length:0,64&t){var g=c,m=l;c=l=r}var y=p?r:ti(e),b=[e,t,s,c,l,g,m,u,h,d];if(y&&((e,t)=>{var r=e[1],n=t[1],s=r|n,o=s<131,c=n==a&&8==r||n==a&&256==r&&e[7].length<=t[8]||384==n&&t[7].length<=t[8]&&8==r;if(!o&&!c)return e;1&n&&(e[2]=t[2],s|=1&r?0:4);var l=t[3];if(l){var u=e[3];e[3]=u?As(u,l,t[4]):l,e[4]=u?rr(e[3],i):t[4]}(l=t[5])&&(u=e[5],e[5]=u?Is(u,l,t[6]):l,e[6]=u?rr(e[5],i):t[6]),(l=t[7])&&(e[7]=l),n&a&&(e[8]=null==e[8]?t[8]:gr(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=s})(b,y),e=b[0],t=b[1],s=b[2],c=b[3],l=b[4],!(d=b[9]=b[9]===r?p?0:e.length:fr(b[9]-f,0))&&24&t&&(t&=-25),t&&1!=t)w=8==t||16==t?function(e,t,n){var s=Ds(e);return function i(){for(var o=arguments.length,a=we(o),c=o,l=ni(i);c--;)a[c]=arguments[c];var u=o<3&&a[0]!==l&&a[o-1]!==l?[]:rr(a,l);return(o-=u.length)<n?js(e,t,Os,i.placeholder,r,a,u,r,r,n-o):wt(this&&this!==at&&this instanceof i?s:e,this,a)}}(e,t,d):t!=o&&33!=t||l.length?Os.apply(r,b):function(e,t,r,n){var s=1&t,i=Ds(e);return function t(){for(var o=-1,a=arguments.length,c=-1,l=n.length,u=we(l+a),h=this&&this!==at&&this instanceof t?i:e;++c<l;)u[c]=n[c];for(;a--;)u[c++]=arguments[++o];return wt(h,s?r:this,u)}}(e,t,s,c);else var w=function(e,t,r){var n=1&t,s=Ds(e);return function t(){return(this&&this!==at&&this instanceof t?s:e).apply(n?r:this,arguments)}}(e,t,s);return ki((y?Zn:_i)(w,b),e,t)}function Ws(e,t,n,s){return e===r||Oo(e,Pe[n])&&!De.call(s,n)?t:e}function Xs(e,t,n,s,i,o){return Zo(e)&&Zo(t)&&(o.set(t,e),Fn(e,t,r,Xs,o),o.delete(t)),e}function Zs(e){return ea(e)?r:e}function Ys(e,t,n,s,i,o){var a=1&n,c=e.length,l=t.length;if(c!=l&&!(a&&l>c))return!1;var u=o.get(e),h=o.get(t);if(u&&h)return u==t&&h==e;var d=-1,p=!0,f=2&n?new Kr:r;for(o.set(e,t),o.set(t,e);++d<c;){var g=e[d],m=t[d];if(s)var y=a?s(m,g,d,t,e,o):s(g,m,d,e,t,o);if(y!==r){if(y)continue;p=!1;break}if(f){if(!Rt(t,((e,t)=>{if(!Gt(f,t)&&(g===e||i(g,e,n,s,o)))return f.push(t)}))){p=!1;break}}else if(g!==m&&!i(g,m,n,s,o)){p=!1;break}}return o.delete(e),o.delete(t),p}function Qs(e){return xi(Si(e,r,$i),e+"")}function Js(e){return En(e,xa,ci)}function ei(e){return En(e,ka,li)}var ti=Cr?e=>Cr.get(e):sc;function ri(e){for(var t=e.name+"",r=xr[t],n=De.call(xr,t)?r.length:0;n--;){var s=r[n],i=s.func;if(null==i||i==e)return s.name}return t}function ni(e){return(De.call(Or,"placeholder")?Or:e).placeholder}function si(){var e=Or.iteratee||ec;return e=e===ec?Ln:e,arguments.length?e(arguments[0],arguments[1]):e}function ii(e,t){var r,n,s=e.__data__;return("string"==(n=typeof(r=t))||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==r:null===r)?s["string"==typeof t?"string":"hash"]:s.map}function oi(e){for(var t=xa(e),r=t.length;r--;){var n=t[r],s=e[n];t[r]=[n,s,vi(s)]}return t}function ai(e,t){var n=((e,t)=>null==e?r:e[t])(e,t);return Rn(n)?n:r}var ci=lr?e=>null==e?[]:(e=Ie(e),It(lr(e),(t=>We.call(e,t)))):hc,li=lr?e=>{for(var t=[];e;)kt(t,ci(e)),e=Ke(e);return t}:hc,ui=Sn;function hi(e,t,r){for(var n=-1,s=(t=gs(t,e)).length,i=!1;++n<s;){var o=Li(t[n]);if(!(i=null!=e&&r(e,o)))break;e=e[o]}return i||++n!=s?i:!!(s=null==e?0:e.length)&&Xo(s)&&fi(o,s)&&($o(e)||Bo(e))}function di(e){return"function"!=typeof e.constructor||wi(e)?{}:Ur(Ke(e))}function pi(e){return $o(e)||Bo(e)||!!(rt&&e&&e[rt])}function fi(e,t){var r=typeof e;return!!(t=null==t?l:t)&&("number"==r||"symbol"!=r&&ge.test(e))&&e>-1&&e%1==0&&e<t}function gi(e,t,r){if(!Zo(r))return!1;var n=typeof t;return!!("number"==n?zo(r)&&fi(t,r.length):"string"==n&&t in r)&&Oo(r[t],e)}function mi(e,t){if($o(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!sa(e))||Y.test(e)||!Z.test(e)||null!=t&&e in Ie(t)}function yi(e){var t=ri(e),r=Or[t];if("function"!=typeof r||!(t in $r.prototype))return!1;if(e===r)return!0;var n=ti(r);return!!n&&e===n[0]}(vr&&ui(new vr(new ArrayBuffer(1)))!=P||Er&&ui(new Er)!=v||Sr&&ui(Sr.resolve())!=A||Ar&&ui(new Ar)!=_||Ir&&ui(new Ir)!=k)&&(ui=e=>{var t=Sn(e),n=t==S?e.constructor:r,s=n?Di(n):"";if(s)switch(s){case kr:return P;case Tr:return v;case Pr:return A;case Rr:return _;case Lr:return k}return t});var bi=Re?Go:dc;function wi(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Pe)}function vi(e){return e==e&&!Zo(e)}function Ei(e,t){return n=>null!=n&&n[e]===t&&(t!==r||e in Ie(n))}function Si(e,t,n){return t=fr(t===r?e.length-1:t,0),function(){for(var r=arguments,s=-1,i=fr(r.length-t,0),o=we(i);++s<i;)o[s]=r[t+s];s=-1;for(var a=we(t+1);++s<t;)a[s]=r[s];return a[t]=n(o),wt(e,this,a)}}function Ai(e,t){return t.length<2?e:vn(e,Jn(t,0,-1))}function Ii(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}var _i=Ti(Zn),Ci=dt||((e,t)=>at.setTimeout(e,t)),xi=Ti(Yn);function ki(e,t,r){var n=t+"";return xi(e,((e,t)=>{var r=t.length;if(!r)return e;var n=r-1;return t[n]=(r>1?"& ":"")+t[n],t=t.join(r>2?", ":" "),e.replace(ne,"{\n/* [wrapped with "+t+"] */\n")})(n,((e,t)=>(Et(d,(r=>{var n="_."+r[0];t&r[1]&&!_t(e,n)&&e.push(n)})),e.sort()))((e=>{var t=e.match(se);return t?t[1].split(ie):[]})(n),r)))}function Ti(e){var t=0,n=0;return function(){var s=mr(),i=16-(s-n);if(n=s,i>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(r,arguments)}}function Pi(e,t){var n=-1,s=e.length,i=s-1;for(t=t===r?s:t;++n<t;){var o=Kn(n,i),a=e[o];e[o]=e[n],e[n]=a}return e.length=t,e}var Ri=(e=>{var t=Po((e=>{var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(Q,((e,r,n,s)=>{t.push(n?s.replace(ce,"$1"):r||e)})),t}),(e=>(500===r.size&&r.clear(),e))),r=t.cache;return t})();function Li(e){if("string"==typeof e||sa(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function Di(e){if(null!=e){try{return Le.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Mi(e){if(e instanceof $r)return e.clone();var t=new Br(e.__wrapped__,e.__chain__);return t.__actions__=_s(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}var Ni=Hn(((e,t)=>jo(e)?cn(e,fn(t,1,jo,!0)):[])),Oi=Hn(((e,t)=>{var n=Vi(t);return jo(n)&&(n=r),jo(e)?cn(e,fn(t,1,jo,!0),si(n,2)):[]})),Ui=Hn(((e,t)=>{var n=Vi(t);return jo(n)&&(n=r),jo(e)?cn(e,fn(t,1,jo,!0),r,n):[]}));function Fi(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var s=null==r?0:ua(r);return s<0&&(s=fr(n+s,0)),Mt(e,si(t,3),s)}function Bi(e,t,n){var s=null==e?0:e.length;if(!s)return-1;var i=s-1;return n!==r&&(i=ua(n),i=n<0?fr(s+i,0):gr(i,s-1)),Mt(e,si(t,3),i,!0)}function $i(e){return null!=e&&e.length?fn(e,1):[]}function qi(e){return e&&e.length?e[0]:r}var zi=Hn((e=>{var t=xt(e,ps);return t.length&&t[0]===e[0]?Cn(t):[]})),ji=Hn((e=>{var t=Vi(e),n=xt(e,ps);return t===Vi(n)?t=r:n.pop(),n.length&&n[0]===e[0]?Cn(n,si(t,2)):[]})),Ki=Hn((e=>{var t=Vi(e),n=xt(e,ps);return(t="function"==typeof t?t:r)&&n.pop(),n.length&&n[0]===e[0]?Cn(n,r,t):[]}));function Vi(e){var t=null==e?0:e.length;return t?e[t-1]:r}var Hi=Hn(Gi);function Gi(e,t){return e&&e.length&&t&&t.length?zn(e,t):e}var Wi=Qs(((e,t)=>{var r=null==e?0:e.length,n=rn(e,t);return jn(e,xt(t,(e=>fi(e,r)?+e:e)).sort(Ss)),n}));function Xi(e){return null==e?e:wr.call(e)}var Zi=Hn((e=>os(fn(e,1,jo,!0)))),Yi=Hn((e=>{var t=Vi(e);return jo(t)&&(t=r),os(fn(e,1,jo,!0),si(t,2))})),Qi=Hn((e=>{var t=Vi(e);return t="function"==typeof t?t:r,os(fn(e,1,jo,!0),r,t)}));function Ji(e){if(!e||!e.length)return[];var t=0;return e=It(e,(e=>{if(jo(e))return t=fr(e.length,t),!0})),jt(t,(t=>xt(e,Bt(t))))}function eo(e,t){if(!e||!e.length)return[];var n=Ji(e);return null==t?n:xt(n,(e=>wt(t,r,e)))}var to=Hn(((e,t)=>jo(e)?cn(e,t):[])),ro=Hn((e=>hs(It(e,jo)))),no=Hn((e=>{var t=Vi(e);return jo(t)&&(t=r),hs(It(e,jo),si(t,2))})),so=Hn((e=>{var t=Vi(e);return t="function"==typeof t?t:r,hs(It(e,jo),r,t)})),io=Hn(Ji),oo=Hn((e=>{var t=e.length,n=t>1?e[t-1]:r;return n="function"==typeof n?(e.pop(),n):r,eo(e,n)}));function ao(e){var t=Or(e);return t.__chain__=!0,t}function co(e,t){return t(e)}var lo=Qs((function(e){var t=e.length,n=t?e[0]:0,s=this.__wrapped__,i=t=>rn(t,e);return!(t>1||this.__actions__.length)&&s instanceof $r&&fi(n)?((s=s.slice(n,+n+(t?1:0))).__actions__.push({func:co,args:[i],thisArg:r}),new Br(s,this.__chain__).thru((e=>(t&&!e.length&&e.push(r),e)))):this.thru(i)})),uo=xs(((e,t,r)=>{De.call(e,r)?++e[r]:tn(e,r,1)})),ho=Ms(Fi),po=Ms(Bi);function fo(e,t){return($o(e)?Et:ln)(e,si(t,3))}function go(e,t){return($o(e)?St:un)(e,si(t,3))}var mo=xs(((e,t,r)=>{De.call(e,r)?e[r].push(t):tn(e,r,[t])})),yo=Hn(((e,t,r)=>{var n=-1,s="function"==typeof t,i=zo(e)?we(e.length):[];return ln(e,(e=>{i[++n]=s?wt(t,e,r):xn(e,t,r)})),i})),bo=xs(((e,t,r)=>{tn(e,r,t)}));function wo(e,t){return($o(e)?xt:Nn)(e,si(t,3))}var vo=xs(((e,t,r)=>{e[r?0:1].push(t)}),(()=>[[],[]])),Eo=Hn(((e,t)=>{if(null==e)return[];var r=t.length;return r>1&&gi(e,t[0],t[1])?t=[]:r>2&&gi(t[0],t[1],t[2])&&(t=[t[0]]),$n(e,fn(t,1),[])})),So=ht||(()=>at.Date.now());function Ao(e,t,n){return t=n?r:t,t=e&&null==t?e.length:t,Gs(e,a,r,r,r,r,t)}function Io(e,t){var s;if("function"!=typeof t)throw new xe(n);return e=ua(e),function(){return--e>0&&(s=t.apply(this,arguments)),e<=1&&(t=r),s}}var _o=Hn(((e,t,r)=>{var n=1;if(r.length){var s=rr(r,ni(_o));n|=o}return Gs(e,n,t,r,s)})),Co=Hn(((e,t,r)=>{var n=3;if(r.length){var s=rr(r,ni(Co));n|=o}return Gs(t,n,e,r,s)}));function xo(e,t,s){var i,o,a,c,l,u,h=0,d=!1,p=!1,f=!0;if("function"!=typeof e)throw new xe(n);function g(t){var n=i,s=o;return i=o=r,h=t,c=e.apply(s,n)}function m(e){var n=e-u;return u===r||n>=t||n<0||p&&e-h>=a}function y(){var e=So();if(m(e))return b(e);l=Ci(y,(e=>{var r=t-(e-u);return p?gr(r,a-(e-h)):r})(e))}function b(e){return l=r,f&&i?g(e):(i=o=r,c)}function w(){var e=So(),n=m(e);if(i=arguments,o=this,u=e,n){if(l===r)return(e=>(h=e,l=Ci(y,t),d?g(e):c))(u);if(p)return bs(l),l=Ci(y,t),g(u)}return l===r&&(l=Ci(y,t)),c}return t=da(t)||0,Zo(s)&&(d=!!s.leading,a=(p="maxWait"in s)?fr(da(s.maxWait)||0,t):a,f="trailing"in s?!!s.trailing:f),w.cancel=()=>{l!==r&&bs(l),h=0,i=u=o=l=r},w.flush=()=>l===r?c:b(So()),w}var ko=Hn(((e,t)=>an(e,1,t))),To=Hn(((e,t,r)=>an(e,da(t)||0,r)));function Po(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new xe(n);var r=function(){var n=arguments,s=t?t.apply(this,n):n[0],i=r.cache;if(i.has(s))return i.get(s);var o=e.apply(this,n);return r.cache=i.set(s,o)||i,o};return r.cache=new(Po.Cache||jr),r}function Ro(e){if("function"!=typeof e)throw new xe(n);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}Po.Cache=jr;var Lo=ms((function(e,t){var r=(t=1==t.length&&$o(t[0])?xt(t[0],Vt(si())):xt(fn(t,1),Vt(si()))).length;return Hn((function(n){for(var s=-1,i=gr(n.length,r);++s<i;)n[s]=t[s].call(this,n[s]);return wt(e,this,n)}))})),Do=Hn(((e,t)=>{var n=rr(t,ni(Do));return Gs(e,o,r,t,n)})),Mo=Hn(((e,t)=>{var n=rr(t,ni(Mo));return Gs(e,64,r,t,n)})),No=Qs(((e,t)=>Gs(e,256,r,r,r,t)));function Oo(e,t){return e===t||e!=e&&t!=t}var Uo=zs(An),Fo=zs(((e,t)=>e>=t)),Bo=kn(function(){return arguments}())?kn:e=>Yo(e)&&De.call(e,"callee")&&!We.call(e,"callee"),$o=we.isArray,qo=pt?Vt(pt):e=>Yo(e)&&Sn(e)==T;function zo(e){return null!=e&&Xo(e.length)&&!Go(e)}function jo(e){return Yo(e)&&zo(e)}var Ko=ur||dc,Vo=ft?Vt(ft):e=>Yo(e)&&Sn(e)==m;function Ho(e){if(!Yo(e))return!1;var t=Sn(e);return t==y||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!ea(e)}function Go(e){if(!Zo(e))return!1;var t=Sn(e);return t==b||t==w||"[object AsyncFunction]"==t||"[object Proxy]"==t}function Wo(e){return"number"==typeof e&&e==ua(e)}function Xo(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=l}function Zo(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function Yo(e){return null!=e&&"object"==typeof e}var Qo=gt?Vt(gt):e=>Yo(e)&&ui(e)==v;function Jo(e){return"number"==typeof e||Yo(e)&&Sn(e)==E}function ea(e){if(!Yo(e)||Sn(e)!=S)return!1;var t=Ke(e);if(null===t)return!0;var r=De.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Le.call(r)==Ue}var ta=mt?Vt(mt):e=>Yo(e)&&Sn(e)==I,ra=yt?Vt(yt):e=>Yo(e)&&ui(e)==_;function na(e){return"string"==typeof e||!$o(e)&&Yo(e)&&Sn(e)==C}function sa(e){return"symbol"==typeof e||Yo(e)&&Sn(e)==x}var ia=bt?Vt(bt):e=>Yo(e)&&Xo(e.length)&&!!et[Sn(e)],oa=zs(Mn),aa=zs(((e,t)=>e<=t));function ca(e){if(!e)return[];if(zo(e))return na(e)?ir(e):_s(e);if(it&&e[it])return(e=>{for(var t,r=[];!(t=e.next()).done;)r.push(t.value);return r})(e[it]());var t=ui(e);return(t==v?er:t==_?nr:Oa)(e)}function la(e){return e?(e=da(e))===c||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}function ua(e){var t=la(e),r=t%1;return t==t?r?t-r:t:0}function ha(e){return e?nn(ua(e),0,h):0}function da(e){if("number"==typeof e)return e;if(sa(e))return u;if(Zo(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=Zo(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=Kt(e);var r=de.test(e);return r||fe.test(e)?st(e.slice(2),r?2:8):he.test(e)?u:+e}function pa(e){return Cs(e,ka(e))}function fa(e){return null==e?"":is(e)}var ga=ks(((e,t)=>{if(wi(t)||zo(t))Cs(t,xa(t),e);else for(var r in t)De.call(t,r)&&Yr(e,r,t[r])})),ma=ks(((e,t)=>{Cs(t,ka(t),e)})),ya=ks(((e,t,r,n)=>{Cs(t,ka(t),e,n)})),ba=ks(((e,t,r,n)=>{Cs(t,xa(t),e,n)})),wa=Qs(rn),va=Hn(((e,t)=>{e=Ie(e);var n=-1,s=t.length,i=s>2?t[2]:r;for(i&&gi(t[0],t[1],i)&&(s=1);++n<s;)for(var o=t[n],a=ka(o),c=-1,l=a.length;++c<l;){var u=a[c],h=e[u];(h===r||Oo(h,Pe[u])&&!De.call(e,u))&&(e[u]=o[u])}return e})),Ea=Hn((e=>(e.push(r,Xs),wt(Pa,r,e))));function Sa(e,t,n){var s=null==e?r:vn(e,t);return s===r?n:s}function Aa(e,t){return null!=e&&hi(e,t,_n)}var Ia=Us(((e,t,r)=>{null!=t&&"function"!=typeof t.toString&&(t=Oe.call(t)),e[t]=r}),Za(Ja)),_a=Us(((e,t,r)=>{null!=t&&"function"!=typeof t.toString&&(t=Oe.call(t)),De.call(e,t)?e[t].push(r):e[t]=[r]}),si),Ca=Hn(xn);function xa(e){return zo(e)?Hr(e):Dn(e)}function ka(e){return zo(e)?Hr(e,!0):function(e){if(!Zo(e))return(e=>{var t=[];if(null!=e)for(var r in Ie(e))t.push(r);return t})(e);var t=wi(e),r=[];for(var n in e)("constructor"!=n||!t&&De.call(e,n))&&r.push(n);return r}(e)}var Ta=ks(((e,t,r)=>{Fn(e,t,r)})),Pa=ks(((e,t,r,n)=>{Fn(e,t,r,n)})),Ra=Qs(((e,t)=>{var r={};if(null==e)return r;var n=!1;t=xt(t,(t=>(t=gs(t,e),n||(n=t.length>1),t))),Cs(e,ei(e),r),n&&(r=sn(r,7,Zs));for(var s=t.length;s--;)as(r,t[s]);return r})),La=Qs(((e,t)=>null==e?{}:((e,t)=>qn(e,t,((t,r)=>Aa(e,r))))(e,t)));function Da(e,t){if(null==e)return{};var r=xt(ei(e),(e=>[e]));return t=si(t),qn(e,r,((e,r)=>t(e,r[0])))}var Ma=Hs(xa),Na=Hs(ka);function Oa(e){return null==e?[]:Ht(e,xa(e))}var Ua=Ls(((e,t,r)=>(t=t.toLowerCase(),e+(r?Fa(t):t))));function Fa(e){return Ha(fa(e).toLowerCase())}function Ba(e){return(e=fa(e))&&e.replace(me,Zt).replace(Ge,"")}var $a=Ls(((e,t,r)=>e+(r?"-":"")+t.toLowerCase())),qa=Ls(((e,t,r)=>e+(r?" ":"")+t.toLowerCase())),za=Rs("toLowerCase"),ja=Ls(((e,t,r)=>e+(r?"_":"")+t.toLowerCase())),Ka=Ls(((e,t,r)=>e+(r?" ":"")+Ha(t))),Va=Ls(((e,t,r)=>e+(r?" ":"")+t.toUpperCase())),Ha=Rs("toUpperCase");function Ga(e,t,n){return e=fa(e),(t=n?r:t)===r?(e=>Ye.test(e))(e)?(e=>e.match(Xe)||[])(e):(e=>e.match(oe)||[])(e):e.match(t)||[]}var Wa=Hn(((e,t)=>{try{return wt(e,r,t)}catch(e){return Ho(e)?e:new Ee(e)}})),Xa=Qs(((e,t)=>(Et(t,(t=>{t=Li(t),tn(e,t,_o(e[t],e))})),e)));function Za(e){return()=>e}var Ya=Ns(),Qa=Ns(!0);function Ja(e){return e}function ec(e){return Ln("function"==typeof e?e:sn(e,1))}var tc=Hn(((e,t)=>r=>xn(r,e,t))),rc=Hn(((e,t)=>r=>xn(e,r,t)));function nc(e,t,r){var n=xa(t),s=wn(t,n);null!=r||Zo(t)&&(s.length||!n.length)||(r=t,t=e,e=this,s=wn(t,xa(t)));var i=!(Zo(r)&&"chain"in r&&!r.chain),o=Go(e);return Et(s,(function(r){var n=t[r];e[r]=n,o&&(e.prototype[r]=function(){var t=this.__chain__;if(i||t){var r=e(this.__wrapped__);return(r.__actions__=_s(this.__actions__)).push({func:n,args:arguments,thisArg:e}),r.__chain__=t,r}return n.apply(e,kt([this.value()],arguments))})})),e}function sc(){}var ic=Bs(xt),oc=Bs(At),ac=Bs(Rt);function cc(e){return mi(e)?Bt(Li(e)):(e=>t=>vn(t,e))(e)}var lc=qs(),uc=qs(!0);function hc(){return[]}function dc(){return!1}var pc=Fs(((e,t)=>e+t),0),fc=Ks("ceil"),gc=Fs(((e,t)=>e/t),1),mc=Ks("floor"),yc=Fs(((e,t)=>e*t),1),bc=Ks("round"),wc=Fs(((e,t)=>e-t),0);return Or.after=function(e,t){if("function"!=typeof t)throw new xe(n);return e=ua(e),function(){if(--e<1)return t.apply(this,arguments)}},Or.ary=Ao,Or.assign=ga,Or.assignIn=ma,Or.assignInWith=ya,Or.assignWith=ba,Or.at=wa,Or.before=Io,Or.bind=_o,Or.bindAll=Xa,Or.bindKey=Co,Or.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return $o(e)?e:[e]},Or.chain=ao,Or.chunk=(e,t,n)=>{t=(n?gi(e,t,n):t===r)?1:fr(ua(t),0);var s=null==e?0:e.length;if(!s||t<1)return[];for(var i=0,o=0,a=we(Lt(s/t));i<s;)a[o++]=Jn(e,i,i+=t);return a},Or.compact=e=>{for(var t=-1,r=null==e?0:e.length,n=0,s=[];++t<r;){var i=e[t];i&&(s[n++]=i)}return s},Or.concat=function(){var e=arguments.length;if(!e)return[];for(var t=we(e-1),r=arguments[0],n=e;n--;)t[n-1]=arguments[n];return kt($o(r)?_s(r):[r],fn(t,1))},Or.cond=function(e){var t=null==e?0:e.length,r=si();return e=t?xt(e,(e=>{if("function"!=typeof e[1])throw new xe(n);return[r(e[0]),e[1]]})):[],Hn((function(r){for(var n=-1;++n<t;){var s=e[n];if(wt(s[0],this,r))return wt(s[1],this,r)}}))},Or.conforms=e=>(e=>{var t=xa(e);return r=>on(r,e,t)})(sn(e,1)),Or.constant=Za,Or.countBy=uo,Or.create=(e,t)=>{var r=Ur(e);return null==t?r:en(r,t)},Or.curry=function e(t,n,s){var i=Gs(t,8,r,r,r,r,r,n=s?r:n);return i.placeholder=e.placeholder,i},Or.curryRight=function e(t,n,s){var i=Gs(t,16,r,r,r,r,r,n=s?r:n);return i.placeholder=e.placeholder,i},Or.debounce=xo,Or.defaults=va,Or.defaultsDeep=Ea,Or.defer=ko,Or.delay=To,Or.difference=Ni,Or.differenceBy=Oi,Or.differenceWith=Ui,Or.drop=(e,t,n)=>{var s=null==e?0:e.length;return s?Jn(e,(t=n||t===r?1:ua(t))<0?0:t,s):[]},Or.dropRight=(e,t,n)=>{var s=null==e?0:e.length;return s?Jn(e,0,(t=s-(t=n||t===r?1:ua(t)))<0?0:t):[]},Or.dropRightWhile=(e,t)=>e&&e.length?ls(e,si(t,3),!0,!0):[],Or.dropWhile=(e,t)=>e&&e.length?ls(e,si(t,3),!0):[],Or.fill=(e,t,n,s)=>{var i=null==e?0:e.length;return i?(n&&"number"!=typeof n&&gi(e,t,n)&&(n=0,s=i),((e,t,n,s)=>{var i=e.length;for((n=ua(n))<0&&(n=-n>i?0:i+n),(s=s===r||s>i?i:ua(s))<0&&(s+=i),s=n>s?0:ha(s);n<s;)e[n++]=t;return e})(e,t,n,s)):[]},Or.filter=(e,t)=>($o(e)?It:pn)(e,si(t,3)),Or.flatMap=(e,t)=>fn(wo(e,t),1),Or.flatMapDeep=(e,t)=>fn(wo(e,t),c),Or.flatMapDepth=(e,t,n)=>(n=n===r?1:ua(n),fn(wo(e,t),n)),Or.flatten=$i,Or.flattenDeep=e=>null!=e&&e.length?fn(e,c):[],Or.flattenDepth=(e,t)=>null!=e&&e.length?fn(e,t=t===r?1:ua(t)):[],Or.flip=e=>Gs(e,512),Or.flow=Ya,Or.flowRight=Qa,Or.fromPairs=e=>{for(var t=-1,r=null==e?0:e.length,n={};++t<r;){var s=e[t];n[s[0]]=s[1]}return n},Or.functions=e=>null==e?[]:wn(e,xa(e)),Or.functionsIn=e=>null==e?[]:wn(e,ka(e)),Or.groupBy=mo,Or.initial=e=>null!=e&&e.length?Jn(e,0,-1):[],Or.intersection=zi,Or.intersectionBy=ji,Or.intersectionWith=Ki,Or.invert=Ia,Or.invertBy=_a,Or.invokeMap=yo,Or.iteratee=ec,Or.keyBy=bo,Or.keys=xa,Or.keysIn=ka,Or.map=wo,Or.mapKeys=(e,t)=>{var r={};return t=si(t,3),yn(e,((e,n,s)=>{tn(r,t(e,n,s),e)})),r},Or.mapValues=(e,t)=>{var r={};return t=si(t,3),yn(e,((e,n,s)=>{tn(r,n,t(e,n,s))})),r},Or.matches=e=>On(sn(e,1)),Or.matchesProperty=(e,t)=>Un(e,sn(t,1)),Or.memoize=Po,Or.merge=Ta,Or.mergeWith=Pa,Or.method=tc,Or.methodOf=rc,Or.mixin=nc,Or.negate=Ro,Or.nthArg=e=>(e=ua(e),Hn((t=>Bn(t,e)))),Or.omit=Ra,Or.omitBy=(e,t)=>Da(e,Ro(si(t))),Or.once=e=>Io(2,e),Or.orderBy=(e,t,n,s)=>null==e?[]:($o(t)||(t=null==t?[]:[t]),$o(n=s?r:n)||(n=null==n?[]:[n]),$n(e,t,n)),Or.over=ic,Or.overArgs=Lo,Or.overEvery=oc,Or.overSome=ac,Or.partial=Do,Or.partialRight=Mo,Or.partition=vo,Or.pick=La,Or.pickBy=Da,Or.property=cc,Or.propertyOf=e=>t=>null==e?r:vn(e,t),Or.pull=Hi,Or.pullAll=Gi,Or.pullAllBy=(e,t,r)=>e&&e.length&&t&&t.length?zn(e,t,si(r,2)):e,Or.pullAllWith=(e,t,n)=>e&&e.length&&t&&t.length?zn(e,t,r,n):e,Or.pullAt=Wi,Or.range=lc,Or.rangeRight=uc,Or.rearg=No,Or.reject=(e,t)=>($o(e)?It:pn)(e,Ro(si(t,3))),Or.remove=(e,t)=>{var r=[];if(!e||!e.length)return r;var n=-1,s=[],i=e.length;for(t=si(t,3);++n<i;){var o=e[n];t(o,n,e)&&(r.push(o),s.push(n))}return jn(e,s),r},Or.rest=(e,t)=>{if("function"!=typeof e)throw new xe(n);return Hn(e,t=t===r?t:ua(t))},Or.reverse=Xi,Or.sampleSize=(e,t,n)=>(t=(n?gi(e,t,n):t===r)?1:ua(t),($o(e)?Wr:Wn)(e,t)),Or.set=(e,t,r)=>null==e?e:Xn(e,t,r),Or.setWith=(e,t,n,s)=>(s="function"==typeof s?s:r,null==e?e:Xn(e,t,n,s)),Or.shuffle=e=>($o(e)?Xr:Qn)(e),Or.slice=(e,t,n)=>{var s=null==e?0:e.length;return s?(n&&"number"!=typeof n&&gi(e,t,n)?(t=0,n=s):(t=null==t?0:ua(t),n=n===r?s:ua(n)),Jn(e,t,n)):[]},Or.sortBy=Eo,Or.sortedUniq=e=>e&&e.length?ns(e):[],Or.sortedUniqBy=(e,t)=>e&&e.length?ns(e,si(t,2)):[],Or.split=(e,t,n)=>(n&&"number"!=typeof n&&gi(e,t,n)&&(t=n=r),(n=n===r?h:n>>>0)?(e=fa(e))&&("string"==typeof t||null!=t&&!ta(t))&&!(t=is(t))&&Jt(e)?ys(ir(e),0,n):e.split(t,n):[]),Or.spread=function(e,t){if("function"!=typeof e)throw new xe(n);return t=null==t?0:fr(ua(t),0),Hn((function(r){var n=r[t],s=ys(r,0,t);return n&&kt(s,n),wt(e,this,s)}))},Or.tail=e=>{var t=null==e?0:e.length;return t?Jn(e,1,t):[]},Or.take=(e,t,n)=>e&&e.length?Jn(e,0,(t=n||t===r?1:ua(t))<0?0:t):[],Or.takeRight=(e,t,n)=>{var s=null==e?0:e.length;return s?Jn(e,(t=s-(t=n||t===r?1:ua(t)))<0?0:t,s):[]},Or.takeRightWhile=(e,t)=>e&&e.length?ls(e,si(t,3),!1,!0):[],Or.takeWhile=(e,t)=>e&&e.length?ls(e,si(t,3)):[],Or.tap=(e,t)=>(t(e),e),Or.throttle=(e,t,r)=>{var s=!0,i=!0;if("function"!=typeof e)throw new xe(n);return Zo(r)&&(s="leading"in r?!!r.leading:s,i="trailing"in r?!!r.trailing:i),xo(e,t,{leading:s,maxWait:t,trailing:i})},Or.thru=co,Or.toArray=ca,Or.toPairs=Ma,Or.toPairsIn=Na,Or.toPath=e=>$o(e)?xt(e,Li):sa(e)?[e]:_s(Ri(fa(e))),Or.toPlainObject=pa,Or.transform=(e,t,r)=>{var n=$o(e),s=n||Ko(e)||ia(e);if(t=si(t,4),null==r){var i=e&&e.constructor;r=s?n?new i:[]:Zo(e)&&Go(i)?Ur(Ke(e)):{}}return(s?Et:yn)(e,((e,n,s)=>t(r,e,n,s))),r},Or.unary=e=>Ao(e,1),Or.union=Zi,Or.unionBy=Yi,Or.unionWith=Qi,Or.uniq=e=>e&&e.length?os(e):[],Or.uniqBy=(e,t)=>e&&e.length?os(e,si(t,2)):[],Or.uniqWith=(e,t)=>(t="function"==typeof t?t:r,e&&e.length?os(e,r,t):[]),Or.unset=(e,t)=>null==e||as(e,t),Or.unzip=Ji,Or.unzipWith=eo,Or.update=(e,t,r)=>null==e?e:cs(e,t,fs(r)),Or.updateWith=(e,t,n,s)=>(s="function"==typeof s?s:r,null==e?e:cs(e,t,fs(n),s)),Or.values=Oa,Or.valuesIn=e=>null==e?[]:Ht(e,ka(e)),Or.without=to,Or.words=Ga,Or.wrap=(e,t)=>Do(fs(t),e),Or.xor=ro,Or.xorBy=no,Or.xorWith=so,Or.zip=io,Or.zipObject=(e,t)=>ds(e||[],t||[],Yr),Or.zipObjectDeep=(e,t)=>ds(e||[],t||[],Xn),Or.zipWith=oo,Or.entries=Ma,Or.entriesIn=Na,Or.extend=ma,Or.extendWith=ya,nc(Or,Or),Or.add=pc,Or.attempt=Wa,Or.camelCase=Ua,Or.capitalize=Fa,Or.ceil=fc,Or.clamp=(e,t,n)=>(n===r&&(n=t,t=r),n!==r&&(n=(n=da(n))==n?n:0),t!==r&&(t=(t=da(t))==t?t:0),nn(da(e),t,n)),Or.clone=e=>sn(e,4),Or.cloneDeep=e=>sn(e,5),Or.cloneDeepWith=(e,t)=>sn(e,5,t="function"==typeof t?t:r),Or.cloneWith=(e,t)=>sn(e,4,t="function"==typeof t?t:r),Or.conformsTo=(e,t)=>null==t||on(e,t,xa(t)),Or.deburr=Ba,Or.defaultTo=(e,t)=>null==e||e!=e?t:e,Or.divide=gc,Or.endsWith=(e,t,n)=>{e=fa(e),t=is(t);var s=e.length,i=n=n===r?s:nn(ua(n),0,s);return(n-=t.length)>=0&&e.slice(n,i)==t},Or.eq=Oo,Or.escape=e=>(e=fa(e))&&H.test(e)?e.replace(K,Yt):e,Or.escapeRegExp=e=>(e=fa(e))&&ee.test(e)?e.replace(J,"\\$&"):e,Or.every=(e,t,n)=>{var s=$o(e)?At:hn;return n&&gi(e,t,n)&&(t=r),s(e,si(t,3))},Or.find=ho,Or.findIndex=Fi,Or.findKey=(e,t)=>Dt(e,si(t,3),yn),Or.findLast=po,Or.findLastIndex=Bi,Or.findLastKey=(e,t)=>Dt(e,si(t,3),bn),Or.floor=mc,Or.forEach=fo,Or.forEachRight=go,Or.forIn=(e,t)=>null==e?e:gn(e,si(t,3),ka),Or.forInRight=(e,t)=>null==e?e:mn(e,si(t,3),ka),Or.forOwn=(e,t)=>e&&yn(e,si(t,3)),Or.forOwnRight=(e,t)=>e&&bn(e,si(t,3)),Or.get=Sa,Or.gt=Uo,Or.gte=Fo,Or.has=(e,t)=>null!=e&&hi(e,t,In),Or.hasIn=Aa,Or.head=qi,Or.identity=Ja,Or.includes=(e,t,r,n)=>{e=zo(e)?e:Oa(e),r=r&&!n?ua(r):0;var s=e.length;return r<0&&(r=fr(s+r,0)),na(e)?r<=s&&e.indexOf(t,r)>-1:!!s&&Nt(e,t,r)>-1},Or.indexOf=(e,t,r)=>{var n=null==e?0:e.length;if(!n)return-1;var s=null==r?0:ua(r);return s<0&&(s=fr(n+s,0)),Nt(e,t,s)},Or.inRange=(e,t,n)=>(t=la(t),n===r?(n=t,t=0):n=la(n),((e,t,r)=>e>=gr(t,r)&&e<fr(t,r))(e=da(e),t,n)),Or.invoke=Ca,Or.isArguments=Bo,Or.isArray=$o,Or.isArrayBuffer=qo,Or.isArrayLike=zo,Or.isArrayLikeObject=jo,Or.isBoolean=e=>!0===e||!1===e||Yo(e)&&Sn(e)==g,Or.isBuffer=Ko,Or.isDate=Vo,Or.isElement=e=>Yo(e)&&1===e.nodeType&&!ea(e),Or.isEmpty=e=>{if(null==e)return!0;if(zo(e)&&($o(e)||"string"==typeof e||"function"==typeof e.splice||Ko(e)||ia(e)||Bo(e)))return!e.length;var t=ui(e);if(t==v||t==_)return!e.size;if(wi(e))return!Dn(e).length;for(var r in e)if(De.call(e,r))return!1;return!0},Or.isEqual=(e,t)=>Tn(e,t),Or.isEqualWith=(e,t,n)=>{var s=(n="function"==typeof n?n:r)?n(e,t):r;return s===r?Tn(e,t,r,n):!!s},Or.isError=Ho,Or.isFinite=e=>"number"==typeof e&&hr(e),Or.isFunction=Go,Or.isInteger=Wo,Or.isLength=Xo,Or.isMap=Qo,Or.isMatch=(e,t)=>e===t||Pn(e,t,oi(t)),Or.isMatchWith=(e,t,n)=>(n="function"==typeof n?n:r,Pn(e,t,oi(t),n)),Or.isNaN=e=>Jo(e)&&e!=+e,Or.isNative=e=>{if(bi(e))throw new Ee("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");return Rn(e)},Or.isNil=e=>null==e,Or.isNull=e=>null===e,Or.isNumber=Jo,Or.isObject=Zo,Or.isObjectLike=Yo,Or.isPlainObject=ea,Or.isRegExp=ta,Or.isSafeInteger=e=>Wo(e)&&e>=-9007199254740991&&e<=l,Or.isSet=ra,Or.isString=na,Or.isSymbol=sa,Or.isTypedArray=ia,Or.isUndefined=e=>e===r,Or.isWeakMap=e=>Yo(e)&&ui(e)==k,Or.isWeakSet=e=>Yo(e)&&"[object WeakSet]"==Sn(e),Or.join=(e,t)=>null==e?"":dr.call(e,t),Or.kebabCase=$a,Or.last=Vi,Or.lastIndexOf=(e,t,n)=>{var s=null==e?0:e.length;if(!s)return-1;var i=s;return n!==r&&(i=(i=ua(n))<0?fr(s+i,0):gr(i,s-1)),t==t?((e,t,r)=>{for(var n=r+1;n--;)if(e[n]===t)return n;return n})(e,t,i):Mt(e,Ut,i,!0)},Or.lowerCase=qa,Or.lowerFirst=za,Or.lt=oa,Or.lte=aa,Or.max=e=>e&&e.length?dn(e,Ja,An):r,Or.maxBy=(e,t)=>e&&e.length?dn(e,si(t,2),An):r,Or.mean=e=>Ft(e,Ja),Or.meanBy=(e,t)=>Ft(e,si(t,2)),Or.min=e=>e&&e.length?dn(e,Ja,Mn):r,Or.minBy=(e,t)=>e&&e.length?dn(e,si(t,2),Mn):r,Or.stubArray=hc,Or.stubFalse=dc,Or.stubObject=()=>({}),Or.stubString=()=>"",Or.stubTrue=()=>!0,Or.multiply=yc,Or.nth=(e,t)=>e&&e.length?Bn(e,ua(t)):r,Or.noConflict=function(){return at._===this&&(at._=Fe),this},Or.noop=sc,Or.now=So,Or.pad=(e,t,r)=>{e=fa(e);var n=(t=ua(t))?sr(e):0;if(!t||n>=t)return e;var s=(t-n)/2;return $s($t(s),r)+e+$s(Lt(s),r)},Or.padEnd=(e,t,r)=>{e=fa(e);var n=(t=ua(t))?sr(e):0;return t&&n<t?e+$s(t-n,r):e},Or.padStart=(e,t,r)=>{e=fa(e);var n=(t=ua(t))?sr(e):0;return t&&n<t?$s(t-n,r)+e:e},Or.parseInt=(e,t,r)=>(r||null==t?t=0:t&&(t=+t),yr(fa(e).replace(te,""),t||0)),Or.random=(e,t,n)=>{if(n&&"boolean"!=typeof n&&gi(e,t,n)&&(t=n=r),n===r&&("boolean"==typeof t?(n=t,t=r):"boolean"==typeof e&&(n=e,e=r)),e===r&&t===r?(e=0,t=1):(e=la(e),t===r?(t=e,e=0):t=la(t)),e>t){var s=e;e=t,t=s}if(n||e%1||t%1){var i=br();return gr(e+i*(t-e+nt("1e-"+((i+"").length-1))),t)}return Kn(e,t)},Or.reduce=function(e,t,r){var n=$o(e)?Tt:qt,s=arguments.length<3;return n(e,si(t,4),r,s,ln)},Or.reduceRight=function(e,t,r){var n=$o(e)?Pt:qt,s=arguments.length<3;return n(e,si(t,4),r,s,un)},Or.repeat=(e,t,n)=>(t=(n?gi(e,t,n):t===r)?1:ua(t),Vn(fa(e),t)),Or.replace=function(){var e=arguments,t=fa(e[0]);return e.length<3?t:t.replace(e[1],e[2])},Or.result=(e,t,n)=>{var s=-1,i=(t=gs(t,e)).length;for(i||(i=1,e=r);++s<i;){var o=null==e?r:e[Li(t[s])];o===r&&(s=i,o=n),e=Go(o)?o.call(e):o}return e},Or.round=bc,Or.runInContext=e,Or.sample=e=>($o(e)?Gr:Gn)(e),Or.size=e=>{if(null==e)return 0;if(zo(e))return na(e)?sr(e):e.length;var t=ui(e);return t==v||t==_?e.size:Dn(e).length},Or.snakeCase=ja,Or.some=(e,t,n)=>{var s=$o(e)?Rt:es;return n&&gi(e,t,n)&&(t=r),s(e,si(t,3))},Or.sortedIndex=(e,t)=>ts(e,t),Or.sortedIndexBy=(e,t,r)=>rs(e,t,si(r,2)),Or.sortedIndexOf=(e,t)=>{var r=null==e?0:e.length;if(r){var n=ts(e,t);if(n<r&&Oo(e[n],t))return n}return-1},Or.sortedLastIndex=(e,t)=>ts(e,t,!0),Or.sortedLastIndexBy=(e,t,r)=>rs(e,t,si(r,2),!0),Or.sortedLastIndexOf=(e,t)=>{if(null!=e&&e.length){var r=ts(e,t,!0)-1;if(Oo(e[r],t))return r}return-1},Or.startCase=Ka,Or.startsWith=(e,t,r)=>(e=fa(e),r=null==r?0:nn(ua(r),0,e.length),t=is(t),e.slice(r,r+t.length)==t),Or.subtract=wc,Or.sum=e=>e&&e.length?zt(e,Ja):0,Or.sumBy=(e,t)=>e&&e.length?zt(e,si(t,2)):0,Or.template=(e,t,n)=>{var s=Or.templateSettings;n&&gi(e,t,n)&&(t=r),e=fa(e),t=ya({},t,s,Ws);var i,o,a=ya({},t.imports,s.imports,Ws),c=xa(a),l=Ht(a,c),u=0,h=t.interpolate||ye,d="__p += '",p=_e((t.escape||ye).source+"|"+h.source+"|"+(h===X?le:ye).source+"|"+(t.evaluate||ye).source+"|$","g"),f="//# sourceURL="+(De.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++Je+"]")+"\n";e.replace(p,((t,r,n,s,a,c)=>(n||(n=s),d+=e.slice(u,c).replace(be,Qt),r&&(i=!0,d+="' +\n__e("+r+") +\n'"),a&&(o=!0,d+="';\n"+a+";\n__p += '"),n&&(d+="' +\n((__t = ("+n+")) == null ? '' : __t) +\n'"),u=c+t.length,t))),d+="';\n";var g=De.call(t,"variable")&&t.variable;if(g){if(ae.test(g))throw new Ee("Invalid `variable` option passed into `_.template`")}else d="with (obj) {\n"+d+"\n}\n";d=(o?d.replace($,""):d).replace(q,"$1").replace(z,"$1;"),d="function("+(g||"obj")+") {\n"+(g?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(i?", __e = _.escape":"")+(o?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+d+"return __p\n}";var m=Wa((()=>Se(c,f+"return "+d).apply(r,l)));if(m.source=d,Ho(m))throw m;return m},Or.times=(e,t)=>{if((e=ua(e))<1||e>l)return[];var r=h,n=gr(e,h);t=si(t),e-=h;for(var s=jt(n,t);++r<e;)t(r);return s},Or.toFinite=la,Or.toInteger=ua,Or.toLength=ha,Or.toLower=e=>fa(e).toLowerCase(),Or.toNumber=da,Or.toSafeInteger=e=>e?nn(ua(e),-9007199254740991,l):0===e?e:0,Or.toString=fa,Or.toUpper=e=>fa(e).toUpperCase(),Or.trim=(e,t,n)=>{if((e=fa(e))&&(n||t===r))return Kt(e);if(!e||!(t=is(t)))return e;var s=ir(e),i=ir(t);return ys(s,Wt(s,i),Xt(s,i)+1).join("")},Or.trimEnd=(e,t,n)=>{if((e=fa(e))&&(n||t===r))return e.slice(0,or(e)+1);if(!e||!(t=is(t)))return e;var s=ir(e);return ys(s,0,Xt(s,ir(t))+1).join("")},Or.trimStart=(e,t,n)=>{if((e=fa(e))&&(n||t===r))return e.replace(te,"");if(!e||!(t=is(t)))return e;var s=ir(e);return ys(s,Wt(s,ir(t))).join("")},Or.truncate=(e,t)=>{var n=30,s="...";if(Zo(t)){var i="separator"in t?t.separator:i;n="length"in t?ua(t.length):n,s="omission"in t?is(t.omission):s}var o=(e=fa(e)).length;if(Jt(e)){var a=ir(e);o=a.length}if(n>=o)return e;var c=n-sr(s);if(c<1)return s;var l=a?ys(a,0,c).join(""):e.slice(0,c);if(i===r)return l+s;if(a&&(c+=l.length-c),ta(i)){if(e.slice(c).search(i)){var u,h=l;for(i.global||(i=_e(i.source,fa(ue.exec(i))+"g")),i.lastIndex=0;u=i.exec(h);)var d=u.index;l=l.slice(0,d===r?c:d)}}else if(e.indexOf(is(i),c)!=c){var p=l.lastIndexOf(i);p>-1&&(l=l.slice(0,p))}return l+s},Or.unescape=e=>(e=fa(e))&&V.test(e)?e.replace(j,ar):e,Or.uniqueId=e=>{var t=++Me;return fa(e)+t},Or.upperCase=Va,Or.upperFirst=Ha,Or.each=fo,Or.eachRight=go,Or.first=qi,nc(Or,(()=>{var e={};return yn(Or,((t,r)=>{De.call(Or.prototype,r)||(e[r]=t)})),e})(),{chain:!1}),Or.VERSION="4.17.21",Et(["bind","bindKey","curry","curryRight","partial","partialRight"],(e=>{Or[e].placeholder=Or})),Et(["drop","take"],(function(e,t){$r.prototype[e]=function(n){n=n===r?1:fr(ua(n),0);var s=this.__filtered__&&!t?new $r(this):this.clone();return s.__filtered__?s.__takeCount__=gr(n,s.__takeCount__):s.__views__.push({size:gr(n,h),type:e+(s.__dir__<0?"Right":"")}),s},$r.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),Et(["filter","map","takeWhile"],(function(e,t){var r=t+1,n=1==r||3==r;$r.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:si(e,3),type:r}),t.__filtered__=t.__filtered__||n,t}})),Et(["head","last"],(function(e,t){var r="take"+(t?"Right":"");$r.prototype[e]=function(){return this[r](1).value()[0]}})),Et(["initial","tail"],(function(e,t){var r="drop"+(t?"":"Right");$r.prototype[e]=function(){return this.__filtered__?new $r(this):this[r](1)}})),$r.prototype.compact=function(){return this.filter(Ja)},$r.prototype.find=function(e){return this.filter(e).head()},$r.prototype.findLast=function(e){return this.reverse().find(e)},$r.prototype.invokeMap=Hn((function(e,t){return"function"==typeof e?new $r(this):this.map((r=>xn(r,e,t)))})),$r.prototype.reject=function(e){return this.filter(Ro(si(e)))},$r.prototype.slice=function(e,t){e=ua(e);var n=this;return n.__filtered__&&(e>0||t<0)?new $r(n):(e<0?n=n.takeRight(-e):e&&(n=n.drop(e)),t!==r&&(n=(t=ua(t))<0?n.dropRight(-t):n.take(t-e)),n)},$r.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},$r.prototype.toArray=function(){return this.take(h)},yn($r.prototype,(function(e,t){var n=/^(?:filter|find|map|reject)|While$/.test(t),s=/^(?:head|last)$/.test(t),i=Or[s?"take"+("last"==t?"Right":""):t],o=s||/^find/.test(t);i&&(Or.prototype[t]=function(){var t=this.__wrapped__,a=s?[1]:arguments,c=t instanceof $r,l=a[0],u=c||$o(t),h=e=>{var t=i.apply(Or,kt([e],a));return s&&d?t[0]:t};u&&n&&"function"==typeof l&&1!=l.length&&(c=u=!1);var d=this.__chain__,p=!!this.__actions__.length,f=o&&!d,g=c&&!p;if(!o&&u){t=g?t:new $r(this);var m=e.apply(t,a);return m.__actions__.push({func:co,args:[h],thisArg:r}),new Br(m,d)}return f&&g?e.apply(this,a):(m=this.thru(h),f?s?m.value()[0]:m.value():m)})})),Et(["pop","push","shift","sort","splice","unshift"],(function(e){var t=ke[e],r=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",n=/^(?:pop|shift)$/.test(e);Or.prototype[e]=function(){var e=arguments;if(n&&!this.__chain__){var s=this.value();return t.apply($o(s)?s:[],e)}return this[r]((r=>t.apply($o(r)?r:[],e)))}})),yn($r.prototype,((e,t)=>{var r=Or[t];if(r){var n=r.name+"";De.call(xr,n)||(xr[n]=[]),xr[n].push({name:t,func:r})}})),xr[Os(r,2).name]=[{name:"wrapper",func:r}],$r.prototype.clone=function(){var e=new $r(this.__wrapped__);return e.__actions__=_s(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=_s(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=_s(this.__views__),e},$r.prototype.reverse=function(){if(this.__filtered__){var e=new $r(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},$r.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,r=$o(e),n=t<0,s=r?e.length:0,i=((e,t,r)=>{for(var n=-1,s=r.length;++n<s;){var i=r[n],o=i.size;switch(i.type){case"drop":e+=o;break;case"dropRight":t-=o;break;case"take":t=gr(t,e+o);break;case"takeRight":e=fr(e,t-o)}}return{start:e,end:t}})(0,s,this.__views__),o=i.start,a=i.end,c=a-o,l=n?a:o-1,u=this.__iteratees__,h=u.length,d=0,p=gr(c,this.__takeCount__);if(!r||!n&&s==c&&p==c)return us(e,this.__actions__);var f=[];e:for(;c--&&d<p;){for(var g=-1,m=e[l+=t];++g<h;){var y=u[g],b=y.iteratee,w=y.type,v=b(m);if(2==w)m=v;else if(!v){if(1==w)continue e;break e}}f[d++]=m}return f},Or.prototype.at=lo,Or.prototype.chain=function(){return ao(this)},Or.prototype.commit=function(){return new Br(this.value(),this.__chain__)},Or.prototype.next=function(){this.__values__===r&&(this.__values__=ca(this.value()));var e=this.__index__>=this.__values__.length;return{done:e,value:e?r:this.__values__[this.__index__++]}},Or.prototype.plant=function(e){for(var t,n=this;n instanceof Fr;){var s=Mi(n);s.__index__=0,s.__values__=r,t?i.__wrapped__=s:t=s;var i=s;n=n.__wrapped__}return i.__wrapped__=e,t},Or.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof $r){var t=e;return this.__actions__.length&&(t=new $r(this)),(t=t.reverse()).__actions__.push({func:co,args:[Xi],thisArg:r}),new Br(t,this.__chain__)}return this.thru(Xi)},Or.prototype.toJSON=Or.prototype.valueOf=Or.prototype.value=function(){return us(this.__wrapped__,this.__actions__)},Or.prototype.first=Or.prototype.head,it&&(Or.prototype[it]=function(){return this}),Or}();lt?((lt.exports=cr)._=cr,ct._=cr):at._=cr}()}(LS,LS.exports)),new fs("sds:message"),new fs("sds:message-channel"),new fs("sdk:query-on-connect"),(e=>{e.MessagesRetrieved="messages:retrieved"})(RS||(RS={})),new fs("sdk:missing-message-retriever"),new fs("sdk:reliable-channel"),As.ENCODE_FAILED,As.EMPTY_PAYLOAD,As.SIZE_TOO_BIG,As.RLN_PROOF_GENERATION;const{floor:DS,random:MS}=Math,NS="Trystero",OS=(e,t)=>Array(e).fill().map(t),US=OS(20,(()=>"0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"[DS(62*MS())])).join(""),FS=Promise.all.bind(Promise),BS="undefined"!=typeof window,{entries:$S,fromEntries:qS,keys:zS}=Object,jS=()=>{},KS=e=>Error(`${NS}: ${e}`),VS=new TextEncoder,HS=new TextDecoder,GS=e=>VS.encode(e),WS=e=>HS.decode(e),XS=(...e)=>e.join("@"),ZS=JSON.stringify,YS=JSON.parse;let QS=null,JS=null;const eA=()=>{QS||(QS=new Promise((e=>{JS=e})).finally((()=>{JS=null,QS=null})))},tA=()=>JS?.(),rA="AES-GCM",nA={},sA=async e=>nA[e]||=Array.from(await(async(e,t)=>new Uint8Array(await crypto.subtle.digest("SHA-1",GS(t))))(0,e)).map((e=>e.toString(36))).join(""),iA=async(e,t)=>{const r=crypto.getRandomValues(new Uint8Array(16));var n;return r.join(",")+"$"+(n=await crypto.subtle.encrypt({name:rA,iv:r},await e,GS(t)),btoa(String.fromCharCode.apply(null,new Uint8Array(n))))},oA=async(e,t)=>{const[r,n]=t.split("$");return WS(await crypto.subtle.decrypt({name:rA,iv:new Uint8Array(r.split(","))},await e,(e=>{const t=atob(e);return new Uint8Array(t.length).map(((e,r)=>t.charCodeAt(r))).buffer})(n)))},aA="icegatheringstatechange",cA="offer";var lA=(e,{rtcConfig:t,rtcPolyfill:r,turnConfig:n})=>{const s=new(r||RTCPeerConnection)({iceServers:uA.concat(n||[]),...t}),i={};let o=!1,a=!1,c=null;const l=e=>{e.binaryType="arraybuffer",e.bufferedAmountLowThreshold=65535,e.onmessage=e=>i.data?.(e.data),e.onopen=()=>i.connect?.(),e.onclose=()=>i.close?.(),e.onerror=e=>i.error?.(e)},u=e=>Promise.race([new Promise((t=>{const r=()=>{"complete"===e.iceGatheringState&&(e.removeEventListener(aA,r),t())};e.addEventListener(aA,r),r()})),new Promise((e=>setTimeout(e,5e3)))]).then((()=>({type:e.localDescription.type,sdp:e.localDescription.sdp.replace(/a=ice-options:trickle\s\n/g,"")})));return e?(c=s.createDataChannel("data"),l(c)):s.ondatachannel=({channel:e})=>{c=e,l(e)},s.onnegotiationneeded=async()=>{try{o=!0,await s.setLocalDescription();const e=await u(s);i.signal?.(e)}catch(e){i.error?.(e)}finally{o=!1}},s.onconnectionstatechange=()=>{["disconnected","failed","closed"].includes(s.connectionState)&&i.close?.()},s.ontrack=e=>{i.track?.(e.track,e.streams[0]),i.stream?.(e.streams[0])},s.onremovestream=e=>i.stream?.(e.stream),e&&(s.canTrickleIceCandidates||s.onnegotiationneeded()),{created:Date.now(),connection:s,get channel(){return c},get isDead(){return"closed"===s.connectionState},async signal(t){if("open"!==c?.readyState||t.sdp?.includes("a=rtpmap"))try{if(t.type===cA){if(o||"stable"!==s.signalingState&&!a){if(e)return;await FS([s.setLocalDescription({type:"rollback"}),s.setRemoteDescription(t)])}else await s.setRemoteDescription(t);await s.setLocalDescription();const r=await u(s);return i.signal?.(r),r}if("answer"===t.type){a=!0;try{await s.setRemoteDescription(t)}finally{a=!1}}}catch(e){i.error?.(e)}},sendData:e=>c.send(e),destroy(){c?.close(),s.close(),o=!1,a=!1},setHandlers:e=>Object.assign(i,e),offerPromise:e?new Promise((e=>i.signal=t=>{t.type===cA&&e(t)})):Promise.resolve(),addStream:e=>e.getTracks().forEach((t=>s.addTrack(t,e))),removeStream:e=>s.getSenders().filter((t=>e.getTracks().includes(t.track))).forEach((e=>s.removeTrack(e))),addTrack:(e,t)=>s.addTrack(e,t),removeTrack(e){const t=s.getSenders().find((t=>t.track===e));t&&s.removeTrack(t)},replaceTrack(e,t){const r=s.getSenders().find((t=>t.track===e));if(r)return r.replaceTrack(t)}}};const uA=[...OS(3,((e,t)=>`stun:stun${t||""}.l.google.com:19302`)),"stun:stun.cloudflare.com:3478"].map((e=>({urls:e}))),hA=Object.getPrototypeOf(Uint8Array),dA=16369,pA=255,fA="bufferedamountlow",gA=e=>"@_"+e,mA=e=>`/${NS}-${e}/0/msg/json`,yA=(e,t,r)=>e.lightPush.send(e.createEncoder({contentTopic:mA(t),ephemeral:!0}),{payload:GS(r)},{autoRetry:!0}),bA=(({init:e,subscribe:t,announce:r})=>{const n={};let s,i,o,a,c=!1;return(l,u,h)=>{const{appId:d}=l;if(n[d]?.[u])return n[d][u];const p={},f={},g=XS(NS,d,u),m=sA(g),y=sA(XS(g,US)),b=(async(e,t,r)=>crypto.subtle.importKey("raw",await crypto.subtle.digest({name:"SHA-256"},GS(`${e}:${t}:${r}`)),{name:rA},!1,["encrypt","decrypt"]))(l.password||"",d,u),w=e=>async t=>({type:t.type,sdp:await e(b,t.sdp)}),v=w(oA),E=w(iA),S=()=>lA(!0,l),A=(e,t,r)=>{f[t]?f[t]!==e&&e.destroy():(f[t]=e,P(e,t),p[t]?.forEach(((e,t)=>{t!==r&&e.destroy()})),delete p[t])},I=(e,t)=>{f[t]===e&&delete f[t]},_=e=>(i.push(...OS(e,S)),FS(i.splice(0,e).map((e=>e.offerPromise.then(E).then((t=>({peer:e,offer:t}))))))),C=(e,t)=>h?.({error:`incorrect password (${l.password}) when decrypting ${t}`,appId:d,peerId:e,roomId:u});if(!l)throw KS("requires a config map as the first argument");if(!d&&!l.firebaseApp)throw KS("config map is missing appId field");if(!u)throw KS("roomId argument required");if(!c){const t=e(l);i=OS(20,S),s=Array.isArray(t)?t:[t],c=!0,o=setInterval((()=>i=i.filter((e=>{const t=Date.now()-e.created<57333;return t||e.destroy(),t}))),59052.99),a=l.manualRelayReconnection?jS:(()=>{if(BS){const e=new AbortController;return addEventListener("online",tA,{signal:e.signal}),addEventListener("offline",eA,{signal:e.signal}),()=>e.abort()}return jS})()}const x=s.map((()=>5333)),k=[],T=s.map((async(e,r)=>t(await e,await m,await y,(e=>async(t,r,n)=>{const[s,i]=await FS([m,y]);if(t!==s&&t!==i)return;const{peerId:o,offer:a,answer:c,peer:u}="string"==typeof r?YS(r):r;if(o!==US&&!f[o])if(!o||a||c){if(a){const t=p[o]?.[e];if(t&&US>o)return;const r=lA(!1,l);let s;r.setHandlers({connect:()=>A(r,o,e),close:()=>I(r,o)});try{s=await v(a)}catch{return void C(o,"offer")}if(r.isDead)return;const[i,c]=await FS([sA(XS(g,o)),r.signal(s)]);n(i,ZS({peerId:US,answer:await E(c)}))}else if(c){let t;try{t=await v(c)}catch(e){return void C(o,"answer")}if(u)u.setHandlers({connect:()=>A(u,o,e),close:()=>I(u,o)}),u.signal(t);else{const r=p[o]?.[e];r&&!r.isDead&&r.signal(t)}}}else{if(p[o]?.[e])return;const[[{peer:t,offer:r}],s]=await FS([_(1),sA(XS(g,o))]);p[o]||=[],p[o][e]=t,setTimeout((()=>((e,t)=>{if(f[e])return;const r=p[e]?.[t];r&&(delete p[e][t],r.destroy())})(o,e)),.9*x[e]),t.setHandlers({connect:()=>A(t,o,e),close:()=>I(t,o)}),n(s,ZS({peerId:US,offer:r}))}})(r),_)));FS([m,y]).then((([e,t])=>{const n=async(s,i)=>{const o=await r(s,e,t);"number"==typeof o&&(x[i]=o),k[i]=setTimeout((()=>n(s,i)),x[i])};T.forEach((async(e,t)=>{await e,n(await s[t],t)}))}));let P=jS;return n[d]||={},n[d][u]=((e,t,r)=>{const n={},s={},i={},o={},a={},c={},l={},u={onPeerJoin:jS,onPeerLeave:jS,onPeerStream:jS,onPeerTrack:jS},h=(e,t)=>(e?Array.isArray(e)?e:[e]:zS(n)).flatMap((e=>{const r=n[e];return r?t(e,r):(console.warn(`${NS}: no peer with id ${e} found`),[])})),d=e=>{n[e]&&(n[e].destroy(),delete n[e],delete o[e],delete a[e],u.onPeerLeave(e),t(e))},p=e=>{if(s[e])return i[e];if(!e)throw KS("action type argument is required");const t=GS(e);if(t.byteLength>12)throw KS(`action type string "${e}" (${t.byteLength}b) exceeds byte limit (12). Hint: choose a shorter name.`);const r=new Uint8Array(12);r.set(t);let o=0;return s[e]={onComplete:jS,onProgress:jS,setOnComplete:t=>s[e]={...s[e],onComplete:t},setOnProgress:t=>s[e]={...s[e],onProgress:t},async send(e,t,s,i){if(s&&"object"!=typeof s)throw KS("action meta argument must be an object");const a=typeof e;if("undefined"===a)throw KS("action data cannot be undefined");const c="string"!==a,l=e instanceof Blob,u=l||e instanceof ArrayBuffer||e instanceof hA;if(s&&!u)throw KS("action meta argument can only be used with binary data");const d=u?new Uint8Array(l?await e.arrayBuffer():e):GS(c?ZS(e):e),p=s?GS(ZS(s)):null,f=Math.ceil(d.byteLength/dA)+(s?1:0)||1,g=OS(f,((e,t)=>{const n=t===f-1,i=s&&0===t,a=new Uint8Array(15+(i?p.byteLength:n?d.byteLength-dA*(f-(s?2:1)):dA));return a.set(r),a.set([o],12),a.set([n|i<<1|u<<2|c<<3],13),a.set([Math.round((t+1)/f*pA)],14),a.set(s?i?p:d.subarray((t-1)*dA,t*dA):d.subarray(t*dA,(t+1)*dA),15),a}));return o=o+1&pA,FS(h(t,(async(e,t)=>{const{channel:r}=t;let o=0;for(;o<f;){const a=g[o];if(r.bufferedAmount>r.bufferedAmountLowThreshold&&await new Promise((e=>{const t=()=>{r.removeEventListener(fA,t),e()};r.addEventListener(fA,t)})),!n[e])break;t.sendData(a),o++,i?.(a[14]/pA,e,s)}})))}},i[e]||=[s[e].send,s[e].setOnComplete,s[e].setOnProgress]},f=async()=>{await _(""),await new Promise((e=>setTimeout(e,99))),$S(n).forEach((([e,t])=>{t.destroy(),delete n[e]})),r()},[g,m]=p(gA("ping")),[y,b]=p(gA("pong")),[w,v]=p(gA("signal")),[E,S]=p(gA("stream")),[A,I]=p(gA("track")),[_,C]=p(gA("leave"));return(e=>{P=e})(((e,t)=>{n[t]||(n[t]=e,e.setHandlers({data:e=>((e,t)=>{const r=new Uint8Array(t),n=WS(r.subarray(0,12)).replaceAll("\0",""),[i]=r.subarray(12,13),[a]=r.subarray(13,14),[c]=r.subarray(14,15),l=r.subarray(15),u=!!(1&a),h=!!(2&a),d=!!(4&a),p=!!(8&a);if(!s[n])return void console.warn(`${NS}: received message with unregistered type (${n})`);o[e]||={},o[e][n]||={};const f=o[e][n][i]||={chunks:[]};if(h?f.meta=YS(WS(l)):f.chunks.push(l),s[n].onProgress(c/pA,e,f.meta),!u)return;const g=new Uint8Array(f.chunks.reduce(((e,t)=>e+t.byteLength),0));if(f.chunks.reduce(((e,t)=>(g.set(t,e),e+t.byteLength)),0),delete o[e][n][i],d)s[n].onComplete(g,e,f.meta);else{const t=WS(g);s[n].onComplete(p?YS(t):t,e)}})(t,e),stream(e){u.onPeerStream(e,t,c[t]),delete c[t]},track(e,r){u.onPeerTrack(e,r,t,l[t]),delete l[t]},signal:e=>w(e,t),close:()=>d(t),error(e){console.error(e),d(t)}}),u.onPeerJoin(t))})),m(((e,t)=>y("",t))),b(((e,t)=>{a[t]?.(),delete a[t]})),v(((e,t)=>n[t]?.signal(e))),S(((e,t)=>c[t]=e)),I(((e,t)=>l[t]=e)),C(((e,t)=>d(t))),BS&&addEventListener("beforeunload",f),{makeAction:p,leave:f,async ping(e){if(!e)throw KS("ping() must be called with target peer ID");const t=Date.now();return g("",e),await new Promise((t=>a[e]=t)),Date.now()-t},getPeers:()=>qS($S(n).map((([e,t])=>[e,t.connection]))),addStream:(e,t,r)=>h(t,(async(t,n)=>{r&&await E(r,t),n.addStream(e)})),removeStream:(e,t)=>h(t,((t,r)=>r.removeStream(e))),addTrack:(e,t,r,n)=>h(r,(async(r,s)=>{n&&await A(n,r),s.addTrack(e,t)})),removeTrack:(e,t)=>h(t,((t,r)=>r.removeTrack(e))),replaceTrack:(e,t,r,n)=>h(r,(async(r,s)=>{n&&await A(n,r),s.replaceTrack(e,t)})),onPeerJoin:e=>u.onPeerJoin=e,onPeerLeave:e=>u.onPeerLeave=e,onPeerStream:e=>u.onPeerStream=e,onPeerTrack:e=>u.onPeerTrack=e}})(0,(e=>delete f[e]),(()=>{delete n[d][u],k.forEach(clearTimeout),T.forEach((async e=>(await e)())),clearInterval(o),a(),c=!1}))}})({init:()=>async function(e={}){const t=await GE(e),r=new du(e,t,{store:!0,lightpush:!0,filter:!0});return!1!==e?.autoStart&&await r.start(),r}({defaultBootstrap:!0,discovery:{dns:!0,peerExchange:!0,peerCache:!0}}).then((async e=>(await e.start(),await e.waitForPeers(),e))),async subscribe(e,t,r,n){const s=await FS([t,r].map((t=>{const r=e.createDecoder({contentTopic:mA(t)});return e.filter.subscribe(r,(t=>r=>{r.payload&&n(t,WS(r.payload),((t,r)=>yA(e,t,r)))})(t)),()=>e.filter.unsubscribe(r)})));return()=>s.forEach((e=>e()))},announce:(e,t)=>yA(e,t,ZS({peerId:US}))})},{c1f15e2440b26488:"fDdlt","@parcel/transformer-js/src/esmodule-helpers.js":"XTfsy"}]},[],0,"parcelRequire55a5");