@libp2p/webrtc 6.0.23-29797a5bb → 6.0.23-5b8813abc
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.
- package/dist/index.min.js +6 -6
- package/dist/index.min.js.map +4 -4
- package/package.json +11 -11
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PWebrtc = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2PWebrtc=(()=>{var Ei=Object.defineProperty;var np=Object.getOwnPropertyDescriptor;var op=Object.getOwnPropertyNames;var sp=Object.prototype.hasOwnProperty;var te=(t,e)=>{for(var r in e)Ei(t,r,{get:e[r],enumerable:!0})},ip=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of op(e))!sp.call(t,o)&&o!==r&&Ei(t,o,{get:()=>e[o],enumerable:!(n=np(e,o))||n.enumerable});return t};var ap=t=>ip(Ei({},"__esModule",{value:!0}),t);var Pb={};te(Pb,{webRTC:()=>Rb,webRTCDirect:()=>Db});var Bo=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},Do=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},q=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Ir=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Ro=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},Po=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},Tr=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var et=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Sn=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Oo=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Uo=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},No=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Fo=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var er=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var ko=class extends Event{data;constructor(e,r){super("message",r),this.data=e}},Br=class extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}},Mo=class extends Br{constructor(e,r){super(!0,e,r)}},Ko=class extends Br{constructor(e,r){super(!1,e,r)}};var Si=Symbol.for("@libp2p/peer-id");var Ho=Symbol.for("@libp2p/transport");var tu;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(tu||(tu={}));function cp(t){return typeof t?.handleEvent=="function"}function fp(t){return(t!==!0&&t!==!1&&t?.once)??!1}var Lt=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){let o=fp(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==r),this.#e.set(i.type,a))}cp(r)?r.handleEvent(i):r(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:r,once:o})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==r),this.#e.set(e,o))}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}};var Dr=Symbol.for("@libp2p/service-capabilities"),ru=Symbol.for("@libp2p/service-dependencies");var Li={};te(Li,{base58btc:()=>ue,base58flickr:()=>gp});var lx=new Uint8Array(0);function nu(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function lt(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function ou(t){return new TextEncoder().encode(t)}function su(t){return new TextDecoder().decode(t)}function up(t,e){if(t.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 o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=t.length,c=t.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var b=0,h=0,y=0,v=p.length;y!==v&&p[y]===0;)y++,b++;for(var _=(v-y)*u+1>>>0,D=new Uint8Array(_);y!==v;){for(var R=p[y],P=0,B=_-1;(R!==0||P<h)&&B!==-1;B--,P++)R+=256*D[B]>>>0,D[B]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");h=P,y++}for(var I=_-h;I!==_&&D[I]===0;)I++;for(var U=c.repeat(b);I<_;++I)U+=t.charAt(D[I]);return U}function m(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var h=0,y=0;p[b]===c;)h++,b++;for(var v=(p.length-b)*f+1>>>0,_=new Uint8Array(v);p[b];){var D=r[p.charCodeAt(b)];if(D===255)return;for(var R=0,P=v-1;(D!==0||R<y)&&P!==-1;P--,R++)D+=a*_[P]>>>0,_[P]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");y=R,b++}if(p[b]!==" "){for(var B=v-y;B!==v&&_[B]===0;)B++;for(var I=new Uint8Array(h+(v-B)),U=h;B!==v;)I[U++]=_[B++];return I}}}function d(p){var b=m(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:m,decode:d}}var lp=up,hp=lp,au=hp;var Ai=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},vi=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){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))}else throw Error("Can only multibase decode strings")}or(e){return cu(this,e)}},Ci=class{decoders;constructor(e){this.decoders=e}or(e){return cu(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function cu(t,e){return new Ci({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var _i=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Ai(e,r,n),this.decoder=new vi(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Rr({name:t,prefix:e,encode:r,decode:n}){return new _i(t,e,r,n)}function It({name:t,prefix:e,alphabet:r}){let{encode:n,decode:o}=au(r,t);return Rr({prefix:e,name:t,encode:n,decode:s=>lt(o(s))})}function dp(t,e,r,n){let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[t[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|u,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function pp(t,e,r){let n=e[e.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function mp(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function fe({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let o=mp(n);return Rr({prefix:e,name:t,encode(s){return pp(s,n,r)},decode(s){return dp(s,o,r,t)}})}var ue=It({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),gp=It({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ii={};te(Ii,{base32:()=>Tt,base32hex:()=>wp,base32hexpad:()=>Sp,base32hexpadupper:()=>Ap,base32hexupper:()=>Ep,base32pad:()=>bp,base32padupper:()=>xp,base32upper:()=>yp,base32z:()=>vp});var Tt=fe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),yp=fe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),bp=fe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),xp=fe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),wp=fe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ep=fe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Sp=fe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ap=fe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),vp=fe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ti={};te(Ti,{base36:()=>An,base36upper:()=>Cp});var An=It({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Cp=It({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var $e={};te($e,{Digest:()=>tr,create:()=>Be,decode:()=>Ur,equals:()=>Di,hasCode:()=>$p});var _p=lu,fu=128,Lp=127,Ip=~Lp,Tp=Math.pow(2,31);function lu(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Tp;)e[r++]=t&255|fu,t/=128;for(;t&Ip;)e[r++]=t&255|fu,t>>>=7;return e[r]=t|0,lu.bytes=r-n+1,e}var Bp=Bi,Dp=128,uu=127;function Bi(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw Bi.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&uu)<<o:(i&uu)*Math.pow(2,o),o+=7}while(i>=Dp);return Bi.bytes=s-n,r}var Rp=Math.pow(2,7),Pp=Math.pow(2,14),Op=Math.pow(2,21),Up=Math.pow(2,28),Np=Math.pow(2,35),Fp=Math.pow(2,42),kp=Math.pow(2,49),Mp=Math.pow(2,56),Kp=Math.pow(2,63),Hp=function(t){return t<Rp?1:t<Pp?2:t<Op?3:t<Up?4:t<Np?5:t<Fp?6:t<kp?7:t<Mp?8:t<Kp?9:10},zp={encode:_p,decode:Bp,encodingLength:Hp},Vp=zp,vn=Vp;function Cn(t,e=0){return[vn.decode(t,e),vn.decode.bytes]}function Pr(t,e,r=0){return vn.encode(t,e,r),e}function Or(t){return vn.encodingLength(t)}function Be(t,e){let r=e.byteLength,n=Or(t),o=n+Or(r),s=new Uint8Array(o+r);return Pr(t,s,0),Pr(r,s,n),s.set(e,o),new tr(t,r,e,s)}function Ur(t){let e=lt(t),[r,n]=Cn(e),[o,s]=Cn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new tr(r,o,i,e)}function Di(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&nu(t.bytes,r.bytes)}}var tr=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};function $p(t,e){return t.code===e}function hu(t,e){let{bytes:r,version:n}=t;return n===0?jp(r,Ri(t),e??ue.encoder):Gp(r,Ri(t),e??Tt.encoder)}var du=new WeakMap;function Ri(t){let e=du.get(t);if(e==null){let r=new Map;return du.set(t,r),r}return e}var pe=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}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:{let{code:e,multihash:r}=this;if(e!==_n)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Wp)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}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:{let{code:e,digest:r}=this.multihash,n=Be(e,r);return t.createV1(this.code,n)}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 t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&Di(e.multihash,n.multihash)}toString(e){return hu(this,e)}toJSON(){return{"/":hu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new t(n,o,s,i??pu(n,o,s.bytes))}else if(r[Xp]===!0){let{version:n,multihash:o,code:s}=r,i=Ur(o);return t.create(n,s,i)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==_n)throw new Error(`Version 0 CID must use dag-pb (code: ${_n}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=pu(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,_n,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=lt(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new tr(r.multihashCode,r.digestSize,s,o);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[l,m]=Cn(e.subarray(r));return r+=m,l},o=n(),s=_n;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),f=r+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,r){let[n,o]=qp(e,r),s=t.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ri(s).set(n,e),s}};function qp(t,e){switch(t[0]){case"Q":{let r=e??ue;return[ue.prefix,r.decode(`${ue.prefix}${t}`)]}case ue.prefix:{let r=e??ue;return[ue.prefix,r.decode(t)]}case Tt.prefix:{let r=e??Tt;return[Tt.prefix,r.decode(t)]}case An.prefix:{let r=e??An;return[An.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function jp(t,e,r){let{prefix:n}=r;if(n!==ue.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function Gp(t,e,r){let{prefix:n}=r,o=e.get(n);if(o==null){let s=r.encode(t);return e.set(n,s),s}else return o}var _n=112,Wp=18;function pu(t,e,r){let n=Or(t),o=n+Or(e),s=new Uint8Array(o+r.byteLength);return Pr(t,s,0),Pr(e,s,n),s.set(r,o),s}var Xp=Symbol.for("@ipld/js-cid/CID");var Pi={};te(Pi,{identity:()=>qe});var mu=0,Yp="identity",gu=lt;function Zp(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return Be(mu,gu(t))}var qe={code:mu,name:Yp,encode:gu,digest:Zp};function Me(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function Jp(t){return t.buffer instanceof ArrayBuffer}function Ke(t){return Jp(t)?t:t.slice()}async function yu(t,e,r,n){let o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,Ke(e),Ke(r.subarray()));return n?.signal?.throwIfAborted(),s}function ht(t=0){return new Uint8Array(t)}function Ln(t=0){return new Uint8Array(t)}function Oi(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=Ln(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}function bu(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}var wu=Symbol.for("@achingbrain/uint8arraylist");function xu(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let o=r+n.byteLength;if(e<o)return{buf:n,index:e-r};r=o}throw new RangeError("index is out of bounds")}function Vo(t){return!!t?.[wu]}var z=class t{bufs;length;[wu]=!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 r=0;for(let n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(Vo(n)){r+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...e){this.prependAll(e)}prependAll(e){let r=0;for(let n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(Vo(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(e){let r=xu(this.bufs,e);return r.buf[r.index]}set(e,r){let n=xu(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(Vo(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,r){let{bufs:n,length:o}=this._subList(e,r);return Oi(n,o)}subarray(e,r){let{bufs:n,length:o}=this._subList(e,r);return n.length===1?n[0]:Oi(n,o)}sublist(e,r){let{bufs:n,length:o}=this._subList(e,r),s=new t;return s.length=o,s.bufs=n,s}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let f=e>=a&&e<c,u=r>a&&r<=c;if(f&&u){if(e===a&&r===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(r-e)));break}if(f){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(r===c){n.push(i);break}n.push(i.subarray(0,r-a));break}n.push(i)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!Vo(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let l=r;l<=c;l+=u){u=0;for(let m=f;m>=0;m--){let d=this.get(l+m);if(n[m]!==d){u=Math.max(1,m-a[d]);break}}if(u===0)return l}return-1}getInt8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=Ln(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){let o=ht(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,e)}getInt32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){let o=ht(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,e)}getBigInt64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){let o=ht(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,e)}getUint8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){let n=Ln(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){let o=ht(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,e)}getUint32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){let o=ht(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,e)}getBigUint64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){let o=ht(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,e)}getFloat32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){let o=ht(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,e)}getFloat64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){let o=ht(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof t)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!bu(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new t;return n.bufs=e,r==null&&(r=e.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}};var Mi={};te(Mi,{base10:()=>im});var $x=new Uint8Array(0);function Eu(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function dt(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return rr(t);if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return rr(new Uint8Array(t.buffer,t.byteOffset,t.byteLength));throw new Error("Unknown type, must be binary type")}function Su(t){return new TextEncoder().encode(t)}function Au(t){return new TextDecoder().decode(t)}function Qp(t){return t?.buffer instanceof ArrayBuffer}function rr(t){return Qp(t)?t:t.slice()}function em(t,e){if(t.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 o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=t.length,c=t.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var b=0,h=0,y=0,v=p.length;y!==v&&p[y]===0;)y++,b++;for(var _=(v-y)*u+1>>>0,D=new Uint8Array(_);y!==v;){for(var R=p[y],P=0,B=_-1;(R!==0||P<h)&&B!==-1;B--,P++)R+=256*D[B]>>>0,D[B]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");h=P,y++}for(var I=_-h;I!==_&&D[I]===0;)I++;for(var U=c.repeat(b);I<_;++I)U+=t.charAt(D[I]);return U}function m(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var h=0,y=0;p[b]===c;)h++,b++;for(var v=(p.length-b)*f+1>>>0,_=new Uint8Array(v);p[b];){var D=r[p.charCodeAt(b)];if(D===255)return;for(var R=0,P=v-1;(D!==0||R<y)&&P!==-1;P--,R++)D+=a*_[P]>>>0,_[P]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");y=R,b++}if(p[b]!==" "){for(var B=v-y;B!==v&&_[B]===0;)B++;for(var I=new Uint8Array(h+(v-B)),U=h;B!==v;)I[U++]=_[B++];return I}}}function d(p){var b=m(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:m,decode:d}}var tm=em,rm=tm,Cu=rm;var Ui=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ni=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){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))}else throw Error("Can only multibase decode strings")}or(e){return _u(this,e)}},Fi=class{decoders;constructor(e){this.decoders=e}or(e){return _u(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function _u(t,e){return new Fi({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var ki=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Ui(e,r,n),this.decoder=new Ni(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Nr({name:t,prefix:e,encode:r,decode:n}){return new ki(t,e,r,n)}function Bt({name:t,prefix:e,alphabet:r}){let{encode:n,decode:o}=Cu(r,t);return Nr({prefix:e,name:t,encode:n,decode:s=>dt(o(s))})}function nm(t,e,r,n){let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[t[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|u,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function om(t,e,r){let n=e[e.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function sm(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function le({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let o=sm(n);return Nr({prefix:e,name:t,encode(s){return om(s,n,r)},decode(s){return nm(s,o,r,t)}})}var im=Bt({prefix:"9",name:"base10",alphabet:"0123456789"});var Ki={};te(Ki,{base16:()=>am,base16upper:()=>cm});var am=le({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),cm=le({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Hi={};te(Hi,{base2:()=>fm});var fm=le({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var zi={};te(zi,{base256emoji:()=>pm});var Lu=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),um=Lu.reduce((t,e,r)=>(t[r]=e,t),[]),lm=Lu.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function hm(t){return t.reduce((e,r)=>(e+=um[r],e),"")}function dm(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=lm[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var pm=Nr({prefix:"\u{1F680}",name:"base256emoji",encode:hm,decode:dm});var Vi={};te(Vi,{base32:()=>Fr,base32hex:()=>bm,base32hexpad:()=>wm,base32hexpadupper:()=>Em,base32hexupper:()=>xm,base32pad:()=>gm,base32padupper:()=>ym,base32upper:()=>mm,base32z:()=>Sm});var Fr=le({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),mm=le({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),gm=le({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ym=le({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),bm=le({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),xm=le({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),wm=le({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Em=le({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Sm=le({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var $i={};te($i,{base36:()=>In,base36upper:()=>Am});var In=Bt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Am=Bt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var qi={};te(qi,{base58btc:()=>tt,base58flickr:()=>vm});var tt=Bt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),vm=Bt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ji={};te(ji,{base64:()=>Cm,base64pad:()=>_m,base64url:()=>Lm,base64urlpad:()=>Im});var Cm=le({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),_m=le({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Lm=le({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Im=le({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Gi={};te(Gi,{base8:()=>Tm});var Tm=le({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Wi={};te(Wi,{identity:()=>Bm});var Bm=Nr({prefix:"\0",name:"identity",encode:t=>Au(t),decode:t=>Su(t)});var iw=new TextEncoder,aw=new TextDecoder;var Yi={};te(Yi,{identity:()=>Qm});var Pm=Bu,Iu=128,Om=127,Um=~Om,Nm=Math.pow(2,31);function Bu(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Nm;)e[r++]=t&255|Iu,t/=128;for(;t&Um;)e[r++]=t&255|Iu,t>>>=7;return e[r]=t|0,Bu.bytes=r-n+1,e}var Fm=Xi,km=128,Tu=127;function Xi(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw Xi.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&Tu)<<o:(i&Tu)*Math.pow(2,o),o+=7}while(i>=km);return Xi.bytes=s-n,r}var Mm=Math.pow(2,7),Km=Math.pow(2,14),Hm=Math.pow(2,21),zm=Math.pow(2,28),Vm=Math.pow(2,35),$m=Math.pow(2,42),qm=Math.pow(2,49),jm=Math.pow(2,56),Gm=Math.pow(2,63),Wm=function(t){return t<Mm?1:t<Km?2:t<Hm?3:t<zm?4:t<Vm?5:t<$m?6:t<qm?7:t<jm?8:t<Gm?9:10},Xm={encode:Pm,decode:Fm,encodingLength:Wm},Ym=Xm,Tn=Ym;function Bn(t,e=0){return[Tn.decode(t,e),Tn.decode.bytes]}function kr(t,e,r=0){return Tn.encode(t,e,r),e}function Mr(t){return Tn.encodingLength(t)}function Hr(t,e){let r=e.byteLength,n=Mr(t),o=n+Mr(r),s=new Uint8Array(o+r);return kr(t,s,0),kr(r,s,n),s.set(e,o),new Kr(t,r,e,s)}function Du(t){let e=dt(t),[r,n]=Bn(e),[o,s]=Bn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Kr(r,o,i,e)}function Ru(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Eu(t.bytes,r.bytes)}}var Kr=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=rr(n),this.bytes=rr(o)}};var Pu=0,Zm="identity",Ou=dt;function Jm(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return Hr(Pu,Ou(t))}var Qm={code:Pu,name:Zm,encode:Ou,digest:Jm};var Qi={};te(Qi,{sha256:()=>t0,sha512:()=>r0});var e0=20;function Ji({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new Zi(t,e,r,n,o)}var Zi=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??e0,this.maxDigestLength=s}digest(e,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Uu(n,this.code,r?.truncate):n.then(o=>Uu(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function Uu(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return Hr(e,t)}function Fu(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var t0=Ji({name:"sha2-256",code:18,encode:Fu("SHA-256")}),r0=Ji({name:"sha2-512",code:19,encode:Fu("SHA-512")});function ku(t,e){let{bytes:r,version:n}=t;return n===0?o0(r,ea(t),e??tt.encoder):s0(r,ea(t),e??Fr.encoder)}var Mu=new WeakMap;function ea(t){let e=Mu.get(t);if(e==null){let r=new Map;return Mu.set(t,r),r}return e}var qo=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=rr(o),this["/"]=this.bytes}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:{let{code:e,multihash:r}=this;if(e!==Rn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==i0)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}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:{let{code:e,digest:r}=this.multihash,n=Hr(e,r);return t.createV1(this.code,n)}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 t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&Ru(e.multihash,n.multihash)}toString(e){return ku(this,e)}toJSON(){return{"/":ku(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new t(n,o,s,i??Ku(n,o,s.bytes))}else if(r[a0]===!0){let{version:n,multihash:o,code:s}=r,i=Du(o);return t.create(n,s,i)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==Rn)throw new Error(`Version 0 CID must use dag-pb (code: ${Rn}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=Ku(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,Rn,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=dt(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new Kr(r.multihashCode,r.digestSize,s,o);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[l,m]=Bn(e.subarray(r));return r+=m,l},o=n(),s=Rn;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),f=r+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,r){let[n,o]=n0(e,r),s=t.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ea(s).set(n,e),s}};function n0(t,e){switch(t[0]){case"Q":{let r=e??tt;return[tt.prefix,r.decode(`${tt.prefix}${t}`)]}case tt.prefix:{let r=e??tt;return[tt.prefix,r.decode(t)]}case Fr.prefix:{let r=e??Fr;return[Fr.prefix,r.decode(t)]}case In.prefix:{let r=e??In;return[In.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function o0(t,e,r){let{prefix:n}=r;if(n!==tt.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function s0(t,e,r){let{prefix:n}=r,o=e.get(n);if(o==null){let s=r.encode(t);return e.set(n,s),s}else return o}var Rn=112,i0=18;function Ku(t,e,r){let n=Mr(t),o=n+Mr(e),s=new Uint8Array(o+r.byteLength);return kr(t,s,0),kr(e,s,n),s.set(r,o),s}var a0=Symbol.for("@ipld/js-cid/CID");var ta={...Wi,...Hi,...Gi,...Mi,...Ki,...Vi,...$i,...qi,...ji,...zi},Tw={...Qi,...Yi};function jo(t=0){return new Uint8Array(t)}function zu(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var Hu=zu("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ra=zu("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=jo(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),c0={utf8:Hu,"utf-8":Hu,hex:ta.base16,latin1:ra,ascii:ra,binary:ra,...ta},Go=c0;function he(t,e="utf8"){let r=Go[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function ie(t,e="utf8"){let r=Go[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}var f0=parseInt("11111",2),na=parseInt("10000000",2),u0=parseInt("01111111",2),Vu={0:Pn,1:Pn,2:l0,3:p0,4:m0,5:d0,6:h0,16:Pn,22:Pn,48:Pn};function pt(t,e={offset:0}){let r=t[e.offset]&f0;if(e.offset++,Vu[r]!=null)return Vu[r](t,e);throw new Error("No decoder for tag "+r)}function On(t,e){let r=0;if((t[e.offset]&na)===na){let n=t[e.offset]&u0,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=t[e.offset].toString(16).padStart(2,"0");r=parseInt(o,16)}else r=t[e.offset],e.offset++;return r}function Pn(t,e){On(t,e);let r=[];for(;!(e.offset>=t.byteLength);){let n=pt(t,e);if(n===null)break;r.push(n)}return r}function l0(t,e){let r=On(t,e),n=e.offset,o=e.offset+r,s=[];for(let i=n;i<o;i++)i===n&&t[i]===0||s.push(t[i]);return e.offset+=r,Uint8Array.from(s)}function h0(t,e){let r=On(t,e),n=e.offset+r,o=t[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let f=t[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let u=0;for(let l=0;l<c.length;l++)u+=c[l]<<l*7;a+=`.${u}`,c=[]}}return a}function d0(t,e){return e.offset++,null}function p0(t,e){let r=On(t,e),n=t[e.offset];e.offset++;let o=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function m0(t,e){let r=On(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function g0(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);let r=new z;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function oa(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);let e=g0(t.byteLength);return new z(Uint8Array.from([e.byteLength|na]),e)}function De(t){let e=new z,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new z(Uint8Array.from([2]),oa(e),e)}function Wo(t){let e=Uint8Array.from([0]),r=new z(e,t);return new z(Uint8Array.from([3]),oa(r),r)}function Dt(t,e=48){let r=new z;for(let n of t)r.append(n);return new z(Uint8Array.from([e]),oa(r),r)}var y0=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),b0=Uint8Array.from([6,5,43,129,4,0,34]),x0=Uint8Array.from([6,5,43,129,4,0,35]),w0={ext:!0,kty:"EC",crv:"P-256"},E0={ext:!0,kty:"EC",crv:"P-384"},S0={ext:!0,kty:"EC",crv:"P-521"},sa=32,ia=48,aa=66;function ca(t){let e=pt(t);return $u(e)}function $u(t){let e=t[1][1][0],r=1,n,o;if(e.byteLength===sa*2+1)return n=ie(e.subarray(r,r+sa),"base64url"),o=ie(e.subarray(r+sa),"base64url"),new zr({...w0,key_ops:["verify"],x:n,y:o});if(e.byteLength===ia*2+1)return n=ie(e.subarray(r,r+ia),"base64url"),o=ie(e.subarray(r+ia),"base64url"),new zr({...E0,key_ops:["verify"],x:n,y:o});if(e.byteLength===aa*2+1)return n=ie(e.subarray(r,r+aa),"base64url"),o=ie(e.subarray(r+aa),"base64url"),new zr({...S0,key_ops:["verify"],x:n,y:o});throw new q(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function qu(t){return Dt([De(Uint8Array.from([1])),Dt([A0(t.crv)],160),Dt([Wo(new z(Uint8Array.from([4]),he(t.x??"","base64url"),he(t.y??"","base64url")))],161)]).subarray()}function A0(t){if(t==="P-256")return y0;if(t==="P-384")return b0;if(t==="P-521")return x0;throw new q(`Invalid curve ${t}`)}var zr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=qu(this.jwk)),this._raw}toMultihash(){return qe.digest(Rt(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return ue.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Me(this.raw,e.raw)}async verify(e,r,n){return yu(this.jwk,r,e,n)}};function fa(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function rt(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(`${r}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new RangeError(`${r}expected integer >= 0, got ${t}`)}}function ve(t,e,r=""){let n=fa(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return t}function nr(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(rt(t.outputLen),rt(t.blockLen),t.outputLen<1)throw new Error('"outputLen" must be >= 1');if(t.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Vr(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Xo(t,e){ve(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function je(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Yo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Ge(t,e){return t<<32-e|t>>>e}var Gu=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",v0=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Zo(t){if(ve(t),Gu)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=v0[t[r]];return e}var mt={_0:48,_9:57,A:65,F:70,a:97,f:102};function ju(t){if(t>=mt._0&&t<=mt._9)return t-mt._0;if(t>=mt.A&&t<=mt.F)return t-(mt.A-10);if(t>=mt.a&&t<=mt.f)return t-(mt.a-10)}function Un(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Gu)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=ju(t.charCodeAt(s)),a=ju(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function ua(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];ve(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let s=t[n];r.set(s,o),o+=s.length}return r}function la(t,e={}){let r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function Wu(t=32){rt(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var ha=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Xu(t,e,r){return t&e^~t&r}function Yu(t,e,r){return t&e^t&r^e&r}var Nn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Yo(this.buffer)}update(e){Vr(this),ve(e);let{view:r,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Yo(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Vr(this),Xo(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,je(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)r[l]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Yo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<f;l++)a.setUint32(4*l,u[l],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},gt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Jo=BigInt(4294967295),Zu=BigInt(32);function C0(t,e=!1){return e?{h:Number(t&Jo),l:Number(t>>Zu&Jo)}:{h:Number(t>>Zu&Jo)|0,l:Number(t&Jo)|0}}function Ju(t,e=!1){let r=t.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=C0(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var da=(t,e,r)=>t>>>r,pa=(t,e,r)=>t<<32-r|e>>>r,or=(t,e,r)=>t>>>r|e<<32-r,sr=(t,e,r)=>t<<32-r|e>>>r,Fn=(t,e,r)=>t<<64-r|e>>>r-32,kn=(t,e,r)=>t>>>r-32|e<<64-r;function nt(t,e,r,n){let o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}var Qu=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),el=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,tl=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),rl=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,nl=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),ol=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0;var L0=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]),Pt=new Uint32Array(64),ma=class extends Nn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,r){for(let l=0;l<16;l++,r+=4)Pt[l]=e.getUint32(r,!1);for(let l=16;l<64;l++){let m=Pt[l-15],d=Pt[l-2],p=Ge(m,7)^Ge(m,18)^m>>>3,b=Ge(d,17)^Ge(d,19)^d>>>10;Pt[l]=b+Pt[l-7]+p+Pt[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:u}=this;for(let l=0;l<64;l++){let m=Ge(a,6)^Ge(a,11)^Ge(a,25),d=u+m+Xu(a,c,f)+L0[l]+Pt[l]|0,b=(Ge(n,2)^Ge(n,13)^Ge(n,22))+Yu(n,o,s)|0;u=f,f=c,c=a,a=i+d|0,i=s,s=o,o=n,n=d+b|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,f,u)}roundClean(){je(Pt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),je(this.buffer)}},ga=class extends ma{A=gt[0]|0;B=gt[1]|0;C=gt[2]|0;D=gt[3]|0;E=gt[4]|0;F=gt[5]|0;G=gt[6]|0;H=gt[7]|0;constructor(){super(32)}};var sl=Ju(["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(t=>BigInt(t))),I0=sl[0],T0=sl[1],Ot=new Uint32Array(80),Ut=new Uint32Array(80),ya=class extends Nn{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:u,Fh:l,Fl:m,Gh:d,Gl:p,Hh:b,Hl:h}=this;return[e,r,n,o,s,i,a,c,f,u,l,m,d,p,b,h]}set(e,r,n,o,s,i,a,c,f,u,l,m,d,p,b,h){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=u|0,this.Fh=l|0,this.Fl=m|0,this.Gh=d|0,this.Gl=p|0,this.Hh=b|0,this.Hl=h|0}process(e,r){for(let _=0;_<16;_++,r+=4)Ot[_]=e.getUint32(r),Ut[_]=e.getUint32(r+=4);for(let _=16;_<80;_++){let D=Ot[_-15]|0,R=Ut[_-15]|0,P=or(D,R,1)^or(D,R,8)^da(D,R,7),B=sr(D,R,1)^sr(D,R,8)^pa(D,R,7),I=Ot[_-2]|0,U=Ut[_-2]|0,k=or(I,U,19)^Fn(I,U,61)^da(I,U,6),N=sr(I,U,19)^kn(I,U,61)^pa(I,U,6),g=tl(B,N,Ut[_-7],Ut[_-16]),A=rl(g,P,k,Ot[_-7],Ot[_-16]);Ot[_]=A|0,Ut[_]=g|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:l,El:m,Fh:d,Fl:p,Gh:b,Gl:h,Hh:y,Hl:v}=this;for(let _=0;_<80;_++){let D=or(l,m,14)^or(l,m,18)^Fn(l,m,41),R=sr(l,m,14)^sr(l,m,18)^kn(l,m,41),P=l&d^~l&b,B=m&p^~m&h,I=nl(v,R,B,T0[_],Ut[_]),U=ol(I,y,D,P,I0[_],Ot[_]),k=I|0,N=or(n,o,28)^Fn(n,o,34)^Fn(n,o,39),g=sr(n,o,28)^kn(n,o,34)^kn(n,o,39),A=n&s^n&a^s&a,S=o&i^o&c^i&c;y=b|0,v=h|0,b=d|0,h=p|0,d=l|0,p=m|0,{h:l,l:m}=nt(f|0,u|0,U|0,k|0),f=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let w=Qu(k,g,S);n=el(w,U,N,A),o=w|0}({h:n,l:o}=nt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=nt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=nt(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=nt(this.Dh|0,this.Dl|0,f|0,u|0),{h:l,l:m}=nt(this.Eh|0,this.El|0,l|0,m|0),{h:d,l:p}=nt(this.Fh|0,this.Fl|0,d|0,p|0),{h:b,l:h}=nt(this.Gh|0,this.Gl|0,b|0,h|0),{h:y,l:v}=nt(this.Hh|0,this.Hl|0,y|0,v|0),this.set(n,o,s,i,a,c,f,u,l,m,d,p,b,h,y,v)}roundClean(){je(Ot,Ut)}destroy(){this.destroyed=!0,je(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},ba=class extends ya{Ah=xe[0]|0;Al=xe[1]|0;Bh=xe[2]|0;Bl=xe[3]|0;Ch=xe[4]|0;Cl=xe[5]|0;Dh=xe[6]|0;Dl=xe[7]|0;Eh=xe[8]|0;El=xe[9]|0;Fh=xe[10]|0;Fl=xe[11]|0;Gh=xe[12]|0;Gl=xe[13]|0;Hh=xe[14]|0;Hl=xe[15]|0;constructor(){super(64)}};var ot=la(()=>new ga,ha(1));var Qo=la(()=>new ba,ha(3));var V=(t,e,r)=>ve(t,e,r),wa=rt,$r=Zo,me=(...t)=>ua(...t),qr=t=>Un(t),ir=fa,ar=t=>Wu(t),ts=BigInt(0),xa=BigInt(1);function We(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new TypeError(r+"expected boolean, got type="+typeof t)}return t}function rs(t){if(typeof t=="bigint"){if(!es(t))throw new RangeError("positive bigint expected, got "+t)}else wa(t);return t}function Xe(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(r+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let r=e&&`"${e}" `;throw new RangeError(r+"expected safe integer, got "+t)}}function Mn(t){let e=rs(t).toString(16);return e.length&1?"0"+e:e}function il(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?ts:BigInt("0x"+t)}function cr(t){return il(Zo(t))}function Pe(t){return il(Zo(Nt(ve(t)).reverse()))}function ns(t,e){if(rt(e),e===0)throw new RangeError("zero length");t=rs(t);let r=t.toString(16);if(r.length>e*2)throw new RangeError("number too large");return Un(r.padStart(e*2,"0"))}function Kn(t,e){return ns(t,e).reverse()}function al(t,e){if(t=V(t),e=V(e),t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Nt(t){return Uint8Array.from(V(t))}function os(t){if(typeof t!="string")throw new TypeError("ascii string expected, got "+typeof t);return Uint8Array.from(t,(e,r)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${t[r]}" with code ${n} at position ${r}`);return n})}var es=t=>typeof t=="bigint"&&ts<=t;function B0(t,e,r){return es(t)&&es(e)&&es(r)&&e<=t&&t<r}function yt(t,e,r,n){if(!B0(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function jr(t){if(t<ts)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>ts;t>>=xa,e+=1);return e}var Hn=t=>(xa<<BigInt(t))-xa;function cl(t,e,r){if(rt(t,"hashLen"),rt(e,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let n=h=>new Uint8Array(h),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(t),f=n(t),u=0,l=()=>{c.fill(1),f.fill(0),u=0},m=(...h)=>r(f,me(c,...h)),d=(h=o)=>{f=m(s,h),c=m(),h.length!==0&&(f=m(i,h),c=m())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let h=0,y=[];for(;h<e;){c=m();let v=c.slice();y.push(v),h+=c.length}return me(...y)};return(h,y)=>{l(),d(h);let v;for(;(v=y(p()))===void 0;)d();return l(),v}}function Oe(t,e={},r={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(t,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=t[s];if(a&&c===void 0)return;let f=typeof c;if(f!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${f}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(r,!0)}var Ea=()=>{throw new Error("not implemented")};var we=BigInt(0),de=BigInt(1),fr=BigInt(2),hl=BigInt(3),dl=BigInt(4),pl=BigInt(5),D0=BigInt(7),ml=BigInt(8),R0=BigInt(9),gl=BigInt(16);function ae(t,e){if(e<=we)throw new Error("mod: expected positive modulus, got "+e);let r=t%e;return r>=we?r:e+r}function oe(t,e,r){if(e<we)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >we;)n*=n,n%=r;return n}function fl(t,e){if(t===we)throw new Error("invert: expected non-zero number");if(e<=we)throw new Error("invert: expected positive modulus, got "+e);let r=ae(t,e),n=e,o=we,s=de,i=de,a=we;for(;r!==we;){let f=n/r,u=n-r*f,l=o-i*f,m=s-a*f;n=r,r=u,o=i,s=a,i=l,a=m}if(n!==de)throw new Error("invert: does not exist");return ae(o,e)}function Sa(t,e,r){let n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function yl(t,e){let r=t,n=(r.ORDER+de)/dl,o=r.pow(e,n);return Sa(r,o,e),o}function P0(t,e){let r=t,n=(r.ORDER-pl)/ml,o=r.mul(e,fr),s=r.pow(o,n),i=r.mul(e,s),a=r.mul(r.mul(i,fr),s),c=r.mul(i,r.sub(a,r.ONE));return Sa(r,c,e),c}function O0(t){let e=Gr(t),r=bl(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+D0)/gl;return((a,c)=>{let f=a,u=f.pow(c,i),l=f.mul(u,n),m=f.mul(u,o),d=f.mul(u,s),p=f.eql(f.sqr(l),c),b=f.eql(f.sqr(m),c);u=f.cmov(u,l,p),l=f.cmov(d,m,b);let h=f.eql(f.sqr(l),c),y=f.cmov(u,l,h);return Sa(f,y,c),y})}function bl(t){if(t<hl)throw new Error("sqrt is not defined for small field");let e=t-de,r=0;for(;e%fr===we;)e/=fr,r++;let n=fr,o=Gr(t);for(;ul(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return yl;let s=o.pow(n,e),i=(e+de)/fr;return function(c,f){let u=c;if(u.is0(f))return f;if(ul(u,f)!==1)throw new Error("Cannot find square root");let l=r,m=u.mul(u.ONE,s),d=u.pow(f,e),p=u.pow(f,i);for(;!u.eql(d,u.ONE);){if(u.is0(d))return u.ZERO;let b=1,h=u.sqr(d);for(;!u.eql(h,u.ONE);)if(b++,h=u.sqr(h),b===l)throw new Error("Cannot find square root");let y=de<<BigInt(l-b-1),v=u.pow(m,y);l=b,m=u.sqr(v),d=u.mul(d,m),p=u.mul(p,v)}return p}}function U0(t){return t%dl===hl?yl:t%ml===pl?P0:t%gl===R0?O0(t):bl(t)}var bt=(t,e)=>(ae(t,e)&de)===de,N0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Aa(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=N0.reduce((n,o)=>(n[o]="function",n),e);if(Oe(t,r),Xe(t.BYTES,"BYTES"),Xe(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=de)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function F0(t,e,r){let n=t;if(r<we)throw new Error("invalid exponent, negatives unsupported");if(r===we)return n.ONE;if(r===de)return e;let o=n.ONE,s=e;for(;r>we;)r&de&&(o=n.mul(o,s)),s=n.sqr(s),r>>=de;return o}function zn(t,e,r=!1){let n=t,o=new Array(e.length).fill(r?n.ZERO:void 0),s=e.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),i),o}function ul(t,e){let r=t,n=(r.ORDER-de)/fr,o=r.pow(e,n),s=r.eql(o,r.ONE),i=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function k0(t,e){if(e!==void 0&&wa(e),t<=we)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let r=jr(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected bit length (${r}) >= n.length (${e})`);let n=e!==void 0?e:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var ll=new WeakMap,ss=class{ORDER;BITS;BYTES;isLE;ZERO=we;ONE=de;_lengths;_mod;constructor(e,r={}){if(e<=de)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:o,nByteLength:s}=k0(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return ae(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return we<=e&&e<this.ORDER}is0(e){return e===we}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&de)===de}neg(e){return ae(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return ae(e*e,this.ORDER)}add(e,r){return ae(e+r,this.ORDER)}sub(e,r){return ae(e-r,this.ORDER)}mul(e,r){return ae(e*r,this.ORDER)}pow(e,r){return F0(this,e,r)}div(e,r){return ae(e*fl(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return fl(e,this.ORDER)}sqrt(e){let r=ll.get(this);return r||ll.set(this,r=U0(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?Kn(e,this.BYTES):ns(e,this.BYTES)}fromBytes(e,r=!1){V(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let f=new Uint8Array(o);f.set(e,s?0:f.length-e.length),e=f}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?Pe(e):cr(e);if(a&&(c=ae(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return zn(this,e)}cmov(e,r,n){return We(n,"condition"),n?r:e}};Object.freeze(ss.prototype);function Gr(t,e={}){return new ss(t,e)}function xl(t){if(typeof t!="bigint")throw new Error("field order must be bigint");if(t<=de)throw new Error("field order must be greater than 1");let e=jr(t-de);return Math.ceil(e/8)}function va(t){let e=xl(t);return e+Math.ceil(e/2)}function Ca(t,e,r=!1){V(t);let n=t.length,o=xl(e),s=Math.max(va(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?Pe(t):cr(t),a=ae(i,e-de)+de;return r?Kn(a,o):ns(a,o)}var Wr=BigInt(0),ur=BigInt(1);function Vn(t,e){let r=e.negate();return t?r:e}function lr(t,e){let r=zn(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function Al(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function _a(t,e){Al(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),o=2**t,s=Hn(t),i=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function wl(t,e,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(t&o),c=t>>i;a>n&&(a-=s,c+=ur);let f=e*n,u=f+Math.abs(a)-1,l=a===0,m=a<0,d=e%2!==0;return{nextN:c,offset:u,isZero:l,isNeg:m,isNegF:d,offsetF:f}}var La=new WeakMap,vl=new WeakMap;function Ia(t){return vl.get(t)||1}function El(t){if(t!==Wr)throw new Error("invalid wNAF")}var Xr=class{BASE;ZERO;Fn;bits;constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let o=e;for(;r>Wr;)r&ur&&(n=n.add(o)),o=o.double(),r>>=ur;return n}precomputeWindow(e,r){let{windows:n,windowSize:o}=_a(r,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let f=1;f<o;f++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=_a(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:u,isNeg:l,isNegF:m,offsetF:d}=wl(n,a,i);n=c,u?s=s.add(Vn(m,r[d])):o=o.add(Vn(l,r[f]))}return El(n),{p:o,f:s}}wNAFUnsafe(e,r,n,o=this.ZERO){let s=_a(e,this.bits);for(let i=0;i<s.windows&&n!==Wr;i++){let{nextN:a,offset:c,isZero:f,isNeg:u}=wl(n,i,s);if(n=a,!f){let l=r[c];o=o.add(u?l.negate():l)}}return El(n),o}getPrecomputes(e,r,n){let o=La.get(r);return o||(o=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(o=n(o)),La.set(r,o))),o}cached(e,r,n){let o=Ia(e);return this.wNAF(o,this.getPrecomputes(o,e,n),r)}unsafe(e,r,n,o){let s=Ia(e);return s===1?this._unsafeLadder(e,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,o)}createCache(e,r){Al(r,this.bits),vl.set(e,r),La.delete(e)}hasCache(e){return Ia(e)!==1}};function Cl(t,e,r,n){let o=e,s=t.ZERO,i=t.ZERO;for(;r>Wr||n>Wr;)r&ur&&(s=s.add(o)),n&ur&&(i=i.add(o)),o=o.double(),r>>=ur,n>>=ur;return{p1:s,p2:i}}function Sl(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Aa(e),e}else return Gr(t,{isLE:r})}function is(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let f=e[c];if(!(typeof f=="bigint"&&f>Wr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Sl(e.p,r.Fp,n),s=Sl(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function Yr(t,e){return function(n){let o=t(n);return{secretKey:o,publicKey:e(o)}}}var Ft=BigInt(0),ye=BigInt(1),Ta=BigInt(2),M0=BigInt(8);function K0(t,e,r,n){let o=t.sqr(r),s=t.sqr(n),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function _l(t,e={}){let r=e,n=is("edwards",t,r,r.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;Oe(r,{},{uvRatio:"function"});let c=Ta<<BigInt(s.BYTES*8)-ye,f=b=>o.create(b),u=r.uvRatio===void 0?(b,h)=>{try{return{isValid:!0,value:o.sqrt(o.div(b,h))}}catch{return{isValid:!1,value:Ft}}}:r.uvRatio;if(!K0(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function l(b,h,y=!1){let v=y?ye:Ft;return yt("coordinate "+b,h,v,c),h}function m(b){if(!(b instanceof d))throw new Error("EdwardsPoint expected")}class d{static BASE=new d(i.Gx,i.Gy,ye,f(i.Gx*i.Gy));static ZERO=new d(Ft,ye,ye,Ft);static Fp=o;static Fn=s;X;Y;Z;T;constructor(h,y,v,_){this.X=l("x",h),this.Y=l("y",y),this.Z=l("z",v,!0),this.T=l("t",_),Object.freeze(this)}static CURVE(){return i}static fromAffine(h){if(h instanceof d)throw new Error("extended point not allowed");let{x:y,y:v}=h||{};return l("x",y),l("y",v),new d(y,v,ye,f(y*v))}static fromBytes(h,y=!1){let v=o.BYTES,{a:_,d:D}=i;h=Nt(V(h,v,"point")),We(y,"zip215");let R=Nt(h),P=h[v-1];R[v-1]=P&-129;let B=Pe(R),I=y?c:o.ORDER;yt("point.y",B,Ft,I);let U=f(B*B),k=f(U-ye),N=f(D*U-_),{isValid:g,value:A}=u(k,N);if(!g)throw new Error("bad point: invalid y coordinate");let S=(A&ye)===ye,w=(P&128)!==0;if(!y&&A===Ft&&w)throw new Error("bad point: x=0 and x_0=1");return w!==S&&(A=f(-A)),d.fromAffine({x:A,y:B})}static fromHex(h,y=!1){return d.fromBytes(qr(h),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,y=!0){return p.createCache(this,h),y||this.multiply(Ta),this}assertValidity(){let h=this,{a:y,d:v}=i;if(h.is0())throw new Error("bad point: ZERO");let{X:_,Y:D,Z:R,T:P}=h,B=f(_*_),I=f(D*D),U=f(R*R),k=f(U*U),N=f(B*y),g=f(U*f(N+I)),A=f(k+f(v*f(B*I)));if(g!==A)throw new Error("bad point: equation left != right (1)");let S=f(_*D),w=f(R*P);if(S!==w)throw new Error("bad point: equation left != right (2)")}equals(h){m(h);let{X:y,Y:v,Z:_}=this,{X:D,Y:R,Z:P}=h,B=f(y*P),I=f(D*_),U=f(v*P),k=f(R*_);return B===I&&U===k}is0(){return this.equals(d.ZERO)}negate(){return new d(f(-this.X),this.Y,this.Z,f(-this.T))}double(){let{a:h}=i,{X:y,Y:v,Z:_}=this,D=f(y*y),R=f(v*v),P=f(Ta*f(_*_)),B=f(h*D),I=y+v,U=f(f(I*I)-D-R),k=B+R,N=k-P,g=B-R,A=f(U*N),S=f(k*g),w=f(U*g),x=f(N*k);return new d(A,S,x,w)}add(h){m(h);let{a:y,d:v}=i,{X:_,Y:D,Z:R,T:P}=this,{X:B,Y:I,Z:U,T:k}=h,N=f(_*B),g=f(D*I),A=f(P*v*k),S=f(R*U),w=f((_+D)*(B+I)-N-g),x=S-A,C=S+A,L=f(g-y*N),E=f(w*x),T=f(C*L),O=f(w*L),F=f(x*C);return new d(E,T,F,O)}subtract(h){return m(h),this.add(h.negate())}multiply(h){if(!s.isValidNot0(h))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:v}=p.cached(this,h,_=>lr(d,_));return lr(d,[y,v])[0]}multiplyUnsafe(h){if(!s.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===Ft?d.ZERO:this.is0()||h===ye?this:p.unsafe(this,h,y=>lr(d,y))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return p.unsafe(this,i.n).is0()}toAffine(h){let y=this,v=h,{X:_,Y:D,Z:R}=y,P=y.is0();v==null&&(v=P?M0:o.inv(R));let B=f(_*v),I=f(D*v),U=o.mul(R,v);if(P)return{x:Ft,y:ye};if(U!==ye)throw new Error("invZ was invalid");return{x:B,y:I}}clearCofactor(){return a===ye?this:this.multiplyUnsafe(a)}toBytes(){let{x:h,y}=this.toAffine(),v=o.toBytes(y);return v[v.length-1]|=h&ye?128:0,v}toHex(){return $r(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let p=new Xr(d,s.BITS);return s.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var as=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Ea()}static fromHex(e){Ea()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return $r(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,r){return this.ep.precompute(e,r),this}};function Ll(t,e,r={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=r;Oe(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=t,f=n.outputLen,u=2*a.BYTES;if(f!==void 0&&(Xe(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let l=o.randomBytes===void 0?ar:o.randomBytes,m=o.adjustScalarBytes===void 0?g=>g:o.adjustScalarBytes,d=o.domain===void 0?(g,A,S)=>{if(We(S,"phflag"),A.length||S)throw new Error("Contexts/pre-hash are not supported");return g}:o.domain;function p(g){return c.create(Pe(g))}function b(g){let A=B.secretKey;V(g,B.secretKey,"secretKey");let S=V(n(g),2*A,"hashedSecretKey"),w=m(S.slice(0,A)),x=S.slice(A,2*A),C=p(w);return{head:w,prefix:x,scalar:C}}function h(g){let{head:A,prefix:S,scalar:w}=b(g),x=i.multiply(w),C=x.toBytes();return{head:A,prefix:S,scalar:w,point:x,pointBytes:C}}function y(g){return h(g).pointBytes}function v(g=Uint8Array.of(),...A){let S=me(...A);return p(n(d(S,V(g,void 0,"context"),!!s)))}function _(g,A,S={}){g=V(g,void 0,"message"),s&&(g=s(g));let{prefix:w,scalar:x,pointBytes:C}=h(A),L=v(S.context,w,g),E=i.multiply(L).toBytes(),T=v(S.context,E,C,g),O=c.create(L+T*x);if(!c.isValid(O))throw new Error("sign failed: invalid s");let F=me(E,c.toBytes(O));return V(F,B.signature,"result")}let D={zip215:o.zip215};function R(g,A,S,w=D){let{context:x}=w,C=w.zip215===void 0?!!D.zip215:w.zip215,L=B.signature;g=V(g,L,"signature"),A=V(A,void 0,"message"),S=V(S,B.publicKey,"publicKey"),C!==void 0&&We(C,"zip215"),s&&(A=s(A));let E=L/2,T=g.subarray(0,E),O=Pe(g.subarray(E,L)),F,H,K;try{F=t.fromBytes(S,C),H=t.fromBytes(T,C),K=i.multiplyUnsafe(O)}catch{return!1}if(!C&&F.isSmallOrder())return!1;let Z=v(x,T,S,A);return H.add(F.multiplyUnsafe(Z)).subtract(K).clearCofactor().is0()}let P=a.BYTES,B={secretKey:P,publicKey:P,signature:2*P,seed:P};function I(g){return g=g===void 0?l(B.seed):g,V(g,B.seed,"seed")}function U(g){return ir(g)&&g.length===B.secretKey}function k(g,A){try{return!!t.fromBytes(g,A===void 0?D.zip215:A)}catch{return!1}}let N={getExtendedPublicKey:h,randomSecretKey:I,isValidSecretKey:U,isValidPublicKey:k,toMontgomery(g){let{y:A}=t.fromBytes(g),S=B.publicKey,w=S===32;if(!w&&S!==57)throw new Error("only defined for 25519 and 448");let x=w?a.div(ye+A,ye-A):a.div(A-ye,A+ye);return a.toBytes(x)},toMontgomerySecret(g){let A=B.secretKey;V(g,A);let S=n(g.subarray(0,A));return m(S).subarray(0,A)}};return Object.freeze(B),Object.freeze(N),Object.freeze({keygen:Yr(I,y),getPublicKey:y,sign:_,verify:R,utils:N,Point:t,lengths:B})}function $n(t,e){if(Xe(t),Xe(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(t<0||t>2**(8*e)-1)throw new Error("invalid I2OSP input: "+t);let r=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)r[n]=t&255,t>>>=8;return new Uint8Array(r)}function H0(t,e){let r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t[n]^e[n];return r}function z0(t){if(!ir(t)&&typeof t!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof t=="string"?os(t):t;if(e.length===0)throw new Error("DST must be non-empty");return e}function Ba(t,e,r,n){V(t),Xe(r),e=z0(e),e.length>255&&(e=n(me(os("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(r/o);if(r>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=me(e,$n(e.length,1)),c=new Uint8Array(s),f=$n(r,2),u=new Array(i),l=n(me(c,t,f,$n(0,1),a));u[0]=n(me(l,$n(1,1),a));for(let d=1;d<i;d++){let p=[H0(l,u[d-1]),$n(d+1,1),a];u[d]=n(me(...p))}return me(...u).slice(0,r)}var Il="HashToScalar-";var qn=BigInt(0),Zr=BigInt(1),cs=BigInt(2);function V0(t){return Oe(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...t})}function Tl(t){let e=V0(t),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i===void 0?ar:i,f=a?255:448,u=a?32:56,l=BigInt(a?9:5),m=BigInt(a?121665:39081),d=a?cs**BigInt(254):cs**BigInt(447),p=a?BigInt(8)*cs**BigInt(251)-Zr:BigInt(4)*cs**BigInt(445)-Zr,b=d+p+Zr,h=S=>ae(S,r),y=v(l);function v(S){return Kn(h(S),u)}function _(S){let w=Nt(V(S,u,"uCoordinate"));return a&&(w[31]&=127),h(Pe(w))}function D(S){return Pe(o(Nt(V(S,u,"scalar"))))}function R(S,w){let x=k(_(w),D(S));if(x===qn)throw new Error("invalid private or public key received");return v(x)}function P(S){return R(S,y)}let B=P,I=R;function U(S,w,x){let C=h(S*(w-x));return w=h(w-C),x=h(x+C),{x_2:w,x_3:x}}function k(S,w){yt("u",S,qn,r),yt("scalar",w,d,b);let x=w,C=S,L=Zr,E=qn,T=S,O=Zr,F=qn;for(let K=BigInt(f-1);K>=qn;K--){let Z=x>>K&Zr;F^=Z,{x_2:L,x_3:T}=U(F,L,T),{x_2:E,x_3:O}=U(F,E,O),F=Z;let J=L+E,Q=h(J*J),G=L-E,se=h(G*G),ut=Q-se,Qt=T+O,Lr=T-O,wn=h(Lr*J),En=h(Qt*G),Qf=wn+En,eu=wn-En;T=h(Qf*Qf),O=h(C*h(eu*eu)),L=h(Q*se),E=h(ut*(Q+h(m*ut)))}({x_2:L,x_3:T}=U(F,L,T)),{x_2:E,x_3:O}=U(F,E,O);let H=s(E);return h(L*H)}let N={secretKey:u,publicKey:u,seed:u},g=S=>(S=S===void 0?c(u):S,V(S,N.seed,"seed"),S),A={randomSecretKey:g};return Object.freeze(N),Object.freeze(A),Object.freeze({keygen:Yr(g,B),getSharedSecret:I,getPublicKey:B,scalarMult:R,scalarMultBase:P,utils:A,GuBytes:y.slice(),lengths:N})}var $0=BigInt(0),xt=BigInt(1),Bl=BigInt(2),q0=BigInt(3),j0=BigInt(5),G0=BigInt(8),hr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Oa={p:hr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:G0,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Pl(t){let e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=hr,a=t*t%s*t%s,c=oe(a,Bl,s)*a%s,f=oe(c,xt,s)*t%s,u=oe(f,j0,s)*f%s,l=oe(u,e,s)*u%s,m=oe(l,r,s)*l%s,d=oe(m,n,s)*m%s,p=oe(d,o,s)*d%s,b=oe(p,o,s)*d%s,h=oe(b,e,s)*u%s;return{pow_p_5_8:oe(h,Bl,s)*t%s,b2:a}}function Ol(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var Da=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ua(t,e){let r=hr,n=ae(e*e*e,r),o=ae(n*n*e,r),s=Pl(t*o).pow_p_5_8,i=ae(t*n*s,r),a=ae(e*i*i,r),c=i,f=ae(i*Da,r),u=a===t,l=a===ae(-t,r),m=a===ae(-t*Da,r);return u&&(i=c),(l||m)&&(i=f),bt(i,r)&&(i=ae(-i,r)),{isValid:u||l,value:i}}var Mt=_l(Oa,{uvRatio:Ua}),kt=Mt.Fp,Ul=Mt.Fn;function W0(t){return Ll(Mt,Qo,Object.assign({adjustScalarBytes:Ol,zip215:!0},t))}var Nl=W0({});var jn=(()=>{let t=hr;return Tl({P:t,type:"x25519",powPminus2:e=>{let{pow_p_5_8:r,b2:n}=Pl(e);return ae(oe(r,q0,t)*n,t)},adjustScalarBytes:Ol})})();var Ra=Da,X0=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Y0=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Z0=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),J0=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Dl=t=>Ua(xt,t),Q0=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Pa=t=>kt.create(Pe(t)&Q0);function Rl(t){let{d:e}=Oa,r=hr,n=y=>kt.create(y),o=n(Ra*t*t),s=n((o+xt)*Z0),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:f}=Ua(s,a),u=n(f*t);bt(u,r)||(u=n(-u)),c||(f=u),c||(i=o);let l=n(i*(o-xt)*J0-a),m=f*f,d=n((f+f)*a),p=n(l*X0),b=n(xt-m),h=n(xt+m);return new Mt(n(d*h),n(b*p),n(p*h),n(d*b))}var Kt=class t extends as{static BASE=new t(Mt.BASE);static ZERO=new t(Mt.ZERO);static Fp=kt;static Fn=Ul;constructor(e){super(e)}static fromAffine(e){return new t(Mt.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoPoint expected")}init(e){return new t(e)}static fromBytes(e){ve(e,32);let{a:r,d:n}=Oa,o=hr,s=D=>kt.create(D),i=Pa(e);if(!al(kt.toBytes(i),e)||bt(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(xt+r*a),f=s(xt-r*a),u=s(c*c),l=s(f*f),m=s(r*n*u-l),{isValid:d,value:p}=Dl(s(m*l)),b=s(p*f),h=s(p*b*m),y=s((i+i)*b);bt(y,o)&&(y=s(-y));let v=s(c*h),_=s(y*v);if(!d||bt(_,o)||v===$0)throw new Error("invalid ristretto255 encoding 2");return new t(new Mt(y,v,xt,_))}static fromHex(e){return t.fromBytes(Un(e))}toBytes(){let{X:e,Y:r,Z:n,T:o}=this.ep,s=hr,i=h=>kt.create(h),a=i(i(n+r)*i(n-r)),c=i(e*r),f=i(c*c),{value:u}=Dl(i(a*f)),l=i(u*a),m=i(u*c),d=i(l*m*o),p;if(bt(o*d,s)){let h=i(r*Ra),y=i(e*Ra);e=h,r=y,p=i(l*Y0)}else p=m;bt(e*d,s)&&(r=i(-r));let b=i((n-r)*p);return bt(b,s)&&(b=i(-b)),kt.toBytes(b)}equals(e){this.assertSame(e);let{X:r,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=f=>kt.create(f),a=i(r*s)===i(n*o),c=i(n*s)===i(r*o);return a||c}is0(){return this.equals(t.ZERO)}};Object.freeze(Kt.BASE);Object.freeze(Kt.ZERO);Object.freeze(Kt.prototype);Object.freeze(Kt);var eg=Object.freeze({Point:Kt,hashToCurve(t,e){let r=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=Ba(t,r,64,Qo);return eg.deriveToCurve(n)},hashToScalar(t,e={DST:Il}){let r=Ba(t,e.DST,64,Qo);return Ul.create(Pe(r))},deriveToCurve(t){ve(t,64);let e=Pa(t.subarray(0,32)),r=Rl(e),n=Pa(t.subarray(32,64)),o=Rl(n);return new Kt(r.add(o))}});var Gn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},fs=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var He={get(t=globalThis){let e=t.crypto;if(e?.subtle==null)throw new fs("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 e}};var us=32;var Na,tg=(async()=>{try{return await He.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function rg(t,e,r){if(t.buffer instanceof ArrayBuffer){let n=await He.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await He.get().subtle.verify({name:"Ed25519"},n,Ke(e),Ke(r instanceof Uint8Array?r:r.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function ng(t,e,r){return Nl.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function Fl(t,e,r){return Na==null&&(Na=await tg),Na?rg(t,e,r):ng(t,e,r)}function og(t){return t?.buffer instanceof ArrayBuffer}function Ml(t){if(og(t))return t;let e=t.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function ls(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=jo(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return Ml(r)}function hs(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var ds=class{type="Ed25519";raw;constructor(e){this.raw=Fa(e,us)}toMultihash(){return qe.digest(Rt(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return ue.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Me(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();let o=Fl(this.raw,r,e);return hs(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function ka(t){return t=Fa(t,us),new ds(t)}function Fa(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new q(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}function Kl(t=0){return new Uint8Array(t)}var ig=Math.pow(2,7),ag=Math.pow(2,14),cg=Math.pow(2,21),Ma=Math.pow(2,28),Ka=Math.pow(2,35),Ha=Math.pow(2,42),za=Math.pow(2,49),X=128,Ce=127;function ee(t){if(t<ig)return 1;if(t<ag)return 2;if(t<cg)return 3;if(t<Ma)return 4;if(t<Ka)return 5;if(t<Ha)return 6;if(t<za)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ht(t,e,r=0){switch(ee(t)){case 8:e[r++]=t&255|X,t/=128;case 7:e[r++]=t&255|X,t/=128;case 6:e[r++]=t&255|X,t/=128;case 5:e[r++]=t&255|X,t/=128;case 4:e[r++]=t&255|X,t>>>=7;case 3:e[r++]=t&255|X,t>>>=7;case 2:e[r++]=t&255|X,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function fg(t,e,r=0){switch(ee(t)){case 8:e.set(r++,t&255|X),t/=128;case 7:e.set(r++,t&255|X),t/=128;case 6:e.set(r++,t&255|X),t/=128;case 5:e.set(r++,t&255|X),t/=128;case 4:e.set(r++,t&255|X),t>>>=7;case 3:e.set(r++,t&255|X),t>>>=7;case 2:e.set(r++,t&255|X),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function Wn(t,e){let r=t[e],n=0;if(n+=r&Ce,r<X||(r=t[e+1],n+=(r&Ce)<<7,r<X)||(r=t[e+2],n+=(r&Ce)<<14,r<X)||(r=t[e+3],n+=(r&Ce)<<21,r<X)||(r=t[e+4],n+=(r&Ce)*Ma,r<X)||(r=t[e+5],n+=(r&Ce)*Ka,r<X)||(r=t[e+6],n+=(r&Ce)*Ha,r<X)||(r=t[e+7],n+=(r&Ce)*za,r<X))return n;throw new RangeError("Could not decode varint")}function ug(t,e){let r=t.get(e),n=0;if(n+=r&Ce,r<X||(r=t.get(e+1),n+=(r&Ce)<<7,r<X)||(r=t.get(e+2),n+=(r&Ce)<<14,r<X)||(r=t.get(e+3),n+=(r&Ce)<<21,r<X)||(r=t.get(e+4),n+=(r&Ce)*Ma,r<X)||(r=t.get(e+5),n+=(r&Ce)*Ka,r<X)||(r=t.get(e+6),n+=(r&Ce)*Ha,r<X)||(r=t.get(e+7),n+=(r&Ce)*za,r<X))return n;throw new RangeError("Could not decode varint")}function ps(t,e,r=0){return e==null&&(e=Kl(ee(t))),e instanceof Uint8Array?Ht(t,e,r):fg(t,e,r)}function wt(t,e=0){return t instanceof Uint8Array?Wn(t,e):ug(t,e)}var Va=new Float32Array([-0]),zt=new Uint8Array(Va.buffer);function Hl(t,e,r){Va[0]=t,e[r]=zt[0],e[r+1]=zt[1],e[r+2]=zt[2],e[r+3]=zt[3]}function zl(t,e){return zt[0]=t[e],zt[1]=t[e+1],zt[2]=t[e+2],zt[3]=t[e+3],Va[0]}var $a=new Float64Array([-0]),_e=new Uint8Array($a.buffer);function Vl(t,e,r){$a[0]=t,e[r]=_e[0],e[r+1]=_e[1],e[r+2]=_e[2],e[r+3]=_e[3],e[r+4]=_e[4],e[r+5]=_e[5],e[r+6]=_e[6],e[r+7]=_e[7]}function $l(t,e){return _e[0]=t[e],_e[1]=t[e+1],_e[2]=t[e+2],_e[3]=t[e+3],_e[4]=t[e+4],_e[5]=t[e+5],_e[6]=t[e+6],_e[7]=t[e+7],$a[0]}var lg=BigInt(Number.MAX_SAFE_INTEGER),hg=BigInt(Number.MIN_SAFE_INTEGER),Ue=class t{lo;hi;constructor(e,r){this.lo=e|0,this.hi=r|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return dr;if(e<lg&&e>hg)return this.fromNumber(Number(e));let r=e<0n;r&&(e=-e);let n=e>>32n,o=e-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>ql&&(o=0n,++n>ql&&(n=0n))),new t(Number(o),Number(n))}static fromNumber(e){if(e===0)return dr;let r=e<0;r&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new t(n,o)}static from(e){return typeof e=="number"?t.fromNumber(e):typeof e=="bigint"?t.fromBigInt(e):typeof e=="string"?t.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new t(e.low>>>0,e.high>>>0):dr}},dr=new Ue(0,0);dr.toBigInt=function(){return 0n};dr.zzEncode=dr.zzDecode=function(){return this};dr.length=function(){return 1};var ql=4294967296n;function jl(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(r&64512)===55296&&(t.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Gl(t,e,r){if(r-e<1)return"";let o,s=[],i=0,a;for(;e<r;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function qa(t,e,r){let n=r,o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128);return r-n}function Ye(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function ms(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}var ja=class{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=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Ye(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Ye(this,4);return ms(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ye(this,4);return ms(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ye(this,4);let e=zl(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ye(this,4);let e=$l(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw Ye(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let e=this.bytes();return Gl(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ye(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ye(this);while((this.buf[this.pos++]&128)!==0);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(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Ue(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw Ye(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,e}if(this.len-this.pos>4){for(;r<5;++r)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;r<5;++r){if(this.pos>=this.len)throw Ye(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Ye(this,8);let e=ms(this.buf,this.pos+=4),r=ms(this.buf,this.pos+=4);return new Ue(e,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Wn(this.buf,this.pos);return this.pos+=ee(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 Yn(t){return new ja(t instanceof Uint8Array?t:t.subarray())}function Vt(t,e,r){let n=Yn(t);return e.decode(n,void 0,r)}function pr(t=0){return new Uint8Array(t)}var Ga={};te(Ga,{base10:()=>dg});var dg=It({prefix:"9",name:"base10",alphabet:"0123456789"});var Wa={};te(Wa,{base16:()=>pg,base16upper:()=>mg});var pg=fe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),mg=fe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Xa={};te(Xa,{base2:()=>gg});var gg=fe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ya={};te(Ya,{base256emoji:()=>Eg});var Xl=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),yg=Xl.reduce((t,e,r)=>(t[r]=e,t),[]),bg=Xl.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function xg(t){return t.reduce((e,r)=>(e+=yg[r],e),"")}function wg(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=bg[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var Eg=Rr({prefix:"\u{1F680}",name:"base256emoji",encode:xg,decode:wg});var Za={};te(Za,{base64:()=>Sg,base64pad:()=>Ag,base64url:()=>Zn,base64urlpad:()=>vg});var Sg=fe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ag=fe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zn=fe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),vg=fe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ja={};te(Ja,{base8:()=>Cg});var Cg=fe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Qa={};te(Qa,{identity:()=>_g});var _g=Rr({prefix:"\0",name:"identity",encode:t=>su(t),decode:t=>ou(t)});var O2=new TextEncoder,U2=new TextDecoder;var rc={};te(rc,{sha256:()=>Et,sha512:()=>Bg});var Tg=20;function tc({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new ec(t,e,r,n,o)}var ec=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??Tg,this.maxDigestLength=s}digest(e,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Yl(n,this.code,r?.truncate):n.then(o=>Yl(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function Yl(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return Be(e,t)}function Jl(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var Et=tc({name:"sha2-256",code:18,encode:Jl("SHA-256")}),Bg=tc({name:"sha2-512",code:19,encode:Jl("SHA-512")});var Ne={...Qa,...Xa,...Ja,...Ga,...Wa,...Ii,...Ti,...Li,...Za,...Ya},G2={...rc,...Pi};function eh(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var Ql=eh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),nc=eh("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=pr(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Dg={utf8:Ql,"utf-8":Ql,hex:Ne.base16,latin1:nc,ascii:nc,binary:nc,...Ne},th=Dg;function rh(t,e="utf8"){let r=th[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function oc(t){let e=t??8192,r=e>>>1,n,o=e;return function(i){if(i<1||i>r)return pr(i);o+i>e&&(n=pr(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var mr=class{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}};function sc(){}var ac=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Rg=oc();function Pg(t){return globalThis.Buffer!=null?pr(t):Rg(t)}var Qn=class{len;head;tail;states;constructor(){this.len=0,this.head=new mr(sc,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new mr(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new cc((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(gs,10,Ue.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let r=Ue.fromBigInt(e);return this._push(gs,r.length(),r)}uint64Number(e){return this._push(Ht,ee(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){let r=Ue.fromBigInt(e).zzEncode();return this._push(gs,r.length(),r)}sint64Number(e){let r=Ue.fromNumber(e).zzEncode();return this._push(gs,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ic,1,e?1:0)}fixed32(e){return this._push(Jn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let r=Ue.fromBigInt(e);return this._push(Jn,4,r.lo)._push(Jn,4,r.hi)}fixed64Number(e){let r=Ue.fromNumber(e);return this._push(Jn,4,r.lo)._push(Jn,4,r.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(Hl,4,e)}double(e){return this._push(Vl,8,e)}bytes(e){let r=e.length>>>0;return r===0?this._push(ic,1,0):this.uint32(r)._push(Ug,r,e)}string(e){let r=jl(e);return r!==0?this.uint32(r)._push(qa,r,e):this._push(ic,1,0)}fork(){return this.states=new ac(this),this.head=this.tail=new mr(sc,0,0),this.len=0,this}reset(){return this.states!=null?(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 mr(sc,0,0),this.len=0),this}ldelim(){let e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next,r=Pg(this.len),n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}};function ic(t,e,r){e[r]=t&255}function Og(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}var cc=class extends mr{next;constructor(e,r){super(Og,e,r),this.next=void 0}};function gs(t,e,r){for(;t.hi!==0;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}function Jn(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function Ug(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(Qn.prototype.bytes=function(t){let e=t.length>>>0;return this.uint32(e),e>0&&this._push(Ng,e,t),this},Qn.prototype.string=function(t){let e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(Fg,e,t),this});function Ng(t,e,r){e.set(t,r)}function Fg(t,e,r){t.length<40?qa(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(rh(t),r)}function fc(){return new Qn}function $t(t,e){let r=fc();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}function*qt(t,e,r){let n=Yn(t);yield*e.stream(n,void 0,"$",r)}var ys={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function bs(t,e,r,n,o){return{name:t,type:e,encode:r,decode:n,stream:o}}function gr(t){function e(s){if(t[s.toString()]==null)throw new Error("Invalid enum value");return t[s]}let r=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return bs("enum",ys.VARINT,r,n,o)}function jt(t,e,r){return bs("message",ys.LENGTH_DELIMITED,t,e,r)}var ce;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(ce||(ce={}));var uc;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(uc||(uc={}));(function(t){t.codec=()=>gr(uc)})(ce||(ce={}));var st;(function(t){let e;t.codec=()=>(e==null&&(e=jt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ce.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=ce.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:ce.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function r(s){return $t(s,t.codec())}t.encode=r;function n(s,i){return Vt(s,t.codec(),i)}t.decode=n;function o(s,i){return qt(s,t.codec(),i)}t.stream=o})(st||(st={}));var lc;(function(t){let e;t.codec=()=>(e==null&&(e=jt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ce.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=ce.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:ce.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function r(s){return $t(s,t.codec())}t.encode=r;function n(s,i){return Vt(s,t.codec(),i)}t.decode=n;function o(s,i){return qt(s,t.codec(),i)}t.stream=o})(lc||(lc={}));var to={};te(to,{MAX_RSA_KEY_SIZE:()=>hc,generateRSAKeyPair:()=>ah,jwkToJWKKeyPair:()=>ch,jwkToPkcs1:()=>Hg,jwkToPkix:()=>gc,jwkToRSAPrivateKey:()=>wc,pkcs1MessageToJwk:()=>pc,pkcs1MessageToRSAPrivateKey:()=>yc,pkcs1ToJwk:()=>Kg,pkcs1ToRSAPrivateKey:()=>ih,pkixMessageToJwk:()=>mc,pkixMessageToRSAPublicKey:()=>xc,pkixToJwk:()=>zg,pkixToRSAPublicKey:()=>bc});var Jr=class{type="RSA";jwk;_raw;_multihash;constructor(e,r){this.jwk=e,this._multihash=r}get raw(){return this._raw==null&&(this._raw=to.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return pe.createV1(114,this._multihash)}toString(){return ue.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Me(this.raw,e.raw)}verify(e,r,n){return sh(this.jwk,r,e,n)}},eo=class{type="RSA";jwk;_raw;publicKey;constructor(e,r){this.jwk=e,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=to.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Me(this.raw,e.raw)}sign(e,r){return oh(this.jwk,e,r)}};var hc=8192,dc=18,kg=1062,Mg=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Kg(t){let e=pt(t);return pc(e)}function pc(t){return{n:ie(t[1],"base64url"),e:ie(t[2],"base64url"),d:ie(t[3],"base64url"),p:ie(t[4],"base64url"),q:ie(t[5],"base64url"),dp:ie(t[6],"base64url"),dq:ie(t[7],"base64url"),qi:ie(t[8],"base64url"),kty:"RSA"}}function Hg(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new q("JWK was missing components");return Dt([De(Uint8Array.from([0])),De(he(t.n,"base64url")),De(he(t.e,"base64url")),De(he(t.d,"base64url")),De(he(t.p,"base64url")),De(he(t.q,"base64url")),De(he(t.dp,"base64url")),De(he(t.dq,"base64url")),De(he(t.qi,"base64url"))]).subarray()}function zg(t){let e=pt(t,{offset:0});return mc(e)}function mc(t){let e=pt(t[1],{offset:0});return{kty:"RSA",n:ie(e[0],"base64url"),e:ie(e[1],"base64url")}}function gc(t){if(t.n==null||t.e==null)throw new q("JWK was missing components");return Dt([Mg,Wo(Dt([De(he(t.n,"base64url")),De(he(t.e,"base64url"))]))]).subarray()}function ih(t){let e=pt(t);return yc(e)}function yc(t){let e=pc(t);return wc(e)}function bc(t,e){if(t.byteLength>=kg)throw new Ir("Key size is too large");let r=pt(t,{offset:0});return xc(r,t,e)}function xc(t,e,r){let n=mc(t);if(r==null){let o=ot(st.encode({Type:ce.RSA,Data:e}));r=Be(dc,o)}return new Jr(n,r)}function wc(t){if(uh(t)>hc)throw new q("Key size is too large");let e=ch(t),r=ot(st.encode({Type:ce.RSA,Data:gc(e.publicKey)})),n=Be(dc,r);return new eo(e.privateKey,new Jr(e.publicKey,n))}async function ah(t){if(t>hc)throw new q("Key size is too large");let e=await fh(t),r=ot(st.encode({Type:ce.RSA,Data:gc(e.publicKey)})),n=Be(dc,r);return new eo(e.privateKey,new Jr(e.publicKey,n))}function ch(t){if(t==null)throw new q("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function fh(t,e){let r=await He.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await Vg(r,e);return{privateKey:n[0],publicKey:n[1]}}async function oh(t,e,r){let n=await He.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let o=await He.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Ke(e instanceof Uint8Array?e:e.subarray()));return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function sh(t,e,r,n){let o=await He.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await He.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Ke(e),Ke(r instanceof Uint8Array?r:r.subarray()));return n?.signal?.throwIfAborted(),s}async function Vg(t,e){if(t.privateKey==null||t.publicKey==null)throw new q("Private and public key are required");let r=await Promise.all([He.get().subtle.exportKey("jwk",t.privateKey),He.get().subtle.exportKey("jwk",t.publicKey)]);return e?.signal?.throwIfAborted(),r}function uh(t){if(t.kty!=="RSA")throw new q("invalid key type");if(t.n==null)throw new q("invalid key modulus");return he(t.n,"base64url").length*8}var xs=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(nr(e),ve(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),je(o)}update(e){return Vr(this),this.iHash.update(e),this}digestInto(e){Vr(this),Xo(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ro=(()=>{let t=((e,r,n)=>new xs(e,r).update(n).digest());return t.create=(e,r)=>new xs(e,r),t})();var lh=(t,e)=>(t+(t>=0?e:-e)/hh)/e;function $g(t,e,r){yt("scalar",t,it,r);let[[n,o],[s,i]]=e,a=lh(i*t,r),c=lh(-o*t,r),f=t-a*n-c*s,u=-a*o-c*i,l=f<it,m=u<it;l&&(f=-f),m&&(u=-u);let d=Hn(Math.ceil(jr(r)/2))+Gt;if(f<it||f>=d||u<it||u>=d)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:l,k1:f,k2neg:m,k2:u}}function Sc(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Ec(t,e){Oe(t);let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return We(r.lowS,"lowS"),We(r.prehash,"prehash"),r.format!==void 0&&Sc(r.format),r}var Ac=class extends Error{constructor(e=""){super(e)}},Ze={Err:Ac,_tlv:{encode:(t,e)=>{let{Err:r}=Ze;if(Xe(t,"tag"),t<0||t>255)throw new r("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,o=Mn(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?Mn(o.length/2|128):"";return Mn(t)+s+o+e},decode(t,e){let{Err:r}=Ze;e=V(e,void 0,"DER data");let n=0;if(t<0||t>255)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let f=e.subarray(n,n+c);if(f.length!==c)throw new r("tlv.decode: length bytes not complete");if(f[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let u of f)i=i<<8|u;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){let{Err:e}=Ze;if(rs(t),t<it)throw new e("integer: negative integers are not allowed");let r=Mn(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=Ze;if(t.length<1)throw new e("invalid signature integer: empty");if(t[0]&128)throw new e("invalid signature integer: negative");if(t.length>1&&t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return cr(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=Ze,o=V(t,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:f,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(f)}},hexFromSig(t){let{_tlv:e,_int:r}=Ze,n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}};Object.freeze(Ze._tlv);Object.freeze(Ze._int);Object.freeze(Ze);var it=BigInt(0),Gt=BigInt(1),hh=BigInt(2),ws=BigInt(3),qg=BigInt(4);function dh(t,e={}){let r=is("weierstrass",t,e),n=r.Fp,o=r.Fn,s=r.CURVE,{h:i,n:a}=s;Oe(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:f}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=mh(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function m(N,g,A){if(f&&g.is0())return Uint8Array.of(0);let{x:S,y:w}=g.toAffine(),x=n.toBytes(S);if(We(A,"isCompressed"),A){l();let C=!n.isOdd(w);return me(ph(C),x)}else return me(Uint8Array.of(4),x,n.toBytes(w))}function d(N){V(N,void 0,"Point");let{publicKey:g,publicKeyUncompressed:A}=u,S=N.length,w=N[0],x=N.subarray(1);if(f&&S===1&&w===0)return{x:n.ZERO,y:n.ZERO};if(S===g&&(w===2||w===3)){let C=n.fromBytes(x);if(!n.isValid(C))throw new Error("bad point: is not on curve, wrong x");let L=h(C),E;try{E=n.sqrt(L)}catch(F){let H=F instanceof Error?": "+F.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}l();let T=n.isOdd(E);return(w&1)===1!==T&&(E=n.neg(E)),{x:C,y:E}}else if(S===A&&w===4){let C=n.BYTES,L=n.fromBytes(x.subarray(0,C)),E=n.fromBytes(x.subarray(C,C*2));if(!y(L,E))throw new Error("bad point: is not on curve");return{x:L,y:E}}else throw new Error(`bad point: got length ${S}, expected compressed=${g} or uncompressed=${A}`)}let p=e.toBytes===void 0?m:e.toBytes,b=e.fromBytes===void 0?d:e.fromBytes;function h(N){let g=n.sqr(N),A=n.mul(g,N);return n.add(n.add(A,n.mul(N,s.a)),s.b)}function y(N,g){let A=n.sqr(g),S=h(N);return n.eql(A,S)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,ws),qg),_=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,_)))throw new Error("bad curve params: a or b");function D(N,g,A=!1){if(!n.isValid(g)||A&&n.is0(g))throw new Error(`bad point coordinate ${N}`);return g}function R(N){if(!(N instanceof I))throw new Error("Weierstrass Point expected")}function P(N){if(!c||!c.basises)throw new Error("no endo");return $g(N,c.basises,o.ORDER)}function B(N,g,A,S,w){return A=new I(n.mul(A.X,N),A.Y,A.Z),g=Vn(S,g),A=Vn(w,A),g.add(A)}class I{static BASE=new I(s.Gx,s.Gy,n.ONE);static ZERO=new I(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(g,A,S){this.X=D("x",g),this.Y=D("y",A,!0),this.Z=D("z",S),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){let{x:A,y:S}=g||{};if(!g||!n.isValid(A)||!n.isValid(S))throw new Error("invalid affine point");if(g instanceof I)throw new Error("projective point not allowed");return n.is0(A)&&n.is0(S)?I.ZERO:new I(A,S,n.ONE)}static fromBytes(g){let A=I.fromAffine(b(V(g,void 0,"point")));return A.assertValidity(),A}static fromHex(g){return I.fromBytes(qr(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,A=!0){return k.createCache(this,g),A||this.multiply(ws),this}assertValidity(){let g=this;if(g.is0()){if(e.allowInfinityPoint&&n.is0(g.X)&&n.eql(g.Y,n.ONE)&&n.is0(g.Z))return;throw new Error("bad point: ZERO")}let{x:A,y:S}=g.toAffine();if(!n.isValid(A)||!n.isValid(S))throw new Error("bad point: x or y not field elements");if(!y(A,S))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:g}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(g)}equals(g){R(g);let{X:A,Y:S,Z:w}=this,{X:x,Y:C,Z:L}=g,E=n.eql(n.mul(A,L),n.mul(x,w)),T=n.eql(n.mul(S,L),n.mul(C,w));return E&&T}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:g,b:A}=s,S=n.mul(A,ws),{X:w,Y:x,Z:C}=this,L=n.ZERO,E=n.ZERO,T=n.ZERO,O=n.mul(w,w),F=n.mul(x,x),H=n.mul(C,C),K=n.mul(w,x);return K=n.add(K,K),T=n.mul(w,C),T=n.add(T,T),L=n.mul(g,T),E=n.mul(S,H),E=n.add(L,E),L=n.sub(F,E),E=n.add(F,E),E=n.mul(L,E),L=n.mul(K,L),T=n.mul(S,T),H=n.mul(g,H),K=n.sub(O,H),K=n.mul(g,K),K=n.add(K,T),T=n.add(O,O),O=n.add(T,O),O=n.add(O,H),O=n.mul(O,K),E=n.add(E,O),H=n.mul(x,C),H=n.add(H,H),O=n.mul(H,K),L=n.sub(L,O),T=n.mul(H,F),T=n.add(T,T),T=n.add(T,T),new I(L,E,T)}add(g){R(g);let{X:A,Y:S,Z:w}=this,{X:x,Y:C,Z:L}=g,E=n.ZERO,T=n.ZERO,O=n.ZERO,F=s.a,H=n.mul(s.b,ws),K=n.mul(A,x),Z=n.mul(S,C),J=n.mul(w,L),Q=n.add(A,S),G=n.add(x,C);Q=n.mul(Q,G),G=n.add(K,Z),Q=n.sub(Q,G),G=n.add(A,w);let se=n.add(x,L);return G=n.mul(G,se),se=n.add(K,J),G=n.sub(G,se),se=n.add(S,w),E=n.add(C,L),se=n.mul(se,E),E=n.add(Z,J),se=n.sub(se,E),O=n.mul(F,G),E=n.mul(H,J),O=n.add(E,O),E=n.sub(Z,O),O=n.add(Z,O),T=n.mul(E,O),Z=n.add(K,K),Z=n.add(Z,K),J=n.mul(F,J),G=n.mul(H,G),Z=n.add(Z,J),J=n.sub(K,J),J=n.mul(F,J),G=n.add(G,J),K=n.mul(Z,G),T=n.add(T,K),K=n.mul(se,G),E=n.mul(Q,E),E=n.sub(E,K),K=n.mul(Q,Z),O=n.mul(se,O),O=n.add(O,K),new I(E,T,O)}subtract(g){return R(g),this.add(g.negate())}is0(){return this.equals(I.ZERO)}multiply(g){let{endo:A}=e;if(!o.isValidNot0(g))throw new RangeError("invalid scalar: out of range");let S,w,x=C=>k.cached(this,C,L=>lr(I,L));if(A){let{k1neg:C,k1:L,k2neg:E,k2:T}=P(g),{p:O,f:F}=x(L),{p:H,f:K}=x(T);w=F.add(K),S=B(A.beta,O,H,C,E)}else{let{p:C,f:L}=x(g);S=C,w=L}return lr(I,[S,w])[0]}multiplyUnsafe(g){let{endo:A}=e,S=this,w=g;if(!o.isValid(w))throw new RangeError("invalid scalar: out of range");if(w===it||S.is0())return I.ZERO;if(w===Gt)return S;if(k.hasCache(this))return this.multiply(w);if(A){let{k1neg:x,k1:C,k2neg:L,k2:E}=P(w),{p1:T,p2:O}=Cl(I,S,C,E);return B(A.beta,T,O,x,L)}else return k.unsafe(S,w)}toAffine(g){let A=this,S=g,{X:w,Y:x,Z:C}=A;if(n.eql(C,n.ONE))return{x:w,y:x};let L=A.is0();S==null&&(S=L?n.ONE:n.inv(C));let E=n.mul(w,S),T=n.mul(x,S),O=n.mul(C,S);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(O,n.ONE))throw new Error("invZ was invalid");return{x:E,y:T}}isTorsionFree(){let{isTorsionFree:g}=e;return i===Gt?!0:g?g(I,this):k.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:g}=e;return i===Gt?this:g?g(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Gt?this.is0():this.clearCofactor().is0()}toBytes(g=!0){return We(g,"isCompressed"),this.assertValidity(),p(I,this,g)}toHex(g=!0){return $r(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let U=o.BITS,k=new Xr(I,e.endo?Math.ceil(U/2):U);return U>=8&&I.BASE.precompute(8),Object.freeze(I.prototype),Object.freeze(I),I}function ph(t){return Uint8Array.of(t?2:3)}function mh(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function jg(t,e={}){let{Fn:r}=t,n=e.randomBytes===void 0?ar:e.randomBytes,o=Object.assign(mh(t.Fp,r),{seed:Math.max(va(r.ORDER),16)});function s(d){try{let p=r.fromBytes(d);return r.isValidNot0(p)}catch{return!1}}function i(d,p){let{publicKey:b,publicKeyUncompressed:h}=o;try{let y=d.length;return p===!0&&y!==b||p===!1&&y!==h?!1:!!t.fromBytes(d)}catch{return!1}}function a(d){return d=d===void 0?n(o.seed):d,Ca(V(d,o.seed,"seed"),r.ORDER)}function c(d,p=!0){return t.BASE.multiply(r.fromBytes(d)).toBytes(p)}function f(d){let{secretKey:p,publicKey:b,publicKeyUncompressed:h}=o,y=r._lengths;if(!ir(d))return;let v=V(d,void 0,"key").length,_=v===b||v===h,D=v===p||!!y?.includes(v);if(!(_&&D))return _}function u(d,p,b=!0){if(f(d)===!0)throw new Error("first arg must be private key");if(f(p)===!1)throw new Error("second arg must be public key");let h=r.fromBytes(d);return t.fromBytes(p).multiply(h).toBytes(b)}let l={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},m=Yr(a,c);return Object.freeze(l),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:m,Point:t,utils:l,lengths:o})}function gh(t,e,r={}){let n=e;nr(n),Oe(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let o=r.randomBytes===void 0?ar:r.randomBytes,s=r.hmac===void 0?(w,x)=>ro(n,w,x):r.hmac,{Fp:i,Fn:a}=t,{ORDER:c,BITS:f}=a,{keygen:u,getPublicKey:l,getSharedSecret:m,utils:d,lengths:p}=jg(t,r),b={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},h=c*hh+Gt<i.ORDER;function y(w){let x=c>>Gt;return w>x}function v(w,x){if(!a.isValidNot0(x))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return x}function _(){if(h)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function D(w,x){Sc(x);let C=p.signature,L=x==="compact"?C:x==="recovered"?C+1:void 0;return V(w,L)}class R{r;s;recovery;constructor(x,C,L){if(this.r=v("r",x),this.s=v("s",C),L!=null){if(_(),![0,1,2,3].includes(L))throw new Error("invalid recovery id");this.recovery=L}Object.freeze(this)}static fromBytes(x,C=b.format){D(x,C);let L;if(C==="der"){let{r:F,s:H}=Ze.toSig(V(x));return new R(F,H)}C==="recovered"&&(L=x[0],C="compact",x=x.subarray(1));let E=p.signature/2,T=x.subarray(0,E),O=x.subarray(E,E*2);return new R(a.fromBytes(T),a.fromBytes(O),L)}static fromHex(x,C){return this.fromBytes(qr(x),C)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new R(this.r,this.s,x)}recoverPublicKey(x){let{r:C,s:L}=this,E=this.assertRecovery(),T=E===2||E===3?C+c:C;if(!i.isValid(T))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let O=i.toBytes(T),F=t.fromBytes(me(ph((E&1)===0),O)),H=a.inv(T),K=B(V(x,void 0,"msgHash")),Z=a.create(-K*H),J=a.create(L*H),Q=t.BASE.multiplyUnsafe(Z).add(F.multiplyUnsafe(J));if(Q.is0())throw new Error("invalid recovery: point at infinify");return Q.assertValidity(),Q}hasHighS(){return y(this.s)}toBytes(x=b.format){if(Sc(x),x==="der")return qr(Ze.hexFromSig(this));let{r:C,s:L}=this,E=a.toBytes(C),T=a.toBytes(L);return x==="recovered"?(_(),me(Uint8Array.of(this.assertRecovery()),E,T)):me(E,T)}toHex(x){return $r(this.toBytes(x))}}Object.freeze(R.prototype),Object.freeze(R);let P=r.bits2int===void 0?function(x){if(x.length>8192)throw new Error("input is too large");let C=cr(x),L=x.length*8-f;return L>0?C>>BigInt(L):C}:r.bits2int,B=r.bits2int_modN===void 0?function(x){return a.create(P(x))}:r.bits2int_modN,I=Hn(f);function U(w){return yt("num < 2^"+f,w,it,I),a.toBytes(w)}function k(w,x){return V(w,void 0,"message"),x?V(n(w),void 0,"prehashed message"):w}function N(w,x,C){let{lowS:L,prehash:E,extraEntropy:T}=Ec(C,b);w=k(w,E);let O=B(w),F=a.fromBytes(x);if(!a.isValidNot0(F))throw new Error("invalid private key");let H=[U(F),U(O)];if(T!=null&&T!==!1){let Q=T===!0?o(p.secretKey):T;H.push(V(Q,void 0,"extraEntropy"))}let K=me(...H),Z=O;function J(Q){let G=P(Q);if(!a.isValidNot0(G))return;let se=a.inv(G),ut=t.BASE.multiply(G).toAffine(),Qt=a.create(ut.x);if(Qt===it)return;let Lr=a.create(se*a.create(Z+Qt*F));if(Lr===it)return;let wn=(ut.x===Qt?0:2)|Number(ut.y&Gt),En=Lr;return L&&y(Lr)&&(En=a.neg(Lr),wn^=1),new R(Qt,En,h?void 0:wn)}return{seed:K,k2sig:J}}function g(w,x,C={}){let{seed:L,k2sig:E}=N(w,x,C);return cl(n.outputLen,a.BYTES,s)(L,E).toBytes(C.format)}function A(w,x,C,L={}){let{lowS:E,prehash:T,format:O}=Ec(L,b);if(C=V(C,void 0,"publicKey"),x=k(x,T),!ir(w)){let F=w instanceof R?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+F)}D(w,O);try{let F=R.fromBytes(w,O),H=t.fromBytes(C);if(E&&F.hasHighS())return!1;let{r:K,s:Z}=F,J=B(x),Q=a.inv(Z),G=a.create(J*Q),se=a.create(K*Q),ut=t.BASE.multiplyUnsafe(G).add(H.multiplyUnsafe(se));return ut.is0()?!1:a.create(ut.x)===K}catch{return!1}}function S(w,x,C={}){let{prehash:L}=Ec(C,b);return x=k(x,L),R.fromBytes(w,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:m,utils:d,lengths:p,Point:t,sign:g,verify:A,recoverPublicKey:S,Signature:R,hash:n})}var Cc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Gg={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var yh=BigInt(2);function Wg(t){let e=Cc.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=t*t*t%e,u=f*f*t%e,l=oe(u,r,e)*u%e,m=oe(l,r,e)*u%e,d=oe(m,yh,e)*f%e,p=oe(d,o,e)*d%e,b=oe(p,s,e)*p%e,h=oe(b,a,e)*b%e,y=oe(h,c,e)*h%e,v=oe(y,a,e)*b%e,_=oe(v,r,e)*u%e,D=oe(_,i,e)*p%e,R=oe(D,n,e)*f%e,P=oe(R,yh,e);if(!vc.eql(vc.sqr(P),t))throw new Error("Cannot find square root");return P}var vc=Gr(Cc.p,{sqrt:Wg}),Xg=dh(Cc,{Fp:vc,endo:Gg}),Qr=gh(Xg,ot);function bh(t,e,r,n){let o=Et.digest(r instanceof Uint8Array?r:r.subarray());if(hs(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Qr.verify(e,s,t,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Gn(String(s))});try{return n?.signal?.throwIfAborted(),Qr.verify(e,o.digest,t,{prehash:!1,format:"der"})}catch(s){throw new Gn(String(s))}}var Es=class{type="secp256k1";raw;_key;constructor(e){this._key=wh(e),this.raw=xh(this._key)}toMultihash(){return qe.digest(Rt(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return ue.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Me(this.raw,e.raw)}verify(e,r,n){return bh(this._key,r,e,n)}};function _c(t){return new Es(t)}function xh(t){return Qr.Point.fromBytes(t).toBytes()}function wh(t){try{return Qr.Point.fromBytes(t),t}catch(e){throw new Ir(String(e))}}function no(t,e){let{Type:r,Data:n}=st.decode(t),o=n??new Uint8Array;switch(r){case ce.RSA:return bc(o,e);case ce.Ed25519:return ka(o);case ce.secp256k1:return _c(o);case ce.ECDSA:return ca(o);default:throw new er}}function Eh(t){let{Type:e,Data:r}=st.decode(t.digest),n=r??new Uint8Array;switch(e){case ce.Ed25519:return ka(n);case ce.secp256k1:return _c(n);case ce.ECDSA:return ca(n);default:throw new er}}function Rt(t){return st.encode({Type:ce[t.type],Data:t.raw})}var Sh=Symbol.for("nodejs.util.inspect.custom"),Yg=114,oo=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()})`}[Si]=!0;toString(){return this.string==null&&(this.string=ue.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return pe.createV1(Yg,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Me(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Me(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Sh](){return`PeerId(${this.toString()})`}},so=class extends oo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},io=class extends oo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},ao=class extends oo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Zg=2336,co=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=qe.digest(he(this.url))}[Sh](){return`PeerId(${this.url})`}[Si]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pe.createV1(Zg,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=ie(e)),e.toString()===this.toString())}};var Jg=114,Ah=2336;function en(t,e){let r;if(t.charAt(0)==="1"||t.charAt(0)==="Q")r=Ur(ue.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return Qg(pe.parse(t));if(e==null)throw new q('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=Ur(e.decode(t))}return vh(r)}function Lc(t){if(t.type==="Ed25519")return new io({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new ao({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new so({multihash:t.toCID().multihash,publicKey:t});throw new er}function vh(t){if(ty(t))return new so({multihash:t});if(ey(t))try{let e=Eh(t);if(e.type==="Ed25519")return new io({multihash:t,publicKey:e});if(e.type==="secp256k1")return new ao({multihash:t,publicKey:e})}catch{let r=ie(t.digest);return new co(new URL(r))}throw new No("Supplied PeerID Multihash is invalid")}function Qg(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==Jg&&t.code!==Ah)throw new Uo("Supplied PeerID CID is invalid");if(t.code===Ah){let e=ie(t.multihash.digest);return new co(new URL(e))}return vh(t.multihash)}function ey(t){return t.code===qe.code}function ty(t){return t.code===Et.code}function Ch(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function Ss(t=0){return new Uint8Array(t)}function fo(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=Ss(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}function Lh(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var _h=Lh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Ic=Lh("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=Ss(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),ry={utf8:_h,"utf-8":_h,hex:Ne.base16,latin1:Ic,ascii:Ic,binary:Ic,...Ne},As=ry;function uo(t,e="utf8"){let r=As[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function yr(t,e="utf8"){let r=As[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}var Ee=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},St=class extends Error{static name="ValidationError";name="ValidationError"},vs=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Cs=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var _s=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let r=this.index,n=e();return n===void 0&&(this.index=r),n}parseWith(e){let r=e();if(this.index===this.input.length)return r}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(()=>{let r=this.readChar();if(r===e)return r})}readSeparator(e,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,r,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let m=Number.parseInt(l,e);if(!Number.isNaN(m))return m});if(u===void 0)break;if(s*=e,s+=u,s>f||(i+=1,r!==void 0&&i>r))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let r=0;r<e.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[r]=n}return e})}readIPv6Addr(){let e=r=>{for(let n=0;n<r.length/2;n++){let o=n*2;if(n<r.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return r[o]=i[0],r[o+1]=i[1],r[o+2]=i[2],r[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];r[o]=s>>8,r[o+1]=s&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,o]=e(r);if(n===16)return r;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var ny=45,oy=15,Ls=new _s;function Ih(t){if(!(t.length>oy))return Ls.new(t).parseWith(()=>Ls.readIPv4Addr())}function Th(t){if(t.includes("%")&&(t=t.split("%")[0]),!(t.length>ny))return Ls.new(t).parseWith(()=>Ls.readIPv6Addr())}function Is(t){return!!Ih(t)}function Bh(t){return!!Th(t)}function Bc(t){return e=>yr(e,t)}function Dc(t){return e=>uo(e,t)}function tn(t){return new DataView(t.buffer).getUint16(t.byteOffset).toString()}function br(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof t=="string"?parseInt(t):t),new Uint8Array(e)}function Dh(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let r=uo(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=br(n);return fo([r,o],r.length+o.length)}function Rh(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let r=Tt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=br(n);return fo([r,o],r.length+o.length)}function Rc(t){let e=t.subarray(0,t.length-2),r=t.subarray(t.length-2),n=yr(e,"base32"),o=tn(r);return`${n}:${o}`}var Pc=function(t){t=t.toString().trim();let e=new Uint8Array(4);return t.split(/\./g).forEach((r,n)=>{let o=parseInt(r,10);if(isNaN(o)||o<0||o>255)throw new Ee("Invalid byte value in IP address");e[n]=o}),e},Ph=function(t){let e=0;t=t.toString().trim();let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=Is(r[n]),i;s&&(i=Pc(r[n]),r[n]=yr(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,yr(i.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++);let s=[n,1];for(n=9-r.length;n>0;n--)s.push("0");r.splice.apply(r,s)}let o=new Uint8Array(e+16);for(n=0;n<r.length;n++){r[n]===""&&(r[n]="0");let s=parseInt(r[n],16);if(isNaN(s)||s<0||s>65535)throw new Ee("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},Oh=function(t){if(t.byteLength!==4)throw new Ee("IPv4 address was incorrect length");let e=[];for(let r=0;r<t.byteLength;r++)e.push(t[r]);return e.join(".")},Uh=function(t){if(t.byteLength!==16)throw new Ee("IPv6 address was incorrect length");let e=[];for(let n=0;n<t.byteLength;n+=2){let o=t[n],s=t[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let r=e.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${r}"`)}};function Nh(t){try{let e=new URL(`http://[${t}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${t}"`)}}var Tc=Object.values(Ne).map(t=>t.decoder),sy=(function(){let t=Tc[0].or(Tc[1]);return Tc.slice(2).forEach(e=>t=t.or(e)),t})();function Fh(t){return sy.decode(t)}function kh(t){return e=>t.encoder.encode(e)}function iy(t){if(parseInt(t).toString()!==t)throw new St("Value must be an integer")}function ay(t){if(t<0)throw new St("Value must be a positive integer, or zero")}function cy(t){return e=>{if(e>t)throw new St(`Value must be smaller than or equal to ${t}`)}}function fy(...t){return e=>{for(let r of t)r(e)}}var lo=fy(iy,ay,cy(65535));var be=-1,Oc=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let r;if(typeof e=="string"?r=this.protocolsByName.get(e):r=this.protocolsByCode.get(e),r==null)throw new Cs(`Protocol ${e} was unknown`);return r}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(r=>{this.protocolsByName.set(r,e)})}removeProtocol(e){let r=this.protocolsByCode.get(e);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},vt=new Oc,Ay=[{code:4,name:"ip4",size:32,valueToBytes:Pc,bytesToValue:Oh,validate:t=>{if(!Is(t))throw new St(`Invalid IPv4 address "${t}"`)}},{code:6,name:"tcp",size:16,valueToBytes:br,bytesToValue:tn,validate:lo},{code:273,name:"udp",size:16,valueToBytes:br,bytesToValue:tn,validate:lo},{code:33,name:"dccp",size:16,valueToBytes:br,bytesToValue:tn,validate:lo},{code:41,name:"ip6",size:128,valueToBytes:Ph,bytesToValue:Uh,stringToValue:Nh,validate:t=>{if(!Bh(t))throw new St(`Invalid IPv6 address "${t}"`)}},{code:42,name:"ip6zone",size:be},{code:43,name:"ipcidr",size:8,bytesToValue:Bc("base10"),valueToBytes:Dc("base10")},{code:53,name:"dns",size:be},{code:54,name:"dns4",size:be},{code:55,name:"dns6",size:be},{code:56,name:"dnsaddr",size:be},{code:132,name:"sctp",size:16,valueToBytes:br,bytesToValue:tn,validate:lo},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:be,stringToValue:t=>decodeURIComponent(t),valueToString:t=>encodeURIComponent(t)},{code:421,name:"p2p",aliases:["ipfs"],size:be,bytesToValue:Bc("base58btc"),valueToBytes:t=>t.startsWith("Q")||t.startsWith("1")?Dc("base58btc")(t):pe.parse(t).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Rc,valueToBytes:Dh},{code:445,name:"onion3",size:296,bytesToValue:Rc,valueToBytes:Rh},{code:446,name:"garlic64",size:be},{code:447,name:"garlic32",size:be},{code:448,name:"tls"},{code:449,name:"sni",size:be},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:be,bytesToValue:kh(Zn),valueToBytes:Fh},{code:480,name:"http"},{code:481,name:"http-path",size:be,stringToValue:t=>`/${decodeURIComponent(t)}`,valueToString:t=>encodeURIComponent(t.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:be}];Ay.forEach(t=>{vt.addProtocol(t)});function Mh(t){let e=[],r=0;for(;r<t.length;){let n=wt(t,r),o=vt.getProtocol(n),s=ee(n),i=vy(o,t,r+s),a=0;i>0&&o.size===be&&(a=ee(i));let c=s+a+i,f={code:n,name:o.name,bytes:t.subarray(r,r+c)};if(i>0){let u=r+s+a,l=t.subarray(u,u+i);f.value=o.bytesToValue?.(l)??yr(l)}e.push(f),r+=c}return e}function Kh(t){let e=0,r=[];for(let n of t){if(n.bytes==null){let o=vt.getProtocol(n.code),s=ee(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??uo(n.value),a=i.byteLength,o.size===be&&(c=ee(a)));let f=new Uint8Array(s+c+a),u=0;Ht(n.code,f,u),u+=s,i!=null&&(o.size===be&&(Ht(a,f,u),u+=c),f.set(i,u)),n.bytes=f}r.push(n.bytes),e+=n.bytes.byteLength}return fo(r,e)}function Hh(t){if(t.charAt(0)!=="/")throw new Ee('String multiaddr must start with "/"');let e=[],r="protocol",n="",o="";for(let s=1;s<t.length;s++){let i=t.charAt(s);i!=="/"&&(r==="protocol"?o+=t.charAt(s):n+=t.charAt(s));let a=s===t.length-1;if(i==="/"||a){let c=vt.getProtocol(o);if(r==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",r="protocol";continue}else if(a)throw new Ee(`Component ${o} was missing value`);r="value"}else if(r==="value"){let f={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Ee(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}e.push(f),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new Ee("Incomplete multiaddr");return e}function zh(t){return`/${t.flatMap(e=>{if(e.value==null)return e.name;let r=vt.getProtocol(e.code);if(r==null)throw new Ee(`Unknown protocol code ${e.code}`);return[e.name,r.valueToString?.(e.value)??e.value]}).join("/")}`}function vy(t,e,r){return t.size==null||t.size===0?0:t.size>0?t.size/8:wt(e,r)}var Cy=Symbol.for("nodejs.util.inspect.custom"),Zc=Symbol.for("@multiformats/multiaddr");function _y(t){if(t==null&&(t="/"),Vh(t))return t.getComponents();if(t instanceof Uint8Array)return Mh(t);if(typeof t=="string")return t=t.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),t===""&&(t="/"),Hh(t);if(Array.isArray(t))return t;throw new Ee("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ps=class t{[Zc]=!0;#e;#t;#r;constructor(e="/",r={}){this.#e=_y(e),r.validate!==!1&&Ly(this)}get bytes(){return this.#r==null&&(this.#r=Kh(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=zh(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let r=new t(e);return new t([...this.#e,...r.getComponents()],{validate:!1})}decapsulate(e){let r=e.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new vs(`Address ${this.toString()} does not contain subaddress: ${r}`);return new t(n.slice(0,o),{validate:!1})}decapsulateCode(e){let r;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){r=n;break}return new t(this.#e.slice(0,r),{validate:!1})}equals(e){return Ch(this.bytes,e.bytes)}[Cy](){return`Multiaddr(${this.toString()})`}};function Ly(t){t.getComponents().forEach(e=>{let r=vt.getProtocol(e.code);e.value!=null&&r.validate?.(e.value)})}function Vh(t){return!!t?.[Zc]}function sn(t){return new Ps(t)}var re=t=>({match:e=>{let r=e[0];return r==null||r.code!==t||r.value!=null?!1:e.slice(1)}}),M=(t,e)=>({match:r=>{let n=r[0];return n?.code!==t||n.value==null||e!=null&&n.value!==e?!1:r.slice(1)}}),$h=t=>({match:e=>t.match(e)===!1?e:!1}),$=t=>({match:e=>{let r=t.match(e);return r===!1?e:r}}),Le=(...t)=>({match:e=>{let r;for(let n of t){let o=n.match(e);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1}}),W=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e}});function ne(...t){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of t){let a=i.match(s);if(a===!1)return!1;s=a}return s}function r(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:t,matches:r,exactMatch:n}}var Iy=M(421),uA=ne(Iy),Us=M(54),Ns=M(55),Fs=M(56),Qc=M(53),lA=ne(Us,$(M(421))),hA=ne(Ns,$(M(421))),dA=ne(Fs,$(M(421))),pA=ne(Le(Qc,Fs,Us,Ns),$(M(421))),qh=W(M(4),$(M(43))),jh=W($(M(42)),M(41),$(M(43))),ef=Le(qh,jh),an=Le(ef,Qc,Us,Ns,Fs),mA=ne(Le(ef,W(Le(Qc,Fs,Us,Ns),$(M(421))))),gA=ne(qh),yA=ne(jh),bA=ne(ef),tf=W(an,M(6)),ho=W(an,M(273)),xA=ne(W(tf,$(M(421)))),wA=ne(ho),rf=W(ho,re(460),$(M(421))),ks=W(ho,re(461),$(M(421))),Ty=Le(rf,ks),EA=ne(rf),SA=ne(ks),Jc=Le(an,tf,ho,rf,ks),Gh=Le(W(Jc,re(477),$(M(421)))),AA=ne(Gh),Wh=Le(W(Jc,re(478),$(M(421))),W(Jc,re(448),$(M(449)),re(477),$(M(421)))),vA=ne(Wh),Xh=W(ho,re(280),$(M(466)),$(M(466)),$(M(421))),Yh=ne(Xh),Zh=W(ks,re(465),$(M(466)),$(M(466)),$(M(421))),CA=ne(Zh),Os=Le(Gh,Wh,W(tf,$(M(421))),W(Ty,$(M(421))),W(an,$(M(421))),Xh,Zh,M(421)),Jh=ne(Os),By=W($(Os),re(290),$h(re(281)),$(M(421))),_A=ne(By),Dy=Le(W(Os,re(290),re(281),$(M(421))),W(Os,re(281),$(M(421))),W(re(281),$(M(421)))),Qh=ne(Dy),Ry=W(an,Le(W(M(6,"80")),W(M(6),re(480)),re(480)),$(M(481)),$(M(421))),LA=ne(Ry),Py=W(an,Le(W(M(6,"443")),W(M(6,"443"),re(480)),W(M(6),re(443)),W(M(6),re(448),re(480)),W(re(448),re(480)),re(448),re(443)),$(M(481)),$(M(421))),IA=ne(Py),Oy=Le(W(M(777),$(M(421)))),TA=ne(Oy),Uy=Le(W(M(400),$(M(421)))),BA=ne(Uy);var Ie;(function(t){let e;(function(a){a.FIN="FIN",a.STOP_SENDING="STOP_SENDING",a.RESET="RESET",a.FIN_ACK="FIN_ACK"})(e=t.Flag||(t.Flag={}));let r;(function(a){a[a.FIN=0]="FIN",a[a.STOP_SENDING=1]="STOP_SENDING",a[a.RESET=2]="RESET",a[a.FIN_ACK=3]="FIN_ACK"})(r||(r={})),(function(a){a.codec=()=>gr(r)})(e=t.Flag||(t.Flag={}));let n;t.codec=()=>(n==null&&(n=jt((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.flag!=null&&(c.uint32(8),t.Flag.codec().encode(a.flag,c)),a.message!=null&&(c.uint32(18),c.bytes(a.message)),f.lengthDelimited!==!1&&c.ldelim()},(a,c,f={})=>{let u={},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let m=a.uint32();switch(m>>>3){case 1:{u.flag=t.Flag.codec().decode(a);break}case 2:{u.message=a.bytes();break}default:{a.skipType(m&7);break}}}return u},function*(a,c,f,u={}){let l=c==null?a.len:a.pos+c;for(;a.pos<l;){let m=a.uint32();switch(m>>>3){case 1:{yield{field:`${f}.flag`,value:t.Flag.codec().decode(a)};break}case 2:{yield{field:`${f}.message`,value:a.bytes()};break}default:{a.skipType(m&7);break}}}})),n);function o(a){return $t(a,t.codec())}t.encode=o;function s(a,c){return Vt(a,t.codec(),c)}t.decode=s;function i(a,c){return qt(a,t.codec(),c)}t.stream=i})(Ie||(Ie={}));var ed=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],nf=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),td="libp2p+webrtc+v1/",rd=2*1024*1024,cn=16*1024;function Ny(t=cn){let e=ee(t-ee(t)),r=1+ee(Object.keys(Ie.Flag).length-1),n=1,o=t-e-r-n,s=ee(o);return e+r+n+s}var nd=Ny();var od=1e4,of="/webrtc",po="/webrtc-signaling/0.0.1";function Fy(t){let e=t.getComponents(),r={},n=0;return e[n]?.name==="ip6zone"&&(r.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(r.type=e[n].name,r.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(r.type=e[n].name,r.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(r.protocol=e[n].name==="tcp"?"tcp":"udp",r.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(r.type==="ip4"?r.cidr=parseInt(`${e[n].value}`):r.type==="ip6"&&(r.cidr=`${e[n].value}`),n++),r.type==null||r.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(r.sni=e[n+1].value,n+=2),r)}function sf(t){let e=Fy(t);if(e==null)throw new q(`Multiaddr ${t} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function Ms(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var Ks=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},fn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ks(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new Ks(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var af=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function un(t={}){return ky(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function ky(t,e){e=e??{};let r=e.onEnd,n=new fn,o,s,i,a=Ms(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,y)=>{s=v=>{s=null,n.push(v);try{h(t(n))}catch(_){y(_)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ms()})}},f=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new fn,s!=null?s({error:h}):(n.push({error:h}),o)),l=h=>{if(i)return o;if(e?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:h})},m=h=>i?o:(i=!0,h!=null?u(h):f({done:!0})),d=()=>(n=new fn,m(),{done:!0}),p=h=>(m(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:l,end:m,get readableLength(){return n.size},onEmpty:async h=>{let y=h?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let v,_;y!=null&&(v=new Promise((D,R)=>{_=()=>{R(new af)},y.addEventListener("abort",_)}));try{await Promise.race([a.promise,v])}finally{_!=null&&y!=null&&y?.removeEventListener("abort",_)}}},r==null)return o;let b=o;return o={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(h){return b.throw(h),r!=null&&(r(h),r=void 0),{done:!0}},return(){return b.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(h){return b.end(h),r!=null&&(r(h),r=void 0),o},get readableLength(){return b.readableLength},onEmpty:h=>b.onEmpty(h)},o}var cf=class t extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,t)}},sd=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function ff(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((l,m)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){m(sd(i));return}if(i&&(c=()=>{m(sd(i))},i.addEventListener("abort",c,{once:!0})),t.then(l,m),r===Number.POSITIVE_INFINITY)return;let d=new cf;a=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(p){m(p)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?l():o instanceof Error?m(o):(d.message=o??`Promise timed out after ${r} milliseconds`,m(d))},r)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var My=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function Ky(t,e,r){let n,o=new Promise((s,i)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:u}=My(t),l=async(...d)=>{let p=r.multiArgs?d:d[0];if(r.filter)try{if(!await r.filter(p))return}catch(b){n(),i(b);return}c.push(p),r.count===c.length&&(n(),s(c))},m=(...d)=>{n(),i(r.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)u(d,l);for(let d of r.rejectionEvents)a.includes(d)||u(d,m)};for(let d of a)f(d,l);for(let d of r.rejectionEvents)a.includes(d)||f(d,m);r.signal&&r.signal.addEventListener("abort",()=>{m(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){let s=ff(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Se(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Ky(t,e,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var wr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},Hs=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},zs=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Hy(t){return t.reason}async function Ct(t,e,r){if(e==null)return t;let n=r?.translateError??Hy;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([t,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var zy=Math.pow(2,20)*4,Xt=class extends Lt{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??zy,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new z,this.writeBuffer=new z,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let r=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(o){this.log.error("processSendQueue threw - %e",o)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);let n=o=>{this.onDrainPromise?.reject(o.error??new zs)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Ct(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=un(),r=s=>{e.push(s.data)};this.addEventListener("message",r);let n=s=>{e.end(s.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new et(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new Mo(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new et("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new et("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new et(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new et(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new Tr;this.dispatchEvent(new Ko(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new Br))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,r=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new z(s);this.writeBuffer.consume(s.byteLength);let a=this.sendData(s);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,r,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new ko(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Sn(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Sn(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var Vs=class extends Xt{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",r=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),r.error!=null?r.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):r.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Se(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Se(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function id(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var $s=class extends Lt{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,r){super(),this.maConn=e,this.protocol=r.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(r.name),this.streamOptions=r.streamOptions,this.maxEarlyStreams=r.maxEarlyStreams??10,this.metrics=r.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let o=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",o);let s=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",s)}send(e){let r=this.maConn.send(e);return r===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),r}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await Ct(Promise.all([...this.streams].map(async r=>{await r.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(r=>{r.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(r=>{r.onTransportClosed(e)})}catch(r){this.abort(r)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new Po;let r=this.onCreateStream({...this.streamOptions,...e});return id(r)&&(r=await r),this.streams.push(r),this.cleanUpStream(r),r}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new Hs(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let r=n=>{let o=this.streams.findIndex(s=>s===e);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",r),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(r=>{this.safeDispatchEvent("stream",{detail:r})}),this.earlyStreams=[]})}};var qs=class extends Xt{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Se(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await Se(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};var Vy=4194304,js=class extends Error{static name="UnwrappedError";name="UnwrappedError"},mo=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},lf=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},hf=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function $y(t){return typeof t?.closeRead=="function"}function qy(t){return typeof t?.close=="function"}function uf(t){return $y(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:qy(t)?t.status!=="open":!1}function jy(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function Gy(t,e){let r=e?.maxBufferSize??Vy,n=new z,o,s=!1;if(!jy(t))throw new q("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>r){let l=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${l} > ${r}`))}o?.resolve()};t.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};t.addEventListener("close",a);let c=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",c);let f={readBuffer:n,async read(u){if(s===!0)throw new js("Stream was unwrapped");if(uf(t)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new wr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let l=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=l){o.resolve();break}if(await Ct(o.promise,u?.signal),uf(t)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let m=u?.bytes??n.byteLength;if(n.byteLength<m){if(uf(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,m),new wr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${m} bytes`);return f.read(u)}let d=n.sublist(0,m);return n.consume(m),d},async write(u,l){if(s===!0)throw new js("Stream was unwrapped");t.send(u)||await Se(t,"drain",{signal:l?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.unshift(n))),t}};return f}function Gs(t,e={}){let r=Gy(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ee(e.maxDataLength));let n=e?.lengthDecoder??wt,o=e?.lengthEncoder??ps;return{async read(i){let a=-1,c=new z;for(;;){let u=await r.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new mo("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new hf(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new lf(`Message length too long - ${a} > ${e.maxDataLength}`);let f=await r.read({...i,bytes:a});if(f==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new wr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(f.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",f.byteLength,a),new wr(`Unexpected EOF - read ${f.byteLength}/${a} bytes before the stream closed`);return f},async write(i,a){await r.write(new z(o(i.byteLength),i),a)},async writeV(i,a){let c=new z(...i.flatMap(f=>[o(f.byteLength),f]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function Ws(t,e){let r=Gs(t,e),n={read:async(o,s)=>{let i=await r.read(s);return o.decode(i)},write:async(o,s,i)=>{await r.write(s.encode(o),i)},writeV:async(o,s,i)=>{await r.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var Wy=1024*1024*4,Xy=1024*1024*4,Xs=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new z,this.maxBufferSize=e.maxBufferSize??Wy,this.maxDataLength=e.maxDataLength??Xy,this.lengthDecoder=e.lengthDecoder??wt,this.encodingLength=e.encodingLength??ee}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new q(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let r;try{r=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(r<0||r>this.maxDataLength)throw new mo("Invalid message length");let n=this.encodingLength(r),o=n+r;if(this.buffer.byteLength>=o){let s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}};function ad(t=0){return new Uint8Array(t)}var Ys=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ln=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Zs=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},go=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Js(t){return t[Symbol.asyncIterator]!=null}function cd(t,e){if(t.byteLength>e)throw new ln("Message length too long")}var ei=t=>{let e=ee(t),r=ad(e);return ps(t,r),ei.bytes=e,r};ei.bytes=0;function yo(t,e){e=e??{};let r=e.lengthEncoder??ei,n=e?.maxDataLength??4194304;function*o(s){cd(s,n);let i=r(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Js(t)?(async function*(){for await(let s of t)yield*o(s)})():(function*(){for(let s of t)yield*o(s)})()}yo.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??ei,n=e?.maxDataLength??4194304;return cd(t,n),new z(r(t.byteLength),t)};var Er;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(Er||(Er={}));var df=t=>{let e=wt(t);return df.bytes=ee(e),e};df.bytes=0;function bo(t,e){let r=new z,n=Er.LENGTH,o=-1,s=e?.lengthDecoder??df,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===Er.LENGTH)try{if(o=s(r),o<0)throw new Ys("Invalid message length");if(o>a)throw new ln("Message length too long");let f=s.bytes;r.consume(f),e?.onLength!=null&&e.onLength(o),n=Er.DATA}catch(f){if(f instanceof RangeError){if(r.byteLength>i)throw new Zs("Message length length too long");break}throw f}if(n===Er.DATA){if(r.byteLength<o)break;let f=r.sublist(0,o);r.consume(o),e?.onData!=null&&e.onData(f),yield f,n=Er.LENGTH}}}return Js(t)?(async function*(){for await(let f of t)r.append(f),yield*c();if(r.byteLength>0)throw new go("Unexpected end of input")})():(function*(){for(let f of t)r.append(f),yield*c();if(r.byteLength>0)throw new go("Unexpected end of input")})()}bo.fromReader=(t,e)=>{let r=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await t.next(r);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}})();return bo(n,{...e??{},onLength:s=>{r=s}})};var pf=class extends qs{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(e){super({...e,maxMessageSize:(e.maxMessageSize??cn)-nd}),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=un(),this.maxBufferedAmount=e.maxBufferedAmount??rd,this.finAckTimeout=e.finAckTimeout??od,this.channel.onclose=()=>{this.log.trace("received datachannel close event"),this.onRemoteCloseWrite(),this.onTransportClosed()},this.channel.onerror=n=>{let o=n.error;this.log.trace("received datachannel error event - %e",o),this.abort(o)},this.channel.onmessage=async n=>{this.log("incoming message %d bytes",n.data.byteLength);let{data:o}=n;o===null||o.byteLength===0||this.incomingData.push(new Uint8Array(o,0,o.byteLength))},this.channel.bufferedAmountLowThreshold=0,this.channel.onbufferedamountlow=()=>{this.writableNeedsDrain&&this.safeDispatchEvent("drain")},Promise.resolve().then(async()=>{for await(let n of bo(this.incomingData))this.processIncomingProtobuf(n)}).catch(n=>{this.log.error("error processing incoming data channel messages - %e",n)});let r=()=>{this.channel.readyState==="open"&&(this.log.trace("stream closed, closing underlying datachannel"),this.channel.close())};this.addEventListener("close",r),this.channel.readyState!=="open"&&(this.log('channel ready state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),Se(this.channel,"open",{rejectionEvents:["close","error"]}).then(()=>{this.log('channel ready state is now "%s", dispatching drain',this.channel.readyState),this.safeDispatchEvent("drain")}).catch(n=>{this.abort(n.error??n)}))}sendNewStream(){}_sendMessage(e){if(this.channel.readyState!=="open")throw new et(`Invalid datachannel state - ${this.channel.readyState}`);this.log.trace('sending message, channel state "%s"',this.channel.readyState);try{for(let r of e)this.channel.send(Ke(r))}catch(r){this.log.error("error sending datachannel message - %e",r),this.abort(r)}}sendData(e){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(yo.single(Ie.encode({message:e.subarray()}))),{sentBytes:e.byteLength,canSendMore:this.channel.bufferedAmount<this.maxBufferedAmount})}sendReset(e){try{this.log.error("sending reset - %e",e),this._sendFlag(Ie.Flag.RESET),this.receivedFinAck?.reject(e)}catch(r){this.log.error("failed to send reset - %e",r)}}async sendCloseWrite(e){this._sendFlag(Ie.Flag.FIN),e?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let r=e?.signal??AbortSignal.timeout(this.finAckTimeout),n=[Se(this.channel,"close",{signal:r}),Se(this.channel,"error",{signal:r})];await Promise.any([Ct(this.receivedFinAck.promise,r),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(e){this._sendFlag(Ie.Flag.STOP_SENDING),e?.signal?.throwIfAborted()}processIncomingProtobuf(e){let r=Ie.decode(e);r.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new z(r.message)),r.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',r.flag,this.writeStatus,this.readStatus),r.flag===Ie.Flag.FIN&&(this._sendFlag(Ie.Flag.FIN_ACK),this.onRemoteCloseWrite()),r.flag===Ie.Flag.RESET&&(this.receivedFinAck?.reject(new Tr("The stream was reset")),this.onRemoteReset()),r.flag===Ie.Flag.STOP_SENDING&&this.onRemoteCloseRead(),r.flag===Ie.Flag.FIN_ACK&&this.receivedFinAck?.resolve())}_sendFlag(e){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',e.toString(),this.channel.readyState),!1;this.log.trace("sending flag %s",e.toString());let r=Ie.encode({flag:e}),n=yo.single(r);try{return this._sendMessage(n),!0}catch(o){this.log.error("could not send flag %s - %e",e.toString(),o)}return!1}sendPause(){}sendResume(){}};function xo(t){let{channel:e,direction:r,isHandshake:n}=t;return new pf({...t,id:`${e.id}`,log:t.log.newScope(`${n===!0?"handshake":r}:${e.id}`),protocol:""})}var Yt=class{protocol;peerConnection;metrics;dataChannelOptions;earlyDataChannels;constructor(e){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??of,this.dataChannelOptions=e.dataChannelOptions??{},this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(e){this.earlyDataChannels.push(e.channel)}createStreamMuxer(e){return this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new mf(e,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,earlyDataChannels:this.earlyDataChannels})}},mf=class extends $s{peerConnection;dataChannelOptions;constructor(e,r){super(e,{...r,name:"muxer"}),this.peerConnection=r.peerConnection,this.protocol=r.protocol??of,this.dataChannelOptions=r.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{this.onDataChannel(n)},queueMicrotask(()=>{if(this.status!=="open"){r.earlyDataChannels.forEach(n=>{n.close()});return}r.earlyDataChannels.forEach(n=>{this.onDataChannel(n)})})}onDataChannel(e){if(this.log("incoming datachannel with channel id %d, protocol %s and status %s",e.id,e.protocol,e.readyState),e.label==="init"){this.log.trace("closing init channel %d",e.id),e.close();return}let r=xo({...this.streamOptions,...this.dataChannelOptions,channel:e,direction:"inbound",log:this.log});this.onRemoteStream(r)}async onCreateStream(e){let r=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",r.id,e?.protocol),xo({...e,...this.dataChannelOptions,channel:r,direction:"outbound",log:this.log})}onData(){}};var gf=class extends Vs{peerConnection;constructor(e){super(e),this.peerConnection=e.peerConnection;let r=e.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change %s initial state %s",this.peerConnection.connectionState,r),(this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.onTransportClosed(),this.peerConnection.close())}}sendData(e){return{sentBytes:e.byteLength,canSendMore:!0}}async sendClose(e){this.peerConnection.close(),e?.signal?.throwIfAborted()}sendReset(){this.peerConnection.close()}sendPause(){}sendResume(){}},wo=t=>new gf(t);async function yf(t){return t=t??{},typeof t=="function"&&(t=await t()),t.iceServers=t.iceServers??ed.map(e=>({urls:[e]})),t}var fd=(t=32)=>td+[...Array(t)].map(()=>nf.at(Math.floor(Math.random()*nf.length))).join("");var ti=globalThis.RTCPeerConnection,ri=globalThis.RTCSessionDescription,ud=globalThis.RTCIceCandidate;var Fe=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var Zt=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},ze=class extends Zt{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var ni=class extends Zt{constructor(e,r){super(`Invalid fingerprint "${e}" within ${r}`),this.name="WebRTC/InvalidFingerprintError"}};var oi=class extends Zt{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},si=class extends Zt{constructor(e){super(`unsupported hash algorithm code: ${e} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var Re;(function(t){let e;(function(a){a.SDP_OFFER="SDP_OFFER",a.SDP_ANSWER="SDP_ANSWER",a.ICE_CANDIDATE="ICE_CANDIDATE"})(e=t.Type||(t.Type={}));let r;(function(a){a[a.SDP_OFFER=0]="SDP_OFFER",a[a.SDP_ANSWER=1]="SDP_ANSWER",a[a.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(r||(r={})),(function(a){a.codec=()=>gr(r)})(e=t.Type||(t.Type={}));let n;t.codec=()=>(n==null&&(n=jt((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),t.Type.codec().encode(a.type,c)),a.data!=null&&(c.uint32(18),c.string(a.data)),f.lengthDelimited!==!1&&c.ldelim()},(a,c,f={})=>{let u={},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let m=a.uint32();switch(m>>>3){case 1:{u.type=t.Type.codec().decode(a);break}case 2:{u.data=a.string();break}default:{a.skipType(m&7);break}}}return u},function*(a,c,f,u={}){let l=c==null?a.len:a.pos+c;for(;a.pos<l;){let m=a.uint32();switch(m>>>3){case 1:{yield{field:`${f}.type`,value:t.Type.codec().decode(a)};break}case 2:{yield{field:`${f}.data`,value:a.string()};break}default:{a.skipType(m&7);break}}}})),n);function o(a){return $t(a,t.codec())}t.encode=o;function s(a,c){return Vt(a,t.codec(),c)}t.decode=s;function i(a,c){return qt(a,t.codec(),c)}t.stream=i})(Re||(Re={}));var ii=async(t,e,r)=>{try{let n=Promise.withResolvers();for(Jy(t,n);;){let o=await Promise.race([n.promise,e.read({signal:r.signal})]);if(o==null){r.signal?.throwIfAborted();break}if(o.type!==Re.Type.ICE_CANDIDATE)throw new Fo("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){r.onProgress?.(new Fe("webrtc:end-of-ice-candidates")),r.log.trace("end-of-candidates received");continue}let i=new ud(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{r.onProgress?.(new Fe("webrtc:add-ice-candidate",i.candidate)),await t.addIceCandidate(i)}catch(a){r.log.error("%s bad candidate received %o - %e",r.direction,s,a)}}}catch(n){if(r.log.error("%s error parsing ICE candidate - %e",r.direction,n),r.signal?.aborted===!0&&t.connectionState!=="connected")throw n}};function Jy(t,e){if(t.connectionState==="connected"){e.resolve();return}t.onconnectionstatechange=r=>{switch(t.connectionState){case"connected":e.resolve();break;case"failed":case"closed":e.reject(new Ro(`RTCPeerConnection connection state became "${t.connectionState}"`));break;default:break}}}function ai(t){let e;for(let r of t.getComponents())r.name==="p2p"&&(e=en(r.value??""));if(e==null)throw new Oo("Remote peerId must be present in multiaddr");return e}async function ld({rtcConfiguration:t,dataChannel:e,signal:r,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:f}){let{circuitAddress:u,targetPeer:l}=hd(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing circuit address: %a",u);let m=s.getConnections(l),d;m.length===0?(f?.(new Fe("webrtc:dial-relay")),d=await i.dial(u,{signal:r,onProgress:f})):(f?.(new Fe("webrtc:reuse-relay-connection")),d=m[0]),f?.(new Fe("webrtc:open-signaling-stream"));let p=await d.newStream(po,{signal:r,runOnLimitedConnection:!0}),b=Ws(p).pb(Re),h=new ti(t);h.addEventListener("connectionstatechange",()=>{h.connectionState==="closed"&&h.close()});let y=new Yt({peerConnection:h,dataChannelOptions:e});try{let v=h.createDataChannel("init");h.onicecandidate=({candidate:P})=>{if(h.connectionState==="connected"){a.trace("ignore new ice candidate as peer connection is already connected");return}if(P==null||P?.candidate===""){a.trace("initiator detected end of ICE candidates");return}let B=JSON.stringify(P?.toJSON()??null);a.trace("initiator sending ICE candidate %o",P),b.write({type:Re.Type.ICE_CANDIDATE,data:B},{signal:r}).catch(I=>{a.error("error sending ICE candidate - %e",I)})},h.onicecandidateerror=P=>{a.error("initiator ICE candidate error",P)};let _=await h.createOffer().catch(P=>{throw a.error("could not execute createOffer - %e",P),new ze("Failed to set createOffer")});a.trace("initiator send SDP offer %s",_.sdp),f?.(new Fe("webrtc:send-sdp-offer")),await b.write({type:Re.Type.SDP_OFFER,data:_.sdp},{signal:r}),await h.setLocalDescription(_).catch(P=>{throw a.error("could not execute setLocalDescription - %e",P),new ze("Failed to set localDescription")}),f?.(new Fe("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let D=await b.read({signal:r});if(D.type!==Re.Type.SDP_ANSWER)throw new ze("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",D.data);let R=new ri({type:"answer",sdp:D.data});return await h.setRemoteDescription(R).catch(P=>{throw a.error("could not execute setRemoteDescription - %e",P),new ze("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),f?.(new Fe("webrtc:read-ice-candidates")),await ii(h,b,{direction:"initiator",signal:r,log:a,onProgress:f}),a.trace("initiator connected"),v.readyState!=="open"&&(a.trace("wait for init channel to open"),await Se(v,"open",{signal:r})),a.trace("closing init channel"),v.close(),a.trace("waiting for init channel to close"),await Se(v,"close",{signal:r}),f?.(new Fe("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await p.close({signal:r}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:h,muxerFactory:y}}catch(v){throw a.error("outgoing signaling error - %e",v),h.close(),p.abort(v),v}finally{h.onicecandidate=null,h.onicecandidateerror=null}}var dd=ne(Jh.matchers[0],re(290)),ci=class t extends Lt{transportManager;shutdownController;events;constructor(e,r){super(),this.transportManager=e.transportManager,this.events=e.events,this.shutdownController=r.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(e){e.detail.getAddrs().filter(n=>dd.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(e=>!(e instanceof t)).map(e=>e.getAddrs().filter(r=>dd.exactMatch(r)).map(r=>r.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.events.removeEventListener("transport:listening",this.onTransportListening),this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function pd(t,e,{peerConnection:r,signal:n,log:o}){o.trace("new inbound signaling stream");let s=Ws(t).pb(Re);try{r.onicecandidate=({candidate:l})=>{if(r.connectionState==="connected"){o.trace("ignore new ice candidate as peer connection is already connected");return}if(l==null||l?.candidate===""){o.trace("recipient detected end of ICE candidates");return}let m=JSON.stringify(l?.toJSON()??null);o.trace("recipient sending ICE candidate %s",m),s.write({type:Re.Type.ICE_CANDIDATE,data:m},{signal:n}).catch(d=>{o.error("error sending ICE candidate - %e",d)})},o.trace("recipient read SDP offer");let c=await s.read({signal:n});if(c.type!==Re.Type.SDP_OFFER)throw new ze(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let f=new ri({type:"offer",sdp:c.data});await r.setRemoteDescription(f).catch(l=>{throw o.error("could not execute setRemoteDescription - %e",l),new ze("Failed to set remoteDescription")});let u=await r.createAnswer().catch(l=>{throw o.error("could not execute createAnswer - %e",l),new ze("Failed to create answer")});o.trace("recipient send SDP answer %s",u.sdp),await s.write({type:Re.Type.SDP_ANSWER,data:u.sdp},{signal:n}),await r.setLocalDescription(u).catch(l=>{throw o.error("could not execute setLocalDescription - %e",l),new ze("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await ii(r,s,{direction:"recipient",signal:n,log:o})}catch(c){if(r.connectionState!=="connected")throw o.error("error while handling signaling stream from peer %a - %e",e.remoteAddr,c),r.close(),c;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",e.remoteAddr,c)}let i=ai(e.remoteAddr),a=sn(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var fi=class{components;init;log;_started=!1;metrics;shutdownController;constructor(e,r={}){this.components=e,this.init=r,this.log=e.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[Ho]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Dr]=["@libp2p/transport"];[ru]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(po,(e,r)=>{let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(e,r,n).catch(o=>{this.log.error("failed to handle incoming connect from %p - %e",r.remotePeer,o)}).finally(()=>{n.clear()})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(po),this._started=!1}createListener(e){return new ci(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(Qh.exactMatch)}dialFilter(e){return this.listenFilter(e)}async dial(e,r){this.log.trace("dialing address: %a",e);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await ld({rtcConfiguration:await yf(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:e,dataChannelOptions:this.init.dataChannel,signal:r.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:r.onProgress}),i=wo({peerConnection:o,remoteAddr:n,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")}),a=await r.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,remotePeer:ai(e),muxerFactory:s,onProgress:r.onProgress,signal:r.signal});return this._closeOnShutdown(o,i),a}async _onProtocol(e,r,n){let o=new ti(await yf(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{o.connectionState==="closed"&&o.close()});let s=new Yt({peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i,remotePeer:a}=await pd(e,r,{peerConnection:o,signal:n,log:this.log});await e.close({signal:n});let c=wo({peerConnection:o,remoteAddr:i,metrics:this.metrics?.listenerEvents,direction:"inbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")});await this.components.upgrader.upgradeInbound(c,{skipEncryption:!0,skipProtection:!0,remotePeer:a,muxerFactory:s,signal:n}),this._closeOnShutdown(o,c)}catch(i){throw this.log.error("incoming signaling error - %e",i),o.close(),e.abort(i),i}}_closeOnShutdown(e,r){let n=()=>{r.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection - %e",o)})};this.shutdownController.signal.addEventListener("abort",n),e.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function hd(t){let e=t.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(e==null)throw new q("Destination peer id was missing");return{circuitAddress:sn(t.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:en(e)}}function at(t=0){return new Uint8Array(t)}function Ve(t=0){return new Uint8Array(t)}var hn=!!globalThis.process?.env?.DUMP_SESSION_KEYS,bf=16;function Qy(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function ui(t){if(typeof t!="boolean")throw new TypeError(`boolean expected, not ${t}`)}function dn(t){if(typeof t!="number")throw new TypeError("number expected, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError("positive integer expected, got "+t)}function ge(t,e,r=""){let n=Qy(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return t}function xf(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function md(t,e,r=!1){ge(t,void 0,"output");let n=e.outputLen;if(t.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(r&&!pn(t))throw new Error("invalid output, must be aligned")}function ct(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Je(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function eb(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Sr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,tb=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;var rb=t=>{for(let e=0;e<t.length;e++)t[e]=tb(t[e]);return t},_t=Sr?t=>t:rb;function gd(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function yd(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function bd(t,e,r){let n=e,o=r||(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(t),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}var xd=(t,e)=>{function r(n,...o){if(ge(n,void 0,"key"),t.nonceLength!==void 0){let u=o[0];ge(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength;s&&o[1]!==void 0&&ge(o[1],void 0,"AAD");let i=e(n,...o),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");ge(l,void 0,"output")}},c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,ge(u),a(i.encrypt.length,l),i.encrypt(u,l)},decrypt(u,l){if(ge(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,l),i.decrypt(u,l)}}}return Object.assign(r,t),r};function Eo(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(ge(e,void 0,"output"),e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(r&&!pn(e))throw new Error("invalid output, must be aligned");return e}function wd(t,e,r){dn(t),dn(e),ui(r);let n=new Uint8Array(16),o=eb(n);return o.setBigUint64(0,BigInt(e),r),o.setBigUint64(8,BigInt(t),r),n}function pn(t){return t.byteOffset%4===0}function mn(t){return Uint8Array.from(ge(t))}var Sd=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),nb=_t(ct(Sd("expand 16-byte k"))),ob=_t(ct(Sd("expand 32-byte k")));function j(t,e){return t<<e|t>>>32-e}var So=64,sb=16,wf=2**32-1,Ed=Uint32Array.of();function ib(t,e,r,n,o,s,i,a){let c=o.length,f=new Uint8Array(So),u=ct(f),l=Sr&&pn(o)&&pn(s),m=l?ct(o):Ed,d=l?ct(s):Ed;if(!Sr){for(let p=0;p<c;i++){if(t(e,r,n,u,i,a),_t(u),i>=wf)throw new Error("arx: counter overflow");let b=Math.min(So,c-p);for(let h=0,y;h<b;h++)y=p+h,s[y]=o[y]^f[h];p+=b}return}for(let p=0;p<c;i++){if(t(e,r,n,u,i,a),i>=wf)throw new Error("arx: counter overflow");let b=Math.min(So,c-p);if(l&&b===So){let h=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let y=0,v;y<sb;y++)v=h+y,d[v]=m[v]^u[y];p+=So;continue}for(let h=0,y;h<b;h++)y=p+h,s[y]=o[y]^f[h];p+=b}}function Ad(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=gd({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return dn(o),dn(i),ui(s),ui(r),(a,c,f,u,l=0)=>{ge(a,void 0,"key"),ge(c,void 0,"nonce"),ge(f,void 0,"data");let m=f.length;if(u=Eo(m,u,!1),dn(l),l<0||l>=wf)throw new Error("arx: counter overflow");let d=[],p=a.length,b,h;if(p===32)d.push(b=mn(a)),h=ob;else if(p===16&&r)b=new Uint8Array(32),b.set(a),b.set(a,16),h=nb,d.push(b);else throw ge(a,32,"arx key"),new Error("invalid key size");(!Sr||!pn(c))&&d.push(c=mn(c));let y=ct(b);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let D=c.subarray(0,16);if(Sr)n(h,y,ct(D),y);else{let R=_t(Uint32Array.from(h));n(R,y,ct(D),y),Je(R),_t(y)}c=c.subarray(16)}else Sr||_t(y);let v=16-o;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let D=new Uint8Array(12);D.set(c,s?0:12-c.length),c=D,d.push(c)}let _=_t(ct(c));try{return ib(t,h,y,_,f,u,l,i),u}finally{Je(...d)}}}function Ae(t,e){return t[e++]&255|(t[e++]&255)<<8}var Ef=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=mn(ge(e,32,"key"));let r=Ae(e,0),n=Ae(e,2),o=Ae(e,4),s=Ae(e,6),i=Ae(e,8),a=Ae(e,10),c=Ae(e,12),f=Ae(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|f<<8)&8191,this.r[9]=f>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Ae(e,16+2*u)}process(e,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],f=i[2],u=i[3],l=i[4],m=i[5],d=i[6],p=i[7],b=i[8],h=i[9],y=Ae(e,r+0),v=Ae(e,r+2),_=Ae(e,r+4),D=Ae(e,r+6),R=Ae(e,r+8),P=Ae(e,r+10),B=Ae(e,r+12),I=Ae(e,r+14),U=s[0]+(y&8191),k=s[1]+((y>>>13|v<<3)&8191),N=s[2]+((v>>>10|_<<6)&8191),g=s[3]+((_>>>7|D<<9)&8191),A=s[4]+((D>>>4|R<<12)&8191),S=s[5]+(R>>>1&8191),w=s[6]+((R>>>14|P<<2)&8191),x=s[7]+((P>>>11|B<<5)&8191),C=s[8]+((B>>>8|I<<8)&8191),L=s[9]+(I>>>5|o),E=0,T=E+U*a+k*(5*h)+N*(5*b)+g*(5*p)+A*(5*d);E=T>>>13,T&=8191,T+=S*(5*m)+w*(5*l)+x*(5*u)+C*(5*f)+L*(5*c),E+=T>>>13,T&=8191;let O=E+U*c+k*a+N*(5*h)+g*(5*b)+A*(5*p);E=O>>>13,O&=8191,O+=S*(5*d)+w*(5*m)+x*(5*l)+C*(5*u)+L*(5*f),E+=O>>>13,O&=8191;let F=E+U*f+k*c+N*a+g*(5*h)+A*(5*b);E=F>>>13,F&=8191,F+=S*(5*p)+w*(5*d)+x*(5*m)+C*(5*l)+L*(5*u),E+=F>>>13,F&=8191;let H=E+U*u+k*f+N*c+g*a+A*(5*h);E=H>>>13,H&=8191,H+=S*(5*b)+w*(5*p)+x*(5*d)+C*(5*m)+L*(5*l),E+=H>>>13,H&=8191;let K=E+U*l+k*u+N*f+g*c+A*a;E=K>>>13,K&=8191,K+=S*(5*h)+w*(5*b)+x*(5*p)+C*(5*d)+L*(5*m),E+=K>>>13,K&=8191;let Z=E+U*m+k*l+N*u+g*f+A*c;E=Z>>>13,Z&=8191,Z+=S*a+w*(5*h)+x*(5*b)+C*(5*p)+L*(5*d),E+=Z>>>13,Z&=8191;let J=E+U*d+k*m+N*l+g*u+A*f;E=J>>>13,J&=8191,J+=S*c+w*a+x*(5*h)+C*(5*b)+L*(5*p),E+=J>>>13,J&=8191;let Q=E+U*p+k*d+N*m+g*l+A*u;E=Q>>>13,Q&=8191,Q+=S*f+w*c+x*a+C*(5*h)+L*(5*b),E+=Q>>>13,Q&=8191;let G=E+U*b+k*p+N*d+g*m+A*l;E=G>>>13,G&=8191,G+=S*u+w*f+x*c+C*a+L*(5*h),E+=G>>>13,G&=8191;let se=E+U*h+k*b+N*p+g*d+A*m;E=se>>>13,se&=8191,se+=S*l+w*u+x*f+C*c+L*a,E+=se>>>13,se&=8191,E=(E<<2)+E|0,E=E+T|0,T=E&8191,E=E>>>13,O+=E,s[0]=T,s[1]=O,s[2]=F,s[3]=H,s[4]=K,s[5]=Z,s[6]=J,s[7]=Q,s[8]=G,s[9]=se}finalize(){let{h:e,pad:r}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+r[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+r[a]|0)+(i>>>16)|0,e[a]=i&65535;Je(n)}update(e){xf(this),ge(e),e=mn(e);let{buffer:r,blockLen:n}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,Je(this.h,this.r,this.buffer,this.pad)}digestInto(e){xf(this),md(e,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:o}=this;if(o){for(r[o++]=1;o<16;o++)r[o]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}},vd=bd(32,t=>new Ef(t));function ab(t,e,r,n,o,s=20){let i=t[0],a=t[1],c=t[2],f=t[3],u=e[0],l=e[1],m=e[2],d=e[3],p=e[4],b=e[5],h=e[6],y=e[7],v=o,_=r[0],D=r[1],R=r[2],P=i,B=a,I=c,U=f,k=u,N=l,g=m,A=d,S=p,w=b,x=h,C=y,L=v,E=_,T=D,O=R;for(let H=0;H<s;H+=2)P=P+k|0,L=j(L^P,16),S=S+L|0,k=j(k^S,12),P=P+k|0,L=j(L^P,8),S=S+L|0,k=j(k^S,7),B=B+N|0,E=j(E^B,16),w=w+E|0,N=j(N^w,12),B=B+N|0,E=j(E^B,8),w=w+E|0,N=j(N^w,7),I=I+g|0,T=j(T^I,16),x=x+T|0,g=j(g^x,12),I=I+g|0,T=j(T^I,8),x=x+T|0,g=j(g^x,7),U=U+A|0,O=j(O^U,16),C=C+O|0,A=j(A^C,12),U=U+A|0,O=j(O^U,8),C=C+O|0,A=j(A^C,7),P=P+N|0,O=j(O^P,16),x=x+O|0,N=j(N^x,12),P=P+N|0,O=j(O^P,8),x=x+O|0,N=j(N^x,7),B=B+g|0,L=j(L^B,16),C=C+L|0,g=j(g^C,12),B=B+g|0,L=j(L^B,8),C=C+L|0,g=j(g^C,7),I=I+A|0,E=j(E^I,16),S=S+E|0,A=j(A^S,12),I=I+A|0,E=j(E^I,8),S=S+E|0,A=j(A^S,7),U=U+k|0,T=j(T^U,16),w=w+T|0,k=j(k^w,12),U=U+k|0,T=j(T^U,8),w=w+T|0,k=j(k^w,7);let F=0;n[F++]=i+P|0,n[F++]=a+B|0,n[F++]=c+I|0,n[F++]=f+U|0,n[F++]=u+k|0,n[F++]=l+N|0,n[F++]=m+g|0,n[F++]=d+A|0,n[F++]=p+S|0,n[F++]=b+w|0,n[F++]=h+x|0,n[F++]=y+C|0,n[F++]=v+L|0,n[F++]=_+E|0,n[F++]=D+T|0,n[F++]=R+O|0}var cb=Ad(ab,{counterRight:!1,counterLength:4,allowShortKeys:!1});var fb=new Uint8Array(16),Cd=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(fb.subarray(r))},ub=new Uint8Array(32);function _d(t,e,r,n,o){o!==void 0&&ge(o,void 0,"AAD");let s=t(e,r,ub),i=wd(n.length,o?o.length:0,!0),a=vd.create(s);o&&Cd(a,o),Cd(a,n),a.update(i);let c=a.digest();return Je(s,i),c}var lb=t=>(e,r,n)=>({encrypt(s,i){let a=s.length;i=Eo(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);t(e,r,c,c,1);let f=_d(t,e,r,c,n);return i.set(f,a),Je(f),i},decrypt(s,i){i=Eo(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),f=_d(t,e,r,a,n);if(!yd(c,f))throw Je(f),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,r,i,i,1),Je(f),i}}),Sf=xd({blockSize:64,nonceLength:12,tagLength:16},lb(cb));function Id(t,e,r){return nr(t),r===void 0&&(r=new Uint8Array(t.outputLen)),ro(t,r,e)}var Af=Uint8Array.of(0),Ld=Uint8Array.of();function Td(t,e,r,n=32){nr(t),rt(n,"length"),ve(e,void 0,"prk");let o=t.outputLen;if(e.length<o)throw new Error('"prk" must be at least HashLen octets');if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);r===void 0?r=Ld:ve(r,void 0,"info");let i=new Uint8Array(s*o),a=ro.create(t,e),c=a._cloneInto(),f=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)Af[0]=u+1,c.update(u===0?Ld:f).update(r).update(Af).digestInto(f),i.set(f,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),je(f,Af),i.slice(0,n)}var vf={hashSHA256(t){return ot(t.subarray())},getHKDF(t,e){let r=Id(ot,e,t),o=Td(ot,r,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let t=jn.utils.randomSecretKey();return{publicKey:jn.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:jn.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return jn.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,r,n){return Sf(n,e,r).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,r,n,o){return Sf(n,e,r).decrypt(t.subarray(),o)}};var Bd=vf;function Dd(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,r)=>t.generateX25519SharedKey(e.privateKey,r).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}var gn=t=>{let e=Ve(2);return e[0]=t>>8,e[1]=t,e};gn.bytes=2;var yn=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");if(t instanceof Uint8Array){let e=0;return e+=t[0]<<8,e+=t[1],e}return t.getUint16(0)};yn.bytes=2;function Rd(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Od(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var Pd=Od("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Cf=Od("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=Ve(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),hb={utf8:Pd,"utf-8":Pd,hex:Ne.base16,latin1:Cf,ascii:Cf,binary:Cf,...Ne},li=hb;function ft(t,e="utf8"){let r=li[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}function _f(t,e){!e.enabled||!hn||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${ft(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${ft(t.privateKey,"hex")}`)):e("Missing local static keys."))}function Lf(t,e){!e.enabled||!hn||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${ft(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${ft(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Ud(t,e){!e.enabled||!hn||e(t?`REMOTE_STATIC_PUBLIC_KEY ${ft(t.subarray(),"hex")}`:"Missing remote static public key.")}function If(t,e){!e.enabled||!hn||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${ft(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Tf(t,e,r){!r.enabled||!hn||(r(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&ft(t.k,"hex")}`),r(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&ft(e.k,"hex")}`))}function Bf(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=Ve(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}function Ar(t,e="utf8"){let r=li[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}var bn=class t extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=t.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var pb=0,mb=4294967295,gb="Cipherstate has reached maximum n, a new handshake must be performed",hi=class{n;bytes;view;constructor(e=pb){this.n=e,this.bytes=at(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>mb)throw new Error(gb)}};var vr=at(0),xn=class{k;n;crypto;constructor(e,r=void 0,n=0){this.crypto=e,this.k=r,this.n=new hi(n)}hasKey(){return!!this.k}encryptWithAd(e,r){if(!this.hasKey())return r;this.n.assertValue();let n=this.crypto.encrypt(r,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,r,n){if(!this.hasKey())return r;this.n.assertValue();let o=this.crypto.decrypt(r,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},Df=class{cs;ck;h;crypto;constructor(e,r){this.crypto=e;let n=Ar(r,"utf-8");this.h=yb(e,n),this.ck=this.h,this.cs=new xn(e)}mixKey(e){let[r,n]=this.crypto.hkdf(this.ck,e);this.ck=r,this.cs=new xn(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new z(this.h,e))}encryptAndHash(e){let r=this.cs.encryptWithAd(this.h,e);return this.mixHash(r),r}decryptAndHash(e){let r=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),r}split(){let[e,r]=this.crypto.hkdf(this.ck,vr);return[new xn(this.crypto,e),new xn(this.crypto,r)]}},Rf=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:r,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:f}=e;this.crypto=r,this.ss=new Df(r,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=f}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new 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 new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new 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 new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<r+32)throw new Error("message is not long enough");this.re=e.sublist(r,r+32),this.ss.mixHash(this.re)}readS(e,r=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<r+n)throw new Error("message is not long enough");let o=e.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Ao=class extends Rf{writeMessageA(e){return new z(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let r=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new z(r,n,this.ss.encryptAndHash(e))}writeMessageC(e){let r=this.writeS();return this.writeSE(),new z(r,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(r){throw new bn(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let r=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+r))}catch(r){throw new bn(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(e){try{let r=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(r))}catch(r){throw new bn(`handshake stage 2 validation fail: ${r.message}`)}}};function yb(t,e){if(e.length<=32){let r=at(32);return r.set(e),r}else return t.hash(e)}var Pf=new Float32Array([-0]),Jt=new Uint8Array(Pf.buffer);function Nd(t,e,r){Pf[0]=t,e[r]=Jt[0],e[r+1]=Jt[1],e[r+2]=Jt[2],e[r+3]=Jt[3]}function Fd(t,e){return Jt[0]=t[e],Jt[1]=t[e+1],Jt[2]=t[e+2],Jt[3]=t[e+3],Pf[0]}var Of=new Float64Array([-0]),Te=new Uint8Array(Of.buffer);function kd(t,e,r){Of[0]=t,e[r]=Te[0],e[r+1]=Te[1],e[r+2]=Te[2],e[r+3]=Te[3],e[r+4]=Te[4],e[r+5]=Te[5],e[r+6]=Te[6],e[r+7]=Te[7]}function Md(t,e){return Te[0]=t[e],Te[1]=t[e+1],Te[2]=t[e+2],Te[3]=t[e+3],Te[4]=t[e+4],Te[5]=t[e+5],Te[6]=t[e+6],Te[7]=t[e+7],Of[0]}var bb=BigInt(Number.MAX_SAFE_INTEGER),xb=BigInt(Number.MIN_SAFE_INTEGER),ke=class t{lo;hi;constructor(e,r){this.lo=e|0,this.hi=r|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Cr;if(e<bb&&e>xb)return this.fromNumber(Number(e));let r=e<0n;r&&(e=-e);let n=e>>32n,o=e-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>Kd&&(o=0n,++n>Kd&&(n=0n))),new t(Number(o),Number(n))}static fromNumber(e){if(e===0)return Cr;let r=e<0;r&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new t(n,o)}static from(e){return typeof e=="number"?t.fromNumber(e):typeof e=="bigint"?t.fromBigInt(e):typeof e=="string"?t.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new t(e.low>>>0,e.high>>>0):Cr}},Cr=new ke(0,0);Cr.toBigInt=function(){return 0n};Cr.zzEncode=Cr.zzDecode=function(){return this};Cr.length=function(){return 1};var Kd=4294967296n;function Hd(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(r&64512)===55296&&(t.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function zd(t,e,r){if(r-e<1)return"";let o,s=[],i=0,a;for(;e<r;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Uf(t,e,r){let n=r,o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128);return r-n}function Qe(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function di(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}var Nf=class{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=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Qe(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Qe(this,4);return di(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Qe(this,4);return di(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Qe(this,4);let e=Fd(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Qe(this,4);let e=Md(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw Qe(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let e=this.bytes();return zd(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Qe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Qe(this);while((this.buf[this.pos++]&128)!==0);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(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new ke(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw Qe(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,e}if(this.len-this.pos>4){for(;r<5;++r)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;r<5;++r){if(this.pos>=this.len)throw Qe(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Qe(this,8);let e=di(this.buf,this.pos+=4),r=di(this.buf,this.pos+=4);return new ke(e,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Wn(this.buf,this.pos);return this.pos+=ee(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 Ff(t){return new Nf(t instanceof Uint8Array?t:t.subarray())}function pi(t,e,r){let n=Ff(t);return e.decode(n,void 0,r)}function kf(t){let e=t??8192,r=e>>>1,n,o=e;return function(i){if(i<1||i>r)return Ve(i);o+i>e&&(n=Ve(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var _r=class{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}};function Mf(){}var Hf=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},wb=kf();function Eb(t){return globalThis.Buffer!=null?Ve(t):wb(t)}var Co=class{len;head;tail;states;constructor(){this.len=0,this.head=new _r(Mf,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new _r(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new zf((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(mi,10,ke.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let r=ke.fromBigInt(e);return this._push(mi,r.length(),r)}uint64Number(e){return this._push(Ht,ee(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){let r=ke.fromBigInt(e).zzEncode();return this._push(mi,r.length(),r)}sint64Number(e){let r=ke.fromNumber(e).zzEncode();return this._push(mi,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Kf,1,e?1:0)}fixed32(e){return this._push(vo,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let r=ke.fromBigInt(e);return this._push(vo,4,r.lo)._push(vo,4,r.hi)}fixed64Number(e){let r=ke.fromNumber(e);return this._push(vo,4,r.lo)._push(vo,4,r.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(Nd,4,e)}double(e){return this._push(kd,8,e)}bytes(e){let r=e.length>>>0;return r===0?this._push(Kf,1,0):this.uint32(r)._push(Ab,r,e)}string(e){let r=Hd(e);return r!==0?this.uint32(r)._push(Uf,r,e):this._push(Kf,1,0)}fork(){return this.states=new Hf(this),this.head=this.tail=new _r(Mf,0,0),this.len=0,this}reset(){return this.states!=null?(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 _r(Mf,0,0),this.len=0),this}ldelim(){let e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next,r=Eb(this.len),n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}};function Kf(t,e,r){e[r]=t&255}function Sb(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}var zf=class extends _r{next;constructor(e,r){super(Sb,e,r),this.next=void 0}};function mi(t,e,r){for(;t.hi!==0;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}function vo(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function Ab(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(Co.prototype.bytes=function(t){let e=t.length>>>0;return this.uint32(e),e>0&&this._push(vb,e,t),this},Co.prototype.string=function(t){let e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(Cb,e,t),this});function vb(t,e,r){e.set(t,r)}function Cb(t,e,r){t.length<40?Uf(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(Ar(t),r)}function Vf(){return new Co}function gi(t,e){let r=Vf();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var _o;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(_o||(_o={}));function $f(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function yi(t,e){return $f("message",_o.LENGTH_DELIMITED,t,e)}var Lo=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var bi;(function(t){let e;t.codec=()=>(e==null&&(e=yi((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(let s of r.webtransportCerthashes)n.uint32(10),n.bytes(s);if(r.streamMuxers!=null)for(let s of r.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new Lo('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(r.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new Lo('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(r.string());break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>gi(r,t.codec()),t.decode=(r,n)=>pi(r,t.codec(),n)})(bi||(bi={}));var Io;(function(t){let e;t.codec=()=>(e==null&&(e=yi((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.identityKey!=null&&r.identityKey.byteLength>0&&(n.uint32(10),n.bytes(r.identityKey)),r.identitySig!=null&&r.identitySig.byteLength>0&&(n.uint32(18),n.bytes(r.identitySig)),r.extensions!=null&&(n.uint32(34),bi.codec().encode(r.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={identityKey:at(0),identitySig:at(0)},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{s.identityKey=r.bytes();break}case 2:{s.identitySig=r.bytes();break}case 4:{s.extensions=bi.codec().decode(r,r.uint32(),{limits:o.limits?.extensions});break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>gi(r,t.codec()),t.decode=(r,n)=>pi(r,t.codec(),n)})(Io||(Io={}));async function jf(t,e,r){let n=await t.sign(qd(e));return Io.encode({identityKey:Rt(t.publicKey),identitySig:n,extensions:r})}async function Gf(t,e,r){try{let n=Io.decode(t),o=no(n.identityKey);if(r?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${r}`);if(!e)throw new Error("Remote static does not exist");let s=qd(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Bo(n.message)}}function qd(t){let e=Ar("noise-libp2p-static-key:");return t instanceof Uint8Array?Bf([e,t],e.length+t.length):(t.prepend(e),t)}var qf=class extends Xt{stream;handshake;metrics;decoder;constructor(e,r,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=r,this.metrics=n,this.decoder=new Xs({lengthDecoder:yn,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=c=>{try{for(let f of this.decoder.decode(c.data))this.onData(this.decrypt(f))}catch(f){this.abort(f)}};this.stream.addEventListener("message",o);let s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let r=new z;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),r.append(gn(s.byteLength)),r.append(s)}return r}decrypt(e){let r=new z;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-bf<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);let i=e.subarray(n,o-bf);try{let a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),r.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return r}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function Wf(t,e,r){return new qf(t,e,r)}async function jd(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=t,u=await jf(s,a.publicKey,f),l=new Ao({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});_f(l.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(l.writeMessageA(vr),e),r.trace("Stage 0 - Initiator finished sending first message."),Lf(l.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");let m=l.readMessageB(await n.read(e));r.trace("Stage 1 - Initiator received the message."),If(l.re,r),Ud(l.rs,r),r.trace("Initiator going to check remote's signature...");let d=await Gf(m,l.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(l.writeMessageC(u),e),r.trace("Stage 2 - Initiator sent message with signed payload.");let[p,b]=l.ss.split();return Tf(p,b,r),{payload:d,encrypt:h=>p.encryptWithAd(vr,h),decrypt:(h,y)=>b.decryptWithAd(vr,h,y)}}async function Gd(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=t,u=await jf(s,a.publicKey,f),l=new Ao({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});_f(l.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),l.readMessageA(await n.read(e)),r.trace("Stage 0 - Responder received first message."),If(l.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(l.writeMessageB(u),e),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Lf(l.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");let m=l.readMessageC(await n.read(e));r.trace("Stage 2 - Responder received the message, finished handshake.");let d=await Gf(m,l.rs,c),[p,b]=l.ss.split();return Tf(p,b,r),{payload:d,encrypt:h=>b.encryptWithAd(vr,h),decrypt:(h,y)=>p.decryptWithAd(vr,h,y)}}var xi=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,r={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=r,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=s??Bd;this.crypto=Dd(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Rd(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??at(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Dr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,r){let n=e.log?.newScope("noise")??this.log,o=Gs(e,{lengthEncoder:gn,lengthDecoder:yn,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=no(s.payload.identityKey);return{connection:Wf(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Lc(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let r=this.components.upgrader.getStreamMuxers();if(r!=null)for(let n of e){let o=r.get(n);if(o!=null)return o}if(e.length)throw new Do("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,r){let n=e.log?.newScope("noise")??this.log,o=Gs(e,{lengthEncoder:gn,lengthDecoder:yn,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=no(s.payload.identityKey);return{connection:Wf(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Lc(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await jd({connection:e,privateKey:r,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Gd({connection:e,privateKey:r,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function Wd(t={}){return e=>new xi(e,t)}var Xf=Object.values(Ne).map(t=>t.decoder).reduce((t,e)=>t.or(e)),_b=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function Xd(t){return t?.match(_b)?.groups?.fingerprint}function Yf(t){let r=t.getComponents().find(n=>n.code===466)?.value;if(r===void 0||r==="")throw new q(`Couldn't find a certhash component of multiaddr: ${t.toString()}`);return r}function Lb(t){return $e.decode(Xf.decode(t))}function Ib(t){let e=Lb(Yf(t)),r=Tb(e.code),n=e.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new ni(n,t.toString());return`${r} ${o.join(":").toUpperCase()}`}function Yd(t){let e=t.split(":").map(o=>parseInt(o,16)),r=Uint8Array.from(e),n=Be(Et.code,r);return sn(`/certhash/${Zn.encode(n.bytes)}`)}function Tb(t){switch(t){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new si(t)}}function Zd(t,e){let{host:r,port:n,type:o}=sf(t);if(o!=="ip4"&&o!=="ip6")throw new q(`Multiaddr ${t} was not an IPv4 or IPv6 address`);let s=Ib(t);return{type:"answer",sdp:`v=0
|
|
2
|
+
"use strict";var Libp2PWebrtc=(()=>{var Vi=Object.defineProperty;var Om=Object.getOwnPropertyDescriptor;var Pm=Object.getOwnPropertyNames;var Nm=Object.prototype.hasOwnProperty;var z=(t,e)=>{for(var r in e)Vi(t,r,{get:e[r],enumerable:!0})},Um=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pm(e))!Nm.call(t,o)&&o!==r&&Vi(t,o,{get:()=>e[o],enumerable:!(n=Om(e,o))||n.enumerable});return t};var Mm=t=>Um(Vi({},"__esModule",{value:!0}),t);var q2={};z(q2,{webRTC:()=>$2,webRTCDirect:()=>V2});var Qo=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},es=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},j=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Kr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var ts=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},rs=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},Hr=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var st=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Hn=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var ns=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},os=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},ss=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var is=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var ur=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var as=class extends Event{data;constructor(e,r){super("message",r),this.data=e}},zr=class extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}},cs=class extends zr{constructor(e,r){super(!0,e,r)}},fs=class extends zr{constructor(e,r){super(!1,e,r)}};var $i=Symbol.for("@libp2p/peer-id");var us=Symbol.for("@libp2p/transport");var eh;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(eh||(eh={}));function km(t){return typeof t?.handleEvent=="function"}function Km(t){return(t!==!0&&t!==!1&&t?.once)??!1}var Ot=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){let o=Km(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==r),this.#e.set(i.type,a))}km(r)?r.handleEvent(i):r(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:r,once:o})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==r),this.#e.set(e,o))}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}};var Vr=Symbol.for("@libp2p/service-capabilities"),th=Symbol.for("@libp2p/service-dependencies");var Xi={};z(Xi,{base58btc:()=>le,base58flickr:()=>Wm});var A1=new Uint8Array(0);function rh(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function xt(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return hr(t);if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return hr(new Uint8Array(t.buffer,t.byteOffset,t.byteLength));throw new Error("Unknown type, must be binary type")}function nh(t){return new TextEncoder().encode(t)}function oh(t){return new TextDecoder().decode(t)}function Hm(t){return t?.buffer instanceof ArrayBuffer}function hr(t){return Hm(t)?t:t.slice()}function zm(t,e){if(t.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 o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=t.length,c=t.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,l=0,g=0,E=d.length;g!==E&&d[g]===0;)g++,y++;for(var v=(E-g)*u+1>>>0,T=new Uint8Array(v);g!==E;){for(var B=d[g],R=0,D=v-1;(B!==0||R<l)&&D!==-1;D--,R++)B+=256*T[D]>>>0,T[D]=B%a>>>0,B=B/a>>>0;if(B!==0)throw new Error("Non-zero carry");l=R,g++}for(var I=v-l;I!==v&&T[I]===0;)I++;for(var P=c.repeat(y);I<v;++I)P+=t.charAt(T[I]);return P}function m(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var l=0,g=0;d[y]===c;)l++,y++;for(var E=(d.length-y)*f+1>>>0,v=new Uint8Array(E);d[y];){var T=r[d.charCodeAt(y)];if(T===255)return;for(var B=0,R=E-1;(T!==0||B<g)&&R!==-1;R--,B++)T+=a*v[R]>>>0,v[R]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");g=B,y++}if(d[y]!==" "){for(var D=E-g;D!==E&&v[D]===0;)D++;for(var I=new Uint8Array(l+(E-D)),P=l;D!==E;)I[P++]=v[D++];return I}}}function p(d){var y=m(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:m,decode:p}}var Vm=zm,$m=Vm,ih=$m;var qi=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ji=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){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))}else throw Error("Can only multibase decode strings")}or(e){return ah(this,e)}},Gi=class{decoders;constructor(e){this.decoders=e}or(e){return ah(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ah(t,e){return new Gi({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Wi=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new qi(e,r,n),this.decoder=new ji(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function $r({name:t,prefix:e,encode:r,decode:n}){return new Wi(t,e,r,n)}function Pt({name:t,prefix:e,alphabet:r}){let{encode:n,decode:o}=ih(r,t);return $r({prefix:e,name:t,encode:n,decode:s=>xt(o(s))})}function qm(t,e,r,n){let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[t[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|u,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function jm(t,e,r){let n=e[e.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function Gm(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function he({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let o=Gm(n);return $r({prefix:e,name:t,encode(s){return jm(s,n,r)},decode(s){return qm(s,o,r,t)}})}var le=Pt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Wm=Pt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Yi={};z(Yi,{base32:()=>Nt,base32hex:()=>Jm,base32hexpad:()=>e0,base32hexpadupper:()=>t0,base32hexupper:()=>Qm,base32pad:()=>Ym,base32padupper:()=>Zm,base32upper:()=>Xm,base32z:()=>r0});var Nt=he({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Xm=he({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ym=he({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Zm=he({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Jm=he({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Qm=he({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),e0=he({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),t0=he({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),r0=he({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Zi={};z(Zi,{base36:()=>zn,base36upper:()=>n0});var zn=Pt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),n0=Pt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Xe={};z(Xe,{Digest:()=>lr,create:()=>Oe,decode:()=>Gr,equals:()=>Qi,hasCode:()=>S0});var o0=uh,ch=128,s0=127,i0=~s0,a0=Math.pow(2,31);function uh(t,e,r){e=e||[],r=r||0;for(var n=r;t>=a0;)e[r++]=t&255|ch,t/=128;for(;t&i0;)e[r++]=t&255|ch,t>>>=7;return e[r]=t|0,uh.bytes=r-n+1,e}var c0=Ji,f0=128,fh=127;function Ji(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw Ji.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&fh)<<o:(i&fh)*Math.pow(2,o),o+=7}while(i>=f0);return Ji.bytes=s-n,r}var u0=Math.pow(2,7),h0=Math.pow(2,14),l0=Math.pow(2,21),d0=Math.pow(2,28),p0=Math.pow(2,35),m0=Math.pow(2,42),g0=Math.pow(2,49),y0=Math.pow(2,56),x0=Math.pow(2,63),b0=function(t){return t<u0?1:t<h0?2:t<l0?3:t<d0?4:t<p0?5:t<m0?6:t<g0?7:t<y0?8:t<x0?9:10},w0={encode:o0,decode:c0,encodingLength:b0},E0=w0,Vn=E0;function $n(t,e=0){return[Vn.decode(t,e),Vn.decode.bytes]}function qr(t,e,r=0){return Vn.encode(t,e,r),e}function jr(t){return Vn.encodingLength(t)}function Oe(t,e){let r=e.byteLength,n=jr(t),o=n+jr(r),s=new Uint8Array(o+r);return qr(t,s,0),qr(r,s,n),s.set(e,o),new lr(t,r,e,s)}function Gr(t){let e=xt(t),[r,n]=$n(e),[o,s]=$n(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new lr(r,o,i,e)}function Qi(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&rh(t.bytes,r.bytes)}}var lr=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=hr(n),this.bytes=hr(o)}};function S0(t,e){return t.code===e}function hh(t,e){let{bytes:r,version:n}=t;return n===0?C0(r,ea(t),e??le.encoder):v0(r,ea(t),e??Nt.encoder)}var lh=new WeakMap;function ea(t){let e=lh.get(t);if(e==null){let r=new Map;return lh.set(t,r),r}return e}var ge=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=hr(o),this["/"]=this.bytes}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:{let{code:e,multihash:r}=this;if(e!==qn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==L0)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}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:{let{code:e,digest:r}=this.multihash,n=Oe(e,r);return t.createV1(this.code,n)}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 t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&Qi(e.multihash,n.multihash)}toString(e){return hh(this,e)}toJSON(){return{"/":hh(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new t(n,o,s,i??dh(n,o,s.bytes))}else if(r[I0]===!0){let{version:n,multihash:o,code:s}=r,i=Gr(o);return t.create(n,s,i)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==qn)throw new Error(`Version 0 CID must use dag-pb (code: ${qn}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=dh(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,qn,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=xt(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new lr(r.multihashCode,r.digestSize,s,o);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[h,m]=$n(e.subarray(r));return r+=m,h},o=n(),s=qn;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),f=r+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,r){let[n,o]=A0(e,r),s=t.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ea(s).set(n,e),s}};function A0(t,e){switch(t[0]){case"Q":{let r=e??le;return[le.prefix,r.decode(`${le.prefix}${t}`)]}case le.prefix:{let r=e??le;return[le.prefix,r.decode(t)]}case Nt.prefix:{let r=e??Nt;return[Nt.prefix,r.decode(t)]}case zn.prefix:{let r=e??zn;return[zn.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function C0(t,e,r){let{prefix:n}=r;if(n!==le.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function v0(t,e,r){let{prefix:n}=r,o=e.get(n);if(o==null){let s=r.encode(t);return e.set(n,s),s}else return o}var qn=112,L0=18;function dh(t,e,r){let n=jr(t),o=n+jr(e),s=new Uint8Array(o+r.byteLength);return qr(t,s,0),qr(e,s,n),s.set(r,o),s}var I0=Symbol.for("@ipld/js-cid/CID");var ta={};z(ta,{identity:()=>Ye});var ph=0,_0="identity",mh=xt;function T0(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return Oe(ph,mh(t))}var Ye={code:ph,name:_0,encode:mh,digest:T0};function Pe(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function D0(t){return t.buffer instanceof ArrayBuffer}function Ne(t){return D0(t)?t:t.slice()}async function gh(t,e,r,n){let o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,Ne(e),Ne(r.subarray()));return n?.signal?.throwIfAborted(),s}function bt(t=0){return new Uint8Array(t)}function jn(t=0){return new Uint8Array(t)}function ra(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=jn(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}function yh(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}var bh=Symbol.for("@achingbrain/uint8arraylist");function xh(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let o=r+n.byteLength;if(e<o)return{buf:n,index:e-r};r=o}throw new RangeError("index is out of bounds")}function ls(t){return!!t?.[bh]}var V=class t{bufs;length;[bh]=!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 r=0;for(let n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(ls(n)){r+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...e){this.prependAll(e)}prependAll(e){let r=0;for(let n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(ls(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(e){let r=xh(this.bufs,e);return r.buf[r.index]}set(e,r){let n=xh(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(ls(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,r){let{bufs:n,length:o}=this._subList(e,r);return ra(n,o)}subarray(e,r){let{bufs:n,length:o}=this._subList(e,r);return n.length===1?n[0]:ra(n,o)}sublist(e,r){let{bufs:n,length:o}=this._subList(e,r),s=new t;return s.length=o,s.bufs=n,s}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let f=e>=a&&e<c,u=r>a&&r<=c;if(f&&u){if(e===a&&r===c){n.push(i);break}let h=e-a;n.push(i.subarray(h,h+(r-e)));break}if(f){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(r===c){n.push(i);break}n.push(i.subarray(0,r-a));break}n.push(i)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!ls(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let h=r;h<=c;h+=u){u=0;for(let m=f;m>=0;m--){let p=this.get(h+m);if(n[m]!==p){u=Math.max(1,m-a[p]);break}}if(u===0)return h}return-1}getInt8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=jn(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){let o=bt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,e)}getInt32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){let o=bt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,e)}getBigInt64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){let o=bt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,e)}getUint8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){let n=jn(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){let o=bt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,e)}getUint32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){let o=bt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,e)}getBigUint64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){let o=bt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,e)}getFloat32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){let o=bt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,e)}getFloat64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){let o=bt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof t)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!yh(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new t;return n.bufs=e,r==null&&(r=e.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}};var na={};z(na,{base10:()=>B0});var B0=Pt({prefix:"9",name:"base10",alphabet:"0123456789"});var oa={};z(oa,{base16:()=>R0,base16upper:()=>F0});var R0=he({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),F0=he({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var sa={};z(sa,{base2:()=>O0});var O0=he({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ia={};z(ia,{base256emoji:()=>k0});var wh=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),P0=wh.reduce((t,e,r)=>(t[r]=e,t),[]),N0=wh.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function U0(t){return t.reduce((e,r)=>(e+=P0[r],e),"")}function M0(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=N0[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var k0=$r({prefix:"\u{1F680}",name:"base256emoji",encode:U0,decode:M0});var aa={};z(aa,{base64:()=>K0,base64pad:()=>H0,base64url:()=>Gn,base64urlpad:()=>z0});var K0=he({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),H0=he({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Gn=he({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),z0=he({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ca={};z(ca,{base8:()=>V0});var V0=he({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var fa={};z(fa,{identity:()=>$0});var $0=$r({prefix:"\0",name:"identity",encode:t=>oh(t),decode:t=>nh(t)});var uE=new TextEncoder,hE=new TextDecoder;var la={};z(la,{sha256:()=>wt,sha512:()=>W0});var G0=20;function ha({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new ua(t,e,r,n,o)}var ua=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??G0,this.maxDigestLength=s}digest(e,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Eh(n,this.code,r?.truncate):n.then(o=>Eh(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function Eh(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return Oe(e,t)}function Ah(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var wt=ha({name:"sha2-256",code:18,encode:Ah("SHA-256")}),W0=ha({name:"sha2-512",code:19,encode:Ah("SHA-512")});var dr={...fa,...sa,...ca,...na,...oa,...Yi,...Zi,...Xi,...aa,...ia},AE={...la,...ta};function pr(t=0){return new Uint8Array(t)}function vh(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var Ch=vh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),da=vh("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=pr(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),X0={utf8:Ch,"utf-8":Ch,hex:dr.base16,latin1:da,ascii:da,binary:da,...dr},ds=X0;function ne(t,e="utf8"){let r=ds[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function X(t,e="utf8"){let r=ds[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}var Y0=parseInt("11111",2),pa=parseInt("10000000",2),Z0=parseInt("01111111",2),Lh={0:Wn,1:Wn,2:J0,3:tg,4:rg,5:eg,6:Q0,16:Wn,22:Wn,48:Wn};function Et(t,e={offset:0}){let r=t[e.offset]&Y0;if(e.offset++,Lh[r]!=null)return Lh[r](t,e);throw new Error("No decoder for tag "+r)}function Xn(t,e){let r=0;if((t[e.offset]&pa)===pa){let n=t[e.offset]&Z0,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=t[e.offset].toString(16).padStart(2,"0");r=parseInt(o,16)}else r=t[e.offset],e.offset++;return r}function Wn(t,e){Xn(t,e);let r=[];for(;!(e.offset>=t.byteLength);){let n=Et(t,e);if(n===null)break;r.push(n)}return r}function J0(t,e){let r=Xn(t,e),n=e.offset,o=e.offset+r,s=[];for(let i=n;i<o;i++)i===n&&t[i]===0||s.push(t[i]);return e.offset+=r,Uint8Array.from(s)}function Q0(t,e){let r=Xn(t,e),n=e.offset+r,o=t[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let f=t[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function eg(t,e){return e.offset++,null}function tg(t,e){let r=Xn(t,e),n=t[e.offset];e.offset++;let o=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function rg(t,e){let r=Xn(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function ng(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);let r=new V;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function ma(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);let e=ng(t.byteLength);return new V(Uint8Array.from([e.byteLength|pa]),e)}function ke(t){let e=new V,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new V(Uint8Array.from([2]),ma(e),e)}function ps(t){let e=Uint8Array.from([0]),r=new V(e,t);return new V(Uint8Array.from([3]),ma(r),r)}function Ut(t,e=48){let r=new V;for(let n of t)r.append(n);return new V(Uint8Array.from([e]),ma(r),r)}var og=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),sg=Uint8Array.from([6,5,43,129,4,0,34]),ig=Uint8Array.from([6,5,43,129,4,0,35]),ag={ext:!0,kty:"EC",crv:"P-256"},cg={ext:!0,kty:"EC",crv:"P-384"},fg={ext:!0,kty:"EC",crv:"P-521"},ga=32,ya=48,xa=66;function ba(t){let e=Et(t);return Ih(e)}function Ih(t){let e=t[1][1][0],r=1,n,o;if(e.byteLength===ga*2+1)return n=X(e.subarray(r,r+ga),"base64url"),o=X(e.subarray(r+ga),"base64url"),new Wr({...ag,key_ops:["verify"],x:n,y:o});if(e.byteLength===ya*2+1)return n=X(e.subarray(r,r+ya),"base64url"),o=X(e.subarray(r+ya),"base64url"),new Wr({...cg,key_ops:["verify"],x:n,y:o});if(e.byteLength===xa*2+1)return n=X(e.subarray(r,r+xa),"base64url"),o=X(e.subarray(r+xa),"base64url"),new Wr({...fg,key_ops:["verify"],x:n,y:o});throw new j(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function _h(t){return Ut([ke(Uint8Array.from([1])),Ut([ug(t.crv)],160),Ut([ps(new V(Uint8Array.from([4]),ne(t.x??"","base64url"),ne(t.y??"","base64url")))],161)]).subarray()}function ug(t){if(t==="P-256")return og;if(t==="P-384")return sg;if(t==="P-521")return ig;throw new j(`Invalid curve ${t}`)}var Wr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=_h(this.jwk)),this._raw}toMultihash(){return Ye.digest(Mt(this))}toCID(){return ge.createV1(114,this.toMultihash())}toString(){return le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}async verify(e,r,n){return gh(this.jwk,r,e,n)}};function wa(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function it(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(`${r}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new RangeError(`${r}expected integer >= 0, got ${t}`)}}function Le(t,e,r=""){let n=wa(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return t}function mr(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(it(t.outputLen),it(t.blockLen),t.outputLen<1)throw new Error('"outputLen" must be >= 1');if(t.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Xr(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ms(t,e){Le(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function Ze(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function gs(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Je(t,e){return t<<32-e|t>>>e}var Dh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hg=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ys(t){if(Le(t),Dh)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=hg[t[r]];return e}var St={_0:48,_9:57,A:65,F:70,a:97,f:102};function Th(t){if(t>=St._0&&t<=St._9)return t-St._0;if(t>=St.A&&t<=St.F)return t-(St.A-10);if(t>=St.a&&t<=St.f)return t-(St.a-10)}function Yn(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Dh)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=Th(t.charCodeAt(s)),a=Th(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ea(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];Le(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let s=t[n];r.set(s,o),o+=s.length}return r}function Sa(t,e={}){let r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function Bh(t=32){it(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var Aa=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Rh(t,e,r){return t&e^~t&r}function Fh(t,e,r){return t&e^t&r^e&r}var Zn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=gs(this.buffer)}update(e){Xr(this),Le(e);let{view:r,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=gs(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Xr(this),ms(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,Ze(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let h=i;h<o;h++)r[h]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=gs(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<f;h++)a.setUint32(4*h,u[h],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},At=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Ee=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var xs=BigInt(4294967295),Oh=BigInt(32);function lg(t,e=!1){return e?{h:Number(t&xs),l:Number(t>>Oh&xs)}:{h:Number(t>>Oh&xs)|0,l:Number(t&xs)|0}}function Ph(t,e=!1){let r=t.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=lg(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ca=(t,e,r)=>t>>>r,va=(t,e,r)=>t<<32-r|e>>>r,gr=(t,e,r)=>t>>>r|e<<32-r,yr=(t,e,r)=>t<<32-r|e>>>r,Jn=(t,e,r)=>t<<64-r|e>>>r-32,Qn=(t,e,r)=>t>>>r-32|e<<64-r;function at(t,e,r,n){let o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}var Nh=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Uh=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Mh=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),kh=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,Kh=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),Hh=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0;var pg=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]),kt=new Uint32Array(64),La=class extends Zn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)kt[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){let m=kt[h-15],p=kt[h-2],d=Je(m,7)^Je(m,18)^m>>>3,y=Je(p,17)^Je(p,19)^p>>>10;kt[h]=y+kt[h-7]+d+kt[h-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:u}=this;for(let h=0;h<64;h++){let m=Je(a,6)^Je(a,11)^Je(a,25),p=u+m+Rh(a,c,f)+pg[h]+kt[h]|0,y=(Je(n,2)^Je(n,13)^Je(n,22))+Fh(n,o,s)|0;u=f,f=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+y|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,f,u)}roundClean(){Ze(kt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ze(this.buffer)}},Ia=class extends La{A=At[0]|0;B=At[1]|0;C=At[2]|0;D=At[3]|0;E=At[4]|0;F=At[5]|0;G=At[6]|0;H=At[7]|0;constructor(){super(32)}};var zh=Ph(["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(t=>BigInt(t))),mg=zh[0],gg=zh[1],Kt=new Uint32Array(80),Ht=new Uint32Array(80),_a=class extends Zn{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:u,Fh:h,Fl:m,Gh:p,Gl:d,Hh:y,Hl:l}=this;return[e,r,n,o,s,i,a,c,f,u,h,m,p,d,y,l]}set(e,r,n,o,s,i,a,c,f,u,h,m,p,d,y,l){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=u|0,this.Fh=h|0,this.Fl=m|0,this.Gh=p|0,this.Gl=d|0,this.Hh=y|0,this.Hl=l|0}process(e,r){for(let v=0;v<16;v++,r+=4)Kt[v]=e.getUint32(r),Ht[v]=e.getUint32(r+=4);for(let v=16;v<80;v++){let T=Kt[v-15]|0,B=Ht[v-15]|0,R=gr(T,B,1)^gr(T,B,8)^Ca(T,B,7),D=yr(T,B,1)^yr(T,B,8)^va(T,B,7),I=Kt[v-2]|0,P=Ht[v-2]|0,M=gr(I,P,19)^Jn(I,P,61)^Ca(I,P,6),N=yr(I,P,19)^Qn(I,P,61)^va(I,P,6),x=Mh(D,N,Ht[v-7],Ht[v-16]),C=kh(x,R,M,Kt[v-7],Kt[v-16]);Kt[v]=C|0,Ht[v]=x|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:h,El:m,Fh:p,Fl:d,Gh:y,Gl:l,Hh:g,Hl:E}=this;for(let v=0;v<80;v++){let T=gr(h,m,14)^gr(h,m,18)^Jn(h,m,41),B=yr(h,m,14)^yr(h,m,18)^Qn(h,m,41),R=h&p^~h&y,D=m&d^~m&l,I=Kh(E,B,D,gg[v],Ht[v]),P=Hh(I,g,T,R,mg[v],Kt[v]),M=I|0,N=gr(n,o,28)^Jn(n,o,34)^Jn(n,o,39),x=yr(n,o,28)^Qn(n,o,34)^Qn(n,o,39),C=n&s^n&a^s&a,A=o&i^o&c^i&c;g=y|0,E=l|0,y=p|0,l=d|0,p=h|0,d=m|0,{h,l:m}=at(f|0,u|0,P|0,M|0),f=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let w=Nh(M,x,A);n=Uh(w,P,N,C),o=w|0}({h:n,l:o}=at(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=at(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=at(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=at(this.Dh|0,this.Dl|0,f|0,u|0),{h,l:m}=at(this.Eh|0,this.El|0,h|0,m|0),{h:p,l:d}=at(this.Fh|0,this.Fl|0,p|0,d|0),{h:y,l}=at(this.Gh|0,this.Gl|0,y|0,l|0),{h:g,l:E}=at(this.Hh|0,this.Hl|0,g|0,E|0),this.set(n,o,s,i,a,c,f,u,h,m,p,d,y,l,g,E)}roundClean(){Ze(Kt,Ht)}destroy(){this.destroyed=!0,Ze(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ta=class extends _a{Ah=Ee[0]|0;Al=Ee[1]|0;Bh=Ee[2]|0;Bl=Ee[3]|0;Ch=Ee[4]|0;Cl=Ee[5]|0;Dh=Ee[6]|0;Dl=Ee[7]|0;Eh=Ee[8]|0;El=Ee[9]|0;Fh=Ee[10]|0;Fl=Ee[11]|0;Gh=Ee[12]|0;Gl=Ee[13]|0;Hh=Ee[14]|0;Hl=Ee[15]|0;constructor(){super(64)}};var ct=Sa(()=>new Ia,Aa(1));var bs=Sa(()=>new Ta,Aa(3));var $=(t,e,r)=>Le(t,e,r),Ba=it,Yr=ys,ye=(...t)=>Ea(...t),Zr=t=>Yn(t),xr=wa,br=t=>Bh(t),Es=BigInt(0),Da=BigInt(1);function Qe(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new TypeError(r+"expected boolean, got type="+typeof t)}return t}function Ss(t){if(typeof t=="bigint"){if(!ws(t))throw new RangeError("positive bigint expected, got "+t)}else Ba(t);return t}function et(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(r+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let r=e&&`"${e}" `;throw new RangeError(r+"expected safe integer, got "+t)}}function eo(t){let e=Ss(t).toString(16);return e.length&1?"0"+e:e}function Vh(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Es:BigInt("0x"+t)}function wr(t){return Vh(ys(t))}function He(t){return Vh(ys(zt(Le(t)).reverse()))}function As(t,e){if(it(e),e===0)throw new RangeError("zero length");t=Ss(t);let r=t.toString(16);if(r.length>e*2)throw new RangeError("number too large");return Yn(r.padStart(e*2,"0"))}function to(t,e){return As(t,e).reverse()}function $h(t,e){if(t=$(t),e=$(e),t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function zt(t){return Uint8Array.from($(t))}function Cs(t){if(typeof t!="string")throw new TypeError("ascii string expected, got "+typeof t);return Uint8Array.from(t,(e,r)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${t[r]}" with code ${n} at position ${r}`);return n})}var ws=t=>typeof t=="bigint"&&Es<=t;function yg(t,e,r){return ws(t)&&ws(e)&&ws(r)&&e<=t&&t<r}function Ct(t,e,r,n){if(!yg(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Jr(t){if(t<Es)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>Es;t>>=Da,e+=1);return e}var ro=t=>(Da<<BigInt(t))-Da;function qh(t,e,r){if(it(t,"hashLen"),it(e,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let n=l=>new Uint8Array(l),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(t),f=n(t),u=0,h=()=>{c.fill(1),f.fill(0),u=0},m=(...l)=>r(f,ye(c,...l)),p=(l=o)=>{f=m(s,l),c=m(),l.length!==0&&(f=m(i,l),c=m())},d=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let l=0,g=[];for(;l<e;){c=m();let E=c.slice();g.push(E),l+=c.length}return ye(...g)};return(l,g)=>{h(),p(l);let E;for(;(E=g(d()))===void 0;)p();return h(),E}}function ze(t,e={},r={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(t,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=t[s];if(a&&c===void 0)return;let f=typeof c;if(f!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${f}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(r,!0)}var Ra=()=>{throw new Error("not implemented")};var Se=BigInt(0),de=BigInt(1),Er=BigInt(2),Xh=BigInt(3),Yh=BigInt(4),Zh=BigInt(5),xg=BigInt(7),Jh=BigInt(8),bg=BigInt(9),Qh=BigInt(16);function ce(t,e){if(e<=Se)throw new Error("mod: expected positive modulus, got "+e);let r=t%e;return r>=Se?r:e+r}function ie(t,e,r){if(e<Se)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >Se;)n*=n,n%=r;return n}function jh(t,e){if(t===Se)throw new Error("invert: expected non-zero number");if(e<=Se)throw new Error("invert: expected positive modulus, got "+e);let r=ce(t,e),n=e,o=Se,s=de,i=de,a=Se;for(;r!==Se;){let f=n/r,u=n-r*f,h=o-i*f,m=s-a*f;n=r,r=u,o=i,s=a,i=h,a=m}if(n!==de)throw new Error("invert: does not exist");return ce(o,e)}function Fa(t,e,r){let n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function el(t,e){let r=t,n=(r.ORDER+de)/Yh,o=r.pow(e,n);return Fa(r,o,e),o}function wg(t,e){let r=t,n=(r.ORDER-Zh)/Jh,o=r.mul(e,Er),s=r.pow(o,n),i=r.mul(e,s),a=r.mul(r.mul(i,Er),s),c=r.mul(i,r.sub(a,r.ONE));return Fa(r,c,e),c}function Eg(t){let e=Qr(t),r=tl(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+xg)/Qh;return((a,c)=>{let f=a,u=f.pow(c,i),h=f.mul(u,n),m=f.mul(u,o),p=f.mul(u,s),d=f.eql(f.sqr(h),c),y=f.eql(f.sqr(m),c);u=f.cmov(u,h,d),h=f.cmov(p,m,y);let l=f.eql(f.sqr(h),c),g=f.cmov(u,h,l);return Fa(f,g,c),g})}function tl(t){if(t<Xh)throw new Error("sqrt is not defined for small field");let e=t-de,r=0;for(;e%Er===Se;)e/=Er,r++;let n=Er,o=Qr(t);for(;Gh(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return el;let s=o.pow(n,e),i=(e+de)/Er;return function(c,f){let u=c;if(u.is0(f))return f;if(Gh(u,f)!==1)throw new Error("Cannot find square root");let h=r,m=u.mul(u.ONE,s),p=u.pow(f,e),d=u.pow(f,i);for(;!u.eql(p,u.ONE);){if(u.is0(p))return u.ZERO;let y=1,l=u.sqr(p);for(;!u.eql(l,u.ONE);)if(y++,l=u.sqr(l),y===h)throw new Error("Cannot find square root");let g=de<<BigInt(h-y-1),E=u.pow(m,g);h=y,m=u.sqr(E),p=u.mul(p,m),d=u.mul(d,E)}return d}}function Sg(t){return t%Yh===Xh?el:t%Jh===Zh?wg:t%Qh===bg?Eg(t):tl(t)}var vt=(t,e)=>(ce(t,e)&de)===de,Ag=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Oa(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=Ag.reduce((n,o)=>(n[o]="function",n),e);if(ze(t,r),et(t.BYTES,"BYTES"),et(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=de)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Cg(t,e,r){let n=t;if(r<Se)throw new Error("invalid exponent, negatives unsupported");if(r===Se)return n.ONE;if(r===de)return e;let o=n.ONE,s=e;for(;r>Se;)r&de&&(o=n.mul(o,s)),s=n.sqr(s),r>>=de;return o}function no(t,e,r=!1){let n=t,o=new Array(e.length).fill(r?n.ZERO:void 0),s=e.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),i),o}function Gh(t,e){let r=t,n=(r.ORDER-de)/Er,o=r.pow(e,n),s=r.eql(o,r.ONE),i=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function vg(t,e){if(e!==void 0&&Ba(e),t<=Se)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let r=Jr(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected bit length (${r}) >= n.length (${e})`);let n=e!==void 0?e:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Wh=new WeakMap,vs=class{ORDER;BITS;BYTES;isLE;ZERO=Se;ONE=de;_lengths;_mod;constructor(e,r={}){if(e<=de)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:o,nByteLength:s}=vg(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return ce(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Se<=e&&e<this.ORDER}is0(e){return e===Se}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&de)===de}neg(e){return ce(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return ce(e*e,this.ORDER)}add(e,r){return ce(e+r,this.ORDER)}sub(e,r){return ce(e-r,this.ORDER)}mul(e,r){return ce(e*r,this.ORDER)}pow(e,r){return Cg(this,e,r)}div(e,r){return ce(e*jh(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return jh(e,this.ORDER)}sqrt(e){let r=Wh.get(this);return r||Wh.set(this,r=Sg(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?to(e,this.BYTES):As(e,this.BYTES)}fromBytes(e,r=!1){$(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let f=new Uint8Array(o);f.set(e,s?0:f.length-e.length),e=f}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?He(e):wr(e);if(a&&(c=ce(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return no(this,e)}cmov(e,r,n){return Qe(n,"condition"),n?r:e}};Object.freeze(vs.prototype);function Qr(t,e={}){return new vs(t,e)}function rl(t){if(typeof t!="bigint")throw new Error("field order must be bigint");if(t<=de)throw new Error("field order must be greater than 1");let e=Jr(t-de);return Math.ceil(e/8)}function Pa(t){let e=rl(t);return e+Math.ceil(e/2)}function Na(t,e,r=!1){$(t);let n=t.length,o=rl(e),s=Math.max(Pa(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?He(t):wr(t),a=ce(i,e-de)+de;return r?to(a,o):As(a,o)}var en=BigInt(0),Sr=BigInt(1);function oo(t,e){let r=e.negate();return t?r:e}function Ar(t,e){let r=no(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function il(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ua(t,e){il(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),o=2**t,s=ro(t),i=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function nl(t,e,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(t&o),c=t>>i;a>n&&(a-=s,c+=Sr);let f=e*n,u=f+Math.abs(a)-1,h=a===0,m=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:m,isNegF:p,offsetF:f}}var Ma=new WeakMap,al=new WeakMap;function ka(t){return al.get(t)||1}function ol(t){if(t!==en)throw new Error("invalid wNAF")}var tn=class{BASE;ZERO;Fn;bits;constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let o=e;for(;r>en;)r&Sr&&(n=n.add(o)),o=o.double(),r>>=Sr;return n}precomputeWindow(e,r){let{windows:n,windowSize:o}=Ua(r,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let f=1;f<o;f++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Ua(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:u,isNeg:h,isNegF:m,offsetF:p}=nl(n,a,i);n=c,u?s=s.add(oo(m,r[p])):o=o.add(oo(h,r[f]))}return ol(n),{p:o,f:s}}wNAFUnsafe(e,r,n,o=this.ZERO){let s=Ua(e,this.bits);for(let i=0;i<s.windows&&n!==en;i++){let{nextN:a,offset:c,isZero:f,isNeg:u}=nl(n,i,s);if(n=a,!f){let h=r[c];o=o.add(u?h.negate():h)}}return ol(n),o}getPrecomputes(e,r,n){let o=Ma.get(r);return o||(o=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(o=n(o)),Ma.set(r,o))),o}cached(e,r,n){let o=ka(e);return this.wNAF(o,this.getPrecomputes(o,e,n),r)}unsafe(e,r,n,o){let s=ka(e);return s===1?this._unsafeLadder(e,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,o)}createCache(e,r){il(r,this.bits),al.set(e,r),Ma.delete(e)}hasCache(e){return ka(e)!==1}};function cl(t,e,r,n){let o=e,s=t.ZERO,i=t.ZERO;for(;r>en||n>en;)r&Sr&&(s=s.add(o)),n&Sr&&(i=i.add(o)),o=o.double(),r>>=Sr,n>>=Sr;return{p1:s,p2:i}}function sl(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Oa(e),e}else return Qr(t,{isLE:r})}function Ls(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let f=e[c];if(!(typeof f=="bigint"&&f>en))throw new Error(`CURVE.${c} must be positive bigint`)}let o=sl(e.p,r.Fp,n),s=sl(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function rn(t,e){return function(n){let o=t(n);return{secretKey:o,publicKey:e(o)}}}var Vt=BigInt(0),be=BigInt(1),Ka=BigInt(2),Lg=BigInt(8);function Ig(t,e,r,n){let o=t.sqr(r),s=t.sqr(n),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function fl(t,e={}){let r=e,n=Ls("edwards",t,r,r.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;ze(r,{},{uvRatio:"function"});let c=Ka<<BigInt(s.BYTES*8)-be,f=y=>o.create(y),u=r.uvRatio===void 0?(y,l)=>{try{return{isValid:!0,value:o.sqrt(o.div(y,l))}}catch{return{isValid:!1,value:Vt}}}:r.uvRatio;if(!Ig(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function h(y,l,g=!1){let E=g?be:Vt;return Ct("coordinate "+y,l,E,c),l}function m(y){if(!(y instanceof p))throw new Error("EdwardsPoint expected")}class p{static BASE=new p(i.Gx,i.Gy,be,f(i.Gx*i.Gy));static ZERO=new p(Vt,be,be,Vt);static Fp=o;static Fn=s;X;Y;Z;T;constructor(l,g,E,v){this.X=h("x",l),this.Y=h("y",g),this.Z=h("z",E,!0),this.T=h("t",v),Object.freeze(this)}static CURVE(){return i}static fromAffine(l){if(l instanceof p)throw new Error("extended point not allowed");let{x:g,y:E}=l||{};return h("x",g),h("y",E),new p(g,E,be,f(g*E))}static fromBytes(l,g=!1){let E=o.BYTES,{a:v,d:T}=i;l=zt($(l,E,"point")),Qe(g,"zip215");let B=zt(l),R=l[E-1];B[E-1]=R&-129;let D=He(B),I=g?c:o.ORDER;Ct("point.y",D,Vt,I);let P=f(D*D),M=f(P-be),N=f(T*P-v),{isValid:x,value:C}=u(M,N);if(!x)throw new Error("bad point: invalid y coordinate");let A=(C&be)===be,w=(R&128)!==0;if(!g&&C===Vt&&w)throw new Error("bad point: x=0 and x_0=1");return w!==A&&(C=f(-C)),p.fromAffine({x:C,y:D})}static fromHex(l,g=!1){return p.fromBytes(Zr(l),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(l=8,g=!0){return d.createCache(this,l),g||this.multiply(Ka),this}assertValidity(){let l=this,{a:g,d:E}=i;if(l.is0())throw new Error("bad point: ZERO");let{X:v,Y:T,Z:B,T:R}=l,D=f(v*v),I=f(T*T),P=f(B*B),M=f(P*P),N=f(D*g),x=f(P*f(N+I)),C=f(M+f(E*f(D*I)));if(x!==C)throw new Error("bad point: equation left != right (1)");let A=f(v*T),w=f(B*R);if(A!==w)throw new Error("bad point: equation left != right (2)")}equals(l){m(l);let{X:g,Y:E,Z:v}=this,{X:T,Y:B,Z:R}=l,D=f(g*R),I=f(T*v),P=f(E*R),M=f(B*v);return D===I&&P===M}is0(){return this.equals(p.ZERO)}negate(){return new p(f(-this.X),this.Y,this.Z,f(-this.T))}double(){let{a:l}=i,{X:g,Y:E,Z:v}=this,T=f(g*g),B=f(E*E),R=f(Ka*f(v*v)),D=f(l*T),I=g+E,P=f(f(I*I)-T-B),M=D+B,N=M-R,x=D-B,C=f(P*N),A=f(M*x),w=f(P*x),b=f(N*M);return new p(C,A,b,w)}add(l){m(l);let{a:g,d:E}=i,{X:v,Y:T,Z:B,T:R}=this,{X:D,Y:I,Z:P,T:M}=l,N=f(v*D),x=f(T*I),C=f(R*E*M),A=f(B*P),w=f((v+T)*(D+I)-N-x),b=A-C,L=A+C,_=f(x-g*N),S=f(w*b),F=f(L*_),O=f(w*_),U=f(b*L);return new p(S,F,U,O)}subtract(l){return m(l),this.add(l.negate())}multiply(l){if(!s.isValidNot0(l))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:g,f:E}=d.cached(this,l,v=>Ar(p,v));return Ar(p,[g,E])[0]}multiplyUnsafe(l){if(!s.isValid(l))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return l===Vt?p.ZERO:this.is0()||l===be?this:d.unsafe(this,l,g=>Ar(p,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return d.unsafe(this,i.n).is0()}toAffine(l){let g=this,E=l,{X:v,Y:T,Z:B}=g,R=g.is0();E==null&&(E=R?Lg:o.inv(B));let D=f(v*E),I=f(T*E),P=o.mul(B,E);if(R)return{x:Vt,y:be};if(P!==be)throw new Error("invZ was invalid");return{x:D,y:I}}clearCofactor(){return a===be?this:this.multiplyUnsafe(a)}toBytes(){let{x:l,y:g}=this.toAffine(),E=o.toBytes(g);return E[E.length-1]|=l&be?128:0,E}toHex(){return Yr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let d=new tn(p,s.BITS);return s.BITS>=8&&p.BASE.precompute(8),Object.freeze(p.prototype),Object.freeze(p),p}var Is=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Ra()}static fromHex(e){Ra()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Yr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,r){return this.ep.precompute(e,r),this}};function ul(t,e,r={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=r;ze(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=t,f=n.outputLen,u=2*a.BYTES;if(f!==void 0&&(et(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let h=o.randomBytes===void 0?br:o.randomBytes,m=o.adjustScalarBytes===void 0?x=>x:o.adjustScalarBytes,p=o.domain===void 0?(x,C,A)=>{if(Qe(A,"phflag"),C.length||A)throw new Error("Contexts/pre-hash are not supported");return x}:o.domain;function d(x){return c.create(He(x))}function y(x){let C=D.secretKey;$(x,D.secretKey,"secretKey");let A=$(n(x),2*C,"hashedSecretKey"),w=m(A.slice(0,C)),b=A.slice(C,2*C),L=d(w);return{head:w,prefix:b,scalar:L}}function l(x){let{head:C,prefix:A,scalar:w}=y(x),b=i.multiply(w),L=b.toBytes();return{head:C,prefix:A,scalar:w,point:b,pointBytes:L}}function g(x){return l(x).pointBytes}function E(x=Uint8Array.of(),...C){let A=ye(...C);return d(n(p(A,$(x,void 0,"context"),!!s)))}function v(x,C,A={}){x=$(x,void 0,"message"),s&&(x=s(x));let{prefix:w,scalar:b,pointBytes:L}=l(C),_=E(A.context,w,x),S=i.multiply(_).toBytes(),F=E(A.context,S,L,x),O=c.create(_+F*b);if(!c.isValid(O))throw new Error("sign failed: invalid s");let U=ye(S,c.toBytes(O));return $(U,D.signature,"result")}let T={zip215:o.zip215};function B(x,C,A,w=T){let{context:b}=w,L=w.zip215===void 0?!!T.zip215:w.zip215,_=D.signature;x=$(x,_,"signature"),C=$(C,void 0,"message"),A=$(A,D.publicKey,"publicKey"),L!==void 0&&Qe(L,"zip215"),s&&(C=s(C));let S=_/2,F=x.subarray(0,S),O=He(x.subarray(S,_)),U,H,K;try{U=t.fromBytes(A,L),H=t.fromBytes(F,L),K=i.multiplyUnsafe(O)}catch{return!1}if(!L&&U.isSmallOrder())return!1;let ee=E(b,F,A,C);return H.add(U.multiplyUnsafe(ee)).subtract(K).clearCofactor().is0()}let R=a.BYTES,D={secretKey:R,publicKey:R,signature:2*R,seed:R};function I(x){return x=x===void 0?h(D.seed):x,$(x,D.seed,"seed")}function P(x){return xr(x)&&x.length===D.secretKey}function M(x,C){try{return!!t.fromBytes(x,C===void 0?T.zip215:C)}catch{return!1}}let N={getExtendedPublicKey:l,randomSecretKey:I,isValidSecretKey:P,isValidPublicKey:M,toMontgomery(x){let{y:C}=t.fromBytes(x),A=D.publicKey,w=A===32;if(!w&&A!==57)throw new Error("only defined for 25519 and 448");let b=w?a.div(be+C,be-C):a.div(C-be,C+be);return a.toBytes(b)},toMontgomerySecret(x){let C=D.secretKey;$(x,C);let A=n(x.subarray(0,C));return m(A).subarray(0,C)}};return Object.freeze(D),Object.freeze(N),Object.freeze({keygen:rn(I,g),getPublicKey:g,sign:v,verify:B,utils:N,Point:t,lengths:D})}function so(t,e){if(et(t),et(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(t<0||t>2**(8*e)-1)throw new Error("invalid I2OSP input: "+t);let r=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)r[n]=t&255,t>>>=8;return new Uint8Array(r)}function _g(t,e){let r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t[n]^e[n];return r}function Tg(t){if(!xr(t)&&typeof t!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof t=="string"?Cs(t):t;if(e.length===0)throw new Error("DST must be non-empty");return e}function Ha(t,e,r,n){$(t),et(r),e=Tg(e),e.length>255&&(e=n(ye(Cs("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(r/o);if(r>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=ye(e,so(e.length,1)),c=new Uint8Array(s),f=so(r,2),u=new Array(i),h=n(ye(c,t,f,so(0,1),a));u[0]=n(ye(h,so(1,1),a));for(let p=1;p<i;p++){let d=[_g(h,u[p-1]),so(p+1,1),a];u[p]=n(ye(...d))}return ye(...u).slice(0,r)}var hl="HashToScalar-";var io=BigInt(0),nn=BigInt(1),_s=BigInt(2);function Dg(t){return ze(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...t})}function ll(t){let e=Dg(t),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i===void 0?br:i,f=a?255:448,u=a?32:56,h=BigInt(a?9:5),m=BigInt(a?121665:39081),p=a?_s**BigInt(254):_s**BigInt(447),d=a?BigInt(8)*_s**BigInt(251)-nn:BigInt(4)*_s**BigInt(445)-nn,y=p+d+nn,l=A=>ce(A,r),g=E(h);function E(A){return to(l(A),u)}function v(A){let w=zt($(A,u,"uCoordinate"));return a&&(w[31]&=127),l(He(w))}function T(A){return He(o(zt($(A,u,"scalar"))))}function B(A,w){let b=M(v(w),T(A));if(b===io)throw new Error("invalid private or public key received");return E(b)}function R(A){return B(A,g)}let D=R,I=B;function P(A,w,b){let L=l(A*(w-b));return w=l(w-L),b=l(b+L),{x_2:w,x_3:b}}function M(A,w){Ct("u",A,io,r),Ct("scalar",w,p,y);let b=w,L=A,_=nn,S=io,F=A,O=nn,U=io;for(let K=BigInt(f-1);K>=io;K--){let ee=b>>K&nn;U^=ee,{x_2:_,x_3:F}=P(U,_,F),{x_2:S,x_3:O}=P(U,S,O),U=ee;let te=_+S,re=l(te*te),W=_-S,ae=l(W*W),yt=re-ae,fr=F+O,kr=F-O,kn=l(kr*te),Kn=l(fr*W),Ju=kn+Kn,Qu=kn-Kn;F=l(Ju*Ju),O=l(L*l(Qu*Qu)),_=l(re*ae),S=l(yt*(re+l(m*yt)))}({x_2:_,x_3:F}=P(U,_,F)),{x_2:S,x_3:O}=P(U,S,O);let H=s(S);return l(_*H)}let N={secretKey:u,publicKey:u,seed:u},x=A=>(A=A===void 0?c(u):A,$(A,N.seed,"seed"),A),C={randomSecretKey:x};return Object.freeze(N),Object.freeze(C),Object.freeze({keygen:rn(x,D),getSharedSecret:I,getPublicKey:D,scalarMult:B,scalarMultBase:R,utils:C,GuBytes:g.slice(),lengths:N})}var Bg=BigInt(0),Lt=BigInt(1),dl=BigInt(2),Rg=BigInt(3),Fg=BigInt(5),Og=BigInt(8),Cr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),qa={p:Cr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Og,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function gl(t){let e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=Cr,a=t*t%s*t%s,c=ie(a,dl,s)*a%s,f=ie(c,Lt,s)*t%s,u=ie(f,Fg,s)*f%s,h=ie(u,e,s)*u%s,m=ie(h,r,s)*h%s,p=ie(m,n,s)*m%s,d=ie(p,o,s)*p%s,y=ie(d,o,s)*p%s,l=ie(y,e,s)*u%s;return{pow_p_5_8:ie(l,dl,s)*t%s,b2:a}}function yl(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var za=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ja(t,e){let r=Cr,n=ce(e*e*e,r),o=ce(n*n*e,r),s=gl(t*o).pow_p_5_8,i=ce(t*n*s,r),a=ce(e*i*i,r),c=i,f=ce(i*za,r),u=a===t,h=a===ce(-t,r),m=a===ce(-t*za,r);return u&&(i=c),(h||m)&&(i=f),vt(i,r)&&(i=ce(-i,r)),{isValid:u||h,value:i}}var qt=fl(qa,{uvRatio:ja}),$t=qt.Fp,xl=qt.Fn;function Pg(t){return ul(qt,bs,Object.assign({adjustScalarBytes:yl,zip215:!0},t))}var bl=Pg({});var ao=(()=>{let t=Cr;return ll({P:t,type:"x25519",powPminus2:e=>{let{pow_p_5_8:r,b2:n}=gl(e);return ce(ie(r,Rg,t)*n,t)},adjustScalarBytes:yl})})();var Va=za,Ng=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Ug=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Mg=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),kg=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),pl=t=>ja(Lt,t),Kg=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),$a=t=>$t.create(He(t)&Kg);function ml(t){let{d:e}=qa,r=Cr,n=g=>$t.create(g),o=n(Va*t*t),s=n((o+Lt)*Mg),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:f}=ja(s,a),u=n(f*t);vt(u,r)||(u=n(-u)),c||(f=u),c||(i=o);let h=n(i*(o-Lt)*kg-a),m=f*f,p=n((f+f)*a),d=n(h*Ng),y=n(Lt-m),l=n(Lt+m);return new qt(n(p*l),n(y*d),n(d*l),n(p*y))}var jt=class t extends Is{static BASE=new t(qt.BASE);static ZERO=new t(qt.ZERO);static Fp=$t;static Fn=xl;constructor(e){super(e)}static fromAffine(e){return new t(qt.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoPoint expected")}init(e){return new t(e)}static fromBytes(e){Le(e,32);let{a:r,d:n}=qa,o=Cr,s=T=>$t.create(T),i=$a(e);if(!$h($t.toBytes(i),e)||vt(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Lt+r*a),f=s(Lt-r*a),u=s(c*c),h=s(f*f),m=s(r*n*u-h),{isValid:p,value:d}=pl(s(m*h)),y=s(d*f),l=s(d*y*m),g=s((i+i)*y);vt(g,o)&&(g=s(-g));let E=s(c*l),v=s(g*E);if(!p||vt(v,o)||E===Bg)throw new Error("invalid ristretto255 encoding 2");return new t(new qt(g,E,Lt,v))}static fromHex(e){return t.fromBytes(Yn(e))}toBytes(){let{X:e,Y:r,Z:n,T:o}=this.ep,s=Cr,i=l=>$t.create(l),a=i(i(n+r)*i(n-r)),c=i(e*r),f=i(c*c),{value:u}=pl(i(a*f)),h=i(u*a),m=i(u*c),p=i(h*m*o),d;if(vt(o*p,s)){let l=i(r*Va),g=i(e*Va);e=l,r=g,d=i(h*Ug)}else d=m;vt(e*p,s)&&(r=i(-r));let y=i((n-r)*d);return vt(y,s)&&(y=i(-y)),$t.toBytes(y)}equals(e){this.assertSame(e);let{X:r,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=f=>$t.create(f),a=i(r*s)===i(n*o),c=i(n*s)===i(r*o);return a||c}is0(){return this.equals(t.ZERO)}};Object.freeze(jt.BASE);Object.freeze(jt.ZERO);Object.freeze(jt.prototype);Object.freeze(jt);var Hg=Object.freeze({Point:jt,hashToCurve(t,e){let r=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=Ha(t,r,64,bs);return Hg.deriveToCurve(n)},hashToScalar(t,e={DST:hl}){let r=Ha(t,e.DST,64,bs);return xl.create(He(r))},deriveToCurve(t){Le(t,64);let e=$a(t.subarray(0,32)),r=ml(e),n=$a(t.subarray(32,64)),o=ml(n);return new jt(r.add(o))}});var co=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Ts=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ge={get(t=globalThis){let e=t.crypto;if(e?.subtle==null)throw new Ts("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 e}};var Ds=32;var Ga,zg=(async()=>{try{return await Ge.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Vg(t,e,r){if(t.buffer instanceof ArrayBuffer){let n=await Ge.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await Ge.get().subtle.verify({name:"Ed25519"},n,Ne(e),Ne(r instanceof Uint8Array?r:r.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function $g(t,e,r){return bl.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function wl(t,e,r){return Ga==null&&(Ga=await zg),Ga?Vg(t,e,r):$g(t,e,r)}function qg(t){return t?.buffer instanceof ArrayBuffer}function Wa(t){if(qg(t))return t;let e=t.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function ft(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=pr(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return Wa(r)}function Bs(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var Rs=class{type="Ed25519";raw;constructor(e){this.raw=Xa(e,Ds)}toMultihash(){return Ye.digest(Mt(this))}toCID(){return ge.createV1(114,this.toMultihash())}toString(){return le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();let o=wl(this.raw,r,e);return Bs(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Ya(t){return t=Xa(t,Ds),new Rs(t)}function Xa(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new j(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}function Gt(t=0){return new Uint8Array(t)}var Gg=Math.pow(2,7),Wg=Math.pow(2,14),Xg=Math.pow(2,21),Sl=Math.pow(2,28),Al=Math.pow(2,35),Cl=Math.pow(2,42),vl=Math.pow(2,49),Ue=128,Wt=127;function fo(t){if(t<Gg)return 1;if(t<Wg)return 2;if(t<Xg)return 3;if(t<Sl)return 4;if(t<Al)return 5;if(t<Cl)return 6;if(t<vl)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ll(t,e,r=0){switch(fo(t)){case 8:e[r++]=t&255|Ue,t/=128;case 7:e[r++]=t&255|Ue,t/=128;case 6:e[r++]=t&255|Ue,t/=128;case 5:e[r++]=t&255|Ue,t/=128;case 4:e[r++]=t&255|Ue,t>>>=7;case 3:e[r++]=t&255|Ue,t>>>=7;case 2:e[r++]=t&255|Ue,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Il(t,e){let r=t[e],n=0;if(n+=r&Wt,r<Ue||(r=t[e+1],n+=(r&Wt)<<7,r<Ue)||(r=t[e+2],n+=(r&Wt)<<14,r<Ue)||(r=t[e+3],n+=(r&Wt)<<21,r<Ue)||(r=t[e+4],n+=(r&Wt)*Sl,r<Ue)||(r=t[e+5],n+=(r&Wt)*Al,r<Ue)||(r=t[e+6],n+=(r&Wt)*Cl,r<Ue)||(r=t[e+7],n+=(r&Wt)*vl,r<Ue))return n;throw new RangeError("Could not decode varint")}var Za=new Float32Array([-0]),Xt=new Uint8Array(Za.buffer);function _l(t,e,r){Za[0]=t,e[r]=Xt[0],e[r+1]=Xt[1],e[r+2]=Xt[2],e[r+3]=Xt[3]}function Tl(t,e){return Xt[0]=t[e],Xt[1]=t[e+1],Xt[2]=t[e+2],Xt[3]=t[e+3],Za[0]}var Ja=new Float64Array([-0]),Ie=new Uint8Array(Ja.buffer);function Dl(t,e,r){Ja[0]=t,e[r]=Ie[0],e[r+1]=Ie[1],e[r+2]=Ie[2],e[r+3]=Ie[3],e[r+4]=Ie[4],e[r+5]=Ie[5],e[r+6]=Ie[6],e[r+7]=Ie[7]}function Bl(t,e){return Ie[0]=t[e],Ie[1]=t[e+1],Ie[2]=t[e+2],Ie[3]=t[e+3],Ie[4]=t[e+4],Ie[5]=t[e+5],Ie[6]=t[e+6],Ie[7]=t[e+7],Ja[0]}var Yg=BigInt(Number.MAX_SAFE_INTEGER),Zg=BigInt(Number.MIN_SAFE_INTEGER),Ve=class t{lo;hi;constructor(e,r){this.lo=e|0,this.hi=r|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return vr;if(e<Yg&&e>Zg)return this.fromNumber(Number(e));let r=e<0n;r&&(e=-e);let n=e>>32n,o=e-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>Rl&&(o=0n,++n>Rl&&(n=0n))),new t(Number(o),Number(n))}static fromNumber(e){if(e===0)return vr;let r=e<0;r&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new t(n,o)}static from(e){return typeof e=="number"?t.fromNumber(e):typeof e=="bigint"?t.fromBigInt(e):typeof e=="string"?t.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new t(e.low>>>0,e.high>>>0):vr}},vr=new Ve(0,0);vr.toBigInt=function(){return 0n};vr.zzEncode=vr.zzDecode=function(){return this};vr.length=function(){return 1};var Rl=4294967296n;function Fl(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(r&64512)===55296&&(t.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Ol(t,e,r){if(r-e<1)return"";let o,s=[],i=0,a;for(;e<r;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Qa(t,e,r){let n=r,o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128);return r-n}function tt(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function Fs(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}var ec=class{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=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,tt(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw tt(this,4);return Fs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw tt(this,4);return Fs(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw tt(this,4);let e=Tl(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw tt(this,4);let e=Bl(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw tt(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let e=this.bytes();return Ol(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw tt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw tt(this);while((this.buf[this.pos++]&128)!==0);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(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Ve(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw tt(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,e}if(this.len-this.pos>4){for(;r<5;++r)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;r<5;++r){if(this.pos>=this.len)throw tt(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw tt(this,8);let e=Fs(this.buf,this.pos+=4),r=Fs(this.buf,this.pos+=4);return new Ve(e,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Il(this.buf,this.pos);return this.pos+=fo(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 uo(t){return new ec(t instanceof Uint8Array?t:t.subarray())}function Yt(t,e,r){let n=uo(t);return e.decode(n,void 0,r)}var sc={};z(sc,{base10:()=>oy});var w6=new Uint8Array(0);function Nl(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function It(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function Ul(t){return new TextEncoder().encode(t)}function Ml(t){return new TextDecoder().decode(t)}function Jg(t,e){if(t.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 o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=t.length,c=t.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,l=0,g=0,E=d.length;g!==E&&d[g]===0;)g++,y++;for(var v=(E-g)*u+1>>>0,T=new Uint8Array(v);g!==E;){for(var B=d[g],R=0,D=v-1;(B!==0||R<l)&&D!==-1;D--,R++)B+=256*T[D]>>>0,T[D]=B%a>>>0,B=B/a>>>0;if(B!==0)throw new Error("Non-zero carry");l=R,g++}for(var I=v-l;I!==v&&T[I]===0;)I++;for(var P=c.repeat(y);I<v;++I)P+=t.charAt(T[I]);return P}function m(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var l=0,g=0;d[y]===c;)l++,y++;for(var E=(d.length-y)*f+1>>>0,v=new Uint8Array(E);d[y];){var T=r[d.charCodeAt(y)];if(T===255)return;for(var B=0,R=E-1;(T!==0||B<g)&&R!==-1;R--,B++)T+=a*v[R]>>>0,v[R]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");g=B,y++}if(d[y]!==" "){for(var D=E-g;D!==E&&v[D]===0;)D++;for(var I=new Uint8Array(l+(E-D)),P=l;D!==E;)I[P++]=v[D++];return I}}}function p(d){var y=m(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:m,decode:p}}var Qg=Jg,ey=Qg,Kl=ey;var tc=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},rc=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){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))}else throw Error("Can only multibase decode strings")}or(e){return Hl(this,e)}},nc=class{decoders;constructor(e){this.decoders=e}or(e){return Hl(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Hl(t,e){return new nc({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var oc=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new tc(e,r,n),this.decoder=new rc(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function on({name:t,prefix:e,encode:r,decode:n}){return new oc(t,e,r,n)}function Zt({name:t,prefix:e,alphabet:r}){let{encode:n,decode:o}=Kl(r,t);return on({prefix:e,name:t,encode:n,decode:s=>It(o(s))})}function ty(t,e,r,n){let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[t[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|u,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function ry(t,e,r){let n=e[e.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function ny(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function pe({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let o=ny(n);return on({prefix:e,name:t,encode(s){return ry(s,n,r)},decode(s){return ty(s,o,r,t)}})}var oy=Zt({prefix:"9",name:"base10",alphabet:"0123456789"});var ic={};z(ic,{base16:()=>sy,base16upper:()=>iy});var sy=pe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),iy=pe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ac={};z(ac,{base2:()=>ay});var ay=pe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var cc={};z(cc,{base256emoji:()=>ly});var zl=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),cy=zl.reduce((t,e,r)=>(t[r]=e,t),[]),fy=zl.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function uy(t){return t.reduce((e,r)=>(e+=cy[r],e),"")}function hy(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=fy[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var ly=on({prefix:"\u{1F680}",name:"base256emoji",encode:uy,decode:hy});var fc={};z(fc,{base32:()=>sn,base32hex:()=>gy,base32hexpad:()=>xy,base32hexpadupper:()=>by,base32hexupper:()=>yy,base32pad:()=>py,base32padupper:()=>my,base32upper:()=>dy,base32z:()=>wy});var sn=pe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),dy=pe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),py=pe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),my=pe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),gy=pe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),yy=pe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),xy=pe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),by=pe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),wy=pe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var uc={};z(uc,{base36:()=>ho,base36upper:()=>Ey});var ho=Zt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ey=Zt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var hc={};z(hc,{base58btc:()=>ut,base58flickr:()=>Sy});var ut=Zt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Sy=Zt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var lc={};z(lc,{base64:()=>Ay,base64pad:()=>Cy,base64url:()=>vy,base64urlpad:()=>Ly});var Ay=pe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Cy=pe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),vy=pe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ly=pe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var dc={};z(dc,{base8:()=>Iy});var Iy=pe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var pc={};z(pc,{identity:()=>_y});var _y=on({prefix:"\0",name:"identity",encode:t=>Ml(t),decode:t=>Ul(t)});var N6=new TextEncoder,U6=new TextDecoder;var gc={};z(gc,{identity:()=>Zy});var By=ql,Vl=128,Ry=127,Fy=~Ry,Oy=Math.pow(2,31);function ql(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Oy;)e[r++]=t&255|Vl,t/=128;for(;t&Fy;)e[r++]=t&255|Vl,t>>>=7;return e[r]=t|0,ql.bytes=r-n+1,e}var Py=mc,Ny=128,$l=127;function mc(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw mc.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&$l)<<o:(i&$l)*Math.pow(2,o),o+=7}while(i>=Ny);return mc.bytes=s-n,r}var Uy=Math.pow(2,7),My=Math.pow(2,14),ky=Math.pow(2,21),Ky=Math.pow(2,28),Hy=Math.pow(2,35),zy=Math.pow(2,42),Vy=Math.pow(2,49),$y=Math.pow(2,56),qy=Math.pow(2,63),jy=function(t){return t<Uy?1:t<My?2:t<ky?3:t<Ky?4:t<Hy?5:t<zy?6:t<Vy?7:t<$y?8:t<qy?9:10},Gy={encode:By,decode:Py,encodingLength:jy},Wy=Gy,lo=Wy;function po(t,e=0){return[lo.decode(t,e),lo.decode.bytes]}function an(t,e,r=0){return lo.encode(t,e,r),e}function cn(t){return lo.encodingLength(t)}function un(t,e){let r=e.byteLength,n=cn(t),o=n+cn(r),s=new Uint8Array(o+r);return an(t,s,0),an(r,s,n),s.set(e,o),new fn(t,r,e,s)}function jl(t){let e=It(t),[r,n]=po(e),[o,s]=po(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new fn(r,o,i,e)}function Gl(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Nl(t.bytes,r.bytes)}}var fn=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};var Wl=0,Xy="identity",Xl=It;function Yy(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return un(Wl,Xl(t))}var Zy={code:Wl,name:Xy,encode:Xl,digest:Yy};var bc={};z(bc,{sha256:()=>Qy,sha512:()=>ex});var Jy=20;function xc({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new yc(t,e,r,n,o)}var yc=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??Jy,this.maxDigestLength=s}digest(e,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Yl(n,this.code,r?.truncate):n.then(o=>Yl(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function Yl(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return un(e,t)}function Jl(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var Qy=xc({name:"sha2-256",code:18,encode:Jl("SHA-256")}),ex=xc({name:"sha2-512",code:19,encode:Jl("SHA-512")});function Ql(t,e){let{bytes:r,version:n}=t;return n===0?rx(r,wc(t),e??ut.encoder):nx(r,wc(t),e??sn.encoder)}var ed=new WeakMap;function wc(t){let e=ed.get(t);if(e==null){let r=new Map;return ed.set(t,r),r}return e}var Ps=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}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:{let{code:e,multihash:r}=this;if(e!==go)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==ox)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}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:{let{code:e,digest:r}=this.multihash,n=un(e,r);return t.createV1(this.code,n)}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 t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&Gl(e.multihash,n.multihash)}toString(e){return Ql(this,e)}toJSON(){return{"/":Ql(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new t(n,o,s,i??td(n,o,s.bytes))}else if(r[sx]===!0){let{version:n,multihash:o,code:s}=r,i=jl(o);return t.create(n,s,i)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==go)throw new Error(`Version 0 CID must use dag-pb (code: ${go}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=td(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,go,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=It(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new fn(r.multihashCode,r.digestSize,s,o);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[h,m]=po(e.subarray(r));return r+=m,h},o=n(),s=go;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),f=r+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,r){let[n,o]=tx(e,r),s=t.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return wc(s).set(n,e),s}};function tx(t,e){switch(t[0]){case"Q":{let r=e??ut;return[ut.prefix,r.decode(`${ut.prefix}${t}`)]}case ut.prefix:{let r=e??ut;return[ut.prefix,r.decode(t)]}case sn.prefix:{let r=e??sn;return[sn.prefix,r.decode(t)]}case ho.prefix:{let r=e??ho;return[ho.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function rx(t,e,r){let{prefix:n}=r;if(n!==ut.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function nx(t,e,r){let{prefix:n}=r,o=e.get(n);if(o==null){let s=r.encode(t);return e.set(n,s),s}else return o}var go=112,ox=18;function td(t,e,r){let n=cn(t),o=n+cn(e),s=new Uint8Array(o+r.byteLength);return an(t,s,0),an(e,s,n),s.set(r,o),s}var sx=Symbol.for("@ipld/js-cid/CID");var Ec={...pc,...ac,...dc,...sc,...ic,...fc,...uc,...hc,...lc,...cc},s8={...bc,...gc};function nd(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var rd=nd("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Sc=nd("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=Gt(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),ix={utf8:rd,"utf-8":rd,hex:Ec.base16,latin1:Sc,ascii:Sc,binary:Sc,...Ec},od=ix;function sd(t,e="utf8"){let r=od[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function Ac(t){let e=t??8192,r=e>>>1,n,o=e;return function(i){if(i<1||i>r)return Gt(i);o+i>e&&(n=Gt(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Lr=class{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}};function Cc(){}var Lc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},ax=Ac();function cx(t){return globalThis.Buffer!=null?Gt(t):ax(t)}var xo=class{len;head;tail;states;constructor(){this.len=0,this.head=new Lr(Cc,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new Lr(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ic((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Ns,10,Ve.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let r=Ve.fromBigInt(e);return this._push(Ns,r.length(),r)}uint64Number(e){return this._push(Ll,fo(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){let r=Ve.fromBigInt(e).zzEncode();return this._push(Ns,r.length(),r)}sint64Number(e){let r=Ve.fromNumber(e).zzEncode();return this._push(Ns,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(vc,1,e?1:0)}fixed32(e){return this._push(yo,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let r=Ve.fromBigInt(e);return this._push(yo,4,r.lo)._push(yo,4,r.hi)}fixed64Number(e){let r=Ve.fromNumber(e);return this._push(yo,4,r.lo)._push(yo,4,r.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(_l,4,e)}double(e){return this._push(Dl,8,e)}bytes(e){let r=e.length>>>0;return r===0?this._push(vc,1,0):this.uint32(r)._push(ux,r,e)}string(e){let r=Fl(e);return r!==0?this.uint32(r)._push(Qa,r,e):this._push(vc,1,0)}fork(){return this.states=new Lc(this),this.head=this.tail=new Lr(Cc,0,0),this.len=0,this}reset(){return this.states!=null?(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 Lr(Cc,0,0),this.len=0),this}ldelim(){let e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next,r=cx(this.len),n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}};function vc(t,e,r){e[r]=t&255}function fx(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}var Ic=class extends Lr{next;constructor(e,r){super(fx,e,r),this.next=void 0}};function Ns(t,e,r){for(;t.hi!==0;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}function yo(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function ux(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(xo.prototype.bytes=function(t){let e=t.length>>>0;return this.uint32(e),e>0&&this._push(hx,e,t),this},xo.prototype.string=function(t){let e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(lx,e,t),this});function hx(t,e,r){e.set(t,r)}function lx(t,e,r){t.length<40?Qa(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(sd(t),r)}function _c(){return new xo}function Jt(t,e){let r=_c();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}function*Qt(t,e,r){let n=uo(t);yield*e.stream(n,void 0,"$",r)}var Us={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Ms(t,e,r,n,o){return{name:t,type:e,encode:r,decode:n,stream:o}}function Ir(t){function e(s){if(t[s.toString()]==null)throw new Error("Invalid enum value");return t[s]}let r=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return Ms("enum",Us.VARINT,r,n,o)}function er(t,e,r){return Ms("message",Us.LENGTH_DELIMITED,t,e,r)}var fe;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(fe||(fe={}));var Tc;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(Tc||(Tc={}));(function(t){t.codec=()=>Ir(Tc)})(fe||(fe={}));var ht;(function(t){let e;t.codec=()=>(e==null&&(e=er((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),fe.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=fe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:fe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function r(s){return Jt(s,t.codec())}t.encode=r;function n(s,i){return Yt(s,t.codec(),i)}t.decode=n;function o(s,i){return Qt(s,t.codec(),i)}t.stream=o})(ht||(ht={}));var Dc;(function(t){let e;t.codec=()=>(e==null&&(e=er((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),fe.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=fe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:fe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function r(s){return Jt(s,t.codec())}t.encode=r;function n(s,i){return Yt(s,t.codec(),i)}t.decode=n;function o(s,i){return Qt(s,t.codec(),i)}t.stream=o})(Dc||(Dc={}));var wo={};z(wo,{MAX_RSA_KEY_SIZE:()=>Bc,generateRSAKeyPair:()=>ud,jwkToJWKKeyPair:()=>hd,jwkToPkcs1:()=>gx,jwkToPkix:()=>Pc,jwkToRSAPrivateKey:()=>kc,pkcs1MessageToJwk:()=>Fc,pkcs1MessageToRSAPrivateKey:()=>Nc,pkcs1ToJwk:()=>mx,pkcs1ToRSAPrivateKey:()=>fd,pkixMessageToJwk:()=>Oc,pkixMessageToRSAPublicKey:()=>Mc,pkixToJwk:()=>yx,pkixToRSAPublicKey:()=>Uc});var hn=class{type="RSA";jwk;_raw;_multihash;constructor(e,r){this.jwk=e,this._multihash=r}get raw(){return this._raw==null&&(this._raw=wo.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ge.createV1(114,this._multihash)}toString(){return le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}verify(e,r,n){return cd(this.jwk,r,e,n)}},bo=class{type="RSA";jwk;_raw;publicKey;constructor(e,r){this.jwk=e,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=wo.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}sign(e,r){return ad(this.jwk,e,r)}};var Bc=8192,Rc=18,dx=1062,px=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function mx(t){let e=Et(t);return Fc(e)}function Fc(t){return{n:X(t[1],"base64url"),e:X(t[2],"base64url"),d:X(t[3],"base64url"),p:X(t[4],"base64url"),q:X(t[5],"base64url"),dp:X(t[6],"base64url"),dq:X(t[7],"base64url"),qi:X(t[8],"base64url"),kty:"RSA"}}function gx(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new j("JWK was missing components");return Ut([ke(Uint8Array.from([0])),ke(ne(t.n,"base64url")),ke(ne(t.e,"base64url")),ke(ne(t.d,"base64url")),ke(ne(t.p,"base64url")),ke(ne(t.q,"base64url")),ke(ne(t.dp,"base64url")),ke(ne(t.dq,"base64url")),ke(ne(t.qi,"base64url"))]).subarray()}function yx(t){let e=Et(t,{offset:0});return Oc(e)}function Oc(t){let e=Et(t[1],{offset:0});return{kty:"RSA",n:X(e[0],"base64url"),e:X(e[1],"base64url")}}function Pc(t){if(t.n==null||t.e==null)throw new j("JWK was missing components");return Ut([px,ps(Ut([ke(ne(t.n,"base64url")),ke(ne(t.e,"base64url"))]))]).subarray()}function fd(t){let e=Et(t);return Nc(e)}function Nc(t){let e=Fc(t);return kc(e)}function Uc(t,e){if(t.byteLength>=dx)throw new Kr("Key size is too large");let r=Et(t,{offset:0});return Mc(r,t,e)}function Mc(t,e,r){let n=Oc(t);if(r==null){let o=ct(ht.encode({Type:fe.RSA,Data:e}));r=Oe(Rc,o)}return new hn(n,r)}function kc(t){if(dd(t)>Bc)throw new j("Key size is too large");let e=hd(t),r=ct(ht.encode({Type:fe.RSA,Data:Pc(e.publicKey)})),n=Oe(Rc,r);return new bo(e.privateKey,new hn(e.publicKey,n))}async function ud(t){if(t>Bc)throw new j("Key size is too large");let e=await ld(t),r=ct(ht.encode({Type:fe.RSA,Data:Pc(e.publicKey)})),n=Oe(Rc,r);return new bo(e.privateKey,new hn(e.publicKey,n))}function hd(t){if(t==null)throw new j("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function ld(t,e){let r=await Ge.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await xx(r,e);return{privateKey:n[0],publicKey:n[1]}}async function ad(t,e,r){let n=await Ge.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let o=await Ge.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Ne(e instanceof Uint8Array?e:e.subarray()));return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function cd(t,e,r,n){let o=await Ge.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ge.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Ne(e),Ne(r instanceof Uint8Array?r:r.subarray()));return n?.signal?.throwIfAborted(),s}async function xx(t,e){if(t.privateKey==null||t.publicKey==null)throw new j("Private and public key are required");let r=await Promise.all([Ge.get().subtle.exportKey("jwk",t.privateKey),Ge.get().subtle.exportKey("jwk",t.publicKey)]);return e?.signal?.throwIfAborted(),r}function dd(t){if(t.kty!=="RSA")throw new j("invalid key type");if(t.n==null)throw new j("invalid key modulus");return ne(t.n,"base64url").length*8}var ks=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(mr(e),Le(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Ze(o)}update(e){return Xr(this),this.iHash.update(e),this}digestInto(e){Xr(this),ms(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Eo=(()=>{let t=((e,r,n)=>new ks(e,r).update(n).digest());return t.create=(e,r)=>new ks(e,r),t})();var pd=(t,e)=>(t+(t>=0?e:-e)/md)/e;function bx(t,e,r){Ct("scalar",t,lt,r);let[[n,o],[s,i]]=e,a=pd(i*t,r),c=pd(-o*t,r),f=t-a*n-c*s,u=-a*o-c*i,h=f<lt,m=u<lt;h&&(f=-f),m&&(u=-u);let p=ro(Math.ceil(Jr(r)/2))+tr;if(f<lt||f>=p||u<lt||u>=p)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:h,k1:f,k2neg:m,k2:u}}function Hc(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Kc(t,e){ze(t);let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Qe(r.lowS,"lowS"),Qe(r.prehash,"prehash"),r.format!==void 0&&Hc(r.format),r}var zc=class extends Error{constructor(e=""){super(e)}},rt={Err:zc,_tlv:{encode:(t,e)=>{let{Err:r}=rt;if(et(t,"tag"),t<0||t>255)throw new r("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,o=eo(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?eo(o.length/2|128):"";return eo(t)+s+o+e},decode(t,e){let{Err:r}=rt;e=$(e,void 0,"DER data");let n=0;if(t<0||t>255)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let f=e.subarray(n,n+c);if(f.length!==c)throw new r("tlv.decode: length bytes not complete");if(f[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let u of f)i=i<<8|u;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){let{Err:e}=rt;if(Ss(t),t<lt)throw new e("integer: negative integers are not allowed");let r=eo(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=rt;if(t.length<1)throw new e("invalid signature integer: empty");if(t[0]&128)throw new e("invalid signature integer: negative");if(t.length>1&&t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return wr(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=rt,o=$(t,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:f,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(f)}},hexFromSig(t){let{_tlv:e,_int:r}=rt,n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}};Object.freeze(rt._tlv);Object.freeze(rt._int);Object.freeze(rt);var lt=BigInt(0),tr=BigInt(1),md=BigInt(2),Ks=BigInt(3),wx=BigInt(4);function gd(t,e={}){let r=Ls("weierstrass",t,e),n=r.Fp,o=r.Fn,s=r.CURVE,{h:i,n:a}=s;ze(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:f}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=xd(n,o);function h(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function m(N,x,C){if(f&&x.is0())return Uint8Array.of(0);let{x:A,y:w}=x.toAffine(),b=n.toBytes(A);if(Qe(C,"isCompressed"),C){h();let L=!n.isOdd(w);return ye(yd(L),b)}else return ye(Uint8Array.of(4),b,n.toBytes(w))}function p(N){$(N,void 0,"Point");let{publicKey:x,publicKeyUncompressed:C}=u,A=N.length,w=N[0],b=N.subarray(1);if(f&&A===1&&w===0)return{x:n.ZERO,y:n.ZERO};if(A===x&&(w===2||w===3)){let L=n.fromBytes(b);if(!n.isValid(L))throw new Error("bad point: is not on curve, wrong x");let _=l(L),S;try{S=n.sqrt(_)}catch(U){let H=U instanceof Error?": "+U.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}h();let F=n.isOdd(S);return(w&1)===1!==F&&(S=n.neg(S)),{x:L,y:S}}else if(A===C&&w===4){let L=n.BYTES,_=n.fromBytes(b.subarray(0,L)),S=n.fromBytes(b.subarray(L,L*2));if(!g(_,S))throw new Error("bad point: is not on curve");return{x:_,y:S}}else throw new Error(`bad point: got length ${A}, expected compressed=${x} or uncompressed=${C}`)}let d=e.toBytes===void 0?m:e.toBytes,y=e.fromBytes===void 0?p:e.fromBytes;function l(N){let x=n.sqr(N),C=n.mul(x,N);return n.add(n.add(C,n.mul(N,s.a)),s.b)}function g(N,x){let C=n.sqr(x),A=l(N);return n.eql(C,A)}if(!g(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let E=n.mul(n.pow(s.a,Ks),wx),v=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(E,v)))throw new Error("bad curve params: a or b");function T(N,x,C=!1){if(!n.isValid(x)||C&&n.is0(x))throw new Error(`bad point coordinate ${N}`);return x}function B(N){if(!(N instanceof I))throw new Error("Weierstrass Point expected")}function R(N){if(!c||!c.basises)throw new Error("no endo");return bx(N,c.basises,o.ORDER)}function D(N,x,C,A,w){return C=new I(n.mul(C.X,N),C.Y,C.Z),x=oo(A,x),C=oo(w,C),x.add(C)}class I{static BASE=new I(s.Gx,s.Gy,n.ONE);static ZERO=new I(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(x,C,A){this.X=T("x",x),this.Y=T("y",C,!0),this.Z=T("z",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(x){let{x:C,y:A}=x||{};if(!x||!n.isValid(C)||!n.isValid(A))throw new Error("invalid affine point");if(x instanceof I)throw new Error("projective point not allowed");return n.is0(C)&&n.is0(A)?I.ZERO:new I(C,A,n.ONE)}static fromBytes(x){let C=I.fromAffine(y($(x,void 0,"point")));return C.assertValidity(),C}static fromHex(x){return I.fromBytes(Zr(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,C=!0){return M.createCache(this,x),C||this.multiply(Ks),this}assertValidity(){let x=this;if(x.is0()){if(e.allowInfinityPoint&&n.is0(x.X)&&n.eql(x.Y,n.ONE)&&n.is0(x.Z))return;throw new Error("bad point: ZERO")}let{x:C,y:A}=x.toAffine();if(!n.isValid(C)||!n.isValid(A))throw new Error("bad point: x or y not field elements");if(!g(C,A))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:x}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(x)}equals(x){B(x);let{X:C,Y:A,Z:w}=this,{X:b,Y:L,Z:_}=x,S=n.eql(n.mul(C,_),n.mul(b,w)),F=n.eql(n.mul(A,_),n.mul(L,w));return S&&F}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:x,b:C}=s,A=n.mul(C,Ks),{X:w,Y:b,Z:L}=this,_=n.ZERO,S=n.ZERO,F=n.ZERO,O=n.mul(w,w),U=n.mul(b,b),H=n.mul(L,L),K=n.mul(w,b);return K=n.add(K,K),F=n.mul(w,L),F=n.add(F,F),_=n.mul(x,F),S=n.mul(A,H),S=n.add(_,S),_=n.sub(U,S),S=n.add(U,S),S=n.mul(_,S),_=n.mul(K,_),F=n.mul(A,F),H=n.mul(x,H),K=n.sub(O,H),K=n.mul(x,K),K=n.add(K,F),F=n.add(O,O),O=n.add(F,O),O=n.add(O,H),O=n.mul(O,K),S=n.add(S,O),H=n.mul(b,L),H=n.add(H,H),O=n.mul(H,K),_=n.sub(_,O),F=n.mul(H,U),F=n.add(F,F),F=n.add(F,F),new I(_,S,F)}add(x){B(x);let{X:C,Y:A,Z:w}=this,{X:b,Y:L,Z:_}=x,S=n.ZERO,F=n.ZERO,O=n.ZERO,U=s.a,H=n.mul(s.b,Ks),K=n.mul(C,b),ee=n.mul(A,L),te=n.mul(w,_),re=n.add(C,A),W=n.add(b,L);re=n.mul(re,W),W=n.add(K,ee),re=n.sub(re,W),W=n.add(C,w);let ae=n.add(b,_);return W=n.mul(W,ae),ae=n.add(K,te),W=n.sub(W,ae),ae=n.add(A,w),S=n.add(L,_),ae=n.mul(ae,S),S=n.add(ee,te),ae=n.sub(ae,S),O=n.mul(U,W),S=n.mul(H,te),O=n.add(S,O),S=n.sub(ee,O),O=n.add(ee,O),F=n.mul(S,O),ee=n.add(K,K),ee=n.add(ee,K),te=n.mul(U,te),W=n.mul(H,W),ee=n.add(ee,te),te=n.sub(K,te),te=n.mul(U,te),W=n.add(W,te),K=n.mul(ee,W),F=n.add(F,K),K=n.mul(ae,W),S=n.mul(re,S),S=n.sub(S,K),K=n.mul(re,ee),O=n.mul(ae,O),O=n.add(O,K),new I(S,F,O)}subtract(x){return B(x),this.add(x.negate())}is0(){return this.equals(I.ZERO)}multiply(x){let{endo:C}=e;if(!o.isValidNot0(x))throw new RangeError("invalid scalar: out of range");let A,w,b=L=>M.cached(this,L,_=>Ar(I,_));if(C){let{k1neg:L,k1:_,k2neg:S,k2:F}=R(x),{p:O,f:U}=b(_),{p:H,f:K}=b(F);w=U.add(K),A=D(C.beta,O,H,L,S)}else{let{p:L,f:_}=b(x);A=L,w=_}return Ar(I,[A,w])[0]}multiplyUnsafe(x){let{endo:C}=e,A=this,w=x;if(!o.isValid(w))throw new RangeError("invalid scalar: out of range");if(w===lt||A.is0())return I.ZERO;if(w===tr)return A;if(M.hasCache(this))return this.multiply(w);if(C){let{k1neg:b,k1:L,k2neg:_,k2:S}=R(w),{p1:F,p2:O}=cl(I,A,L,S);return D(C.beta,F,O,b,_)}else return M.unsafe(A,w)}toAffine(x){let C=this,A=x,{X:w,Y:b,Z:L}=C;if(n.eql(L,n.ONE))return{x:w,y:b};let _=C.is0();A==null&&(A=_?n.ONE:n.inv(L));let S=n.mul(w,A),F=n.mul(b,A),O=n.mul(L,A);if(_)return{x:n.ZERO,y:n.ZERO};if(!n.eql(O,n.ONE))throw new Error("invZ was invalid");return{x:S,y:F}}isTorsionFree(){let{isTorsionFree:x}=e;return i===tr?!0:x?x(I,this):M.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return i===tr?this:x?x(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===tr?this.is0():this.clearCofactor().is0()}toBytes(x=!0){return Qe(x,"isCompressed"),this.assertValidity(),d(I,this,x)}toHex(x=!0){return Yr(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let P=o.BITS,M=new tn(I,e.endo?Math.ceil(P/2):P);return P>=8&&I.BASE.precompute(8),Object.freeze(I.prototype),Object.freeze(I),I}function yd(t){return Uint8Array.of(t?2:3)}function xd(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Ex(t,e={}){let{Fn:r}=t,n=e.randomBytes===void 0?br:e.randomBytes,o=Object.assign(xd(t.Fp,r),{seed:Math.max(Pa(r.ORDER),16)});function s(p){try{let d=r.fromBytes(p);return r.isValidNot0(d)}catch{return!1}}function i(p,d){let{publicKey:y,publicKeyUncompressed:l}=o;try{let g=p.length;return d===!0&&g!==y||d===!1&&g!==l?!1:!!t.fromBytes(p)}catch{return!1}}function a(p){return p=p===void 0?n(o.seed):p,Na($(p,o.seed,"seed"),r.ORDER)}function c(p,d=!0){return t.BASE.multiply(r.fromBytes(p)).toBytes(d)}function f(p){let{secretKey:d,publicKey:y,publicKeyUncompressed:l}=o,g=r._lengths;if(!xr(p))return;let E=$(p,void 0,"key").length,v=E===y||E===l,T=E===d||!!g?.includes(E);if(!(v&&T))return v}function u(p,d,y=!0){if(f(p)===!0)throw new Error("first arg must be private key");if(f(d)===!1)throw new Error("second arg must be public key");let l=r.fromBytes(p);return t.fromBytes(d).multiply(l).toBytes(y)}let h={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},m=rn(a,c);return Object.freeze(h),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:m,Point:t,utils:h,lengths:o})}function bd(t,e,r={}){let n=e;mr(n),ze(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let o=r.randomBytes===void 0?br:r.randomBytes,s=r.hmac===void 0?(w,b)=>Eo(n,w,b):r.hmac,{Fp:i,Fn:a}=t,{ORDER:c,BITS:f}=a,{keygen:u,getPublicKey:h,getSharedSecret:m,utils:p,lengths:d}=Ex(t,r),y={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},l=c*md+tr<i.ORDER;function g(w){let b=c>>tr;return w>b}function E(w,b){if(!a.isValidNot0(b))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return b}function v(){if(l)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function T(w,b){Hc(b);let L=d.signature,_=b==="compact"?L:b==="recovered"?L+1:void 0;return $(w,_)}class B{r;s;recovery;constructor(b,L,_){if(this.r=E("r",b),this.s=E("s",L),_!=null){if(v(),![0,1,2,3].includes(_))throw new Error("invalid recovery id");this.recovery=_}Object.freeze(this)}static fromBytes(b,L=y.format){T(b,L);let _;if(L==="der"){let{r:U,s:H}=rt.toSig($(b));return new B(U,H)}L==="recovered"&&(_=b[0],L="compact",b=b.subarray(1));let S=d.signature/2,F=b.subarray(0,S),O=b.subarray(S,S*2);return new B(a.fromBytes(F),a.fromBytes(O),_)}static fromHex(b,L){return this.fromBytes(Zr(b),L)}assertRecovery(){let{recovery:b}=this;if(b==null)throw new Error("invalid recovery id: must be present");return b}addRecoveryBit(b){return new B(this.r,this.s,b)}recoverPublicKey(b){let{r:L,s:_}=this,S=this.assertRecovery(),F=S===2||S===3?L+c:L;if(!i.isValid(F))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let O=i.toBytes(F),U=t.fromBytes(ye(yd((S&1)===0),O)),H=a.inv(F),K=D($(b,void 0,"msgHash")),ee=a.create(-K*H),te=a.create(_*H),re=t.BASE.multiplyUnsafe(ee).add(U.multiplyUnsafe(te));if(re.is0())throw new Error("invalid recovery: point at infinify");return re.assertValidity(),re}hasHighS(){return g(this.s)}toBytes(b=y.format){if(Hc(b),b==="der")return Zr(rt.hexFromSig(this));let{r:L,s:_}=this,S=a.toBytes(L),F=a.toBytes(_);return b==="recovered"?(v(),ye(Uint8Array.of(this.assertRecovery()),S,F)):ye(S,F)}toHex(b){return Yr(this.toBytes(b))}}Object.freeze(B.prototype),Object.freeze(B);let R=r.bits2int===void 0?function(b){if(b.length>8192)throw new Error("input is too large");let L=wr(b),_=b.length*8-f;return _>0?L>>BigInt(_):L}:r.bits2int,D=r.bits2int_modN===void 0?function(b){return a.create(R(b))}:r.bits2int_modN,I=ro(f);function P(w){return Ct("num < 2^"+f,w,lt,I),a.toBytes(w)}function M(w,b){return $(w,void 0,"message"),b?$(n(w),void 0,"prehashed message"):w}function N(w,b,L){let{lowS:_,prehash:S,extraEntropy:F}=Kc(L,y);w=M(w,S);let O=D(w),U=a.fromBytes(b);if(!a.isValidNot0(U))throw new Error("invalid private key");let H=[P(U),P(O)];if(F!=null&&F!==!1){let re=F===!0?o(d.secretKey):F;H.push($(re,void 0,"extraEntropy"))}let K=ye(...H),ee=O;function te(re){let W=R(re);if(!a.isValidNot0(W))return;let ae=a.inv(W),yt=t.BASE.multiply(W).toAffine(),fr=a.create(yt.x);if(fr===lt)return;let kr=a.create(ae*a.create(ee+fr*U));if(kr===lt)return;let kn=(yt.x===fr?0:2)|Number(yt.y&tr),Kn=kr;return _&&g(kr)&&(Kn=a.neg(kr),kn^=1),new B(fr,Kn,l?void 0:kn)}return{seed:K,k2sig:te}}function x(w,b,L={}){let{seed:_,k2sig:S}=N(w,b,L);return qh(n.outputLen,a.BYTES,s)(_,S).toBytes(L.format)}function C(w,b,L,_={}){let{lowS:S,prehash:F,format:O}=Kc(_,y);if(L=$(L,void 0,"publicKey"),b=M(b,F),!xr(w)){let U=w instanceof B?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+U)}T(w,O);try{let U=B.fromBytes(w,O),H=t.fromBytes(L);if(S&&U.hasHighS())return!1;let{r:K,s:ee}=U,te=D(b),re=a.inv(ee),W=a.create(te*re),ae=a.create(K*re),yt=t.BASE.multiplyUnsafe(W).add(H.multiplyUnsafe(ae));return yt.is0()?!1:a.create(yt.x)===K}catch{return!1}}function A(w,b,L={}){let{prehash:_}=Kc(L,y);return b=M(b,_),B.fromBytes(w,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:u,getPublicKey:h,getSharedSecret:m,utils:p,lengths:d,Point:t,sign:x,verify:C,recoverPublicKey:A,Signature:B,hash:n})}var $c={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Sx={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var wd=BigInt(2);function Ax(t){let e=$c.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=t*t*t%e,u=f*f*t%e,h=ie(u,r,e)*u%e,m=ie(h,r,e)*u%e,p=ie(m,wd,e)*f%e,d=ie(p,o,e)*p%e,y=ie(d,s,e)*d%e,l=ie(y,a,e)*y%e,g=ie(l,c,e)*l%e,E=ie(g,a,e)*y%e,v=ie(E,r,e)*u%e,T=ie(v,i,e)*d%e,B=ie(T,n,e)*f%e,R=ie(B,wd,e);if(!Vc.eql(Vc.sqr(R),t))throw new Error("Cannot find square root");return R}var Vc=Qr($c.p,{sqrt:Ax}),Cx=gd($c,{Fp:Vc,endo:Sx}),ln=bd(Cx,ct);function Ed(t,e,r,n){let o=wt.digest(r instanceof Uint8Array?r:r.subarray());if(Bs(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),ln.verify(e,s,t,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new co(String(s))});try{return n?.signal?.throwIfAborted(),ln.verify(e,o.digest,t,{prehash:!1,format:"der"})}catch(s){throw new co(String(s))}}var Hs=class{type="secp256k1";raw;_key;constructor(e){this._key=Ad(e),this.raw=Sd(this._key)}toMultihash(){return Ye.digest(Mt(this))}toCID(){return ge.createV1(114,this.toMultihash())}toString(){return le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}verify(e,r,n){return Ed(this._key,r,e,n)}};function qc(t){return new Hs(t)}function Sd(t){return ln.Point.fromBytes(t).toBytes()}function Ad(t){try{return ln.Point.fromBytes(t),t}catch(e){throw new Kr(String(e))}}function So(t,e){let{Type:r,Data:n}=ht.decode(t),o=n??new Uint8Array;switch(r){case fe.RSA:return Uc(o,e);case fe.Ed25519:return Ya(o);case fe.secp256k1:return qc(o);case fe.ECDSA:return ba(o);default:throw new ur}}function Cd(t){let{Type:e,Data:r}=ht.decode(t.digest),n=r??new Uint8Array;switch(e){case fe.Ed25519:return Ya(n);case fe.secp256k1:return qc(n);case fe.ECDSA:return ba(n);default:throw new ur}}function Mt(t){return ht.encode({Type:fe[t.type],Data:t.raw})}var vd=Symbol.for("nodejs.util.inspect.custom"),vx=114,Ao=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()})`}[$i]=!0;toString(){return this.string==null&&(this.string=le.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ge.createV1(vx,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Pe(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Pe(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[vd](){return`PeerId(${this.toString()})`}},Co=class extends Ao{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},vo=class extends Ao{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Lo=class extends Ao{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Lx=2336,Io=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ye.digest(ne(this.url))}[vd](){return`PeerId(${this.url})`}[$i]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ge.createV1(Lx,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=X(e)),e.toString()===this.toString())}};var Ix=114,Ld=2336;function dn(t,e){let r;if(t.charAt(0)==="1"||t.charAt(0)==="Q")r=Gr(le.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return _x(ge.parse(t));if(e==null)throw new j('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=Gr(e.decode(t))}return Id(r)}function jc(t){if(t.type==="Ed25519")return new vo({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new Lo({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new Co({multihash:t.toCID().multihash,publicKey:t});throw new ur}function Id(t){if(Dx(t))return new Co({multihash:t});if(Tx(t))try{let e=Cd(t);if(e.type==="Ed25519")return new vo({multihash:t,publicKey:e});if(e.type==="secp256k1")return new Lo({multihash:t,publicKey:e})}catch{let r=X(t.digest);return new Io(new URL(r))}throw new ss("Supplied PeerID Multihash is invalid")}function _x(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==Ix&&t.code!==Ld)throw new os("Supplied PeerID CID is invalid");if(t.code===Ld){let e=X(t.multihash.digest);return new Io(new URL(e))}return Id(t.multihash)}function Tx(t){return t.code===Ye.code}function Dx(t){return t.code===wt.code}var Bx=Math.pow(2,7),Rx=Math.pow(2,14),Fx=Math.pow(2,21),Gc=Math.pow(2,28),Wc=Math.pow(2,35),Xc=Math.pow(2,42),Yc=Math.pow(2,49),ue=128,_e=127;function pn(t){if(t<Bx)return 1;if(t<Rx)return 2;if(t<Fx)return 3;if(t<Gc)return 4;if(t<Wc)return 5;if(t<Xc)return 6;if(t<Yc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Zc(t,e,r=0){switch(pn(t)){case 8:e[r++]=t&255|ue,t/=128;case 7:e[r++]=t&255|ue,t/=128;case 6:e[r++]=t&255|ue,t/=128;case 5:e[r++]=t&255|ue,t/=128;case 4:e[r++]=t&255|ue,t>>>=7;case 3:e[r++]=t&255|ue,t>>>=7;case 2:e[r++]=t&255|ue,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Ox(t,e){let r=t[e],n=0;if(n+=r&_e,r<ue||(r=t[e+1],n+=(r&_e)<<7,r<ue)||(r=t[e+2],n+=(r&_e)<<14,r<ue)||(r=t[e+3],n+=(r&_e)<<21,r<ue)||(r=t[e+4],n+=(r&_e)*Gc,r<ue)||(r=t[e+5],n+=(r&_e)*Wc,r<ue)||(r=t[e+6],n+=(r&_e)*Xc,r<ue)||(r=t[e+7],n+=(r&_e)*Yc,r<ue))return n;throw new RangeError("Could not decode varint")}function Px(t,e){let r=t.get(e),n=0;if(n+=r&_e,r<ue||(r=t.get(e+1),n+=(r&_e)<<7,r<ue)||(r=t.get(e+2),n+=(r&_e)<<14,r<ue)||(r=t.get(e+3),n+=(r&_e)<<21,r<ue)||(r=t.get(e+4),n+=(r&_e)*Gc,r<ue)||(r=t.get(e+5),n+=(r&_e)*Wc,r<ue)||(r=t.get(e+6),n+=(r&_e)*Xc,r<ue)||(r=t.get(e+7),n+=(r&_e)*Yc,r<ue))return n;throw new RangeError("Could not decode varint")}function Jc(t,e=0){return t instanceof Uint8Array?Ox(t,e):Px(t,e)}var Ae=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},_t=class extends Error{static name="ValidationError";name="ValidationError"},zs=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Vs=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var $s=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let r=this.index,n=e();return n===void 0&&(this.index=r),n}parseWith(e){let r=e();if(this.index===this.input.length)return r}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(()=>{let r=this.readChar();if(r===e)return r})}readSeparator(e,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,r,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let m=Number.parseInt(h,e);if(!Number.isNaN(m))return m});if(u===void 0)break;if(s*=e,s+=u,s>f||(i+=1,r!==void 0&&i>r))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let r=0;r<e.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[r]=n}return e})}readIPv6Addr(){let e=r=>{for(let n=0;n<r.length/2;n++){let o=n*2;if(n<r.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return r[o]=i[0],r[o+1]=i[1],r[o+2]=i[2],r[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];r[o]=s>>8,r[o+1]=s&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,o]=e(r);if(n===16)return r;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ux=45,Mx=15,qs=new $s;function _d(t){if(!(t.length>Mx))return qs.new(t).parseWith(()=>qs.readIPv4Addr())}function Td(t){if(t.includes("%")&&(t=t.split("%")[0]),!(t.length>Ux))return qs.new(t).parseWith(()=>qs.readIPv6Addr())}function js(t){return!!_d(t)}function Dd(t){return!!Td(t)}function ef(t){return e=>X(e,t)}function tf(t){return e=>ne(e,t)}function mn(t){return new DataView(t.buffer).getUint16(t.byteOffset).toString()}function _r(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof t=="string"?parseInt(t):t),new Uint8Array(e)}function Bd(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let r=ne(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=_r(n);return ft([r,o],r.length+o.length)}function Rd(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let r=Nt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=_r(n);return ft([r,o],r.length+o.length)}function rf(t){let e=t.subarray(0,t.length-2),r=t.subarray(t.length-2),n=X(e,"base32"),o=mn(r);return`${n}:${o}`}var nf=function(t){t=t.toString().trim();let e=new Uint8Array(4);return t.split(/\./g).forEach((r,n)=>{let o=parseInt(r,10);if(isNaN(o)||o<0||o>255)throw new Ae("Invalid byte value in IP address");e[n]=o}),e},Fd=function(t){let e=0;t=t.toString().trim();let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=js(r[n]),i;s&&(i=nf(r[n]),r[n]=X(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,X(i.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++);let s=[n,1];for(n=9-r.length;n>0;n--)s.push("0");r.splice.apply(r,s)}let o=new Uint8Array(e+16);for(n=0;n<r.length;n++){r[n]===""&&(r[n]="0");let s=parseInt(r[n],16);if(isNaN(s)||s<0||s>65535)throw new Ae("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},Od=function(t){if(t.byteLength!==4)throw new Ae("IPv4 address was incorrect length");let e=[];for(let r=0;r<t.byteLength;r++)e.push(t[r]);return e.join(".")},Pd=function(t){if(t.byteLength!==16)throw new Ae("IPv6 address was incorrect length");let e=[];for(let n=0;n<t.byteLength;n+=2){let o=t[n],s=t[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let r=e.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Ae(`Invalid IPv6 address "${r}"`)}};function Nd(t){try{let e=new URL(`http://[${t}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ae(`Invalid IPv6 address "${t}"`)}}var Qc=Object.values(dr).map(t=>t.decoder),kx=(function(){let t=Qc[0].or(Qc[1]);return Qc.slice(2).forEach(e=>t=t.or(e)),t})();function Ud(t){return kx.decode(t)}function Md(t){return e=>t.encoder.encode(e)}function Kx(t){if(parseInt(t).toString()!==t)throw new _t("Value must be an integer")}function Hx(t){if(t<0)throw new _t("Value must be a positive integer, or zero")}function zx(t){return e=>{if(e>t)throw new _t(`Value must be smaller than or equal to ${t}`)}}function Vx(...t){return e=>{for(let r of t)r(e)}}var _o=Vx(Kx,Hx,zx(65535));var we=-1,of=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let r;if(typeof e=="string"?r=this.protocolsByName.get(e):r=this.protocolsByCode.get(e),r==null)throw new Vs(`Protocol ${e} was unknown`);return r}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(r=>{this.protocolsByName.set(r,e)})}removeProtocol(e){let r=this.protocolsByCode.get(e);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Dt=new of,nb=[{code:4,name:"ip4",size:32,valueToBytes:nf,bytesToValue:Od,validate:t=>{if(!js(t))throw new _t(`Invalid IPv4 address "${t}"`)}},{code:6,name:"tcp",size:16,valueToBytes:_r,bytesToValue:mn,validate:_o},{code:273,name:"udp",size:16,valueToBytes:_r,bytesToValue:mn,validate:_o},{code:33,name:"dccp",size:16,valueToBytes:_r,bytesToValue:mn,validate:_o},{code:41,name:"ip6",size:128,valueToBytes:Fd,bytesToValue:Pd,stringToValue:Nd,validate:t=>{if(!Dd(t))throw new _t(`Invalid IPv6 address "${t}"`)}},{code:42,name:"ip6zone",size:we},{code:43,name:"ipcidr",size:8,bytesToValue:ef("base10"),valueToBytes:tf("base10")},{code:53,name:"dns",size:we},{code:54,name:"dns4",size:we},{code:55,name:"dns6",size:we},{code:56,name:"dnsaddr",size:we},{code:132,name:"sctp",size:16,valueToBytes:_r,bytesToValue:mn,validate:_o},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:we,stringToValue:t=>decodeURIComponent(t),valueToString:t=>encodeURIComponent(t)},{code:421,name:"p2p",aliases:["ipfs"],size:we,bytesToValue:ef("base58btc"),valueToBytes:t=>t.startsWith("Q")||t.startsWith("1")?tf("base58btc")(t):ge.parse(t).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:rf,valueToBytes:Bd},{code:445,name:"onion3",size:296,bytesToValue:rf,valueToBytes:Rd},{code:446,name:"garlic64",size:we},{code:447,name:"garlic32",size:we},{code:448,name:"tls"},{code:449,name:"sni",size:we},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:we,bytesToValue:Md(Gn),valueToBytes:Ud},{code:480,name:"http"},{code:481,name:"http-path",size:we,stringToValue:t=>`/${decodeURIComponent(t)}`,valueToString:t=>encodeURIComponent(t.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:we}];nb.forEach(t=>{Dt.addProtocol(t)});function kd(t){let e=[],r=0;for(;r<t.length;){let n=Jc(t,r),o=Dt.getProtocol(n),s=pn(n),i=ob(o,t,r+s),a=0;i>0&&o.size===we&&(a=pn(i));let c=s+a+i,f={code:n,name:o.name,bytes:Ne(t.subarray(r,r+c))};if(i>0){let u=r+s+a,h=t.subarray(u,u+i);f.value=o.bytesToValue?.(h)??X(h)}e.push(f),r+=c}return e}function Kd(t){let e=0,r=[];for(let n of t){if(n.bytes==null){let o=Dt.getProtocol(n.code),s=pn(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??ne(n.value),a=i.byteLength,o.size===we&&(c=pn(a)));let f=new Uint8Array(s+c+a),u=0;Zc(n.code,f,u),u+=s,i!=null&&(o.size===we&&(Zc(a,f,u),u+=c),f.set(i,u)),n.bytes=f}r.push(n.bytes),e+=n.bytes.byteLength}return ft(r,e)}function Hd(t){if(t.charAt(0)!=="/")throw new Ae('String multiaddr must start with "/"');let e=[],r="protocol",n="",o="";for(let s=1;s<t.length;s++){let i=t.charAt(s);i!=="/"&&(r==="protocol"?o+=t.charAt(s):n+=t.charAt(s));let a=s===t.length-1;if(i==="/"||a){let c=Dt.getProtocol(o);if(r==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",r="protocol";continue}else if(a)throw new Ae(`Component ${o} was missing value`);r="value"}else if(r==="value"){let f={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Ae(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}e.push(f),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new Ae("Incomplete multiaddr");return e}function zd(t){return`/${t.flatMap(e=>{if(e.value==null)return e.name;let r=Dt.getProtocol(e.code);if(r==null)throw new Ae(`Unknown protocol code ${e.code}`);return[e.name,r.valueToString?.(e.value)??e.value]}).join("/")}`}function ob(t,e,r){return t.size==null||t.size===0?0:t.size>0?t.size/8:Jc(e,r)}var sb=Symbol.for("nodejs.util.inspect.custom"),Sf=Symbol.for("@multiformats/multiaddr");function ib(t){if(t==null&&(t="/"),Vd(t))return t.getComponents();if(t instanceof Uint8Array)return kd(t);if(typeof t=="string")return t=t.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),t===""&&(t="/"),Hd(t);if(Array.isArray(t))return t;throw new Ae("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Zs=class t{[Sf]=!0;#e;#t;#r;constructor(e="/",r={}){this.#e=ib(e),r.validate!==!1&&ab(this)}get bytes(){return this.#r==null&&(this.#r=Kd(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=zd(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let r=new t(e);return new t([...this.#e,...r.getComponents()],{validate:!1})}decapsulate(e){let r=e.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new zs(`Address ${this.toString()} does not contain subaddress: ${r}`);return new t(n.slice(0,o),{validate:!1})}decapsulateCode(e){let r;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){r=n;break}return new t(this.#e.slice(0,r),{validate:!1})}equals(e){return Pe(this.bytes,e.bytes)}[sb](){return`Multiaddr(${this.toString()})`}};function ab(t){t.getComponents().forEach(e=>{let r=Dt.getProtocol(e.code);e.value!=null&&r.validate?.(e.value)})}function Vd(t){return!!t?.[Sf]}function bn(t){return new Zs(t)}var oe=t=>({match:e=>{let r=e[0];return r==null||r.code!==t||r.value!=null?!1:e.slice(1)}}),k=(t,e)=>({match:r=>{let n=r[0];return n?.code!==t||n.value==null||e!=null&&n.value!==e?!1:r.slice(1)}}),$d=t=>({match:e=>t.match(e)===!1?e:!1}),q=t=>({match:e=>{let r=t.match(e);return r===!1?e:r}}),Te=(...t)=>({match:e=>{let r;for(let n of t){let o=n.match(e);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1}}),Y=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e}});function se(...t){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of t){let a=i.match(s);if(a===!1)return!1;s=a}return s}function r(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:t,matches:r,exactMatch:n}}var cb=k(421),T5=se(cb),Qs=k(54),ei=k(55),ti=k(56),Cf=k(53),D5=se(Qs,q(k(421))),B5=se(ei,q(k(421))),R5=se(ti,q(k(421))),F5=se(Te(Cf,ti,Qs,ei),q(k(421))),qd=Y(k(4),q(k(43))),jd=Y(q(k(42)),k(41),q(k(43))),vf=Te(qd,jd),wn=Te(vf,Cf,Qs,ei,ti),O5=se(Te(vf,Y(Te(Cf,ti,Qs,ei),q(k(421))))),P5=se(qd),N5=se(jd),U5=se(vf),Lf=Y(wn,k(6)),To=Y(wn,k(273)),M5=se(Y(Lf,q(k(421)))),k5=se(To),If=Y(To,oe(460),q(k(421))),ri=Y(To,oe(461),q(k(421))),fb=Te(If,ri),K5=se(If),H5=se(ri),Af=Te(wn,Lf,To,If,ri),Gd=Te(Y(Af,oe(477),q(k(421)))),z5=se(Gd),Wd=Te(Y(Af,oe(478),q(k(421))),Y(Af,oe(448),q(k(449)),oe(477),q(k(421)))),V5=se(Wd),Xd=Y(To,oe(280),q(k(466)),q(k(466)),q(k(421))),Yd=se(Xd),Zd=Y(ri,oe(465),q(k(466)),q(k(466)),q(k(421))),$5=se(Zd),Js=Te(Gd,Wd,Y(Lf,q(k(421))),Y(fb,q(k(421))),Y(wn,q(k(421))),Xd,Zd,k(421)),Jd=se(Js),ub=Y(q(Js),oe(290),$d(oe(281)),q(k(421))),q5=se(ub),hb=Te(Y(Js,oe(290),oe(281),q(k(421))),Y(Js,oe(281),q(k(421))),Y(oe(281),q(k(421)))),Qd=se(hb),lb=Y(wn,Te(Y(k(6,"80")),Y(k(6),oe(480)),oe(480)),q(k(481)),q(k(421))),j5=se(lb),db=Y(wn,Te(Y(k(6,"443")),Y(k(6,"443"),oe(480)),Y(k(6),oe(443)),Y(k(6),oe(448),oe(480)),Y(oe(448),oe(480)),oe(448),oe(443)),q(k(481)),q(k(421))),G5=se(db),pb=Te(Y(k(777),q(k(421)))),W5=se(pb),mb=Te(Y(k(400),q(k(421)))),X5=se(mb);var gb=Math.pow(2,7),yb=Math.pow(2,14),xb=Math.pow(2,21),bb=Math.pow(2,28),wb=Math.pow(2,35),Eb=Math.pow(2,42),Sb=Math.pow(2,49);function Do(t){if(t<gb)return 1;if(t<yb)return 2;if(t<xb)return 3;if(t<bb)return 4;if(t<wb)return 5;if(t<Eb)return 6;if(t<Sb)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}var De;(function(t){let e;(function(a){a.FIN="FIN",a.STOP_SENDING="STOP_SENDING",a.RESET="RESET",a.FIN_ACK="FIN_ACK"})(e=t.Flag||(t.Flag={}));let r;(function(a){a[a.FIN=0]="FIN",a[a.STOP_SENDING=1]="STOP_SENDING",a[a.RESET=2]="RESET",a[a.FIN_ACK=3]="FIN_ACK"})(r||(r={})),(function(a){a.codec=()=>Ir(r)})(e=t.Flag||(t.Flag={}));let n;t.codec=()=>(n==null&&(n=er((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.flag!=null&&(c.uint32(8),t.Flag.codec().encode(a.flag,c)),a.message!=null&&(c.uint32(18),c.bytes(a.message)),f.lengthDelimited!==!1&&c.ldelim()},(a,c,f={})=>{let u={},h=c==null?a.len:a.pos+c;for(;a.pos<h;){let m=a.uint32();switch(m>>>3){case 1:{u.flag=t.Flag.codec().decode(a);break}case 2:{u.message=a.bytes();break}default:{a.skipType(m&7);break}}}return u},function*(a,c,f,u={}){let h=c==null?a.len:a.pos+c;for(;a.pos<h;){let m=a.uint32();switch(m>>>3){case 1:{yield{field:`${f}.flag`,value:t.Flag.codec().decode(a)};break}case 2:{yield{field:`${f}.message`,value:a.bytes()};break}default:{a.skipType(m&7);break}}}})),n);function o(a){return Jt(a,t.codec())}t.encode=o;function s(a,c){return Yt(a,t.codec(),c)}t.decode=s;function i(a,c){return Qt(a,t.codec(),c)}t.stream=i})(De||(De={}));var ep=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],_f=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),tp="libp2p+webrtc+v1/",rp=2*1024*1024,En=16*1024;function Ab(t=En){let e=Do(t-Do(t)),r=1+Do(Object.keys(De.Flag).length-1),n=1,o=t-e-r-n,s=Do(o);return e+r+n+s}var np=Ab();var op=1e4,Tf="/webrtc",Bo="/webrtc-signaling/0.0.1";function Cb(t){let e=t.getComponents(),r={},n=0;return e[n]?.name==="ip6zone"&&(r.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(r.type=e[n].name,r.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(r.type=e[n].name,r.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(r.protocol=e[n].name==="tcp"?"tcp":"udp",r.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(r.type==="ip4"?r.cidr=parseInt(`${e[n].value}`):r.type==="ip6"&&(r.cidr=`${e[n].value}`),n++),r.type==null||r.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(r.sni=e[n+1].value,n+=2),r)}function Df(t){let e=Cb(t);if(e==null)throw new j(`Multiaddr ${t} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function ni(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var oi=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Sn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new oi(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new oi(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Bf=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function An(t={}){return vb(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function vb(t,e){e=e??{};let r=e.onEnd,n=new Sn,o,s,i,a=ni(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((l,g)=>{s=E=>{s=null,n.push(E);try{l(t(n))}catch(v){g(v)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ni()})}},f=l=>s!=null?s(l):(n.push(l),o),u=l=>(n=new Sn,s!=null?s({error:l}):(n.push({error:l}),o)),h=l=>{if(i)return o;if(e?.objectMode!==!0&&l?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:l})},m=l=>i?o:(i=!0,l!=null?u(l):f({done:!0})),p=()=>(n=new Sn,m(),{done:!0}),d=l=>(m(l),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:d,push:h,end:m,get readableLength(){return n.size},onEmpty:async l=>{let g=l?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let E,v;g!=null&&(E=new Promise((T,B)=>{v=()=>{B(new Bf)},g.addEventListener("abort",v)}));try{await Promise.race([a.promise,E])}finally{v!=null&&g!=null&&g?.removeEventListener("abort",v)}}},r==null)return o;let y=o;return o={[Symbol.asyncIterator](){return this},next(){return y.next()},throw(l){return y.throw(l),r!=null&&(r(l),r=void 0),{done:!0}},return(){return y.return(),r!=null&&(r(),r=void 0),{done:!0}},push:h,end(l){return y.end(l),r!=null&&(r(l),r=void 0),o},get readableLength(){return y.readableLength},onEmpty:l=>y.onEmpty(l)},o}var Rf=class t extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,t)}},sp=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function Ff(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((h,m)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){m(sp(i));return}if(i&&(c=()=>{m(sp(i))},i.addEventListener("abort",c,{once:!0})),t.then(h,m),r===Number.POSITIVE_INFINITY)return;let p=new Rf;a=s.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(d){m(d)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?h():o instanceof Error?m(o):(p.message=o??`Promise timed out after ${r} milliseconds`,m(p))},r)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var Lb=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function Ib(t,e,r){let n,o=new Promise((s,i)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:u}=Lb(t),h=async(...p)=>{let d=r.multiArgs?p:p[0];if(r.filter)try{if(!await r.filter(d))return}catch(y){n(),i(y);return}c.push(d),r.count===c.length&&(n(),s(c))},m=(...p)=>{n(),i(r.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)u(p,h);for(let p of r.rejectionEvents)a.includes(p)||u(p,m)};for(let p of a)f(p,h);for(let p of r.rejectionEvents)a.includes(p)||f(p,m);r.signal&&r.signal.addEventListener("abort",()=>{m(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){let s=Ff(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Ce(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Ib(t,e,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var Dr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},si=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},ii=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function _b(t){return t.reason}async function Bt(t,e,r){if(e==null)return t;let n=r?.translateError??_b;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([t,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Tb=Math.pow(2,20)*4,nr=class extends Ot{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??Tb,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new V,this.writeBuffer=new V,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let r=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(o){this.log.error("processSendQueue threw - %e",o)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);let n=o=>{this.onDrainPromise?.reject(o.error??new ii)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Bt(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=An(),r=s=>{e.push(s.data)};this.addEventListener("message",r);let n=s=>{e.end(s.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new st(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new cs(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new st("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new st("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new st(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new st(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new Hr;this.dispatchEvent(new fs(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new zr))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,r=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new V(s);this.writeBuffer.consume(s.byteLength);let a=this.sendData(s);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,r,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new as(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Hn(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Hn(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var ai=class extends nr{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",r=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),r.error!=null?r.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):r.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ce(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ce(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function ip(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var ci=class extends Ot{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,r){super(),this.maConn=e,this.protocol=r.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(r.name),this.streamOptions=r.streamOptions,this.maxEarlyStreams=r.maxEarlyStreams??10,this.metrics=r.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let o=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",o);let s=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",s)}send(e){let r=this.maConn.send(e);return r===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),r}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await Bt(Promise.all([...this.streams].map(async r=>{await r.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(r=>{r.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(r=>{r.onTransportClosed(e)})}catch(r){this.abort(r)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new rs;let r=this.onCreateStream({...this.streamOptions,...e});return ip(r)&&(r=await r),this.streams.push(r),this.cleanUpStream(r),r}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new si(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let r=n=>{let o=this.streams.findIndex(s=>s===e);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",r),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(r=>{this.safeDispatchEvent("stream",{detail:r})}),this.earlyStreams=[]})}};var fi=class extends nr{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ce(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await Ce(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};function ap(t=0){return new Uint8Array(t)}var Db=Math.pow(2,7),Bb=Math.pow(2,14),Rb=Math.pow(2,21),Of=Math.pow(2,28),Pf=Math.pow(2,35),Nf=Math.pow(2,42),Uf=Math.pow(2,49),J=128,Be=127;function Br(t){if(t<Db)return 1;if(t<Bb)return 2;if(t<Rb)return 3;if(t<Of)return 4;if(t<Pf)return 5;if(t<Nf)return 6;if(t<Uf)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Fb(t,e,r=0){switch(Br(t)){case 8:e[r++]=t&255|J,t/=128;case 7:e[r++]=t&255|J,t/=128;case 6:e[r++]=t&255|J,t/=128;case 5:e[r++]=t&255|J,t/=128;case 4:e[r++]=t&255|J,t>>>=7;case 3:e[r++]=t&255|J,t>>>=7;case 2:e[r++]=t&255|J,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Ob(t,e,r=0){switch(Br(t)){case 8:e.set(r++,t&255|J),t/=128;case 7:e.set(r++,t&255|J),t/=128;case 6:e.set(r++,t&255|J),t/=128;case 5:e.set(r++,t&255|J),t/=128;case 4:e.set(r++,t&255|J),t>>>=7;case 3:e.set(r++,t&255|J),t>>>=7;case 2:e.set(r++,t&255|J),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function Pb(t,e){let r=t[e],n=0;if(n+=r&Be,r<J||(r=t[e+1],n+=(r&Be)<<7,r<J)||(r=t[e+2],n+=(r&Be)<<14,r<J)||(r=t[e+3],n+=(r&Be)<<21,r<J)||(r=t[e+4],n+=(r&Be)*Of,r<J)||(r=t[e+5],n+=(r&Be)*Pf,r<J)||(r=t[e+6],n+=(r&Be)*Nf,r<J)||(r=t[e+7],n+=(r&Be)*Uf,r<J))return n;throw new RangeError("Could not decode varint")}function Nb(t,e){let r=t.get(e),n=0;if(n+=r&Be,r<J||(r=t.get(e+1),n+=(r&Be)<<7,r<J)||(r=t.get(e+2),n+=(r&Be)<<14,r<J)||(r=t.get(e+3),n+=(r&Be)<<21,r<J)||(r=t.get(e+4),n+=(r&Be)*Of,r<J)||(r=t.get(e+5),n+=(r&Be)*Pf,r<J)||(r=t.get(e+6),n+=(r&Be)*Nf,r<J)||(r=t.get(e+7),n+=(r&Be)*Uf,r<J))return n;throw new RangeError("Could not decode varint")}function cp(t,e,r=0){return e==null&&(e=ap(Br(t))),e instanceof Uint8Array?Fb(t,e,r):Ob(t,e,r)}function ui(t,e=0){return t instanceof Uint8Array?Pb(t,e):Nb(t,e)}var Ub=4194304,hi=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Ro=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},kf=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Kf=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Mb(t){return typeof t?.closeRead=="function"}function kb(t){return typeof t?.close=="function"}function Mf(t){return Mb(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:kb(t)?t.status!=="open":!1}function Kb(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function Hb(t,e){let r=e?.maxBufferSize??Ub,n=new V,o,s=!1;if(!Kb(t))throw new j("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>r){let h=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${h} > ${r}`))}o?.resolve()};t.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};t.addEventListener("close",a);let c=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",c);let f={readBuffer:n,async read(u){if(s===!0)throw new hi("Stream was unwrapped");if(Mf(t)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Dr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let h=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=h){o.resolve();break}if(await Bt(o.promise,u?.signal),Mf(t)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let m=u?.bytes??n.byteLength;if(n.byteLength<m){if(Mf(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,m),new Dr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${m} bytes`);return f.read(u)}let p=n.sublist(0,m);return n.consume(m),p},async write(u,h){if(s===!0)throw new hi("Stream was unwrapped");t.send(u)||await Ce(t,"drain",{signal:h?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.unshift(n))),t}};return f}function li(t,e={}){let r=Hb(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Br(e.maxDataLength));let n=e?.lengthDecoder??ui,o=e?.lengthEncoder??cp;return{async read(i){let a=-1,c=new V;for(;;){let u=await r.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(h){if(h instanceof RangeError)continue;throw h}if(a<0)throw new Ro("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Kf(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new kf(`Message length too long - ${a} > ${e.maxDataLength}`);let f=await r.read({...i,bytes:a});if(f==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new Dr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(f.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",f.byteLength,a),new Dr(`Unexpected EOF - read ${f.byteLength}/${a} bytes before the stream closed`);return f},async write(i,a){await r.write(new V(o(i.byteLength),i),a)},async writeV(i,a){let c=new V(...i.flatMap(f=>[o(f.byteLength),f]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function di(t,e){let r=li(t,e),n={read:async(o,s)=>{let i=await r.read(s);return o.decode(i)},write:async(o,s,i)=>{await r.write(s.encode(o),i)},writeV:async(o,s,i)=>{await r.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var zb=1024*1024*4,Vb=1024*1024*4,pi=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new V,this.maxBufferSize=e.maxBufferSize??zb,this.maxDataLength=e.maxDataLength??Vb,this.lengthDecoder=e.lengthDecoder??ui,this.encodingLength=e.encodingLength??Br}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new j(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let r;try{r=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(r<0||r>this.maxDataLength)throw new Ro("Invalid message length");let n=this.encodingLength(r),o=n+r;if(this.buffer.byteLength>=o){let s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}};function mi(t=0){return new Uint8Array(t)}var $b=Math.pow(2,7),qb=Math.pow(2,14),jb=Math.pow(2,21),Hf=Math.pow(2,28),zf=Math.pow(2,35),Vf=Math.pow(2,42),$f=Math.pow(2,49),Q=128,Re=127;function Rr(t){if(t<$b)return 1;if(t<qb)return 2;if(t<jb)return 3;if(t<Hf)return 4;if(t<zf)return 5;if(t<Vf)return 6;if(t<$f)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Gb(t,e,r=0){switch(Rr(t)){case 8:e[r++]=t&255|Q,t/=128;case 7:e[r++]=t&255|Q,t/=128;case 6:e[r++]=t&255|Q,t/=128;case 5:e[r++]=t&255|Q,t/=128;case 4:e[r++]=t&255|Q,t>>>=7;case 3:e[r++]=t&255|Q,t>>>=7;case 2:e[r++]=t&255|Q,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Wb(t,e,r=0){switch(Rr(t)){case 8:e.set(r++,t&255|Q),t/=128;case 7:e.set(r++,t&255|Q),t/=128;case 6:e.set(r++,t&255|Q),t/=128;case 5:e.set(r++,t&255|Q),t/=128;case 4:e.set(r++,t&255|Q),t>>>=7;case 3:e.set(r++,t&255|Q),t>>>=7;case 2:e.set(r++,t&255|Q),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function Xb(t,e){let r=t[e],n=0;if(n+=r&Re,r<Q||(r=t[e+1],n+=(r&Re)<<7,r<Q)||(r=t[e+2],n+=(r&Re)<<14,r<Q)||(r=t[e+3],n+=(r&Re)<<21,r<Q)||(r=t[e+4],n+=(r&Re)*Hf,r<Q)||(r=t[e+5],n+=(r&Re)*zf,r<Q)||(r=t[e+6],n+=(r&Re)*Vf,r<Q)||(r=t[e+7],n+=(r&Re)*$f,r<Q))return n;throw new RangeError("Could not decode varint")}function Yb(t,e){let r=t.get(e),n=0;if(n+=r&Re,r<Q||(r=t.get(e+1),n+=(r&Re)<<7,r<Q)||(r=t.get(e+2),n+=(r&Re)<<14,r<Q)||(r=t.get(e+3),n+=(r&Re)<<21,r<Q)||(r=t.get(e+4),n+=(r&Re)*Hf,r<Q)||(r=t.get(e+5),n+=(r&Re)*zf,r<Q)||(r=t.get(e+6),n+=(r&Re)*Vf,r<Q)||(r=t.get(e+7),n+=(r&Re)*$f,r<Q))return n;throw new RangeError("Could not decode varint")}function up(t,e,r=0){return e==null&&(e=mi(Rr(t))),e instanceof Uint8Array?Gb(t,e,r):Wb(t,e,r)}function hp(t,e=0){return t instanceof Uint8Array?Xb(t,e):Yb(t,e)}var gi=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Cn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},yi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Fo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function xi(t){return t[Symbol.asyncIterator]!=null}function dp(t,e){if(t.byteLength>e)throw new Cn("Message length too long")}var wi=t=>{let e=Rr(t),r=mi(e);return up(t,r),wi.bytes=e,r};wi.bytes=0;function Oo(t,e){e=e??{};let r=e.lengthEncoder??wi,n=e?.maxDataLength??4194304;function*o(s){dp(s,n);let i=r(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return xi(t)?(async function*(){for await(let s of t)yield*o(s)})():(function*(){for(let s of t)yield*o(s)})()}Oo.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??wi,n=e?.maxDataLength??4194304;return dp(t,n),new V(r(t.byteLength),t)};var Fr;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(Fr||(Fr={}));var qf=t=>{let e=hp(t);return qf.bytes=Rr(e),e};qf.bytes=0;function Po(t,e){let r=new V,n=Fr.LENGTH,o=-1,s=e?.lengthDecoder??qf,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===Fr.LENGTH)try{if(o=s(r),o<0)throw new gi("Invalid message length");if(o>a)throw new Cn("Message length too long");let f=s.bytes;r.consume(f),e?.onLength!=null&&e.onLength(o),n=Fr.DATA}catch(f){if(f instanceof RangeError){if(r.byteLength>i)throw new yi("Message length length too long");break}throw f}if(n===Fr.DATA){if(r.byteLength<o)break;let f=r.sublist(0,o);r.consume(o),e?.onData!=null&&e.onData(f),yield f,n=Fr.LENGTH}}}return xi(t)?(async function*(){for await(let f of t)r.append(f),yield*c();if(r.byteLength>0)throw new Fo("Unexpected end of input")})():(function*(){for(let f of t)r.append(f),yield*c();if(r.byteLength>0)throw new Fo("Unexpected end of input")})()}Po.fromReader=(t,e)=>{let r=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await t.next(r);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}})();return Po(n,{...e??{},onLength:s=>{r=s}})};var jf=class extends fi{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(e){super({...e,maxMessageSize:(e.maxMessageSize??En)-np}),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=An(),this.maxBufferedAmount=e.maxBufferedAmount??rp,this.finAckTimeout=e.finAckTimeout??op,this.channel.onclose=()=>{this.log.trace("received datachannel close event"),this.onRemoteCloseWrite(),this.onTransportClosed()},this.channel.onerror=n=>{let o=n.error;this.log.trace("received datachannel error event - %e",o),this.abort(o)},this.channel.onmessage=async n=>{this.log("incoming message %d bytes",n.data.byteLength);let{data:o}=n;o===null||o.byteLength===0||this.incomingData.push(new Uint8Array(o,0,o.byteLength))},this.channel.bufferedAmountLowThreshold=0,this.channel.onbufferedamountlow=()=>{this.writableNeedsDrain&&this.safeDispatchEvent("drain")},Promise.resolve().then(async()=>{for await(let n of Po(this.incomingData))this.processIncomingProtobuf(n)}).catch(n=>{this.log.error("error processing incoming data channel messages - %e",n)});let r=()=>{this.channel.readyState==="open"&&(this.log.trace("stream closed, closing underlying datachannel"),this.channel.close())};this.addEventListener("close",r),this.channel.readyState!=="open"&&(this.log('channel ready state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),Ce(this.channel,"open",{rejectionEvents:["close","error"]}).then(()=>{this.log('channel ready state is now "%s", dispatching drain',this.channel.readyState),this.safeDispatchEvent("drain")}).catch(n=>{this.abort(n.error??n)}))}sendNewStream(){}_sendMessage(e){if(this.channel.readyState!=="open")throw new st(`Invalid datachannel state - ${this.channel.readyState}`);this.log.trace('sending message, channel state "%s"',this.channel.readyState);try{for(let r of e)this.channel.send(Ne(r))}catch(r){this.log.error("error sending datachannel message - %e",r),this.abort(r)}}sendData(e){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(Oo.single(De.encode({message:e.subarray()}))),{sentBytes:e.byteLength,canSendMore:this.channel.bufferedAmount<this.maxBufferedAmount})}sendReset(e){try{this.log.error("sending reset - %e",e),this._sendFlag(De.Flag.RESET),this.receivedFinAck?.reject(e)}catch(r){this.log.error("failed to send reset - %e",r)}}async sendCloseWrite(e){this._sendFlag(De.Flag.FIN),e?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let r=e?.signal??AbortSignal.timeout(this.finAckTimeout),n=[Ce(this.channel,"close",{signal:r}),Ce(this.channel,"error",{signal:r})];await Promise.any([Bt(this.receivedFinAck.promise,r),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(e){this._sendFlag(De.Flag.STOP_SENDING),e?.signal?.throwIfAborted()}processIncomingProtobuf(e){let r=De.decode(e);r.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new V(r.message)),r.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',r.flag,this.writeStatus,this.readStatus),r.flag===De.Flag.FIN&&(this._sendFlag(De.Flag.FIN_ACK),this.onRemoteCloseWrite()),r.flag===De.Flag.RESET&&(this.receivedFinAck?.reject(new Hr("The stream was reset")),this.onRemoteReset()),r.flag===De.Flag.STOP_SENDING&&this.onRemoteCloseRead(),r.flag===De.Flag.FIN_ACK&&this.receivedFinAck?.resolve())}_sendFlag(e){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',e.toString(),this.channel.readyState),!1;this.log.trace("sending flag %s",e.toString());let r=De.encode({flag:e}),n=Oo.single(r);try{return this._sendMessage(n),!0}catch(o){this.log.error("could not send flag %s - %e",e.toString(),o)}return!1}sendPause(){}sendResume(){}};function No(t){let{channel:e,direction:r,isHandshake:n}=t;return new jf({...t,id:`${e.id}`,log:t.log.newScope(`${n===!0?"handshake":r}:${e.id}`),protocol:""})}var or=class{protocol;peerConnection;metrics;dataChannelOptions;earlyDataChannels;constructor(e){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??Tf,this.dataChannelOptions=e.dataChannelOptions??{},this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(e){this.earlyDataChannels.push(e.channel)}createStreamMuxer(e){return this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new Gf(e,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,earlyDataChannels:this.earlyDataChannels})}},Gf=class extends ci{peerConnection;dataChannelOptions;constructor(e,r){super(e,{...r,name:"muxer"}),this.peerConnection=r.peerConnection,this.protocol=r.protocol??Tf,this.dataChannelOptions=r.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{this.onDataChannel(n)},queueMicrotask(()=>{if(this.status!=="open"){r.earlyDataChannels.forEach(n=>{n.close()});return}r.earlyDataChannels.forEach(n=>{this.onDataChannel(n)})})}onDataChannel(e){if(this.log("incoming datachannel with channel id %d, protocol %s and status %s",e.id,e.protocol,e.readyState),e.label==="init"){this.log.trace("closing init channel %d",e.id),e.close();return}let r=No({...this.streamOptions,...this.dataChannelOptions,channel:e,direction:"inbound",log:this.log});this.onRemoteStream(r)}async onCreateStream(e){let r=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",r.id,e?.protocol),No({...e,...this.dataChannelOptions,channel:r,direction:"outbound",log:this.log})}onData(){}};var Wf=class extends ai{peerConnection;constructor(e){super(e),this.peerConnection=e.peerConnection;let r=e.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change %s initial state %s",this.peerConnection.connectionState,r),(this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.onTransportClosed(),this.peerConnection.close())}}sendData(e){return{sentBytes:e.byteLength,canSendMore:!0}}async sendClose(e){this.peerConnection.close(),e?.signal?.throwIfAborted()}sendReset(){this.peerConnection.close()}sendPause(){}sendResume(){}},Uo=t=>new Wf(t);async function Xf(t){return t=t??{},typeof t=="function"&&(t=await t()),t.iceServers=t.iceServers??ep.map(e=>({urls:[e]})),t}var pp=(t=32)=>tp+[...Array(t)].map(()=>_f.at(Math.floor(Math.random()*_f.length))).join("");var Ei=globalThis.RTCPeerConnection,Si=globalThis.RTCSessionDescription,mp=globalThis.RTCIceCandidate;var $e=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var sr=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},We=class extends sr{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var Ai=class extends sr{constructor(e,r){super(`Invalid fingerprint "${e}" within ${r}`),this.name="WebRTC/InvalidFingerprintError"}};var Ci=class extends sr{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},vi=class extends sr{constructor(e){super(`unsupported hash algorithm code: ${e} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var Ke;(function(t){let e;(function(a){a.SDP_OFFER="SDP_OFFER",a.SDP_ANSWER="SDP_ANSWER",a.ICE_CANDIDATE="ICE_CANDIDATE"})(e=t.Type||(t.Type={}));let r;(function(a){a[a.SDP_OFFER=0]="SDP_OFFER",a[a.SDP_ANSWER=1]="SDP_ANSWER",a[a.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(r||(r={})),(function(a){a.codec=()=>Ir(r)})(e=t.Type||(t.Type={}));let n;t.codec=()=>(n==null&&(n=er((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),t.Type.codec().encode(a.type,c)),a.data!=null&&(c.uint32(18),c.string(a.data)),f.lengthDelimited!==!1&&c.ldelim()},(a,c,f={})=>{let u={},h=c==null?a.len:a.pos+c;for(;a.pos<h;){let m=a.uint32();switch(m>>>3){case 1:{u.type=t.Type.codec().decode(a);break}case 2:{u.data=a.string();break}default:{a.skipType(m&7);break}}}return u},function*(a,c,f,u={}){let h=c==null?a.len:a.pos+c;for(;a.pos<h;){let m=a.uint32();switch(m>>>3){case 1:{yield{field:`${f}.type`,value:t.Type.codec().decode(a)};break}case 2:{yield{field:`${f}.data`,value:a.string()};break}default:{a.skipType(m&7);break}}}})),n);function o(a){return Jt(a,t.codec())}t.encode=o;function s(a,c){return Yt(a,t.codec(),c)}t.decode=s;function i(a,c){return Qt(a,t.codec(),c)}t.stream=i})(Ke||(Ke={}));var Li=async(t,e,r)=>{try{let n=Promise.withResolvers();for(Qb(t,n);;){let o=await Promise.race([n.promise,e.read({signal:r.signal})]);if(o==null){r.signal?.throwIfAborted();break}if(o.type!==Ke.Type.ICE_CANDIDATE)throw new is("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){r.onProgress?.(new $e("webrtc:end-of-ice-candidates")),r.log.trace("end-of-candidates received");continue}let i=new mp(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{r.onProgress?.(new $e("webrtc:add-ice-candidate",i.candidate)),await t.addIceCandidate(i)}catch(a){r.log.error("%s bad candidate received %o - %e",r.direction,s,a)}}}catch(n){if(r.log.error("%s error parsing ICE candidate - %e",r.direction,n),r.signal?.aborted===!0&&t.connectionState!=="connected")throw n}};function Qb(t,e){if(t.connectionState==="connected"){e.resolve();return}t.onconnectionstatechange=r=>{switch(t.connectionState){case"connected":e.resolve();break;case"failed":case"closed":e.reject(new ts(`RTCPeerConnection connection state became "${t.connectionState}"`));break;default:break}}}function Ii(t){let e;for(let r of t.getComponents())r.name==="p2p"&&(e=dn(r.value??""));if(e==null)throw new ns("Remote peerId must be present in multiaddr");return e}async function gp({rtcConfiguration:t,dataChannel:e,signal:r,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:f}){let{circuitAddress:u,targetPeer:h}=yp(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing circuit address: %a",u);let m=s.getConnections(h),p;m.length===0?(f?.(new $e("webrtc:dial-relay")),p=await i.dial(u,{signal:r,onProgress:f})):(f?.(new $e("webrtc:reuse-relay-connection")),p=m[0]),f?.(new $e("webrtc:open-signaling-stream"));let d=await p.newStream(Bo,{signal:r,runOnLimitedConnection:!0}),y=di(d).pb(Ke),l=new Ei(t);l.addEventListener("connectionstatechange",()=>{l.connectionState==="closed"&&l.close()});let g=new or({peerConnection:l,dataChannelOptions:e});try{let E=l.createDataChannel("init");l.onicecandidate=({candidate:R})=>{if(l.connectionState==="connected"){a.trace("ignore new ice candidate as peer connection is already connected");return}if(R==null||R?.candidate===""){a.trace("initiator detected end of ICE candidates");return}let D=JSON.stringify(R?.toJSON()??null);a.trace("initiator sending ICE candidate %o",R),y.write({type:Ke.Type.ICE_CANDIDATE,data:D},{signal:r}).catch(I=>{a.error("error sending ICE candidate - %e",I)})},l.onicecandidateerror=R=>{a.error("initiator ICE candidate error",R)};let v=await l.createOffer().catch(R=>{throw a.error("could not execute createOffer - %e",R),new We("Failed to set createOffer")});a.trace("initiator send SDP offer %s",v.sdp),f?.(new $e("webrtc:send-sdp-offer")),await y.write({type:Ke.Type.SDP_OFFER,data:v.sdp},{signal:r}),await l.setLocalDescription(v).catch(R=>{throw a.error("could not execute setLocalDescription - %e",R),new We("Failed to set localDescription")}),f?.(new $e("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let T=await y.read({signal:r});if(T.type!==Ke.Type.SDP_ANSWER)throw new We("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",T.data);let B=new Si({type:"answer",sdp:T.data});return await l.setRemoteDescription(B).catch(R=>{throw a.error("could not execute setRemoteDescription - %e",R),new We("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),f?.(new $e("webrtc:read-ice-candidates")),await Li(l,y,{direction:"initiator",signal:r,log:a,onProgress:f}),a.trace("initiator connected"),E.readyState!=="open"&&(a.trace("wait for init channel to open"),await Ce(E,"open",{signal:r})),a.trace("closing init channel"),E.close(),a.trace("waiting for init channel to close"),await Ce(E,"close",{signal:r}),f?.(new $e("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await d.close({signal:r}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:l,muxerFactory:g}}catch(E){throw a.error("outgoing signaling error - %e",E),l.close(),d.abort(E),E}finally{l.onicecandidate=null,l.onicecandidateerror=null}}var xp=se(Jd.matchers[0],oe(290)),_i=class t extends Ot{transportManager;shutdownController;events;constructor(e,r){super(),this.transportManager=e.transportManager,this.events=e.events,this.shutdownController=r.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(e){e.detail.getAddrs().filter(n=>xp.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(e=>!(e instanceof t)).map(e=>e.getAddrs().filter(r=>xp.exactMatch(r)).map(r=>r.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.events.removeEventListener("transport:listening",this.onTransportListening),this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function bp(t,e,{peerConnection:r,signal:n,log:o}){o.trace("new inbound signaling stream");let s=di(t).pb(Ke);try{r.onicecandidate=({candidate:h})=>{if(r.connectionState==="connected"){o.trace("ignore new ice candidate as peer connection is already connected");return}if(h==null||h?.candidate===""){o.trace("recipient detected end of ICE candidates");return}let m=JSON.stringify(h?.toJSON()??null);o.trace("recipient sending ICE candidate %s",m),s.write({type:Ke.Type.ICE_CANDIDATE,data:m},{signal:n}).catch(p=>{o.error("error sending ICE candidate - %e",p)})},o.trace("recipient read SDP offer");let c=await s.read({signal:n});if(c.type!==Ke.Type.SDP_OFFER)throw new We(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let f=new Si({type:"offer",sdp:c.data});await r.setRemoteDescription(f).catch(h=>{throw o.error("could not execute setRemoteDescription - %e",h),new We("Failed to set remoteDescription")});let u=await r.createAnswer().catch(h=>{throw o.error("could not execute createAnswer - %e",h),new We("Failed to create answer")});o.trace("recipient send SDP answer %s",u.sdp),await s.write({type:Ke.Type.SDP_ANSWER,data:u.sdp},{signal:n}),await r.setLocalDescription(u).catch(h=>{throw o.error("could not execute setLocalDescription - %e",h),new We("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await Li(r,s,{direction:"recipient",signal:n,log:o})}catch(c){if(r.connectionState!=="connected")throw o.error("error while handling signaling stream from peer %a - %e",e.remoteAddr,c),r.close(),c;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",e.remoteAddr,c)}let i=Ii(e.remoteAddr),a=bn(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var Ti=class{components;init;log;_started=!1;metrics;shutdownController;constructor(e,r={}){this.components=e,this.init=r,this.log=e.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[us]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Vr]=["@libp2p/transport"];[th]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(Bo,(e,r)=>{let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(e,r,n).catch(o=>{this.log.error("failed to handle incoming connect from %p - %e",r.remotePeer,o)}).finally(()=>{n.clear()})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(Bo),this._started=!1}createListener(e){return new _i(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(Qd.exactMatch)}dialFilter(e){return this.listenFilter(e)}async dial(e,r){this.log.trace("dialing address: %a",e);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await gp({rtcConfiguration:await Xf(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:e,dataChannelOptions:this.init.dataChannel,signal:r.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:r.onProgress}),i=Uo({peerConnection:o,remoteAddr:n,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")}),a=await r.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,remotePeer:Ii(e),muxerFactory:s,onProgress:r.onProgress,signal:r.signal});return this._closeOnShutdown(o,i),a}async _onProtocol(e,r,n){let o=new Ei(await Xf(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{o.connectionState==="closed"&&o.close()});let s=new or({peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i,remotePeer:a}=await bp(e,r,{peerConnection:o,signal:n,log:this.log});await e.close({signal:n});let c=Uo({peerConnection:o,remoteAddr:i,metrics:this.metrics?.listenerEvents,direction:"inbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")});await this.components.upgrader.upgradeInbound(c,{skipEncryption:!0,skipProtection:!0,remotePeer:a,muxerFactory:s,signal:n}),this._closeOnShutdown(o,c)}catch(i){throw this.log.error("incoming signaling error - %e",i),o.close(),e.abort(i),i}}_closeOnShutdown(e,r){let n=()=>{r.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection - %e",o)})};this.shutdownController.signal.addEventListener("abort",n),e.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function yp(t){let e=t.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(e==null)throw new j("Destination peer id was missing");return{circuitAddress:bn(t.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:dn(e)}}function dt(t=0){return new Uint8Array(t)}function qe(t=0){return new Uint8Array(t)}var vn=!!globalThis.process?.env?.DUMP_SESSION_KEYS,Yf=16;function ew(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function Di(t){if(typeof t!="boolean")throw new TypeError(`boolean expected, not ${t}`)}function Ln(t){if(typeof t!="number")throw new TypeError("number expected, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError("positive integer expected, got "+t)}function xe(t,e,r=""){let n=ew(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return t}function Zf(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function wp(t,e,r=!1){xe(t,void 0,"output");let n=e.outputLen;if(t.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(r&&!In(t))throw new Error("invalid output, must be aligned")}function pt(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function nt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function tw(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Or=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,rw=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;var nw=t=>{for(let e=0;e<t.length;e++)t[e]=rw(t[e]);return t},Rt=Or?t=>t:nw;function Ep(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Sp(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Ap(t,e,r){let n=e,o=r||(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(t),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}var Cp=(t,e)=>{function r(n,...o){if(xe(n,void 0,"key"),t.nonceLength!==void 0){let u=o[0];xe(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength;s&&o[1]!==void 0&&xe(o[1],void 0,"AAD");let i=e(n,...o),a=(u,h)=>{if(h!==void 0){if(u!==2)throw new Error("cipher output not supported");xe(h,void 0,"output")}},c=!1;return{encrypt(u,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,xe(u),a(i.encrypt.length,h),i.encrypt(u,h)},decrypt(u,h){if(xe(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,h),i.decrypt(u,h)}}}return Object.assign(r,t),r};function Mo(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(xe(e,void 0,"output"),e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(r&&!In(e))throw new Error("invalid output, must be aligned");return e}function vp(t,e,r){Ln(t),Ln(e),Di(r);let n=new Uint8Array(16),o=tw(n);return o.setBigUint64(0,BigInt(e),r),o.setBigUint64(8,BigInt(t),r),n}function In(t){return t.byteOffset%4===0}function _n(t){return Uint8Array.from(xe(t))}var Ip=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),ow=Rt(pt(Ip("expand 16-byte k"))),sw=Rt(pt(Ip("expand 32-byte k")));function G(t,e){return t<<e|t>>>32-e}var ko=64,iw=16,Jf=2**32-1,Lp=Uint32Array.of();function aw(t,e,r,n,o,s,i,a){let c=o.length,f=new Uint8Array(ko),u=pt(f),h=Or&&In(o)&&In(s),m=h?pt(o):Lp,p=h?pt(s):Lp;if(!Or){for(let d=0;d<c;i++){if(t(e,r,n,u,i,a),Rt(u),i>=Jf)throw new Error("arx: counter overflow");let y=Math.min(ko,c-d);for(let l=0,g;l<y;l++)g=d+l,s[g]=o[g]^f[l];d+=y}return}for(let d=0;d<c;i++){if(t(e,r,n,u,i,a),i>=Jf)throw new Error("arx: counter overflow");let y=Math.min(ko,c-d);if(h&&y===ko){let l=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let g=0,E;g<iw;g++)E=l+g,p[E]=m[E]^u[g];d+=ko;continue}for(let l=0,g;l<y;l++)g=d+l,s[g]=o[g]^f[l];d+=y}}function _p(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Ep({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Ln(o),Ln(i),Di(s),Di(r),(a,c,f,u,h=0)=>{xe(a,void 0,"key"),xe(c,void 0,"nonce"),xe(f,void 0,"data");let m=f.length;if(u=Mo(m,u,!1),Ln(h),h<0||h>=Jf)throw new Error("arx: counter overflow");let p=[],d=a.length,y,l;if(d===32)p.push(y=_n(a)),l=sw;else if(d===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),l=ow,p.push(y);else throw xe(a,32,"arx key"),new Error("invalid key size");(!Or||!In(c))&&p.push(c=_n(c));let g=pt(y);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let T=c.subarray(0,16);if(Or)n(l,g,pt(T),g);else{let B=Rt(Uint32Array.from(l));n(B,g,pt(T),g),nt(B),Rt(g)}c=c.subarray(16)}else Or||Rt(g);let E=16-o;if(E!==c.length)throw new Error(`arx: nonce must be ${E} or 16 bytes`);if(E!==12){let T=new Uint8Array(12);T.set(c,s?0:12-c.length),c=T,p.push(c)}let v=Rt(pt(c));try{return aw(t,l,g,v,f,u,h,i),u}finally{nt(...p)}}}function ve(t,e){return t[e++]&255|(t[e++]&255)<<8}var Qf=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=_n(xe(e,32,"key"));let r=ve(e,0),n=ve(e,2),o=ve(e,4),s=ve(e,6),i=ve(e,8),a=ve(e,10),c=ve(e,12),f=ve(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|f<<8)&8191,this.r[9]=f>>>5&127;for(let u=0;u<8;u++)this.pad[u]=ve(e,16+2*u)}process(e,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],f=i[2],u=i[3],h=i[4],m=i[5],p=i[6],d=i[7],y=i[8],l=i[9],g=ve(e,r+0),E=ve(e,r+2),v=ve(e,r+4),T=ve(e,r+6),B=ve(e,r+8),R=ve(e,r+10),D=ve(e,r+12),I=ve(e,r+14),P=s[0]+(g&8191),M=s[1]+((g>>>13|E<<3)&8191),N=s[2]+((E>>>10|v<<6)&8191),x=s[3]+((v>>>7|T<<9)&8191),C=s[4]+((T>>>4|B<<12)&8191),A=s[5]+(B>>>1&8191),w=s[6]+((B>>>14|R<<2)&8191),b=s[7]+((R>>>11|D<<5)&8191),L=s[8]+((D>>>8|I<<8)&8191),_=s[9]+(I>>>5|o),S=0,F=S+P*a+M*(5*l)+N*(5*y)+x*(5*d)+C*(5*p);S=F>>>13,F&=8191,F+=A*(5*m)+w*(5*h)+b*(5*u)+L*(5*f)+_*(5*c),S+=F>>>13,F&=8191;let O=S+P*c+M*a+N*(5*l)+x*(5*y)+C*(5*d);S=O>>>13,O&=8191,O+=A*(5*p)+w*(5*m)+b*(5*h)+L*(5*u)+_*(5*f),S+=O>>>13,O&=8191;let U=S+P*f+M*c+N*a+x*(5*l)+C*(5*y);S=U>>>13,U&=8191,U+=A*(5*d)+w*(5*p)+b*(5*m)+L*(5*h)+_*(5*u),S+=U>>>13,U&=8191;let H=S+P*u+M*f+N*c+x*a+C*(5*l);S=H>>>13,H&=8191,H+=A*(5*y)+w*(5*d)+b*(5*p)+L*(5*m)+_*(5*h),S+=H>>>13,H&=8191;let K=S+P*h+M*u+N*f+x*c+C*a;S=K>>>13,K&=8191,K+=A*(5*l)+w*(5*y)+b*(5*d)+L*(5*p)+_*(5*m),S+=K>>>13,K&=8191;let ee=S+P*m+M*h+N*u+x*f+C*c;S=ee>>>13,ee&=8191,ee+=A*a+w*(5*l)+b*(5*y)+L*(5*d)+_*(5*p),S+=ee>>>13,ee&=8191;let te=S+P*p+M*m+N*h+x*u+C*f;S=te>>>13,te&=8191,te+=A*c+w*a+b*(5*l)+L*(5*y)+_*(5*d),S+=te>>>13,te&=8191;let re=S+P*d+M*p+N*m+x*h+C*u;S=re>>>13,re&=8191,re+=A*f+w*c+b*a+L*(5*l)+_*(5*y),S+=re>>>13,re&=8191;let W=S+P*y+M*d+N*p+x*m+C*h;S=W>>>13,W&=8191,W+=A*u+w*f+b*c+L*a+_*(5*l),S+=W>>>13,W&=8191;let ae=S+P*l+M*y+N*d+x*p+C*m;S=ae>>>13,ae&=8191,ae+=A*h+w*u+b*f+L*c+_*a,S+=ae>>>13,ae&=8191,S=(S<<2)+S|0,S=S+F|0,F=S&8191,S=S>>>13,O+=S,s[0]=F,s[1]=O,s[2]=U,s[3]=H,s[4]=K,s[5]=ee,s[6]=te,s[7]=re,s[8]=W,s[9]=ae}finalize(){let{h:e,pad:r}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+r[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+r[a]|0)+(i>>>16)|0,e[a]=i&65535;nt(n)}update(e){Zf(this),xe(e),e=_n(e);let{buffer:r,blockLen:n}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,nt(this.h,this.r,this.buffer,this.pad)}digestInto(e){Zf(this),wp(e,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:o}=this;if(o){for(r[o++]=1;o<16;o++)r[o]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}},Tp=Ap(32,t=>new Qf(t));function cw(t,e,r,n,o,s=20){let i=t[0],a=t[1],c=t[2],f=t[3],u=e[0],h=e[1],m=e[2],p=e[3],d=e[4],y=e[5],l=e[6],g=e[7],E=o,v=r[0],T=r[1],B=r[2],R=i,D=a,I=c,P=f,M=u,N=h,x=m,C=p,A=d,w=y,b=l,L=g,_=E,S=v,F=T,O=B;for(let H=0;H<s;H+=2)R=R+M|0,_=G(_^R,16),A=A+_|0,M=G(M^A,12),R=R+M|0,_=G(_^R,8),A=A+_|0,M=G(M^A,7),D=D+N|0,S=G(S^D,16),w=w+S|0,N=G(N^w,12),D=D+N|0,S=G(S^D,8),w=w+S|0,N=G(N^w,7),I=I+x|0,F=G(F^I,16),b=b+F|0,x=G(x^b,12),I=I+x|0,F=G(F^I,8),b=b+F|0,x=G(x^b,7),P=P+C|0,O=G(O^P,16),L=L+O|0,C=G(C^L,12),P=P+C|0,O=G(O^P,8),L=L+O|0,C=G(C^L,7),R=R+N|0,O=G(O^R,16),b=b+O|0,N=G(N^b,12),R=R+N|0,O=G(O^R,8),b=b+O|0,N=G(N^b,7),D=D+x|0,_=G(_^D,16),L=L+_|0,x=G(x^L,12),D=D+x|0,_=G(_^D,8),L=L+_|0,x=G(x^L,7),I=I+C|0,S=G(S^I,16),A=A+S|0,C=G(C^A,12),I=I+C|0,S=G(S^I,8),A=A+S|0,C=G(C^A,7),P=P+M|0,F=G(F^P,16),w=w+F|0,M=G(M^w,12),P=P+M|0,F=G(F^P,8),w=w+F|0,M=G(M^w,7);let U=0;n[U++]=i+R|0,n[U++]=a+D|0,n[U++]=c+I|0,n[U++]=f+P|0,n[U++]=u+M|0,n[U++]=h+N|0,n[U++]=m+x|0,n[U++]=p+C|0,n[U++]=d+A|0,n[U++]=y+w|0,n[U++]=l+b|0,n[U++]=g+L|0,n[U++]=E+_|0,n[U++]=v+S|0,n[U++]=T+F|0,n[U++]=B+O|0}var fw=_p(cw,{counterRight:!1,counterLength:4,allowShortKeys:!1});var uw=new Uint8Array(16),Dp=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(uw.subarray(r))},hw=new Uint8Array(32);function Bp(t,e,r,n,o){o!==void 0&&xe(o,void 0,"AAD");let s=t(e,r,hw),i=vp(n.length,o?o.length:0,!0),a=Tp.create(s);o&&Dp(a,o),Dp(a,n),a.update(i);let c=a.digest();return nt(s,i),c}var lw=t=>(e,r,n)=>({encrypt(s,i){let a=s.length;i=Mo(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);t(e,r,c,c,1);let f=Bp(t,e,r,c,n);return i.set(f,a),nt(f),i},decrypt(s,i){i=Mo(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),f=Bp(t,e,r,a,n);if(!Sp(c,f))throw nt(f),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,r,i,i,1),nt(f),i}}),eu=Cp({blockSize:64,nonceLength:12,tagLength:16},lw(fw));function Fp(t,e,r){return mr(t),r===void 0&&(r=new Uint8Array(t.outputLen)),Eo(t,r,e)}var tu=Uint8Array.of(0),Rp=Uint8Array.of();function Op(t,e,r,n=32){mr(t),it(n,"length"),Le(e,void 0,"prk");let o=t.outputLen;if(e.length<o)throw new Error('"prk" must be at least HashLen octets');if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);r===void 0?r=Rp:Le(r,void 0,"info");let i=new Uint8Array(s*o),a=Eo.create(t,e),c=a._cloneInto(),f=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)tu[0]=u+1,c.update(u===0?Rp:f).update(r).update(tu).digestInto(f),i.set(f,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),Ze(f,tu),i.slice(0,n)}var ru={hashSHA256(t){return ct(t.subarray())},getHKDF(t,e){let r=Fp(ct,e,t),o=Op(ct,r,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let t=ao.utils.randomSecretKey();return{publicKey:ao.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:ao.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return ao.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,r,n){return eu(n,e,r).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,r,n,o){return eu(n,e,r).decrypt(t.subarray(),o)}};var Pp=ru;function Np(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,r)=>t.generateX25519SharedKey(e.privateKey,r).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}var Tn=t=>{let e=qe(2);return e[0]=t>>8,e[1]=t,e};Tn.bytes=2;var Dn=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");if(t instanceof Uint8Array){let e=0;return e+=t[0]<<8,e+=t[1],e}return t.getUint16(0)};Dn.bytes=2;function Up(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var au={};z(au,{base10:()=>bw});var xL=new Uint8Array(0);function Mp(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function Ft(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function kp(t){return new TextEncoder().encode(t)}function Kp(t){return new TextDecoder().decode(t)}function dw(t,e){if(t.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 o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=t.length,c=t.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,l=0,g=0,E=d.length;g!==E&&d[g]===0;)g++,y++;for(var v=(E-g)*u+1>>>0,T=new Uint8Array(v);g!==E;){for(var B=d[g],R=0,D=v-1;(B!==0||R<l)&&D!==-1;D--,R++)B+=256*T[D]>>>0,T[D]=B%a>>>0,B=B/a>>>0;if(B!==0)throw new Error("Non-zero carry");l=R,g++}for(var I=v-l;I!==v&&T[I]===0;)I++;for(var P=c.repeat(y);I<v;++I)P+=t.charAt(T[I]);return P}function m(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var l=0,g=0;d[y]===c;)l++,y++;for(var E=(d.length-y)*f+1>>>0,v=new Uint8Array(E);d[y];){var T=r[d.charCodeAt(y)];if(T===255)return;for(var B=0,R=E-1;(T!==0||B<g)&&R!==-1;R--,B++)T+=a*v[R]>>>0,v[R]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");g=B,y++}if(d[y]!==" "){for(var D=E-g;D!==E&&v[D]===0;)D++;for(var I=new Uint8Array(l+(E-D)),P=l;D!==E;)I[P++]=v[D++];return I}}}function p(d){var y=m(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:m,decode:p}}var pw=dw,mw=pw,zp=mw;var nu=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ou=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){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))}else throw Error("Can only multibase decode strings")}or(e){return Vp(this,e)}},su=class{decoders;constructor(e){this.decoders=e}or(e){return Vp(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Vp(t,e){return new su({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var iu=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new nu(e,r,n),this.decoder=new ou(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Bn({name:t,prefix:e,encode:r,decode:n}){return new iu(t,e,r,n)}function ir({name:t,prefix:e,alphabet:r}){let{encode:n,decode:o}=zp(r,t);return Bn({prefix:e,name:t,encode:n,decode:s=>Ft(o(s))})}function gw(t,e,r,n){let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=e[t[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|u,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function yw(t,e,r){let n=e[e.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function xw(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function me({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let o=xw(n);return Bn({prefix:e,name:t,encode(s){return yw(s,n,r)},decode(s){return gw(s,o,r,t)}})}var bw=ir({prefix:"9",name:"base10",alphabet:"0123456789"});var cu={};z(cu,{base16:()=>ww,base16upper:()=>Ew});var ww=me({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ew=me({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var fu={};z(fu,{base2:()=>Sw});var Sw=me({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var uu={};z(uu,{base256emoji:()=>Iw});var $p=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Aw=$p.reduce((t,e,r)=>(t[r]=e,t),[]),Cw=$p.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function vw(t){return t.reduce((e,r)=>(e+=Aw[r],e),"")}function Lw(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=Cw[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var Iw=Bn({prefix:"\u{1F680}",name:"base256emoji",encode:vw,decode:Lw});var hu={};z(hu,{base32:()=>Rn,base32hex:()=>Bw,base32hexpad:()=>Fw,base32hexpadupper:()=>Ow,base32hexupper:()=>Rw,base32pad:()=>Tw,base32padupper:()=>Dw,base32upper:()=>_w,base32z:()=>Pw});var Rn=me({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),_w=me({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Tw=me({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Dw=me({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Bw=me({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Rw=me({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Fw=me({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ow=me({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Pw=me({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var lu={};z(lu,{base36:()=>Ko,base36upper:()=>Nw});var Ko=ir({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Nw=ir({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var du={};z(du,{base58btc:()=>mt,base58flickr:()=>Uw});var mt=ir({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Uw=ir({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var pu={};z(pu,{base64:()=>Mw,base64pad:()=>kw,base64url:()=>Kw,base64urlpad:()=>Hw});var Mw=me({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),kw=me({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Kw=me({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Hw=me({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var mu={};z(mu,{base8:()=>zw});var zw=me({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var gu={};z(gu,{identity:()=>Vw});var Vw=Bn({prefix:"\0",name:"identity",encode:t=>Kp(t),decode:t=>kp(t)});var OL=new TextEncoder,PL=new TextDecoder;var xu={};z(xu,{identity:()=>l2});var jw=Gp,qp=128,Gw=127,Ww=~Gw,Xw=Math.pow(2,31);function Gp(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Xw;)e[r++]=t&255|qp,t/=128;for(;t&Ww;)e[r++]=t&255|qp,t>>>=7;return e[r]=t|0,Gp.bytes=r-n+1,e}var Yw=yu,Zw=128,jp=127;function yu(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw yu.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&jp)<<o:(i&jp)*Math.pow(2,o),o+=7}while(i>=Zw);return yu.bytes=s-n,r}var Jw=Math.pow(2,7),Qw=Math.pow(2,14),e2=Math.pow(2,21),t2=Math.pow(2,28),r2=Math.pow(2,35),n2=Math.pow(2,42),o2=Math.pow(2,49),s2=Math.pow(2,56),i2=Math.pow(2,63),a2=function(t){return t<Jw?1:t<Qw?2:t<e2?3:t<t2?4:t<r2?5:t<n2?6:t<o2?7:t<s2?8:t<i2?9:10},c2={encode:jw,decode:Yw,encodingLength:a2},f2=c2,Ho=f2;function zo(t,e=0){return[Ho.decode(t,e),Ho.decode.bytes]}function Fn(t,e,r=0){return Ho.encode(t,e,r),e}function On(t){return Ho.encodingLength(t)}function Nn(t,e){let r=e.byteLength,n=On(t),o=n+On(r),s=new Uint8Array(o+r);return Fn(t,s,0),Fn(r,s,n),s.set(e,o),new Pn(t,r,e,s)}function Wp(t){let e=Ft(t),[r,n]=zo(e),[o,s]=zo(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Pn(r,o,i,e)}function Xp(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Mp(t.bytes,r.bytes)}}var Pn=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};var Yp=0,u2="identity",Zp=Ft;function h2(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return Nn(Yp,Zp(t))}var l2={code:Yp,name:u2,encode:Zp,digest:h2};var Eu={};z(Eu,{sha256:()=>p2,sha512:()=>m2});var d2=20;function wu({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new bu(t,e,r,n,o)}var bu=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??d2,this.maxDigestLength=s}digest(e,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Jp(n,this.code,r?.truncate):n.then(o=>Jp(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function Jp(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return Nn(e,t)}function em(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var p2=wu({name:"sha2-256",code:18,encode:em("SHA-256")}),m2=wu({name:"sha2-512",code:19,encode:em("SHA-512")});function tm(t,e){let{bytes:r,version:n}=t;return n===0?y2(r,Su(t),e??mt.encoder):x2(r,Su(t),e??Rn.encoder)}var rm=new WeakMap;function Su(t){let e=rm.get(t);if(e==null){let r=new Map;return rm.set(t,r),r}return e}var Ri=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}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:{let{code:e,multihash:r}=this;if(e!==$o)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==b2)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}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:{let{code:e,digest:r}=this.multihash,n=Nn(e,r);return t.createV1(this.code,n)}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 t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&Xp(e.multihash,n.multihash)}toString(e){return tm(this,e)}toJSON(){return{"/":tm(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new t(n,o,s,i??nm(n,o,s.bytes))}else if(r[w2]===!0){let{version:n,multihash:o,code:s}=r,i=Wp(o);return t.create(n,s,i)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==$o)throw new Error(`Version 0 CID must use dag-pb (code: ${$o}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=nm(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,$o,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=Ft(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new Pn(r.multihashCode,r.digestSize,s,o);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[h,m]=zo(e.subarray(r));return r+=m,h},o=n(),s=$o;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),f=r+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,r){let[n,o]=g2(e,r),s=t.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Su(s).set(n,e),s}};function g2(t,e){switch(t[0]){case"Q":{let r=e??mt;return[mt.prefix,r.decode(`${mt.prefix}${t}`)]}case mt.prefix:{let r=e??mt;return[mt.prefix,r.decode(t)]}case Rn.prefix:{let r=e??Rn;return[Rn.prefix,r.decode(t)]}case Ko.prefix:{let r=e??Ko;return[Ko.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function y2(t,e,r){let{prefix:n}=r;if(n!==mt.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function x2(t,e,r){let{prefix:n}=r,o=e.get(n);if(o==null){let s=r.encode(t);return e.set(n,s),s}else return o}var $o=112,b2=18;function nm(t,e,r){let n=On(t),o=n+On(e),s=new Uint8Array(o+r.byteLength);return Fn(t,s,0),Fn(e,s,n),s.set(r,o),s}var w2=Symbol.for("@ipld/js-cid/CID");var Au={...gu,...fu,...mu,...au,...cu,...hu,...lu,...du,...pu,...uu},nI={...Eu,...xu};function sm(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var om=sm("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Cu=sm("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=qe(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),E2={utf8:om,"utf-8":om,hex:Au.base16,latin1:Cu,ascii:Cu,binary:Cu,...Au},Fi=E2;function gt(t,e="utf8"){let r=Fi[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}function vu(t,e){!e.enabled||!vn||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${gt(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${gt(t.privateKey,"hex")}`)):e("Missing local static keys."))}function Lu(t,e){!e.enabled||!vn||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${gt(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${gt(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function im(t,e){!e.enabled||!vn||e(t?`REMOTE_STATIC_PUBLIC_KEY ${gt(t.subarray(),"hex")}`:"Missing remote static public key.")}function Iu(t,e){!e.enabled||!vn||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${gt(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function _u(t,e,r){!r.enabled||!vn||(r(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&>(t.k,"hex")}`),r(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&>(e.k,"hex")}`))}function Tu(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=qe(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}function Pr(t,e="utf8"){let r=Fi[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}var Un=class t extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=t.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var A2=0,C2=4294967295,v2="Cipherstate has reached maximum n, a new handshake must be performed",Oi=class{n;bytes;view;constructor(e=A2){this.n=e,this.bytes=dt(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>C2)throw new Error(v2)}};var Nr=dt(0),Mn=class{k;n;crypto;constructor(e,r=void 0,n=0){this.crypto=e,this.k=r,this.n=new Oi(n)}hasKey(){return!!this.k}encryptWithAd(e,r){if(!this.hasKey())return r;this.n.assertValue();let n=this.crypto.encrypt(r,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,r,n){if(!this.hasKey())return r;this.n.assertValue();let o=this.crypto.decrypt(r,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},Du=class{cs;ck;h;crypto;constructor(e,r){this.crypto=e;let n=Pr(r,"utf-8");this.h=L2(e,n),this.ck=this.h,this.cs=new Mn(e)}mixKey(e){let[r,n]=this.crypto.hkdf(this.ck,e);this.ck=r,this.cs=new Mn(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new V(this.h,e))}encryptAndHash(e){let r=this.cs.encryptWithAd(this.h,e);return this.mixHash(r),r}decryptAndHash(e){let r=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),r}split(){let[e,r]=this.crypto.hkdf(this.ck,Nr);return[new Mn(this.crypto,e),new Mn(this.crypto,r)]}},Bu=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:r,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:f}=e;this.crypto=r,this.ss=new Du(r,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=f}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new 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 new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new 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 new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<r+32)throw new Error("message is not long enough");this.re=e.sublist(r,r+32),this.ss.mixHash(this.re)}readS(e,r=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<r+n)throw new Error("message is not long enough");let o=e.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},qo=class extends Bu{writeMessageA(e){return new V(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let r=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new V(r,n,this.ss.encryptAndHash(e))}writeMessageC(e){let r=this.writeS();return this.writeSE(),new V(r,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(r){throw new Un(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let r=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+r))}catch(r){throw new Un(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(e){try{let r=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(r))}catch(r){throw new Un(`handshake stage 2 validation fail: ${r.message}`)}}};function L2(t,e){if(e.length<=32){let r=dt(32);return r.set(e),r}else return t.hash(e)}var I2=Math.pow(2,7),_2=Math.pow(2,14),T2=Math.pow(2,21),am=Math.pow(2,28),cm=Math.pow(2,35),fm=Math.pow(2,42),um=Math.pow(2,49),Me=128,ar=127;function jo(t){if(t<I2)return 1;if(t<_2)return 2;if(t<T2)return 3;if(t<am)return 4;if(t<cm)return 5;if(t<fm)return 6;if(t<um)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function hm(t,e,r=0){switch(jo(t)){case 8:e[r++]=t&255|Me,t/=128;case 7:e[r++]=t&255|Me,t/=128;case 6:e[r++]=t&255|Me,t/=128;case 5:e[r++]=t&255|Me,t/=128;case 4:e[r++]=t&255|Me,t>>>=7;case 3:e[r++]=t&255|Me,t>>>=7;case 2:e[r++]=t&255|Me,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function lm(t,e){let r=t[e],n=0;if(n+=r&ar,r<Me||(r=t[e+1],n+=(r&ar)<<7,r<Me)||(r=t[e+2],n+=(r&ar)<<14,r<Me)||(r=t[e+3],n+=(r&ar)<<21,r<Me)||(r=t[e+4],n+=(r&ar)*am,r<Me)||(r=t[e+5],n+=(r&ar)*cm,r<Me)||(r=t[e+6],n+=(r&ar)*fm,r<Me)||(r=t[e+7],n+=(r&ar)*um,r<Me))return n;throw new RangeError("Could not decode varint")}var Ru=new Float32Array([-0]),cr=new Uint8Array(Ru.buffer);function dm(t,e,r){Ru[0]=t,e[r]=cr[0],e[r+1]=cr[1],e[r+2]=cr[2],e[r+3]=cr[3]}function pm(t,e){return cr[0]=t[e],cr[1]=t[e+1],cr[2]=t[e+2],cr[3]=t[e+3],Ru[0]}var Fu=new Float64Array([-0]),Fe=new Uint8Array(Fu.buffer);function mm(t,e,r){Fu[0]=t,e[r]=Fe[0],e[r+1]=Fe[1],e[r+2]=Fe[2],e[r+3]=Fe[3],e[r+4]=Fe[4],e[r+5]=Fe[5],e[r+6]=Fe[6],e[r+7]=Fe[7]}function gm(t,e){return Fe[0]=t[e],Fe[1]=t[e+1],Fe[2]=t[e+2],Fe[3]=t[e+3],Fe[4]=t[e+4],Fe[5]=t[e+5],Fe[6]=t[e+6],Fe[7]=t[e+7],Fu[0]}var D2=BigInt(Number.MAX_SAFE_INTEGER),B2=BigInt(Number.MIN_SAFE_INTEGER),je=class t{lo;hi;constructor(e,r){this.lo=e|0,this.hi=r|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Ur;if(e<D2&&e>B2)return this.fromNumber(Number(e));let r=e<0n;r&&(e=-e);let n=e>>32n,o=e-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>ym&&(o=0n,++n>ym&&(n=0n))),new t(Number(o),Number(n))}static fromNumber(e){if(e===0)return Ur;let r=e<0;r&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new t(n,o)}static from(e){return typeof e=="number"?t.fromNumber(e):typeof e=="bigint"?t.fromBigInt(e):typeof e=="string"?t.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new t(e.low>>>0,e.high>>>0):Ur}},Ur=new je(0,0);Ur.toBigInt=function(){return 0n};Ur.zzEncode=Ur.zzDecode=function(){return this};Ur.length=function(){return 1};var ym=4294967296n;function xm(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(r&64512)===55296&&(t.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function bm(t,e,r){if(r-e<1)return"";let o,s=[],i=0,a;for(;e<r;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Ou(t,e,r){let n=r,o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128);return r-n}function ot(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function Pi(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}var Pu=class{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=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,ot(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ot(this,4);return Pi(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ot(this,4);return Pi(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ot(this,4);let e=pm(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ot(this,4);let e=gm(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw ot(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let e=this.bytes();return bm(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ot(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ot(this);while((this.buf[this.pos++]&128)!==0);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(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new je(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw ot(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,e}if(this.len-this.pos>4){for(;r<5;++r)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;r<5;++r){if(this.pos>=this.len)throw ot(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ot(this,8);let e=Pi(this.buf,this.pos+=4),r=Pi(this.buf,this.pos+=4);return new je(e,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=lm(this.buf,this.pos);return this.pos+=jo(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 Nu(t){return new Pu(t instanceof Uint8Array?t:t.subarray())}function Ni(t,e,r){let n=Nu(t);return e.decode(n,void 0,r)}function Uu(t){let e=t??8192,r=e>>>1,n,o=e;return function(i){if(i<1||i>r)return qe(i);o+i>e&&(n=qe(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Mr=class{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}};function Mu(){}var Ku=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},R2=Uu();function F2(t){return globalThis.Buffer!=null?qe(t):R2(t)}var Wo=class{len;head;tail;states;constructor(){this.len=0,this.head=new Mr(Mu,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new Mr(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Hu((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Ui,10,je.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let r=je.fromBigInt(e);return this._push(Ui,r.length(),r)}uint64Number(e){return this._push(hm,jo(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){let r=je.fromBigInt(e).zzEncode();return this._push(Ui,r.length(),r)}sint64Number(e){let r=je.fromNumber(e).zzEncode();return this._push(Ui,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ku,1,e?1:0)}fixed32(e){return this._push(Go,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let r=je.fromBigInt(e);return this._push(Go,4,r.lo)._push(Go,4,r.hi)}fixed64Number(e){let r=je.fromNumber(e);return this._push(Go,4,r.lo)._push(Go,4,r.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(dm,4,e)}double(e){return this._push(mm,8,e)}bytes(e){let r=e.length>>>0;return r===0?this._push(ku,1,0):this.uint32(r)._push(P2,r,e)}string(e){let r=xm(e);return r!==0?this.uint32(r)._push(Ou,r,e):this._push(ku,1,0)}fork(){return this.states=new Ku(this),this.head=this.tail=new Mr(Mu,0,0),this.len=0,this}reset(){return this.states!=null?(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 Mr(Mu,0,0),this.len=0),this}ldelim(){let e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next,r=F2(this.len),n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}};function ku(t,e,r){e[r]=t&255}function O2(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}var Hu=class extends Mr{next;constructor(e,r){super(O2,e,r),this.next=void 0}};function Ui(t,e,r){for(;t.hi!==0;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}function Go(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function P2(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(Wo.prototype.bytes=function(t){let e=t.length>>>0;return this.uint32(e),e>0&&this._push(N2,e,t),this},Wo.prototype.string=function(t){let e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(U2,e,t),this});function N2(t,e,r){e.set(t,r)}function U2(t,e,r){t.length<40?Ou(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(Pr(t),r)}function zu(){return new Wo}function Mi(t,e){let r=zu();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var Xo;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(Xo||(Xo={}));function Vu(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function ki(t,e){return Vu("message",Xo.LENGTH_DELIMITED,t,e)}var Yo=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Ki;(function(t){let e;t.codec=()=>(e==null&&(e=ki((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(let s of r.webtransportCerthashes)n.uint32(10),n.bytes(s);if(r.streamMuxers!=null)for(let s of r.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new Yo('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(r.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new Yo('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(r.string());break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Mi(r,t.codec()),t.decode=(r,n)=>Ni(r,t.codec(),n)})(Ki||(Ki={}));var Zo;(function(t){let e;t.codec=()=>(e==null&&(e=ki((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.identityKey!=null&&r.identityKey.byteLength>0&&(n.uint32(10),n.bytes(r.identityKey)),r.identitySig!=null&&r.identitySig.byteLength>0&&(n.uint32(18),n.bytes(r.identitySig)),r.extensions!=null&&(n.uint32(34),Ki.codec().encode(r.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={identityKey:dt(0),identitySig:dt(0)},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{s.identityKey=r.bytes();break}case 2:{s.identitySig=r.bytes();break}case 4:{s.extensions=Ki.codec().decode(r,r.uint32(),{limits:o.limits?.extensions});break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Mi(r,t.codec()),t.decode=(r,n)=>Ni(r,t.codec(),n)})(Zo||(Zo={}));async function qu(t,e,r){let n=await t.sign(Sm(e));return Zo.encode({identityKey:Mt(t.publicKey),identitySig:n,extensions:r})}async function ju(t,e,r){try{let n=Zo.decode(t),o=So(n.identityKey);if(r?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${r}`);if(!e)throw new Error("Remote static does not exist");let s=Sm(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Qo(n.message)}}function Sm(t){let e=Pr("noise-libp2p-static-key:");return t instanceof Uint8Array?Tu([e,t],e.length+t.length):(t.prepend(e),t)}var $u=class extends nr{stream;handshake;metrics;decoder;constructor(e,r,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=r,this.metrics=n,this.decoder=new pi({lengthDecoder:Dn,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=c=>{try{for(let f of this.decoder.decode(c.data))this.onData(this.decrypt(f))}catch(f){this.abort(f)}};this.stream.addEventListener("message",o);let s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let r=new V;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),r.append(Tn(s.byteLength)),r.append(s)}return r}decrypt(e){let r=new V;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-Yf<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);let i=e.subarray(n,o-Yf);try{let a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),r.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return r}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function Gu(t,e,r){return new $u(t,e,r)}async function Am(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=t,u=await qu(s,a.publicKey,f),h=new qo({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});vu(h.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(Nr),e),r.trace("Stage 0 - Initiator finished sending first message."),Lu(h.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");let m=h.readMessageB(await n.read(e));r.trace("Stage 1 - Initiator received the message."),Iu(h.re,r),im(h.rs,r),r.trace("Initiator going to check remote's signature...");let p=await ju(m,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),e),r.trace("Stage 2 - Initiator sent message with signed payload.");let[d,y]=h.ss.split();return _u(d,y,r),{payload:p,encrypt:l=>d.encryptWithAd(Nr,l),decrypt:(l,g)=>y.decryptWithAd(Nr,l,g)}}async function Cm(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=t,u=await qu(s,a.publicKey,f),h=new qo({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});vu(h.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await n.read(e)),r.trace("Stage 0 - Responder received first message."),Iu(h.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(h.writeMessageB(u),e),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Lu(h.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");let m=h.readMessageC(await n.read(e));r.trace("Stage 2 - Responder received the message, finished handshake.");let p=await ju(m,h.rs,c),[d,y]=h.ss.split();return _u(d,y,r),{payload:p,encrypt:l=>y.encryptWithAd(Nr,l),decrypt:(l,g)=>d.decryptWithAd(Nr,l,g)}}var Hi=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,r={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=r,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=s??Pp;this.crypto=Np(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Up(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??dt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Vr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,r){let n=e.log?.newScope("noise")??this.log,o=li(e,{lengthEncoder:Tn,lengthDecoder:Dn,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=So(s.payload.identityKey);return{connection:Gu(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:jc(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let r=this.components.upgrader.getStreamMuxers();if(r!=null)for(let n of e){let o=r.get(n);if(o!=null)return o}if(e.length)throw new es("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,r){let n=e.log?.newScope("noise")??this.log,o=li(e,{lengthEncoder:Tn,lengthDecoder:Dn,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=So(s.payload.identityKey);return{connection:Gu(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:jc(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Am({connection:e,privateKey:r,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Cm({connection:e,privateKey:r,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function vm(t={}){return e=>new Hi(e,t)}var Wu=Object.values(dr).map(t=>t.decoder).reduce((t,e)=>t.or(e)),M2=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function Lm(t){return t?.match(M2)?.groups?.fingerprint}function Xu(t){let r=t.getComponents().find(n=>n.code===466)?.value;if(r===void 0||r==="")throw new j(`Couldn't find a certhash component of multiaddr: ${t.toString()}`);return r}function k2(t){return Xe.decode(Wu.decode(t))}function K2(t){let e=k2(Xu(t)),r=H2(e.code),n=e.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new Ai(n,t.toString());return`${r} ${o.join(":").toUpperCase()}`}function Im(t){let e=t.split(":").map(o=>parseInt(o,16)),r=Uint8Array.from(e),n=Oe(wt.code,r);return bn(`/certhash/${Gn.encode(n.bytes)}`)}function H2(t){switch(t){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new vi(t)}}function _m(t,e){let{host:r,port:n,type:o}=Df(t);if(o!=="ip4"&&o!=="ip6")throw new j(`Multiaddr ${t} was not an IPv4 or IPv6 address`);let s=K2(t);return{type:"answer",sdp:`v=0
|
|
3
3
|
o=- 0 0 IN IP${o==="ip4"?4:6} ${r}
|
|
4
4
|
s=-
|
|
5
5
|
t=0 0
|
|
@@ -13,10 +13,10 @@ a=ice-pwd:${e}
|
|
|
13
13
|
a=fingerprint:${s}
|
|
14
14
|
a=setup:passive
|
|
15
15
|
a=sctp-port:5000
|
|
16
|
-
a=max-message-size:${
|
|
16
|
+
a=max-message-size:${En}
|
|
17
17
|
a=candidate:1467250027 1 UDP 1467250027 ${r} ${n} typ host
|
|
18
18
|
a=end-of-candidates
|
|
19
|
-
`}}function
|
|
19
|
+
`}}function Tm(t,e){let{host:r,port:n,type:o}=Df(t);if(o!=="ip4"&&o!=="ip6")throw new j(`Multiaddr ${t} was not an IPv4 or IPv6 address`);return{type:"offer",sdp:`v=0
|
|
20
20
|
o=- 0 0 IN IP${o==="ip4"?4:6} ${r}
|
|
21
21
|
s=-
|
|
22
22
|
c=IN IP${o==="ip4"?4:6} ${r}
|
|
@@ -29,15 +29,15 @@ a=ice-ufrag:${e}
|
|
|
29
29
|
a=ice-pwd:${e}
|
|
30
30
|
a=fingerprint:sha-256 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00
|
|
31
31
|
a=sctp-port:5000
|
|
32
|
-
a=max-message-size:${
|
|
32
|
+
a=max-message-size:${En}
|
|
33
33
|
a=candidate:1467250027 1 UDP 1467250027 ${r} ${n} typ host
|
|
34
34
|
a=end-of-candidates
|
|
35
|
-
`}}function
|
|
35
|
+
`}}function Yu(t,e){if(t.sdp===void 0)throw new j("Can't munge a missing SDP");let r=t.sdp.includes(`\r
|
|
36
36
|
`)?`\r
|
|
37
37
|
`:`
|
|
38
38
|
`;try{t.sdp=t.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
|
|
39
39
|
a=ice-ufrag:`+e+r).replace(/\na=ice-pwd:[^\n]*\n/,`
|
|
40
|
-
a=ice-pwd:`+e+r)}catch{}return t}var
|
|
40
|
+
a=ice-pwd:`+e+r)}catch{}return t}var Zu=ne("libp2p-webrtc-noise:");function Bm(t,e,r){let n=t.trim().toLowerCase().replaceAll(":",""),o=ne(n,"hex"),s=Oe(wt.code,o),i=Wu.decode(Xu(e)),a=Zu.byteLength+s.bytes.byteLength+i.byteLength;return r==="server"?ft([Zu,i,s.bytes],a):ft([Zu,s.bytes,i],a)}function z2(t,e){return t.role==="server"}async function Rm(t,e,r,n){let o=t.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let h=await t.createOffer();n.log.trace("client created local offer %s",h.sdp);let m=Yu(h,r);n.log.trace("client setting local offer %s",m.sdp),await t.setLocalDescription(m);let p=_m(n.remoteAddr,r);n.log.trace("client setting server description %s",p.sdp),await t.setRemoteDescription(p)}else{let h=Tm(n.remoteAddr,r);n.log.trace("server setting client %s %s",h.type,h.sdp),await t.setRemoteDescription(h),n.log.trace("server creating local answer");let m=await t.createAnswer();n.log.trace("server created local answer");let p=Yu(m,r);n.log.trace("server setting local description %s",m.sdp),await t.setLocalDescription(p)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Ce(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),z2(n,t)){let h=t.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(Im(h))}let s=Lm(t.localDescription?.sdp);if(s==null)throw new sr("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=Bm(s,n.remoteAddr,n.role),a=vm({prologueBytes:i})(n),c=No({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),f=Uo({peerConnection:t,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(t.addEventListener("connectionstatechange",()=>{switch(t.connectionState){case"failed":case"disconnected":case"closed":f.close().catch(h=>{n.log.error("error closing connection - %e",h),f.abort(h)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let h=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(f,{skipProtection:!0,skipEncryption:!0,remotePeer:h.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let u=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});f.remoteAddr=f.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(f,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}catch(s){throw o.close(),t.close(),s}}async function Fm(t,e,r={}){let n=r.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof r.rtcConfiguration=="function"?await r.rtcConfiguration():r.rtcConfiguration,s=new RTCPeerConnection({...o??{},certificates:[n]}),i=new or({peerConnection:s,metrics:r.events,dataChannelOptions:r.dataChannel});return{peerConnection:s,muxerFactory:i}}var zi=class{log;metrics;components;init;constructor(e,r={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=r,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[us]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Vr]=["@libp2p/transport"];async dial(e,r){this.log("dial %a",e),r.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=dn(o));let s=pp(),{peerConnection:i,muxerFactory:a}=await Fm("client",s,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await Rm(i,a,s,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:r.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:r.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw i.close(),c}}createListener(e){throw new Ci("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(Yd.exactMatch)}};function V2(t){return e=>new zi(e,t)}function $2(t){return e=>new Ti(e,t)}return Mm(q2);})();
|
|
41
41
|
/*! Bundled license information:
|
|
42
42
|
|
|
43
43
|
@noble/curves/utils.js:
|