@libp2p/webrtc 6.0.19 → 6.0.20-3a5e46eaa

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 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 zs=Object.defineProperty;var Sh=Object.getOwnPropertyDescriptor;var Ah=Object.getOwnPropertyNames;var vh=Object.prototype.hasOwnProperty;var Dt=(e,t)=>{for(var r in t)zs(e,r,{get:t[r],enumerable:!0})},_h=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ah(t))!vh.call(e,o)&&o!==r&&zs(e,o,{get:()=>t[o],enumerable:!(n=Sh(t,o))||n.enumerable});return e};var Ch=e=>_h(zs({},"__esModule",{value:!0}),e);var F0={};Dt(F0,{webRTC:()=>U0,webRTCDirect:()=>N0});var so=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}},io=class extends Error{static name="InvalidCryptoExchangeError";constructor(t="Invalid crypto exchange"){super(t),this.name="InvalidCryptoExchangeError"}},G=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},br=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var ao=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}},co=class extends Error{static name="MuxerClosedError";constructor(t="The muxer is closed"){super(t),this.name="MuxerClosedError"}},wr=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}};var Jt=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}},sn=class extends Error{static name="StreamBufferError";constructor(t="The stream buffer was full"){super(t),this.name="StreamBufferError"}};var fo=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},uo=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},lo=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var ho=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var Ge=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var po=class extends Event{data;constructor(t,r){super("message",r),this.data=t}},xr=class extends Event{error;local;constructor(t,r,n){super("close",n),this.error=r,this.local=t}},mo=class extends xr{constructor(t,r){super(!0,t,r)}},go=class extends xr{constructor(t,r){super(!1,t,r)}};var qs=Symbol.for("@libp2p/peer-id");var yo=Symbol.for("@libp2p/transport");var Zc;(function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(Zc||(Zc={}));function Lh(e){return typeof e?.handleEvent=="function"}function Th(e){return(e!==!0&&e!==!1&&e?.once)??!1}var Ee=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let r=this.#t.get(t);return r==null?0:r.length}addEventListener(t,r,n){let o=Th(n);super.addEventListener(t,i=>{if(o){let a=this.#t.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==r),this.#t.set(i.type,a))}Lh(r)?r.handleEvent(i):r(i)},n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:r,once:o})}removeEventListener(t,r,n){super.removeEventListener(t.toString(),r??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==r),this.#t.set(t,o))}safeDispatchEvent(t,r={}){return this.dispatchEvent(new CustomEvent(t,r))}};var Er=Symbol.for("@libp2p/service-capabilities"),Qc=Symbol.for("@libp2p/service-dependencies");var Xs={};Dt(Xs,{base58btc:()=>lt,base58flickr:()=>Nh});var mg=new Uint8Array(0);function Jc(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function ae(e){if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}function tf(e){return new TextEncoder().encode(e)}function ef(e){return new TextDecoder().decode(e)}function Ih(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<e.length;o++){var s=e.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=e.length,c=e.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function l(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var S=0,h=0,y=0,v=g.length;y!==v&&g[y]===0;)y++,S++;for(var L=(v-y)*u+1>>>0,O=new Uint8Array(L);y!==v;){for(var D=g[y],P=0,R=L-1;(D!==0||P<h)&&R!==-1;R--,P++)D+=256*O[R]>>>0,O[R]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");h=P,y++}for(var I=L-h;I!==L&&O[I]===0;)I++;for(var N=c.repeat(S);I<L;++I)N+=e.charAt(O[I]);return N}function p(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var S=0;if(g[S]!==" "){for(var h=0,y=0;g[S]===c;)h++,S++;for(var v=(g.length-S)*f+1>>>0,L=new Uint8Array(v);g[S];){var O=r[g.charCodeAt(S)];if(O===255)return;for(var D=0,P=v-1;(O!==0||D<y)&&P!==-1;P--,D++)O+=a*L[P]>>>0,L[P]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");y=D,S++}if(g[S]!==" "){for(var R=v-y;R!==v&&L[R]===0;)R++;for(var I=new Uint8Array(h+(v-R)),N=h;R!==v;)I[N++]=L[R++];return I}}}function d(g){var S=p(g);if(S)return S;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:p,decode:d}}var Bh=Ih,Dh=Bh,nf=Dh;var js=class{name;prefix;baseEncode;constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Gs=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,r,n){this.name=t,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(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return of(this,t)}},Ws=class{decoders;constructor(t){this.decoders=t}or(t){return of(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function of(e,t){return new Ws({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var Ys=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new js(t,r,n),this.decoder=new Gs(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Sr({name:e,prefix:t,encode:r,decode:n}){return new Ys(e,t,r,n)}function Se({name:e,prefix:t,alphabet:r}){let{encode:n,decode:o}=nf(r,e);return Sr({prefix:t,name:e,encode:n,decode:s=>ae(o(s))})}function Rh(e,t,r,n){let o=e.length;for(;e[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=t[e[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 Ph(e,t,r){let n=t[t.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],i+=8;i>r;)i-=r,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function Oh(e){let t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}function ut({name:e,prefix:t,bitsPerChar:r,alphabet:n}){let o=Oh(n);return Sr({prefix:t,name:e,encode(s){return Ph(s,n,r)},decode(s){return Rh(s,o,r,e)}})}var lt=Se({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Nh=Se({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Zs={};Dt(Zs,{base32:()=>Ae,base32hex:()=>Mh,base32hexpad:()=>Hh,base32hexpadupper:()=>Vh,base32hexupper:()=>Kh,base32pad:()=>Fh,base32padupper:()=>kh,base32upper:()=>Uh,base32z:()=>$h});var Ae=ut({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Uh=ut({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Fh=ut({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),kh=ut({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Mh=ut({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kh=ut({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Hh=ut({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Vh=ut({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),$h=ut({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Qs={};Dt(Qs,{base36:()=>an,base36upper:()=>zh});var an=Se({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),zh=Se({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var $t={};Dt($t,{Digest:()=>We,create:()=>Rt,decode:()=>_r,equals:()=>ti,hasCode:()=>fd});var qh=cf,sf=128,jh=127,Gh=~jh,Wh=Math.pow(2,31);function cf(e,t,r){t=t||[],r=r||0;for(var n=r;e>=Wh;)t[r++]=e&255|sf,e/=128;for(;e&Gh;)t[r++]=e&255|sf,e>>>=7;return t[r]=e|0,cf.bytes=r-n+1,t}var Yh=Js,Xh=128,af=127;function Js(e,n){var r=0,n=n||0,o=0,s=n,i,a=e.length;do{if(s>=a)throw Js.bytes=0,new RangeError("Could not decode varint");i=e[s++],r+=o<28?(i&af)<<o:(i&af)*Math.pow(2,o),o+=7}while(i>=Xh);return Js.bytes=s-n,r}var Zh=Math.pow(2,7),Qh=Math.pow(2,14),Jh=Math.pow(2,21),td=Math.pow(2,28),ed=Math.pow(2,35),rd=Math.pow(2,42),nd=Math.pow(2,49),od=Math.pow(2,56),sd=Math.pow(2,63),id=function(e){return e<Zh?1:e<Qh?2:e<Jh?3:e<td?4:e<ed?5:e<rd?6:e<nd?7:e<od?8:e<sd?9:10},ad={encode:qh,decode:Yh,encodingLength:id},cd=ad,cn=cd;function fn(e,t=0){return[cn.decode(e,t),cn.decode.bytes]}function Ar(e,t,r=0){return cn.encode(e,t,r),t}function vr(e){return cn.encodingLength(e)}function Rt(e,t){let r=t.byteLength,n=vr(e),o=n+vr(r),s=new Uint8Array(o+r);return Ar(e,s,0),Ar(r,s,n),s.set(t,o),new We(e,r,t,s)}function _r(e){let t=ae(e),[r,n]=fn(t),[o,s]=fn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new We(r,o,i,t)}function ti(e,t){if(e===t)return!0;{let r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&Jc(e.bytes,r.bytes)}}var We=class{code;size;digest;bytes;constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}};function fd(e,t){return e.code===t}function ff(e,t){let{bytes:r,version:n}=e;return n===0?ld(r,ei(e),t??lt.encoder):hd(r,ei(e),t??Ae.encoder)}var uf=new WeakMap;function ei(e){let t=uf.get(e);if(t==null){let r=new Map;return uf.set(e,r),r}return t}var dt=class e{code;version;multihash;bytes;"/";constructor(t,r,n,o){this.code=r,this.version=t,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:t,multihash:r}=this;if(t!==un)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==dd)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.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:t,digest:r}=this.multihash,n=Rt(t,r);return e.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(t){return e.equals(this,t)}static equals(t,r){let n=r;return n!=null&&t.code===n.code&&t.version===n.version&&ti(t.multihash,n.multihash)}toString(t){return ff(this,t)}toJSON(){return{"/":ff(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let r=t;if(r instanceof e)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new e(n,o,s,i??lf(n,o,s.bytes))}else if(r[pd]===!0){let{version:n,multihash:o,code:s}=r,i=_r(o);return e.create(n,s,i)}else return null}static create(t,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(t){case 0:{if(r!==un)throw new Error(`Version 0 CID must use dag-pb (code: ${un}) block encoding`);return new e(t,r,n,n.bytes)}case 1:{let o=lf(t,r,n.bytes);return new e(t,r,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,un,t)}static createV1(t,r){return e.create(1,t,r)}static decode(t){let[r,n]=e.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=e.inspectBytes(t),n=r.size-r.multihashSize,o=ae(t.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 We(r.multihashCode,r.digestSize,s,o);return[r.version===0?e.createV0(i):e.createV1(r.codec,i),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[l,p]=fn(t.subarray(r));return r+=p,l},o=n(),s=un;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(t,r){let[n,o]=ud(t,r),s=e.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ei(s).set(n,t),s}};function ud(e,t){switch(e[0]){case"Q":{let r=t??lt;return[lt.prefix,r.decode(`${lt.prefix}${e}`)]}case lt.prefix:{let r=t??lt;return[lt.prefix,r.decode(e)]}case Ae.prefix:{let r=t??Ae;return[Ae.prefix,r.decode(e)]}case an.prefix:{let r=t??an;return[an.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function ld(e,t,r){let{prefix:n}=r;if(n!==lt.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=t.get(n);if(o==null){let s=r.encode(e).slice(1);return t.set(n,s),s}else return o}function hd(e,t,r){let{prefix:n}=r,o=t.get(n);if(o==null){let s=r.encode(e);return t.set(n,s),s}else return o}var un=112,dd=18;function lf(e,t,r){let n=vr(e),o=n+vr(t),s=new Uint8Array(o+r.byteLength);return Ar(e,s,0),Ar(t,s,n),s.set(r,o),s}var pd=Symbol.for("@ipld/js-cid/CID");var ri={};Dt(ri,{identity:()=>zt});var hf=0,md="identity",df=ae;function gd(e,t){if(t?.truncate!=null&&t.truncate!==e.byteLength){if(t.truncate<0||t.truncate>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,t.truncate)}return Rt(hf,df(e))}var zt={code:hf,name:md,encode:df,digest:gd};function wt(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}async function pf(e,t,r,n){let o=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,r.subarray());return n?.signal?.throwIfAborted(),s}function pt(e=0){return new Uint8Array(e)}function at(e=0){return new Uint8Array(e)}function Pt(e,t){t==null&&(t=e.reduce((o,s)=>o+s.length,0));let r=at(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}var gf=Symbol.for("@achingbrain/uint8arraylist");function mf(e,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let r=0;for(let n of e){let o=r+n.byteLength;if(t<o)return{buf:n,index:t-r};r=o}throw new RangeError("index is out of bounds")}function wo(e){return!!e?.[gf]}var $=class e{bufs;length;[gf]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let r=0;for(let n of t)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(wo(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(...t){this.prependAll(t)}prependAll(t){let r=0;for(let n of t.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(wo(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(t){let r=mf(this.bufs,t);return r.buf[r.index]}set(t,r){let n=mf(this.bufs,t);n.buf[n.index]=r}write(t,r=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(r+n,t[n]);else if(wo(t))for(let n=0;n<t.length;n++)this.set(r+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,r){let{bufs:n,length:o}=this._subList(t,r);return Pt(n,o)}subarray(t,r){let{bufs:n,length:o}=this._subList(t,r);return n.length===1?n[0]:Pt(n,o)}sublist(t,r){let{bufs:n,length:o}=this._subList(t,r),s=new e;return s.length=o,s.bufs=n,s}_subList(t,r){if(t=t??0,r=r??this.length,t<0&&(t=this.length+t),r<0&&(r=this.length+r),t<0||r>this.length)throw new RangeError("index is out of bounds");if(t===r)return{bufs:[],length:0};if(t===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,t>=c)continue;let f=t>=a&&t<c,u=r>a&&r<=c;if(f&&u){if(t===a&&r===c){n.push(i);break}let l=t-a;n.push(i.subarray(l,l+(r-t)));break}if(f){if(t===0){n.push(i);continue}n.push(i.subarray(t-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-t}}indexOf(t,r=0){if(!wo(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),t.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 p=f;p>=0;p--){let d=this.get(l+p);if(n[p]!==d){u=Math.max(1,p-a[d]);break}}if(u===0)return l}return-1}getInt8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(t,r){let n=at(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,t)}getInt16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(t,r,n){let o=pt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,t)}getInt32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(t,r,n){let o=pt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,t)}getBigInt64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(t,r,n){let o=pt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,t)}getUint8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(t,r){let n=at(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,t)}getUint16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(t,r,n){let o=pt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,t)}getUint32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(t,r,n){let o=pt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,t)}getBigUint64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(t,r,n){let o=pt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,t)}getFloat32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(t,r,n){let o=pt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,t)}getFloat64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(t,r,n){let o=pt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof e)||t.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!wt(this.bufs[r],t.bufs[r]))return!1;return!0}static fromUint8Arrays(t,r){let n=new e;return n.bufs=t,r==null&&(r=t.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}};var ni={};Dt(ni,{base10:()=>bd});var bd=Se({prefix:"9",name:"base10",alphabet:"0123456789"});var oi={};Dt(oi,{base16:()=>wd,base16upper:()=>xd});var wd=ut({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),xd=ut({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var si={};Dt(si,{base2:()=>Ed});var Ed=ut({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ii={};Dt(ii,{base256emoji:()=>Cd});var yf=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}"),Sd=yf.reduce((e,t,r)=>(e[r]=t,e),[]),Ad=yf.reduce((e,t,r)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return e[n]=r,e},[]);function vd(e){return e.reduce((t,r)=>(t+=Sd[r],t),"")}function _d(e){let t=[];for(let r of e){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=Ad[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);t.push(o)}return new Uint8Array(t)}var Cd=Sr({prefix:"\u{1F680}",name:"base256emoji",encode:vd,decode:_d});var ai={};Dt(ai,{base64:()=>Ld,base64pad:()=>Td,base64url:()=>ln,base64urlpad:()=>Id});var Ld=ut({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Td=ut({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ln=ut({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Id=ut({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ci={};Dt(ci,{base8:()=>Bd});var Bd=ut({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var fi={};Dt(fi,{identity:()=>Dd});var Dd=Sr({prefix:"\0",name:"identity",encode:e=>ef(e),decode:e=>tf(e)});var Qg=new TextEncoder,Jg=new TextDecoder;var hi={};Dt(hi,{sha256:()=>ce,sha512:()=>Nd});var Od=20;function li({name:e,code:t,encode:r,minDigestLength:n,maxDigestLength:o}){return new ui(e,t,r,n,o)}var ui=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,r,n,o,s){this.name=t,this.code=r,this.encode=n,this.minDigestLength=o??Od,this.maxDigestLength=s}digest(t,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(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?bf(n,this.code,r?.truncate):n.then(o=>bf(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function bf(e,t,r){if(r!=null&&r!==e.byteLength){if(r>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,r)}return Rt(t,e)}function xf(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}var ce=li({name:"sha2-256",code:18,encode:xf("SHA-256")}),Nd=li({name:"sha2-512",code:19,encode:xf("SHA-512")});var Ye={...fi,...si,...ci,...ni,...oi,...Zs,...Qs,...Xs,...ai,...ii},ly={...hi,...ri};function Sf(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var Ef=Sf("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),di=Sf("ascii","a",e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},e=>{e=e.substring(1);let t=at(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}),Ud={utf8:Ef,"utf-8":Ef,hex:Ye.base16,latin1:di,ascii:di,binary:di,...Ye},xo=Ud;function q(e,t="utf8"){let r=xo[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}function V(e,t="utf8"){let r=xo[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}var Fd=parseInt("11111",2),pi=parseInt("10000000",2),kd=parseInt("01111111",2),Af={0:hn,1:hn,2:Md,3:Vd,4:$d,5:Hd,6:Kd,16:hn,22:hn,48:hn};function fe(e,t={offset:0}){let r=e[t.offset]&Fd;if(t.offset++,Af[r]!=null)return Af[r](e,t);throw new Error("No decoder for tag "+r)}function dn(e,t){let r=0;if((e[t.offset]&pi)===pi){let n=e[t.offset]&kd,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(o,16)}else r=e[t.offset],t.offset++;return r}function hn(e,t){dn(e,t);let r=[];for(;!(t.offset>=e.byteLength);){let n=fe(e,t);if(n===null)break;r.push(n)}return r}function Md(e,t){let r=dn(e,t),n=t.offset,o=t.offset+r,s=[];for(let i=n;i<o;i++)i===n&&e[i]===0||s.push(e[i]);return t.offset+=r,Uint8Array.from(s)}function Kd(e,t){let r=dn(e,t),n=t.offset+r,o=e[t.offset];t.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(;t.offset<n;){let f=e[t.offset];if(t.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 Hd(e,t){return t.offset++,null}function Vd(e,t){let r=dn(e,t),n=e[t.offset];t.offset++;let o=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function $d(e,t){let r=dn(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n}function zd(e){let t=e.toString(16);t.length%2===1&&(t="0"+t);let r=new $;for(let n=0;n<t.length;n+=2)r.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return r}function mi(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);let t=zd(e.byteLength);return new $(Uint8Array.from([t.byteLength|pi]),t)}function Ot(e){let t=new $,r=128;return(e.subarray()[0]&r)===r&&t.append(Uint8Array.from([0])),t.append(e),new $(Uint8Array.from([2]),mi(t),t)}function Eo(e){let t=Uint8Array.from([0]),r=new $(t,e);return new $(Uint8Array.from([3]),mi(r),r)}function ve(e,t=48){let r=new $;for(let n of e)r.append(n);return new $(Uint8Array.from([t]),mi(r),r)}var qd=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),jd=Uint8Array.from([6,5,43,129,4,0,34]),Gd=Uint8Array.from([6,5,43,129,4,0,35]),Wd={ext:!0,kty:"EC",crv:"P-256"},Yd={ext:!0,kty:"EC",crv:"P-384"},Xd={ext:!0,kty:"EC",crv:"P-521"},gi=32,yi=48,bi=66;function wi(e){let t=fe(e);return vf(t)}function vf(e){let t=e[1][1][0],r=1,n,o;if(t.byteLength===gi*2+1)return n=V(t.subarray(r,r+gi),"base64url"),o=V(t.subarray(r+gi),"base64url"),new Cr({...Wd,key_ops:["verify"],x:n,y:o});if(t.byteLength===yi*2+1)return n=V(t.subarray(r,r+yi),"base64url"),o=V(t.subarray(r+yi),"base64url"),new Cr({...Yd,key_ops:["verify"],x:n,y:o});if(t.byteLength===bi*2+1)return n=V(t.subarray(r,r+bi),"base64url"),o=V(t.subarray(r+bi),"base64url"),new Cr({...Xd,key_ops:["verify"],x:n,y:o});throw new G(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function _f(e){return ve([Ot(Uint8Array.from([1])),ve([Zd(e.crv)],160),ve([Eo(new $(Uint8Array.from([4]),q(e.x??"","base64url"),q(e.y??"","base64url")))],161)]).subarray()}function Zd(e){if(e==="P-256")return qd;if(e==="P-384")return jd;if(e==="P-521")return Gd;throw new G(`Invalid curve ${e}`)}var Cr=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=_f(this.jwk)),this._raw}toMultihash(){return zt.digest(_e(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return lt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}async verify(t,r,n){return pf(this.jwk,r,t,n)}};function xi(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function te(e,t=""){if(typeof e!="number"){let r=t&&`"${t}" `;throw new TypeError(`${r}expected number, got ${typeof e}`)}if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw new RangeError(`${r}expected integer >= 0, got ${e}`)}}function _t(e,t,r=""){let n=xi(e),o=e?.length,s=t!==void 0;if(!n||s&&o!==t){let i=r&&`"${r}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return e}function Xe(e){if(typeof e!="function"||typeof e.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(te(e.outputLen),te(e.blockLen),e.outputLen<1)throw new Error('"outputLen" must be >= 1');if(e.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Lr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function So(e,t){_t(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function qt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ao(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function jt(e,t){return e<<32-t|e>>>t}var Lf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qd=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function vo(e){if(_t(e),Lf)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Qd[e[r]];return t}var ue={_0:48,_9:57,A:65,F:70,a:97,f:102};function Cf(e){if(e>=ue._0&&e<=ue._9)return e-ue._0;if(e>=ue.A&&e<=ue.F)return e-(ue.A-10);if(e>=ue.a&&e<=ue.f)return e-(ue.a-10)}function pn(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(Lf)try{return Uint8Array.fromHex(e)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let t=e.length,r=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=Cf(e.charCodeAt(s)),a=Cf(e.charCodeAt(s+1));if(i===void 0||a===void 0){let c=e[s]+e[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ei(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];_t(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let s=e[n];r.set(s,o),o+=s.length}return r}function Si(e,t={}){let r=(o,s)=>e(s).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>e(o),Object.assign(r,t),Object.freeze(r)}function Tf(e=32){te(e,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var Ai=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function If(e,t,r){return e&t^~e&r}function Bf(e,t,r){return e&t^e&r^t&r}var mn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,r,n,o){this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Ao(this.buffer)}update(t){Lr(this),_t(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Ao(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Lr(this),So(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,qt(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=Ao(t),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:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},le=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var _o=BigInt(4294967295),Df=BigInt(32);function Jd(e,t=!1){return t?{h:Number(e&_o),l:Number(e>>Df&_o)}:{h:Number(e>>Df&_o)|0,l:Number(e&_o)|0}}function Rf(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=Jd(e[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var vi=(e,t,r)=>e>>>r,_i=(e,t,r)=>e<<32-r|t>>>r,Ze=(e,t,r)=>e>>>r|t<<32-r,Qe=(e,t,r)=>e<<32-r|t>>>r,gn=(e,t,r)=>e<<64-r|t>>>r-32,yn=(e,t,r)=>e>>>r-32|t<<64-r;function ee(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var Pf=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Of=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,Nf=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Uf=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,Ff=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),kf=(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0;var ep=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]),Ce=new Uint32Array(64),Ci=class extends mn{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,r,n,o,s,i,a,c]}set(t,r,n,o,s,i,a,c){this.A=t|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(t,r){for(let l=0;l<16;l++,r+=4)Ce[l]=t.getUint32(r,!1);for(let l=16;l<64;l++){let p=Ce[l-15],d=Ce[l-2],g=jt(p,7)^jt(p,18)^p>>>3,S=jt(d,17)^jt(d,19)^d>>>10;Ce[l]=S+Ce[l-7]+g+Ce[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 p=jt(a,6)^jt(a,11)^jt(a,25),d=u+p+If(a,c,f)+ep[l]+Ce[l]|0,S=(jt(n,2)^jt(n,13)^jt(n,22))+Bf(n,o,s)|0;u=f,f=c,c=a,a=i+d|0,i=s,s=o,o=n,n=d+S|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(){qt(Ce)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),qt(this.buffer)}},Li=class extends Ci{A=le[0]|0;B=le[1]|0;C=le[2]|0;D=le[3]|0;E=le[4]|0;F=le[5]|0;G=le[6]|0;H=le[7]|0;constructor(){super(32)}};var Mf=Rf(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),rp=Mf[0],np=Mf[1],Le=new Uint32Array(80),Te=new Uint32Array(80),Ti=class extends mn{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:u,Fh:l,Fl:p,Gh:d,Gl:g,Hh:S,Hl:h}=this;return[t,r,n,o,s,i,a,c,f,u,l,p,d,g,S,h]}set(t,r,n,o,s,i,a,c,f,u,l,p,d,g,S,h){this.Ah=t|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=p|0,this.Gh=d|0,this.Gl=g|0,this.Hh=S|0,this.Hl=h|0}process(t,r){for(let L=0;L<16;L++,r+=4)Le[L]=t.getUint32(r),Te[L]=t.getUint32(r+=4);for(let L=16;L<80;L++){let O=Le[L-15]|0,D=Te[L-15]|0,P=Ze(O,D,1)^Ze(O,D,8)^vi(O,D,7),R=Qe(O,D,1)^Qe(O,D,8)^_i(O,D,7),I=Le[L-2]|0,N=Te[L-2]|0,k=Ze(I,N,19)^gn(I,N,61)^vi(I,N,6),U=Qe(I,N,19)^yn(I,N,61)^_i(I,N,6),m=Nf(R,U,Te[L-7],Te[L-16]),A=Uf(m,P,k,Le[L-7],Le[L-16]);Le[L]=A|0,Te[L]=m|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:l,El:p,Fh:d,Fl:g,Gh:S,Gl:h,Hh:y,Hl:v}=this;for(let L=0;L<80;L++){let O=Ze(l,p,14)^Ze(l,p,18)^gn(l,p,41),D=Qe(l,p,14)^Qe(l,p,18)^yn(l,p,41),P=l&d^~l&S,R=p&g^~p&h,I=Ff(v,D,R,np[L],Te[L]),N=kf(I,y,O,P,rp[L],Le[L]),k=I|0,U=Ze(n,o,28)^gn(n,o,34)^gn(n,o,39),m=Qe(n,o,28)^yn(n,o,34)^yn(n,o,39),A=n&s^n&a^s&a,E=o&i^o&c^i&c;y=S|0,v=h|0,S=d|0,h=g|0,d=l|0,g=p|0,{h:l,l:p}=ee(f|0,u|0,N|0,k|0),f=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let w=Pf(k,m,E);n=Of(w,N,U,A),o=w|0}({h:n,l:o}=ee(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ee(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ee(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=ee(this.Dh|0,this.Dl|0,f|0,u|0),{h:l,l:p}=ee(this.Eh|0,this.El|0,l|0,p|0),{h:d,l:g}=ee(this.Fh|0,this.Fl|0,d|0,g|0),{h:S,l:h}=ee(this.Gh|0,this.Gl|0,S|0,h|0),{h:y,l:v}=ee(this.Hh|0,this.Hl|0,y|0,v|0),this.set(n,o,s,i,a,c,f,u,l,p,d,g,S,h,y,v)}roundClean(){qt(Le,Te)}destroy(){this.destroyed=!0,qt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ii=class extends Ti{Ah=xt[0]|0;Al=xt[1]|0;Bh=xt[2]|0;Bl=xt[3]|0;Ch=xt[4]|0;Cl=xt[5]|0;Dh=xt[6]|0;Dl=xt[7]|0;Eh=xt[8]|0;El=xt[9]|0;Fh=xt[10]|0;Fl=xt[11]|0;Gh=xt[12]|0;Gl=xt[13]|0;Hh=xt[14]|0;Hl=xt[15]|0;constructor(){super(64)}};var re=Si(()=>new Li,Ai(1));var Co=Si(()=>new Ii,Ai(3));var z=(e,t,r)=>_t(e,t,r),Di=te,Tr=vo,mt=(...e)=>Ei(...e),Ir=e=>pn(e),Je=xi,tr=e=>Tf(e),To=BigInt(0),Bi=BigInt(1);function Gt(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}" `;throw new TypeError(r+"expected boolean, got type="+typeof e)}return e}function Io(e){if(typeof e=="bigint"){if(!Lo(e))throw new RangeError("positive bigint expected, got "+e)}else Di(e);return e}function Wt(e,t=""){if(typeof e!="number"){let r=t&&`"${t}" `;throw new TypeError(r+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let r=t&&`"${t}" `;throw new RangeError(r+"expected safe integer, got "+e)}}function bn(e){let t=Io(e).toString(16);return t.length&1?"0"+t:t}function Kf(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?To:BigInt("0x"+e)}function er(e){return Kf(vo(e))}function Ut(e){return Kf(vo(Ie(_t(e)).reverse()))}function Bo(e,t){if(te(t),t===0)throw new RangeError("zero length");e=Io(e);let r=e.toString(16);if(r.length>t*2)throw new RangeError("number too large");return pn(r.padStart(t*2,"0"))}function wn(e,t){return Bo(e,t).reverse()}function Hf(e,t){if(e=z(e),t=z(t),e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function Ie(e){return Uint8Array.from(z(e))}function Do(e){if(typeof e!="string")throw new TypeError("ascii string expected, got "+typeof e);return Uint8Array.from(e,(t,r)=>{let n=t.charCodeAt(0);if(t.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${e[r]}" with code ${n} at position ${r}`);return n})}var Lo=e=>typeof e=="bigint"&&To<=e;function op(e,t,r){return Lo(e)&&Lo(t)&&Lo(r)&&t<=e&&e<r}function he(e,t,r,n){if(!op(t,r,n))throw new RangeError("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Br(e){if(e<To)throw new Error("expected non-negative bigint, got "+e);let t;for(t=0;e>To;e>>=Bi,t+=1);return t}var xn=e=>(Bi<<BigInt(e))-Bi;function Vf(e,t,r){if(te(e,"hashLen"),te(t,"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(e),f=n(e),u=0,l=()=>{c.fill(1),f.fill(0),u=0},p=(...h)=>r(f,mt(c,...h)),d=(h=o)=>{f=p(s,h),c=p(),h.length!==0&&(f=p(i,h),c=p())},g=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let h=0,y=[];for(;h<t;){c=p();let v=c.slice();y.push(v),h+=c.length}return mt(...y)};return(h,y)=>{l(),d(h);let v;for(;(v=y(g()))===void 0;)d();return l(),v}}function Ft(e,t={},r={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(e,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=e[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(t,!1),o(r,!0)}var Ri=()=>{throw new Error("not implemented")};var Et=BigInt(0),ht=BigInt(1),rr=BigInt(2),jf=BigInt(3),Gf=BigInt(4),Wf=BigInt(5),sp=BigInt(7),Yf=BigInt(8),ip=BigInt(9),Xf=BigInt(16);function ct(e,t){if(t<=Et)throw new Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=Et?r:t+r}function st(e,t,r){if(t<Et)throw new Error("pow2: expected non-negative exponent, got "+t);let n=e;for(;t-- >Et;)n*=n,n%=r;return n}function $f(e,t){if(e===Et)throw new Error("invert: expected non-zero number");if(t<=Et)throw new Error("invert: expected positive modulus, got "+t);let r=ct(e,t),n=t,o=Et,s=ht,i=ht,a=Et;for(;r!==Et;){let f=n/r,u=n-r*f,l=o-i*f,p=s-a*f;n=r,r=u,o=i,s=a,i=l,a=p}if(n!==ht)throw new Error("invert: does not exist");return ct(o,t)}function Pi(e,t,r){let n=e;if(!n.eql(n.sqr(t),r))throw new Error("Cannot find square root")}function Zf(e,t){let r=e,n=(r.ORDER+ht)/Gf,o=r.pow(t,n);return Pi(r,o,t),o}function ap(e,t){let r=e,n=(r.ORDER-Wf)/Yf,o=r.mul(t,rr),s=r.pow(o,n),i=r.mul(t,s),a=r.mul(r.mul(i,rr),s),c=r.mul(i,r.sub(a,r.ONE));return Pi(r,c,t),c}function cp(e){let t=Dr(e),r=Qf(e),n=r(t,t.neg(t.ONE)),o=r(t,n),s=r(t,t.neg(n)),i=(e+sp)/Xf;return((a,c)=>{let f=a,u=f.pow(c,i),l=f.mul(u,n),p=f.mul(u,o),d=f.mul(u,s),g=f.eql(f.sqr(l),c),S=f.eql(f.sqr(p),c);u=f.cmov(u,l,g),l=f.cmov(d,p,S);let h=f.eql(f.sqr(l),c),y=f.cmov(u,l,h);return Pi(f,y,c),y})}function Qf(e){if(e<jf)throw new Error("sqrt is not defined for small field");let t=e-ht,r=0;for(;t%rr===Et;)t/=rr,r++;let n=rr,o=Dr(e);for(;zf(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Zf;let s=o.pow(n,t),i=(t+ht)/rr;return function(c,f){let u=c;if(u.is0(f))return f;if(zf(u,f)!==1)throw new Error("Cannot find square root");let l=r,p=u.mul(u.ONE,s),d=u.pow(f,t),g=u.pow(f,i);for(;!u.eql(d,u.ONE);){if(u.is0(d))return u.ZERO;let S=1,h=u.sqr(d);for(;!u.eql(h,u.ONE);)if(S++,h=u.sqr(h),S===l)throw new Error("Cannot find square root");let y=ht<<BigInt(l-S-1),v=u.pow(p,y);l=S,p=u.sqr(v),d=u.mul(d,p),g=u.mul(g,v)}return g}}function fp(e){return e%Gf===jf?Zf:e%Yf===Wf?ap:e%Xf===ip?cp(e):Qf(e)}var de=(e,t)=>(ct(e,t)&ht)===ht,up=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Oi(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=up.reduce((n,o)=>(n[o]="function",n),t);if(Ft(e,r),Wt(e.BYTES,"BYTES"),Wt(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=ht)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function lp(e,t,r){let n=e;if(r<Et)throw new Error("invalid exponent, negatives unsupported");if(r===Et)return n.ONE;if(r===ht)return t;let o=n.ONE,s=t;for(;r>Et;)r&ht&&(o=n.mul(o,s)),s=n.sqr(s),r>>=ht;return o}function En(e,t,r=!1){let n=e,o=new Array(t.length).fill(r?n.ZERO:void 0),s=t.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return t.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),i),o}function zf(e,t){let r=e,n=(r.ORDER-ht)/rr,o=r.pow(t,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 hp(e,t){if(t!==void 0&&Di(t),e<=Et)throw new Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);let r=Br(e);if(t!==void 0&&t<r)throw new Error(`invalid n length: expected bit length (${r}) >= n.length (${t})`);let n=t!==void 0?t:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var qf=new WeakMap,Ro=class{ORDER;BITS;BYTES;isLE;ZERO=Et;ONE=ht;_lengths;_mod;constructor(t,r={}){if(t<=ht)throw new Error("invalid field: expected ORDER > 1, got "+t);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}=hp(t,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(t){return ct(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return Et<=t&&t<this.ORDER}is0(t){return t===Et}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&ht)===ht}neg(t){return ct(-t,this.ORDER)}eql(t,r){return t===r}sqr(t){return ct(t*t,this.ORDER)}add(t,r){return ct(t+r,this.ORDER)}sub(t,r){return ct(t-r,this.ORDER)}mul(t,r){return ct(t*r,this.ORDER)}pow(t,r){return lp(this,t,r)}div(t,r){return ct(t*$f(r,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,r){return t+r}subN(t,r){return t-r}mulN(t,r){return t*r}inv(t){return $f(t,this.ORDER)}sqrt(t){let r=qf.get(this);return r||qf.set(this,r=fp(this.ORDER)),r(this,t)}toBytes(t){return this.isLE?wn(t,this.BYTES):Bo(t,this.BYTES)}fromBytes(t,r=!1){z(t);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(t.length<1||!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let f=new Uint8Array(o);f.set(t,s?0:f.length-t.length),t=f}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?Ut(t):er(t);if(a&&(c=ct(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return En(this,t)}cmov(t,r,n){return Gt(n,"condition"),n?r:t}};Object.freeze(Ro.prototype);function Dr(e,t={}){return new Ro(e,t)}function Jf(e){if(typeof e!="bigint")throw new Error("field order must be bigint");if(e<=ht)throw new Error("field order must be greater than 1");let t=Br(e-ht);return Math.ceil(t/8)}function Ni(e){let t=Jf(e);return t+Math.ceil(t/2)}function Ui(e,t,r=!1){z(e);let n=e.length,o=Jf(t),s=Math.max(Ni(t),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?Ut(e):er(e),a=ct(i,t-ht)+ht;return r?wn(a,o):Bo(a,o)}var Rr=BigInt(0),nr=BigInt(1);function Sn(e,t){let r=t.negate();return e?r:t}function or(e,t){let r=En(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function nu(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Fi(e,t){nu(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=xn(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function tu(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=nr);let f=t*n,u=f+Math.abs(a)-1,l=a===0,p=a<0,d=t%2!==0;return{nextN:c,offset:u,isZero:l,isNeg:p,isNegF:d,offsetF:f}}var ki=new WeakMap,ou=new WeakMap;function Mi(e){return ou.get(e)||1}function eu(e){if(e!==Rr)throw new Error("invalid wNAF")}var Pr=class{BASE;ZERO;Fn;bits;constructor(t,r){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=r}_unsafeLadder(t,r,n=this.ZERO){let o=t;for(;r>Rr;)r&nr&&(n=n.add(o)),o=o.double(),r>>=nr;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=Fi(r,this.bits),s=[],i=t,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(t,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Fi(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:u,isNeg:l,isNegF:p,offsetF:d}=tu(n,a,i);n=c,u?s=s.add(Sn(p,r[d])):o=o.add(Sn(l,r[f]))}return eu(n),{p:o,f:s}}wNAFUnsafe(t,r,n,o=this.ZERO){let s=Fi(t,this.bits);for(let i=0;i<s.windows&&n!==Rr;i++){let{nextN:a,offset:c,isZero:f,isNeg:u}=tu(n,i,s);if(n=a,!f){let l=r[c];o=o.add(u?l.negate():l)}}return eu(n),o}getPrecomputes(t,r,n){let o=ki.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&(typeof n=="function"&&(o=n(o)),ki.set(r,o))),o}cached(t,r,n){let o=Mi(t);return this.wNAF(o,this.getPrecomputes(o,t,n),r)}unsafe(t,r,n,o){let s=Mi(t);return s===1?this._unsafeLadder(t,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),r,o)}createCache(t,r){nu(r,this.bits),ou.set(t,r),ki.delete(t)}hasCache(t){return Mi(t)!==1}};function su(e,t,r,n){let o=t,s=e.ZERO,i=e.ZERO;for(;r>Rr||n>Rr;)r&nr&&(s=s.add(o)),n&nr&&(i=i.add(o)),o=o.double(),r>>=nr,n>>=nr;return{p1:s,p2:i}}function ru(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Oi(t),t}else return Dr(e,{isLE:r})}function Po(e,t,r={},n){if(n===void 0&&(n=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let f=t[c];if(!(typeof f=="bigint"&&f>Rr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=ru(t.p,r.Fp,n),s=ru(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function Or(e,t){return function(n){let o=e(n);return{secretKey:o,publicKey:t(o)}}}var Be=BigInt(0),yt=BigInt(1),Ki=BigInt(2),dp=BigInt(8);function pp(e,t,r,n){let o=e.sqr(r),s=e.sqr(n),i=e.add(e.mul(t.a,o),s),a=e.add(e.ONE,e.mul(t.d,e.mul(o,s)));return e.eql(i,a)}function iu(e,t={}){let r=t,n=Po("edwards",e,r,r.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;Ft(r,{},{uvRatio:"function"});let c=Ki<<BigInt(s.BYTES*8)-yt,f=S=>o.create(S),u=r.uvRatio===void 0?(S,h)=>{try{return{isValid:!0,value:o.sqrt(o.div(S,h))}}catch{return{isValid:!1,value:Be}}}:r.uvRatio;if(!pp(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function l(S,h,y=!1){let v=y?yt:Be;return he("coordinate "+S,h,v,c),h}function p(S){if(!(S instanceof d))throw new Error("EdwardsPoint expected")}class d{static BASE=new d(i.Gx,i.Gy,yt,f(i.Gx*i.Gy));static ZERO=new d(Be,yt,yt,Be);static Fp=o;static Fn=s;X;Y;Z;T;constructor(h,y,v,L){this.X=l("x",h),this.Y=l("y",y),this.Z=l("z",v,!0),this.T=l("t",L),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,yt,f(y*v))}static fromBytes(h,y=!1){let v=o.BYTES,{a:L,d:O}=i;h=Ie(z(h,v,"point")),Gt(y,"zip215");let D=Ie(h),P=h[v-1];D[v-1]=P&-129;let R=Ut(D),I=y?c:o.ORDER;he("point.y",R,Be,I);let N=f(R*R),k=f(N-yt),U=f(O*N-L),{isValid:m,value:A}=u(k,U);if(!m)throw new Error("bad point: invalid y coordinate");let E=(A&yt)===yt,w=(P&128)!==0;if(!y&&A===Be&&w)throw new Error("bad point: x=0 and x_0=1");return w!==E&&(A=f(-A)),d.fromAffine({x:A,y:R})}static fromHex(h,y=!1){return d.fromBytes(Ir(h),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,y=!0){return g.createCache(this,h),y||this.multiply(Ki),this}assertValidity(){let h=this,{a:y,d:v}=i;if(h.is0())throw new Error("bad point: ZERO");let{X:L,Y:O,Z:D,T:P}=h,R=f(L*L),I=f(O*O),N=f(D*D),k=f(N*N),U=f(R*y),m=f(N*f(U+I)),A=f(k+f(v*f(R*I)));if(m!==A)throw new Error("bad point: equation left != right (1)");let E=f(L*O),w=f(D*P);if(E!==w)throw new Error("bad point: equation left != right (2)")}equals(h){p(h);let{X:y,Y:v,Z:L}=this,{X:O,Y:D,Z:P}=h,R=f(y*P),I=f(O*L),N=f(v*P),k=f(D*L);return R===I&&N===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:L}=this,O=f(y*y),D=f(v*v),P=f(Ki*f(L*L)),R=f(h*O),I=y+v,N=f(f(I*I)-O-D),k=R+D,U=k-P,m=R-D,A=f(N*U),E=f(k*m),w=f(N*m),b=f(U*k);return new d(A,E,b,w)}add(h){p(h);let{a:y,d:v}=i,{X:L,Y:O,Z:D,T:P}=this,{X:R,Y:I,Z:N,T:k}=h,U=f(L*R),m=f(O*I),A=f(P*v*k),E=f(D*N),w=f((L+O)*(R+I)-U-m),b=E-A,_=E+A,C=f(m-y*U),x=f(w*b),T=f(_*C),B=f(w*C),F=f(b*_);return new d(x,T,F,B)}subtract(h){return p(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}=g.cached(this,h,L=>or(d,L));return or(d,[y,v])[0]}multiplyUnsafe(h){if(!s.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===Be?d.ZERO:this.is0()||h===yt?this:g.unsafe(this,h,y=>or(d,y))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return g.unsafe(this,i.n).is0()}toAffine(h){let y=this,v=h,{X:L,Y:O,Z:D}=y,P=y.is0();v==null&&(v=P?dp:o.inv(D));let R=f(L*v),I=f(O*v),N=o.mul(D,v);if(P)return{x:Be,y:yt};if(N!==yt)throw new Error("invZ was invalid");return{x:R,y:I}}clearCofactor(){return a===yt?this:this.multiplyUnsafe(a)}toBytes(){let{x:h,y}=this.toAffine(),v=o.toBytes(y);return v[v.length-1]|=h&yt?128:0,v}toHex(){return Tr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new Pr(d,s.BITS);return s.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var Oo=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){this.ep=t}static fromBytes(t){Ri()}static fromHex(t){Ri()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return Tr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,r){return this.ep.precompute(t,r),this}};function au(e,t,r={}){if(typeof t!="function")throw new Error('"hash" function param is required');let n=t,o=r;Ft(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=e,f=n.outputLen,u=2*a.BYTES;if(f!==void 0&&(Wt(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let l=o.randomBytes===void 0?tr:o.randomBytes,p=o.adjustScalarBytes===void 0?m=>m:o.adjustScalarBytes,d=o.domain===void 0?(m,A,E)=>{if(Gt(E,"phflag"),A.length||E)throw new Error("Contexts/pre-hash are not supported");return m}:o.domain;function g(m){return c.create(Ut(m))}function S(m){let A=R.secretKey;z(m,R.secretKey,"secretKey");let E=z(n(m),2*A,"hashedSecretKey"),w=p(E.slice(0,A)),b=E.slice(A,2*A),_=g(w);return{head:w,prefix:b,scalar:_}}function h(m){let{head:A,prefix:E,scalar:w}=S(m),b=i.multiply(w),_=b.toBytes();return{head:A,prefix:E,scalar:w,point:b,pointBytes:_}}function y(m){return h(m).pointBytes}function v(m=Uint8Array.of(),...A){let E=mt(...A);return g(n(d(E,z(m,void 0,"context"),!!s)))}function L(m,A,E={}){m=z(m,void 0,"message"),s&&(m=s(m));let{prefix:w,scalar:b,pointBytes:_}=h(A),C=v(E.context,w,m),x=i.multiply(C).toBytes(),T=v(E.context,x,_,m),B=c.create(C+T*b);if(!c.isValid(B))throw new Error("sign failed: invalid s");let F=mt(x,c.toBytes(B));return z(F,R.signature,"result")}let O={zip215:o.zip215};function D(m,A,E,w=O){let{context:b}=w,_=w.zip215===void 0?!!O.zip215:w.zip215,C=R.signature;m=z(m,C,"signature"),A=z(A,void 0,"message"),E=z(E,R.publicKey,"publicKey"),_!==void 0&&Gt(_,"zip215"),s&&(A=s(A));let x=C/2,T=m.subarray(0,x),B=Ut(m.subarray(x,C)),F,H,K;try{F=e.fromBytes(E,_),H=e.fromBytes(T,_),K=i.multiplyUnsafe(B)}catch{return!1}if(!_&&F.isSmallOrder())return!1;let J=v(b,T,E,A);return H.add(F.multiplyUnsafe(J)).subtract(K).clearCofactor().is0()}let P=a.BYTES,R={secretKey:P,publicKey:P,signature:2*P,seed:P};function I(m){return m=m===void 0?l(R.seed):m,z(m,R.seed,"seed")}function N(m){return Je(m)&&m.length===R.secretKey}function k(m,A){try{return!!e.fromBytes(m,A===void 0?O.zip215:A)}catch{return!1}}let U={getExtendedPublicKey:h,randomSecretKey:I,isValidSecretKey:N,isValidPublicKey:k,toMontgomery(m){let{y:A}=e.fromBytes(m),E=R.publicKey,w=E===32;if(!w&&E!==57)throw new Error("only defined for 25519 and 448");let b=w?a.div(yt+A,yt-A):a.div(A-yt,A+yt);return a.toBytes(b)},toMontgomerySecret(m){let A=R.secretKey;z(m,A);let E=n(m.subarray(0,A));return p(E).subarray(0,A)}};return Object.freeze(R),Object.freeze(U),Object.freeze({keygen:Or(I,y),getPublicKey:y,sign:L,verify:D,utils:U,Point:e,lengths:R})}function An(e,t){if(Wt(e),Wt(t),t<0||t>4)throw new Error("invalid I2OSP length: "+t);if(e<0||e>2**(8*t)-1)throw new Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)r[n]=e&255,e>>>=8;return new Uint8Array(r)}function mp(e,t){let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n]^t[n];return r}function gp(e){if(!Je(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or ascii string");let t=typeof e=="string"?Do(e):e;if(t.length===0)throw new Error("DST must be non-empty");return t}function Hi(e,t,r,n){z(e),Wt(r),t=gp(t),t.length>255&&(t=n(mt(Do("H2C-OVERSIZE-DST-"),t)));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=mt(t,An(t.length,1)),c=new Uint8Array(s),f=An(r,2),u=new Array(i),l=n(mt(c,e,f,An(0,1),a));u[0]=n(mt(l,An(1,1),a));for(let d=1;d<i;d++){let g=[mp(l,u[d-1]),An(d+1,1),a];u[d]=n(mt(...g))}return mt(...u).slice(0,r)}var cu="HashToScalar-";var vn=BigInt(0),Nr=BigInt(1),No=BigInt(2);function yp(e){return Ft(e,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...e})}function fu(e){let t=yp(e),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=t,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i===void 0?tr:i,f=a?255:448,u=a?32:56,l=BigInt(a?9:5),p=BigInt(a?121665:39081),d=a?No**BigInt(254):No**BigInt(447),g=a?BigInt(8)*No**BigInt(251)-Nr:BigInt(4)*No**BigInt(445)-Nr,S=d+g+Nr,h=E=>ct(E,r),y=v(l);function v(E){return wn(h(E),u)}function L(E){let w=Ie(z(E,u,"uCoordinate"));return a&&(w[31]&=127),h(Ut(w))}function O(E){return Ut(o(Ie(z(E,u,"scalar"))))}function D(E,w){let b=k(L(w),O(E));if(b===vn)throw new Error("invalid private or public key received");return v(b)}function P(E){return D(E,y)}let R=P,I=D;function N(E,w,b){let _=h(E*(w-b));return w=h(w-_),b=h(b+_),{x_2:w,x_3:b}}function k(E,w){he("u",E,vn,r),he("scalar",w,d,S);let b=w,_=E,C=Nr,x=vn,T=E,B=Nr,F=vn;for(let K=BigInt(f-1);K>=vn;K--){let J=b>>K&Nr;F^=J,{x_2:C,x_3:T}=N(F,C,T),{x_2:x,x_3:B}=N(F,x,B),F=J;let tt=C+x,et=h(tt*tt),Y=C-x,it=h(Y*Y),ie=et-it,je=T+B,yr=T-B,nn=h(yr*tt),on=h(je*Y),Yc=nn+on,Xc=nn-on;T=h(Yc*Yc),B=h(_*h(Xc*Xc)),C=h(et*it),x=h(ie*(et+h(p*ie)))}({x_2:C,x_3:T}=N(F,C,T)),{x_2:x,x_3:B}=N(F,x,B);let H=s(x);return h(C*H)}let U={secretKey:u,publicKey:u,seed:u},m=E=>(E=E===void 0?c(u):E,z(E,U.seed,"seed"),E),A={randomSecretKey:m};return Object.freeze(U),Object.freeze(A),Object.freeze({keygen:Or(m,R),getSharedSecret:I,getPublicKey:R,scalarMult:D,scalarMultBase:P,utils:A,GuBytes:y.slice(),lengths:U})}var bp=BigInt(0),pe=BigInt(1),uu=BigInt(2),wp=BigInt(3),xp=BigInt(5),Ep=BigInt(8),sr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),qi={p:sr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ep,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function du(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=sr,a=e*e%s*e%s,c=st(a,uu,s)*a%s,f=st(c,pe,s)*e%s,u=st(f,xp,s)*f%s,l=st(u,t,s)*u%s,p=st(l,r,s)*l%s,d=st(p,n,s)*p%s,g=st(d,o,s)*d%s,S=st(g,o,s)*d%s,h=st(S,t,s)*u%s;return{pow_p_5_8:st(h,uu,s)*e%s,b2:a}}function pu(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var Vi=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ji(e,t){let r=sr,n=ct(t*t*t,r),o=ct(n*n*t,r),s=du(e*o).pow_p_5_8,i=ct(e*n*s,r),a=ct(t*i*i,r),c=i,f=ct(i*Vi,r),u=a===e,l=a===ct(-e,r),p=a===ct(-e*Vi,r);return u&&(i=c),(l||p)&&(i=f),de(i,r)&&(i=ct(-i,r)),{isValid:u||l,value:i}}var Re=iu(qi,{uvRatio:ji}),De=Re.Fp,mu=Re.Fn;function Sp(e){return au(Re,Co,Object.assign({adjustScalarBytes:pu,zip215:!0},e))}var gu=Sp({});var _n=(()=>{let e=sr;return fu({P:e,type:"x25519",powPminus2:t=>{let{pow_p_5_8:r,b2:n}=du(t);return ct(st(r,wp,e)*n,e)},adjustScalarBytes:pu})})();var $i=Vi,Ap=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),vp=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),_p=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Cp=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),lu=e=>ji(pe,e),Lp=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),zi=e=>De.create(Ut(e)&Lp);function hu(e){let{d:t}=qi,r=sr,n=y=>De.create(y),o=n($i*e*e),s=n((o+pe)*_p),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:f}=ji(s,a),u=n(f*e);de(u,r)||(u=n(-u)),c||(f=u),c||(i=o);let l=n(i*(o-pe)*Cp-a),p=f*f,d=n((f+f)*a),g=n(l*Ap),S=n(pe-p),h=n(pe+p);return new Re(n(d*h),n(S*g),n(g*h),n(d*S))}var Pe=class e extends Oo{static BASE=new e(Re.BASE);static ZERO=new e(Re.ZERO);static Fp=De;static Fn=mu;constructor(t){super(t)}static fromAffine(t){return new e(Re.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoPoint expected")}init(t){return new e(t)}static fromBytes(t){_t(t,32);let{a:r,d:n}=qi,o=sr,s=O=>De.create(O),i=zi(t);if(!Hf(De.toBytes(i),t)||de(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(pe+r*a),f=s(pe-r*a),u=s(c*c),l=s(f*f),p=s(r*n*u-l),{isValid:d,value:g}=lu(s(p*l)),S=s(g*f),h=s(g*S*p),y=s((i+i)*S);de(y,o)&&(y=s(-y));let v=s(c*h),L=s(y*v);if(!d||de(L,o)||v===bp)throw new Error("invalid ristretto255 encoding 2");return new e(new Re(y,v,pe,L))}static fromHex(t){return e.fromBytes(pn(t))}toBytes(){let{X:t,Y:r,Z:n,T:o}=this.ep,s=sr,i=h=>De.create(h),a=i(i(n+r)*i(n-r)),c=i(t*r),f=i(c*c),{value:u}=lu(i(a*f)),l=i(u*a),p=i(u*c),d=i(l*p*o),g;if(de(o*d,s)){let h=i(r*$i),y=i(t*$i);t=h,r=y,g=i(l*vp)}else g=p;de(t*d,s)&&(r=i(-r));let S=i((n-r)*g);return de(S,s)&&(S=i(-S)),De.toBytes(S)}equals(t){this.assertSame(t);let{X:r,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=f=>De.create(f),a=i(r*s)===i(n*o),c=i(n*s)===i(r*o);return a||c}is0(){return this.equals(e.ZERO)}};Object.freeze(Pe.BASE);Object.freeze(Pe.ZERO);Object.freeze(Pe.prototype);Object.freeze(Pe);var Tp=Object.freeze({Point:Pe,hashToCurve(e,t){let r=t?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":t.DST,n=Hi(e,r,64,Co);return Tp.deriveToCurve(n)},hashToScalar(e,t={DST:cu}){let r=Hi(e,t.DST,64,Co);return mu.create(Ut(r))},deriveToCurve(e){_t(e,64);let t=zi(e.subarray(0,32)),r=hu(t),n=zi(e.subarray(32,64)),o=hu(n);return new Pe(r.add(o))}});var Cn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Uo=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var yu={get(e=globalThis){let t=e.crypto;if(t?.subtle==null)throw new Uo("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Ht=yu;var Fo=32;var Gi,Ip=(async()=>{try{return await Ht.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Bp(e,t,r){if(e.buffer instanceof ArrayBuffer){let n=await Ht.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Ht.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Dp(e,t,r){return gu.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}async function bu(e,t,r){return Gi==null&&(Gi=await Ip),Gi?Bp(e,t,r):Dp(e,t,r)}function ko(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var Mo=class{type="Ed25519";raw;constructor(t){this.raw=Wi(t,Fo)}toMultihash(){return zt.digest(_e(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return lt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}verify(t,r,n){n?.signal?.throwIfAborted();let o=bu(this.raw,r,t);return ko(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Yi(e){return e=Wi(e,Fo),new Mo(e)}function Wi(e,t){if(e=Uint8Array.from(e??[]),e.length!==t)throw new G(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var Pp=Math.pow(2,7),Op=Math.pow(2,14),Np=Math.pow(2,21),Xi=Math.pow(2,28),Zi=Math.pow(2,35),Qi=Math.pow(2,42),Ji=Math.pow(2,49),Z=128,Ct=127;function rt(e){if(e<Pp)return 1;if(e<Op)return 2;if(e<Np)return 3;if(e<Xi)return 4;if(e<Zi)return 5;if(e<Qi)return 6;if(e<Ji)return 7;if(Number.MAX_SAFE_INTEGER!=null&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Oe(e,t,r=0){switch(rt(e)){case 8:t[r++]=e&255|Z,e/=128;case 7:t[r++]=e&255|Z,e/=128;case 6:t[r++]=e&255|Z,e/=128;case 5:t[r++]=e&255|Z,e/=128;case 4:t[r++]=e&255|Z,e>>>=7;case 3:t[r++]=e&255|Z,e>>>=7;case 2:t[r++]=e&255|Z,e>>>=7;case 1:{t[r++]=e&255,e>>>=7;break}default:throw new Error("unreachable")}return t}function Up(e,t,r=0){switch(rt(e)){case 8:t.set(r++,e&255|Z),e/=128;case 7:t.set(r++,e&255|Z),e/=128;case 6:t.set(r++,e&255|Z),e/=128;case 5:t.set(r++,e&255|Z),e/=128;case 4:t.set(r++,e&255|Z),e>>>=7;case 3:t.set(r++,e&255|Z),e>>>=7;case 2:t.set(r++,e&255|Z),e>>>=7;case 1:{t.set(r++,e&255),e>>>=7;break}default:throw new Error("unreachable")}return t}function Ln(e,t){let r=e[t],n=0;if(n+=r&Ct,r<Z||(r=e[t+1],n+=(r&Ct)<<7,r<Z)||(r=e[t+2],n+=(r&Ct)<<14,r<Z)||(r=e[t+3],n+=(r&Ct)<<21,r<Z)||(r=e[t+4],n+=(r&Ct)*Xi,r<Z)||(r=e[t+5],n+=(r&Ct)*Zi,r<Z)||(r=e[t+6],n+=(r&Ct)*Qi,r<Z)||(r=e[t+7],n+=(r&Ct)*Ji,r<Z))return n;throw new RangeError("Could not decode varint")}function Fp(e,t){let r=e.get(t),n=0;if(n+=r&Ct,r<Z||(r=e.get(t+1),n+=(r&Ct)<<7,r<Z)||(r=e.get(t+2),n+=(r&Ct)<<14,r<Z)||(r=e.get(t+3),n+=(r&Ct)<<21,r<Z)||(r=e.get(t+4),n+=(r&Ct)*Xi,r<Z)||(r=e.get(t+5),n+=(r&Ct)*Zi,r<Z)||(r=e.get(t+6),n+=(r&Ct)*Qi,r<Z)||(r=e.get(t+7),n+=(r&Ct)*Ji,r<Z))return n;throw new RangeError("Could not decode varint")}function Ko(e,t,r=0){return t==null&&(t=at(rt(e))),t instanceof Uint8Array?Oe(e,t,r):Up(e,t,r)}function me(e,t=0){return e instanceof Uint8Array?Ln(e,t):Fp(e,t)}var ta=new Float32Array([-0]),Ne=new Uint8Array(ta.buffer);function xu(e,t,r){ta[0]=e,t[r]=Ne[0],t[r+1]=Ne[1],t[r+2]=Ne[2],t[r+3]=Ne[3]}function Eu(e,t){return Ne[0]=e[t],Ne[1]=e[t+1],Ne[2]=e[t+2],Ne[3]=e[t+3],ta[0]}var ea=new Float64Array([-0]),Lt=new Uint8Array(ea.buffer);function Su(e,t,r){ea[0]=e,t[r]=Lt[0],t[r+1]=Lt[1],t[r+2]=Lt[2],t[r+3]=Lt[3],t[r+4]=Lt[4],t[r+5]=Lt[5],t[r+6]=Lt[6],t[r+7]=Lt[7]}function Au(e,t){return Lt[0]=e[t],Lt[1]=e[t+1],Lt[2]=e[t+2],Lt[3]=e[t+3],Lt[4]=e[t+4],Lt[5]=e[t+5],Lt[6]=e[t+6],Lt[7]=e[t+7],ea[0]}var kp=BigInt(Number.MAX_SAFE_INTEGER),Mp=BigInt(Number.MIN_SAFE_INTEGER),kt=class e{lo;hi;constructor(t,r){this.lo=t|0,this.hi=r|0}toNumber(t=!1){if(!t&&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(t=!1){if(t)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(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return ir;if(t<kp&&t>Mp)return this.fromNumber(Number(t));let r=t<0n;r&&(t=-t);let n=t>>32n,o=t-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>vu&&(o=0n,++n>vu&&(n=0n))),new e(Number(o),Number(n))}static fromNumber(t){if(t===0)return ir;let r=t<0;r&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new e(n,o)}static from(t){return typeof t=="number"?e.fromNumber(t):typeof t=="bigint"?e.fromBigInt(t):typeof t=="string"?e.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new e(t.low>>>0,t.high>>>0):ir}},ir=new kt(0,0);ir.toBigInt=function(){return 0n};ir.zzEncode=ir.zzDecode=function(){return this};ir.length=function(){return 1};var vu=4294967296n;function _u(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:(r&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Cu(e,t,r){if(r-t<1)return"";let o,s=[],i=0,a;for(;t<r;)a=e[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&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 ra(e,t,r){let n=r,o,s;for(let i=0;i<e.length;++i)o=e.charCodeAt(i),o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=o&63|128):(o&64512)===55296&&((s=e.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=o&63|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=o&63|128);return r-n}function Yt(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Ho(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}var na=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Yt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Yt(this,4);return Ho(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Yt(this,4);return Ho(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Yt(this,4);let t=Eu(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Yt(this,4);let t=Au(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw Yt(this,t);return this.pos+=t,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let t=this.bytes();return Cu(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Yt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Yt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new kt(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw Yt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,t}if(this.len-this.pos>4){for(;r<5;++r)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;r<5;++r){if(this.pos>=this.len)throw Yt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Yt(this,8);let t=Ho(this.buf,this.pos+=4),r=Ho(this.buf,this.pos+=4);return new kt(t,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Ln(this.buf,this.pos);return this.pos+=rt(t),t}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 In(e){return new na(e instanceof Uint8Array?e:e.subarray())}function Ue(e,t,r){let n=In(e);return t.decode(n,void 0,r)}function oa(e){let t=e??8192,r=t>>>1,n,o=t;return function(i){if(i<1||i>r)return at(i);o+i>t&&(n=at(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var ar=class{fn;len;next;val;constructor(t,r,n){this.fn=t,this.len=r,this.next=void 0,this.val=n}};function sa(){}var aa=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Kp=oa();function Hp(e){return globalThis.Buffer!=null?at(e):Kp(e)}var Dn=class{len;head;tail;states;constructor(){this.len=0,this.head=new ar(sa,0,0),this.tail=this.head,this.states=null}_push(t,r,n){return this.tail=this.tail.next=new ar(t,r,n),this.len+=r,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ca((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Vo,10,kt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let r=kt.fromBigInt(t);return this._push(Vo,r.length(),r)}uint64Number(t){return this._push(Oe,rt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let r=kt.fromBigInt(t).zzEncode();return this._push(Vo,r.length(),r)}sint64Number(t){let r=kt.fromNumber(t).zzEncode();return this._push(Vo,r.length(),r)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ia,1,t?1:0)}fixed32(t){return this._push(Bn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let r=kt.fromBigInt(t);return this._push(Bn,4,r.lo)._push(Bn,4,r.hi)}fixed64Number(t){let r=kt.fromNumber(t);return this._push(Bn,4,r.lo)._push(Bn,4,r.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(xu,4,t)}double(t){return this._push(Su,8,t)}bytes(t){let r=t.length>>>0;return r===0?this._push(ia,1,0):this.uint32(r)._push($p,r,t)}string(t){let r=_u(t);return r!==0?this.uint32(r)._push(ra,r,t):this._push(ia,1,0)}fork(){return this.states=new aa(this),this.head=this.tail=new ar(sa,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 ar(sa,0,0),this.len=0),this}ldelim(){let t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=r,this.len+=n),this}finish(){let t=this.head.next,r=Hp(this.len),n=0;for(;t!=null;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}};function ia(e,t,r){t[r]=e&255}function Vp(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}var ca=class extends ar{next;constructor(t,r){super(Vp,t,r),this.next=void 0}};function Vo(e,t,r){for(;e.hi!==0;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}function Bn(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function $p(e,t,r){t.set(e,r)}globalThis.Buffer!=null&&(Dn.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(zp,t,e),this},Dn.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(qp,t,e),this});function zp(e,t,r){t.set(e,r)}function qp(e,t,r){e.length<40?ra(e,t,r):t.utf8Write!=null?t.utf8Write(e,r):t.set(q(e),r)}function fa(){return new Dn}function Fe(e,t){let r=fa();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}function*ke(e,t,r){let n=In(e);yield*t.stream(n,void 0,"$",r)}var $o={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function zo(e,t,r,n,o){return{name:e,type:t,encode:r,decode:n,stream:o}}function cr(e){function t(s){if(e[s.toString()]==null)throw new Error("Invalid enum value");return e[s]}let r=function(i,a){let c=t(i);a.int32(c)},n=function(i){let a=i.int32();return t(a)},o=function*(i){let a=i.int32();yield t(a)};return zo("enum",$o.VARINT,r,n,o)}function Me(e,t,r){return zo("message",$o.LENGTH_DELIMITED,e,t,r)}var ft;(function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(ft||(ft={}));var ua;(function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(ua||(ua={}));(function(e){e.codec=()=>cr(ua)})(ft||(ft={}));var ne;(function(e){let t;e.codec=()=>(t==null&&(t=Me((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ft.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=ft.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:ft.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),t);function r(s){return Fe(s,e.codec())}e.encode=r;function n(s,i){return Ue(s,e.codec(),i)}e.decode=n;function o(s,i){return ke(s,e.codec(),i)}e.stream=o})(ne||(ne={}));var la;(function(e){let t;e.codec=()=>(t==null&&(t=Me((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ft.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=ft.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:ft.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),t);function r(s){return Fe(s,e.codec())}e.encode=r;function n(s,i){return Ue(s,e.codec(),i)}e.decode=n;function o(s,i){return ke(s,e.codec(),i)}e.stream=o})(la||(la={}));var Pn={};Dt(Pn,{MAX_RSA_KEY_SIZE:()=>ha,generateRSAKeyPair:()=>Ru,jwkToJWKKeyPair:()=>Pu,jwkToPkcs1:()=>Yp,jwkToPkix:()=>ga,jwkToRSAPrivateKey:()=>xa,pkcs1MessageToJwk:()=>pa,pkcs1MessageToRSAPrivateKey:()=>ya,pkcs1ToJwk:()=>Wp,pkcs1ToRSAPrivateKey:()=>Du,pkixMessageToJwk:()=>ma,pkixMessageToRSAPublicKey:()=>wa,pkixToJwk:()=>Xp,pkixToRSAPublicKey:()=>ba});var Ur=class{type="RSA";jwk;_raw;_multihash;constructor(t,r){this.jwk=t,this._multihash=r}get raw(){return this._raw==null&&(this._raw=Pn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return dt.createV1(114,this._multihash)}toString(){return lt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}verify(t,r,n){return Bu(this.jwk,r,t,n)}},Rn=class{type="RSA";jwk;_raw;publicKey;constructor(t,r){this.jwk=t,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=Pn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}sign(t,r){return Iu(this.jwk,t,r)}};var ha=8192,da=18,jp=1062,Gp=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Wp(e){let t=fe(e);return pa(t)}function pa(e){return{n:V(e[1],"base64url"),e:V(e[2],"base64url"),d:V(e[3],"base64url"),p:V(e[4],"base64url"),q:V(e[5],"base64url"),dp:V(e[6],"base64url"),dq:V(e[7],"base64url"),qi:V(e[8],"base64url"),kty:"RSA"}}function Yp(e){if(e.n==null||e.e==null||e.d==null||e.p==null||e.q==null||e.dp==null||e.dq==null||e.qi==null)throw new G("JWK was missing components");return ve([Ot(Uint8Array.from([0])),Ot(q(e.n,"base64url")),Ot(q(e.e,"base64url")),Ot(q(e.d,"base64url")),Ot(q(e.p,"base64url")),Ot(q(e.q,"base64url")),Ot(q(e.dp,"base64url")),Ot(q(e.dq,"base64url")),Ot(q(e.qi,"base64url"))]).subarray()}function Xp(e){let t=fe(e,{offset:0});return ma(t)}function ma(e){let t=fe(e[1],{offset:0});return{kty:"RSA",n:V(t[0],"base64url"),e:V(t[1],"base64url")}}function ga(e){if(e.n==null||e.e==null)throw new G("JWK was missing components");return ve([Gp,Eo(ve([Ot(q(e.n,"base64url")),Ot(q(e.e,"base64url"))]))]).subarray()}function Du(e){let t=fe(e);return ya(t)}function ya(e){let t=pa(e);return xa(t)}function ba(e,t){if(e.byteLength>=jp)throw new br("Key size is too large");let r=fe(e,{offset:0});return wa(r,e,t)}function wa(e,t,r){let n=ma(e);if(r==null){let o=re(ne.encode({Type:ft.RSA,Data:t}));r=Rt(da,o)}return new Ur(n,r)}function xa(e){if(Nu(e)>ha)throw new G("Key size is too large");let t=Pu(e),r=re(ne.encode({Type:ft.RSA,Data:ga(t.publicKey)})),n=Rt(da,r);return new Rn(t.privateKey,new Ur(t.publicKey,n))}async function Ru(e){if(e>ha)throw new G("Key size is too large");let t=await Ou(e),r=re(ne.encode({Type:ft.RSA,Data:ga(t.publicKey)})),n=Rt(da,r);return new Rn(t.privateKey,new Ur(t.publicKey,n))}function Pu(e){if(e==null)throw new G("Missing key parameter");return{privateKey:e,publicKey:{kty:e.kty,n:e.n,e:e.e}}}async function Ou(e,t){let r=await Ht.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);t?.signal?.throwIfAborted();let n=await Zp(r,t);return{privateKey:n[0],publicKey:n[1]}}async function Iu(e,t,r){let n=await Ht.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let o=await Ht.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,t instanceof Uint8Array?t:t.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Bu(e,t,r,n){let o=await Ht.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ht.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),s}async function Zp(e,t){if(e.privateKey==null||e.publicKey==null)throw new G("Private and public key are required");let r=await Promise.all([Ht.get().subtle.exportKey("jwk",e.privateKey),Ht.get().subtle.exportKey("jwk",e.publicKey)]);return t?.signal?.throwIfAborted(),r}function Nu(e){if(e.kty!=="RSA")throw new G("invalid key type");if(e.n==null)throw new G("invalid key modulus");return q(e.n,"base64url").length*8}var qo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,r){if(Xe(t),_t(r,void 0,"key"),this.iHash=t.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?t.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),qt(o)}update(t){return Lr(this),this.iHash.update(t),this}digestInto(t){Lr(this),So(t,this),this.finished=!0;let r=t.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},On=(()=>{let e=((t,r,n)=>new qo(t,r).update(n).digest());return e.create=(t,r)=>new qo(t,r),e})();var Uu=(e,t)=>(e+(e>=0?t:-t)/Fu)/t;function Qp(e,t,r){he("scalar",e,oe,r);let[[n,o],[s,i]]=t,a=Uu(i*e,r),c=Uu(-o*e,r),f=e-a*n-c*s,u=-a*o-c*i,l=f<oe,p=u<oe;l&&(f=-f),p&&(u=-u);let d=xn(Math.ceil(Br(r)/2))+Ke;if(f<oe||f>=d||u<oe||u>=d)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:l,k1:f,k2neg:p,k2:u}}function Sa(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Ea(e,t){Ft(e);let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];return Gt(r.lowS,"lowS"),Gt(r.prehash,"prehash"),r.format!==void 0&&Sa(r.format),r}var Aa=class extends Error{constructor(t=""){super(t)}},Xt={Err:Aa,_tlv:{encode:(e,t)=>{let{Err:r}=Xt;if(Wt(e,"tag"),e<0||e>255)throw new r("tlv.encode: wrong tag");if(typeof t!="string")throw new TypeError('"data" expected string, got type='+typeof t);if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=bn(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?bn(o.length/2|128):"";return bn(e)+s+o+t},decode(e,t){let{Err:r}=Xt;t=z(t,void 0,"DER data");let n=0;if(e<0||e>255)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[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=t.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=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=Xt;if(Io(e),e<oe)throw new t("integer: negative integers are not allowed");let r=bn(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=Xt;if(e.length<1)throw new t("invalid signature integer: empty");if(e[0]&128)throw new t("invalid signature integer: negative");if(e.length>1&&e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return er(e)}},toSig(e){let{Err:t,_int:r,_tlv:n}=Xt,o=z(e,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("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 t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(f)}},hexFromSig(e){let{_tlv:t,_int:r}=Xt,n=t.encode(2,r.encode(e.r)),o=t.encode(2,r.encode(e.s)),s=n+o;return t.encode(48,s)}};Object.freeze(Xt._tlv);Object.freeze(Xt._int);Object.freeze(Xt);var oe=BigInt(0),Ke=BigInt(1),Fu=BigInt(2),jo=BigInt(3),Jp=BigInt(4);function ku(e,t={}){let r=Po("weierstrass",e,t),n=r.Fp,o=r.Fn,s=r.CURVE,{h:i,n:a}=s;Ft(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:f}=t;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=Ku(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(U,m,A){if(f&&m.is0())return Uint8Array.of(0);let{x:E,y:w}=m.toAffine(),b=n.toBytes(E);if(Gt(A,"isCompressed"),A){l();let _=!n.isOdd(w);return mt(Mu(_),b)}else return mt(Uint8Array.of(4),b,n.toBytes(w))}function d(U){z(U,void 0,"Point");let{publicKey:m,publicKeyUncompressed:A}=u,E=U.length,w=U[0],b=U.subarray(1);if(f&&E===1&&w===0)return{x:n.ZERO,y:n.ZERO};if(E===m&&(w===2||w===3)){let _=n.fromBytes(b);if(!n.isValid(_))throw new Error("bad point: is not on curve, wrong x");let C=h(_),x;try{x=n.sqrt(C)}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(x);return(w&1)===1!==T&&(x=n.neg(x)),{x:_,y:x}}else if(E===A&&w===4){let _=n.BYTES,C=n.fromBytes(b.subarray(0,_)),x=n.fromBytes(b.subarray(_,_*2));if(!y(C,x))throw new Error("bad point: is not on curve");return{x:C,y:x}}else throw new Error(`bad point: got length ${E}, expected compressed=${m} or uncompressed=${A}`)}let g=t.toBytes===void 0?p:t.toBytes,S=t.fromBytes===void 0?d:t.fromBytes;function h(U){let m=n.sqr(U),A=n.mul(m,U);return n.add(n.add(A,n.mul(U,s.a)),s.b)}function y(U,m){let A=n.sqr(m),E=h(U);return n.eql(A,E)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,jo),Jp),L=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,L)))throw new Error("bad curve params: a or b");function O(U,m,A=!1){if(!n.isValid(m)||A&&n.is0(m))throw new Error(`bad point coordinate ${U}`);return m}function D(U){if(!(U instanceof I))throw new Error("Weierstrass Point expected")}function P(U){if(!c||!c.basises)throw new Error("no endo");return Qp(U,c.basises,o.ORDER)}function R(U,m,A,E,w){return A=new I(n.mul(A.X,U),A.Y,A.Z),m=Sn(E,m),A=Sn(w,A),m.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(m,A,E){this.X=O("x",m),this.Y=O("y",A,!0),this.Z=O("z",E),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){let{x:A,y:E}=m||{};if(!m||!n.isValid(A)||!n.isValid(E))throw new Error("invalid affine point");if(m instanceof I)throw new Error("projective point not allowed");return n.is0(A)&&n.is0(E)?I.ZERO:new I(A,E,n.ONE)}static fromBytes(m){let A=I.fromAffine(S(z(m,void 0,"point")));return A.assertValidity(),A}static fromHex(m){return I.fromBytes(Ir(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,A=!0){return k.createCache(this,m),A||this.multiply(jo),this}assertValidity(){let m=this;if(m.is0()){if(t.allowInfinityPoint&&n.is0(m.X)&&n.eql(m.Y,n.ONE)&&n.is0(m.Z))return;throw new Error("bad point: ZERO")}let{x:A,y:E}=m.toAffine();if(!n.isValid(A)||!n.isValid(E))throw new Error("bad point: x or y not field elements");if(!y(A,E))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(m)}equals(m){D(m);let{X:A,Y:E,Z:w}=this,{X:b,Y:_,Z:C}=m,x=n.eql(n.mul(A,C),n.mul(b,w)),T=n.eql(n.mul(E,C),n.mul(_,w));return x&&T}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:m,b:A}=s,E=n.mul(A,jo),{X:w,Y:b,Z:_}=this,C=n.ZERO,x=n.ZERO,T=n.ZERO,B=n.mul(w,w),F=n.mul(b,b),H=n.mul(_,_),K=n.mul(w,b);return K=n.add(K,K),T=n.mul(w,_),T=n.add(T,T),C=n.mul(m,T),x=n.mul(E,H),x=n.add(C,x),C=n.sub(F,x),x=n.add(F,x),x=n.mul(C,x),C=n.mul(K,C),T=n.mul(E,T),H=n.mul(m,H),K=n.sub(B,H),K=n.mul(m,K),K=n.add(K,T),T=n.add(B,B),B=n.add(T,B),B=n.add(B,H),B=n.mul(B,K),x=n.add(x,B),H=n.mul(b,_),H=n.add(H,H),B=n.mul(H,K),C=n.sub(C,B),T=n.mul(H,F),T=n.add(T,T),T=n.add(T,T),new I(C,x,T)}add(m){D(m);let{X:A,Y:E,Z:w}=this,{X:b,Y:_,Z:C}=m,x=n.ZERO,T=n.ZERO,B=n.ZERO,F=s.a,H=n.mul(s.b,jo),K=n.mul(A,b),J=n.mul(E,_),tt=n.mul(w,C),et=n.add(A,E),Y=n.add(b,_);et=n.mul(et,Y),Y=n.add(K,J),et=n.sub(et,Y),Y=n.add(A,w);let it=n.add(b,C);return Y=n.mul(Y,it),it=n.add(K,tt),Y=n.sub(Y,it),it=n.add(E,w),x=n.add(_,C),it=n.mul(it,x),x=n.add(J,tt),it=n.sub(it,x),B=n.mul(F,Y),x=n.mul(H,tt),B=n.add(x,B),x=n.sub(J,B),B=n.add(J,B),T=n.mul(x,B),J=n.add(K,K),J=n.add(J,K),tt=n.mul(F,tt),Y=n.mul(H,Y),J=n.add(J,tt),tt=n.sub(K,tt),tt=n.mul(F,tt),Y=n.add(Y,tt),K=n.mul(J,Y),T=n.add(T,K),K=n.mul(it,Y),x=n.mul(et,x),x=n.sub(x,K),K=n.mul(et,J),B=n.mul(it,B),B=n.add(B,K),new I(x,T,B)}subtract(m){return D(m),this.add(m.negate())}is0(){return this.equals(I.ZERO)}multiply(m){let{endo:A}=t;if(!o.isValidNot0(m))throw new RangeError("invalid scalar: out of range");let E,w,b=_=>k.cached(this,_,C=>or(I,C));if(A){let{k1neg:_,k1:C,k2neg:x,k2:T}=P(m),{p:B,f:F}=b(C),{p:H,f:K}=b(T);w=F.add(K),E=R(A.beta,B,H,_,x)}else{let{p:_,f:C}=b(m);E=_,w=C}return or(I,[E,w])[0]}multiplyUnsafe(m){let{endo:A}=t,E=this,w=m;if(!o.isValid(w))throw new RangeError("invalid scalar: out of range");if(w===oe||E.is0())return I.ZERO;if(w===Ke)return E;if(k.hasCache(this))return this.multiply(w);if(A){let{k1neg:b,k1:_,k2neg:C,k2:x}=P(w),{p1:T,p2:B}=su(I,E,_,x);return R(A.beta,T,B,b,C)}else return k.unsafe(E,w)}toAffine(m){let A=this,E=m,{X:w,Y:b,Z:_}=A;if(n.eql(_,n.ONE))return{x:w,y:b};let C=A.is0();E==null&&(E=C?n.ONE:n.inv(_));let x=n.mul(w,E),T=n.mul(b,E),B=n.mul(_,E);if(C)return{x:n.ZERO,y:n.ZERO};if(!n.eql(B,n.ONE))throw new Error("invZ was invalid");return{x,y:T}}isTorsionFree(){let{isTorsionFree:m}=t;return i===Ke?!0:m?m(I,this):k.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:m}=t;return i===Ke?this:m?m(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Ke?this.is0():this.clearCofactor().is0()}toBytes(m=!0){return Gt(m,"isCompressed"),this.assertValidity(),g(I,this,m)}toHex(m=!0){return Tr(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,k=new Pr(I,t.endo?Math.ceil(N/2):N);return N>=8&&I.BASE.precompute(8),Object.freeze(I.prototype),Object.freeze(I),I}function Mu(e){return Uint8Array.of(e?2:3)}function Ku(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function tm(e,t={}){let{Fn:r}=e,n=t.randomBytes===void 0?tr:t.randomBytes,o=Object.assign(Ku(e.Fp,r),{seed:Math.max(Ni(r.ORDER),16)});function s(d){try{let g=r.fromBytes(d);return r.isValidNot0(g)}catch{return!1}}function i(d,g){let{publicKey:S,publicKeyUncompressed:h}=o;try{let y=d.length;return g===!0&&y!==S||g===!1&&y!==h?!1:!!e.fromBytes(d)}catch{return!1}}function a(d){return d=d===void 0?n(o.seed):d,Ui(z(d,o.seed,"seed"),r.ORDER)}function c(d,g=!0){return e.BASE.multiply(r.fromBytes(d)).toBytes(g)}function f(d){let{secretKey:g,publicKey:S,publicKeyUncompressed:h}=o,y=r._lengths;if(!Je(d))return;let v=z(d,void 0,"key").length,L=v===S||v===h,O=v===g||!!y?.includes(v);if(!(L&&O))return L}function u(d,g,S=!0){if(f(d)===!0)throw new Error("first arg must be private key");if(f(g)===!1)throw new Error("second arg must be public key");let h=r.fromBytes(d);return e.fromBytes(g).multiply(h).toBytes(S)}let l={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},p=Or(a,c);return Object.freeze(l),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:e,utils:l,lengths:o})}function Hu(e,t,r={}){let n=t;Xe(n),Ft(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let o=r.randomBytes===void 0?tr:r.randomBytes,s=r.hmac===void 0?(w,b)=>On(n,w,b):r.hmac,{Fp:i,Fn:a}=e,{ORDER:c,BITS:f}=a,{keygen:u,getPublicKey:l,getSharedSecret:p,utils:d,lengths:g}=tm(e,r),S={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},h=c*Fu+Ke<i.ORDER;function y(w){let b=c>>Ke;return w>b}function v(w,b){if(!a.isValidNot0(b))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return b}function L(){if(h)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function O(w,b){Sa(b);let _=g.signature,C=b==="compact"?_:b==="recovered"?_+1:void 0;return z(w,C)}class D{r;s;recovery;constructor(b,_,C){if(this.r=v("r",b),this.s=v("s",_),C!=null){if(L(),![0,1,2,3].includes(C))throw new Error("invalid recovery id");this.recovery=C}Object.freeze(this)}static fromBytes(b,_=S.format){O(b,_);let C;if(_==="der"){let{r:F,s:H}=Xt.toSig(z(b));return new D(F,H)}_==="recovered"&&(C=b[0],_="compact",b=b.subarray(1));let x=g.signature/2,T=b.subarray(0,x),B=b.subarray(x,x*2);return new D(a.fromBytes(T),a.fromBytes(B),C)}static fromHex(b,_){return this.fromBytes(Ir(b),_)}assertRecovery(){let{recovery:b}=this;if(b==null)throw new Error("invalid recovery id: must be present");return b}addRecoveryBit(b){return new D(this.r,this.s,b)}recoverPublicKey(b){let{r:_,s:C}=this,x=this.assertRecovery(),T=x===2||x===3?_+c:_;if(!i.isValid(T))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let B=i.toBytes(T),F=e.fromBytes(mt(Mu((x&1)===0),B)),H=a.inv(T),K=R(z(b,void 0,"msgHash")),J=a.create(-K*H),tt=a.create(C*H),et=e.BASE.multiplyUnsafe(J).add(F.multiplyUnsafe(tt));if(et.is0())throw new Error("invalid recovery: point at infinify");return et.assertValidity(),et}hasHighS(){return y(this.s)}toBytes(b=S.format){if(Sa(b),b==="der")return Ir(Xt.hexFromSig(this));let{r:_,s:C}=this,x=a.toBytes(_),T=a.toBytes(C);return b==="recovered"?(L(),mt(Uint8Array.of(this.assertRecovery()),x,T)):mt(x,T)}toHex(b){return Tr(this.toBytes(b))}}Object.freeze(D.prototype),Object.freeze(D);let P=r.bits2int===void 0?function(b){if(b.length>8192)throw new Error("input is too large");let _=er(b),C=b.length*8-f;return C>0?_>>BigInt(C):_}:r.bits2int,R=r.bits2int_modN===void 0?function(b){return a.create(P(b))}:r.bits2int_modN,I=xn(f);function N(w){return he("num < 2^"+f,w,oe,I),a.toBytes(w)}function k(w,b){return z(w,void 0,"message"),b?z(n(w),void 0,"prehashed message"):w}function U(w,b,_){let{lowS:C,prehash:x,extraEntropy:T}=Ea(_,S);w=k(w,x);let B=R(w),F=a.fromBytes(b);if(!a.isValidNot0(F))throw new Error("invalid private key");let H=[N(F),N(B)];if(T!=null&&T!==!1){let et=T===!0?o(g.secretKey):T;H.push(z(et,void 0,"extraEntropy"))}let K=mt(...H),J=B;function tt(et){let Y=P(et);if(!a.isValidNot0(Y))return;let it=a.inv(Y),ie=e.BASE.multiply(Y).toAffine(),je=a.create(ie.x);if(je===oe)return;let yr=a.create(it*a.create(J+je*F));if(yr===oe)return;let nn=(ie.x===je?0:2)|Number(ie.y&Ke),on=yr;return C&&y(yr)&&(on=a.neg(yr),nn^=1),new D(je,on,h?void 0:nn)}return{seed:K,k2sig:tt}}function m(w,b,_={}){let{seed:C,k2sig:x}=U(w,b,_);return Vf(n.outputLen,a.BYTES,s)(C,x).toBytes(_.format)}function A(w,b,_,C={}){let{lowS:x,prehash:T,format:B}=Ea(C,S);if(_=z(_,void 0,"publicKey"),b=k(b,T),!Je(w)){let F=w instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+F)}O(w,B);try{let F=D.fromBytes(w,B),H=e.fromBytes(_);if(x&&F.hasHighS())return!1;let{r:K,s:J}=F,tt=R(b),et=a.inv(J),Y=a.create(tt*et),it=a.create(K*et),ie=e.BASE.multiplyUnsafe(Y).add(H.multiplyUnsafe(it));return ie.is0()?!1:a.create(ie.x)===K}catch{return!1}}function E(w,b,_={}){let{prehash:C}=Ea(_,S);return b=k(b,C),D.fromBytes(w,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:p,utils:d,lengths:g,Point:e,sign:m,verify:A,recoverPublicKey:E,Signature:D,hash:n})}var _a={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},em={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Vu=BigInt(2);function rm(e){let t=_a.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=e*e*e%t,u=f*f*e%t,l=st(u,r,t)*u%t,p=st(l,r,t)*u%t,d=st(p,Vu,t)*f%t,g=st(d,o,t)*d%t,S=st(g,s,t)*g%t,h=st(S,a,t)*S%t,y=st(h,c,t)*h%t,v=st(y,a,t)*S%t,L=st(v,r,t)*u%t,O=st(L,i,t)*g%t,D=st(O,n,t)*f%t,P=st(D,Vu,t);if(!va.eql(va.sqr(P),e))throw new Error("Cannot find square root");return P}var va=Dr(_a.p,{sqrt:rm}),nm=ku(_a,{Fp:va,endo:em}),Fr=Hu(nm,re);function $u(e,t,r,n){let o=ce.digest(r instanceof Uint8Array?r:r.subarray());if(ko(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Fr.verify(t,s,e,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Cn(String(s))});try{return n?.signal?.throwIfAborted(),Fr.verify(t,o.digest,e,{prehash:!1,format:"der"})}catch(s){throw new Cn(String(s))}}var Go=class{type="secp256k1";raw;_key;constructor(t){this._key=qu(t),this.raw=zu(this._key)}toMultihash(){return zt.digest(_e(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return lt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}verify(t,r,n){return $u(this._key,r,t,n)}};function Ca(e){return new Go(e)}function zu(e){return Fr.Point.fromBytes(e).toBytes()}function qu(e){try{return Fr.Point.fromBytes(e),e}catch(t){throw new br(String(t))}}function Nn(e,t){let{Type:r,Data:n}=ne.decode(e),o=n??new Uint8Array;switch(r){case ft.RSA:return ba(o,t);case ft.Ed25519:return Yi(o);case ft.secp256k1:return Ca(o);case ft.ECDSA:return wi(o);default:throw new Ge}}function ju(e){let{Type:t,Data:r}=ne.decode(e.digest),n=r??new Uint8Array;switch(t){case ft.Ed25519:return Yi(n);case ft.secp256k1:return Ca(n);case ft.ECDSA:return wi(n);default:throw new Ge}}function _e(e){return ne.encode({Type:ft[e.type],Data:e.raw})}var Gu=Symbol.for("nodejs.util.inspect.custom"),om=114,Un=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[qs]=!0;toString(){return this.string==null&&(this.string=lt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return dt.createV1(om,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return wt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return wt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Gu](){return`PeerId(${this.toString()})`}},Fn=class extends Un{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},kn=class extends Un{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Mn=class extends Un{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},sm=2336,Kn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=zt.digest(q(this.url))}[Gu](){return`PeerId(${this.url})`}[qs]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return dt.createV1(sm,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=V(t)),t.toString()===this.toString())}};var im=114,Wu=2336;function kr(e,t){let r;if(e.charAt(0)==="1"||e.charAt(0)==="Q")r=_r(lt.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return am(dt.parse(e));if(t==null)throw new G('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=_r(t.decode(e))}return Yu(r)}function La(e){if(e.type==="Ed25519")return new kn({multihash:e.toCID().multihash,publicKey:e});if(e.type==="secp256k1")return new Mn({multihash:e.toCID().multihash,publicKey:e});if(e.type==="RSA")return new Fn({multihash:e.toCID().multihash,publicKey:e});throw new Ge}function Yu(e){if(fm(e))return new Fn({multihash:e});if(cm(e))try{let t=ju(e);if(t.type==="Ed25519")return new kn({multihash:e,publicKey:t});if(t.type==="secp256k1")return new Mn({multihash:e,publicKey:t})}catch{let r=V(e.digest);return new Kn(new URL(r))}throw new lo("Supplied PeerID Multihash is invalid")}function am(e){if(e?.multihash==null||e.version==null||e.version===1&&e.code!==im&&e.code!==Wu)throw new uo("Supplied PeerID CID is invalid");if(e.code===Wu){let t=V(e.multihash.digest);return new Kn(new URL(t))}return Yu(e.multihash)}function cm(e){return e.code===zt.code}function fm(e){return e.code===ce.code}var St=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ge=class extends Error{static name="ValidationError";name="ValidationError"},Wo=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Yo=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Xo=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let r=this.index,n=t();return n===void 0&&(this.index=r),n}parseWith(t){let r=t();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(t){return this.readAtomically(()=>{let r=this.readChar();if(r===t)return r})}readSeparator(t,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,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 p=Number.parseInt(l,t);if(!Number.isNaN(p))return p});if(u===void 0)break;if(s*=t,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 t=new Uint8Array(4);for(let r=0;r<t.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[r]=n}return t})}readIPv6Addr(){let t=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]=t(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]=t(s.subarray(0,i));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var um=45,lm=15,Zo=new Xo;function Xu(e){if(!(e.length>lm))return Zo.new(e).parseWith(()=>Zo.readIPv4Addr())}function Zu(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>um))return Zo.new(e).parseWith(()=>Zo.readIPv6Addr())}function Qo(e){return!!Xu(e)}function Qu(e){return!!Zu(e)}function Ia(e){return t=>V(t,e)}function Ba(e){return t=>q(t,e)}function Mr(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function fr(e){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof e=="string"?parseInt(e):e),new Uint8Array(t)}function Ju(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let r=q(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=fr(n);return Pt([r,o],r.length+o.length)}function tl(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let r=Ae.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=fr(n);return Pt([r,o],r.length+o.length)}function Da(e){let t=e.subarray(0,e.length-2),r=e.subarray(e.length-2),n=V(t,"base32"),o=Mr(r);return`${n}:${o}`}var Ra=function(e){e=e.toString().trim();let t=new Uint8Array(4);return e.split(/\./g).forEach((r,n)=>{let o=parseInt(r,10);if(isNaN(o)||o<0||o>255)throw new St("Invalid byte value in IP address");t[n]=o}),t},el=function(e){let t=0;e=e.toString().trim();let r=e.split(":",8),n;for(n=0;n<r.length;n++){let s=Qo(r[n]),i;s&&(i=Ra(r[n]),r[n]=V(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,V(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(t+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 St("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},rl=function(e){if(e.byteLength!==4)throw new St("IPv4 address was incorrect length");let t=[];for(let r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},nl=function(e){if(e.byteLength!==16)throw new St("IPv6 address was incorrect length");let t=[];for(let n=0;n<e.byteLength;n+=2){let o=e[n],s=e[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}let r=t.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new St(`Invalid IPv6 address "${r}"`)}};function ol(e){try{let t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new St(`Invalid IPv6 address "${e}"`)}}var Ta=Object.values(Ye).map(e=>e.decoder),hm=(function(){let e=Ta[0].or(Ta[1]);return Ta.slice(2).forEach(t=>e=e.or(t)),e})();function sl(e){return hm.decode(e)}function il(e){return t=>e.encoder.encode(t)}function dm(e){if(parseInt(e).toString()!==e)throw new ge("Value must be an integer")}function pm(e){if(e<0)throw new ge("Value must be a positive integer, or zero")}function mm(e){return t=>{if(t>e)throw new ge(`Value must be smaller than or equal to ${e}`)}}function gm(...e){return t=>{for(let r of e)r(t)}}var Hn=gm(dm,pm,mm(65535));var bt=-1,Pa=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let r;if(typeof t=="string"?r=this.protocolsByName.get(t):r=this.protocolsByCode.get(t),r==null)throw new Yo(`Protocol ${t} was unknown`);return r}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(r=>{this.protocolsByName.set(r,t)})}removeProtocol(t){let r=this.protocolsByCode.get(t);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},be=new Pa,Bm=[{code:4,name:"ip4",size:32,valueToBytes:Ra,bytesToValue:rl,validate:e=>{if(!Qo(e))throw new ge(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:fr,bytesToValue:Mr,validate:Hn},{code:273,name:"udp",size:16,valueToBytes:fr,bytesToValue:Mr,validate:Hn},{code:33,name:"dccp",size:16,valueToBytes:fr,bytesToValue:Mr,validate:Hn},{code:41,name:"ip6",size:128,valueToBytes:el,bytesToValue:nl,stringToValue:ol,validate:e=>{if(!Qu(e))throw new ge(`Invalid IPv6 address "${e}"`)}},{code:42,name:"ip6zone",size:bt},{code:43,name:"ipcidr",size:8,bytesToValue:Ia("base10"),valueToBytes:Ba("base10")},{code:53,name:"dns",size:bt},{code:54,name:"dns4",size:bt},{code:55,name:"dns6",size:bt},{code:56,name:"dnsaddr",size:bt},{code:132,name:"sctp",size:16,valueToBytes:fr,bytesToValue:Mr,validate:Hn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:bt,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:bt,bytesToValue:Ia("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?Ba("base58btc")(e):dt.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Da,valueToBytes:Ju},{code:445,name:"onion3",size:296,bytesToValue:Da,valueToBytes:tl},{code:446,name:"garlic64",size:bt},{code:447,name:"garlic32",size:bt},{code:448,name:"tls"},{code:449,name:"sni",size:bt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:bt,bytesToValue:il(ln),valueToBytes:sl},{code:480,name:"http"},{code:481,name:"http-path",size:bt,stringToValue:e=>`/${decodeURIComponent(e)}`,valueToString:e=>encodeURIComponent(e.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:bt}];Bm.forEach(e=>{be.addProtocol(e)});function al(e){let t=[],r=0;for(;r<e.length;){let n=me(e,r),o=be.getProtocol(n),s=rt(n),i=Dm(o,e,r+s),a=0;i>0&&o.size===bt&&(a=rt(i));let c=s+a+i,f={code:n,name:o.name,bytes:e.subarray(r,r+c)};if(i>0){let u=r+s+a,l=e.subarray(u,u+i);f.value=o.bytesToValue?.(l)??V(l)}t.push(f),r+=c}return t}function cl(e){let t=0,r=[];for(let n of e){if(n.bytes==null){let o=be.getProtocol(n.code),s=rt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??q(n.value),a=i.byteLength,o.size===bt&&(c=rt(a)));let f=new Uint8Array(s+c+a),u=0;Oe(n.code,f,u),u+=s,i!=null&&(o.size===bt&&(Oe(a,f,u),u+=c),f.set(i,u)),n.bytes=f}r.push(n.bytes),t+=n.bytes.byteLength}return Pt(r,t)}function fl(e){if(e.charAt(0)!=="/")throw new St('String multiaddr must start with "/"');let t=[],r="protocol",n="",o="";for(let s=1;s<e.length;s++){let i=e.charAt(s);i!=="/"&&(r==="protocol"?o+=e.charAt(s):n+=e.charAt(s));let a=s===e.length-1;if(i==="/"||a){let c=be.getProtocol(o);if(r==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",r="protocol";continue}else if(a)throw new St(`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 St(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}t.push(f),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new St("Incomplete multiaddr");return t}function ul(e){return`/${e.flatMap(t=>{if(t.value==null)return t.name;let r=be.getProtocol(t.code);if(r==null)throw new St(`Unknown protocol code ${t.code}`);return[t.name,r.valueToString?.(t.value)??t.value]}).join("/")}`}function Dm(e,t,r){return e.size==null||e.size===0?0:e.size>0?e.size/8:me(t,r)}var Rm=Symbol.for("nodejs.util.inspect.custom"),Xa=Symbol.for("@multiformats/multiaddr");function Pm(e){if(e==null&&(e="/"),ll(e))return e.getComponents();if(e instanceof Uint8Array)return al(e);if(typeof e=="string")return e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),e===""&&(e="/"),fl(e);if(Array.isArray(e))return e;throw new St("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ns=class e{[Xa]=!0;#t;#e;#r;constructor(t="/",r={}){this.#t=Pm(t),r.validate!==!1&&Om(this)}get bytes(){return this.#r==null&&(this.#r=cl(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=ul(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let r=new e(t);return new e([...this.#t,...r.getComponents()],{validate:!1})}decapsulate(t){let r=t.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new Wo(`Address ${this.toString()} does not contain subaddress: ${r}`);return new e(n.slice(0,o),{validate:!1})}decapsulateCode(t){let r;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){r=n;break}return new e(this.#t.slice(0,r),{validate:!1})}equals(t){return wt(this.bytes,t.bytes)}[Rm](){return`Multiaddr(${this.toString()})`}};function Om(e){e.getComponents().forEach(t=>{let r=be.getProtocol(t.code);t.value!=null&&r.validate?.(t.value)})}function ll(e){return!!e?.[Xa]}function $r(e){return new ns(e)}var nt=e=>({match:t=>{let r=t[0];return r==null||r.code!==e||r.value!=null?!1:t.slice(1)}}),M=(e,t)=>({match:r=>{let n=r[0];return n?.code!==e||n.value==null||t!=null&&n.value!==t?!1:r.slice(1)}}),hl=e=>({match:t=>e.match(t)===!1?t:!1}),j=e=>({match:t=>{let r=e.match(t);return r===!1?t:r}}),Tt=(...e)=>({match:t=>{let r;for(let n of e){let o=n.match(t);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1}}),X=(...e)=>({match:t=>{for(let r of e){let n=r.match(t);if(n===!1)return!1;t=n}return t}});function ot(...e){function t(o){if(o==null)return!1;let s=o.getComponents();for(let i of e){let a=i.match(s);if(a===!1)return!1;s=a}return s}function r(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:e,matches:r,exactMatch:n}}var Nm=M(421),Z1=ot(Nm),ss=M(54),is=M(55),as=M(56),Qa=M(53),Q1=ot(ss,j(M(421))),J1=ot(is,j(M(421))),t2=ot(as,j(M(421))),e2=ot(Tt(Qa,as,ss,is),j(M(421))),dl=X(M(4),j(M(43))),pl=X(j(M(42)),M(41),j(M(43))),Ja=Tt(dl,pl),zr=Tt(Ja,Qa,ss,is,as),r2=ot(Tt(Ja,X(Tt(Qa,as,ss,is),j(M(421))))),n2=ot(dl),o2=ot(pl),s2=ot(Ja),tc=X(zr,M(6)),Vn=X(zr,M(273)),i2=ot(X(tc,j(M(421)))),a2=ot(Vn),ec=X(Vn,nt(460),j(M(421))),cs=X(Vn,nt(461),j(M(421))),Um=Tt(ec,cs),c2=ot(ec),f2=ot(cs),Za=Tt(zr,tc,Vn,ec,cs),ml=Tt(X(Za,nt(477),j(M(421)))),u2=ot(ml),gl=Tt(X(Za,nt(478),j(M(421))),X(Za,nt(448),j(M(449)),nt(477),j(M(421)))),l2=ot(gl),yl=X(Vn,nt(280),j(M(466)),j(M(466)),j(M(421))),bl=ot(yl),wl=X(cs,nt(465),j(M(466)),j(M(466)),j(M(421))),h2=ot(wl),os=Tt(ml,gl,X(tc,j(M(421))),X(Um,j(M(421))),X(zr,j(M(421))),yl,wl,M(421)),xl=ot(os),Fm=X(j(os),nt(290),hl(nt(281)),j(M(421))),d2=ot(Fm),km=Tt(X(os,nt(290),nt(281),j(M(421))),X(os,nt(281),j(M(421))),X(nt(281),j(M(421)))),El=ot(km),Mm=X(zr,Tt(X(M(6,"80")),X(M(6),nt(480)),nt(480)),j(M(481)),j(M(421))),p2=ot(Mm),Km=X(zr,Tt(X(M(6,"443")),X(M(6,"443"),nt(480)),X(M(6),nt(443)),X(M(6),nt(448),nt(480)),X(nt(448),nt(480)),nt(448),nt(443)),j(M(481)),j(M(421))),m2=ot(Km),Hm=Tt(X(M(777),j(M(421)))),g2=ot(Hm),Vm=Tt(X(M(400),j(M(421)))),y2=ot(Vm);var It;(function(e){let t;(function(a){a.FIN="FIN",a.STOP_SENDING="STOP_SENDING",a.RESET="RESET",a.FIN_ACK="FIN_ACK"})(t=e.Flag||(e.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=()=>cr(r)})(t=e.Flag||(e.Flag={}));let n;e.codec=()=>(n==null&&(n=Me((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.flag!=null&&(c.uint32(8),e.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 p=a.uint32();switch(p>>>3){case 1:{u.flag=e.Flag.codec().decode(a);break}case 2:{u.message=a.bytes();break}default:{a.skipType(p&7);break}}}return u},function*(a,c,f,u={}){let l=c==null?a.len:a.pos+c;for(;a.pos<l;){let p=a.uint32();switch(p>>>3){case 1:{yield{field:`${f}.flag`,value:e.Flag.codec().decode(a)};break}case 2:{yield{field:`${f}.message`,value:a.bytes()};break}default:{a.skipType(p&7);break}}}})),n);function o(a){return Fe(a,e.codec())}e.encode=o;function s(a,c){return Ue(a,e.codec(),c)}e.decode=s;function i(a,c){return ke(a,e.codec(),c)}e.stream=i})(It||(It={}));var Sl=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],rc=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Al="libp2p+webrtc+v1/",vl=2*1024*1024,qr=16*1024;function $m(e=qr){let t=rt(e-rt(e)),r=1+rt(Object.keys(It.Flag).length-1),n=1,o=e-t-r-n,s=rt(o);return t+r+n+s}var _l=$m();var Cl=1e4,nc="/webrtc",$n="/webrtc-signaling/0.0.1";function oc(e){let t=e.getComponents(),r={},n=0;if(t[n]?.name==="ip6zone"&&(r.zone=`${t[n].value}`,n++),t[n].name==="ip4"||t[n].name==="ip6"||t[n].name==="dns"||t[n].name==="dns4"||t[n].name==="dns6"?(r.type=t[n].name,r.host=t[n].value,n++):t[n].name==="dnsaddr"&&(r.type=t[n].name,r.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(r.protocol=t[n].name==="tcp"?"tcp":"udp",r.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(r.type==="ip4"?r.cidr=parseInt(`${t[n].value}`):r.type==="ip6"&&(r.cidr=`${t[n].value}`),n++),r.type==null||r.host==null)throw new G(`Multiaddr ${e} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(r.sni=t[n+1].value,n+=2),r}function fs(){let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}var us=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},jr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new us(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let r=this.head;this.head=r.next=new us(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var sc=class extends Error{type;code;constructor(t,r){super(t??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Gr(e={}){return zm(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}},e)}function zm(e,t){t=t??{};let r=t.onEnd,n=new jr,o,s,i,a=fs(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,y)=>{s=v=>{s=null,n.push(v);try{h(e(n))}catch(L){y(L)}return o}}):e(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=fs()})}},f=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new jr,s!=null?s({error:h}):(n.push({error:h}),o)),l=h=>{if(i)return o;if(t?.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})},p=h=>i?o:(i=!0,h!=null?u(h):f({done:!0})),d=()=>(n=new jr,p(),{done:!0}),g=h=>(p(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:g,push:l,end:p,get readableLength(){return n.size},onEmpty:async h=>{let y=h?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let v,L;y!=null&&(v=new Promise((O,D)=>{L=()=>{D(new sc)},y.addEventListener("abort",L)}));try{await Promise.race([a.promise,v])}finally{L!=null&&y!=null&&y?.removeEventListener("abort",L)}}},r==null)return o;let S=o;return o={[Symbol.asyncIterator](){return this},next(){return S.next()},throw(h){return S.throw(h),r!=null&&(r(h),r=void 0),{done:!0}},return(){return S.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(h){return S.end(h),r!=null&&(r(h),r=void 0),o},get readableLength(){return S.readableLength},onEmpty:h=>S.onEmpty(h)},o}var ic=class e extends Error{name="TimeoutError";constructor(t,r){super(t,r),Error.captureStackTrace?.(this,e)}},Ll=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function ac(e,t){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=t,a,c,u=new Promise((l,p)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){p(Ll(i));return}if(i&&(c=()=>{p(Ll(i))},i.addEventListener("abort",c,{once:!0})),e.then(l,p),r===Number.POSITIVE_INFINITY)return;let d=new ic;a=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(g){p(g)}return}typeof e.cancel=="function"&&e.cancel(),o===!1?l():o instanceof Error?p(o):(d.message=o??`Promise timed out after ${r} milliseconds`,p(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 qm=e=>{let t=e.addEventListener||e.on||e.addListener,r=e.removeEventListener||e.off||e.removeListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}};function jm(e,t,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=[t].flat(),c=[],{addListener:f,removeListener:u}=qm(e),l=async(...d)=>{let g=r.multiArgs?d:d[0];if(r.filter)try{if(!await r.filter(g))return}catch(S){n(),i(S);return}c.push(g),r.count===c.length&&(n(),s(c))},p=(...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,p)};for(let d of a)f(d,l);for(let d of r.rejectionEvents)a.includes(d)||f(d,p);r.signal&&r.signal.addEventListener("abort",()=>{p(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){let s=ac(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function At(e,t,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=jm(e,t,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var lr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},ls=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},hs=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Gm(e){return e.reason}async function we(e,t,r){if(t==null)return e;let n=r?.translateError??Gm;if(t.aborted)return e.catch(()=>{}),Promise.reject(n(t));let o;try{return await Promise.race([e,new Promise((s,i)=>{o=()=>{i(n(t))},t.addEventListener("abort",o)})])}finally{o!=null&&t.removeEventListener("abort",o)}}var Wm=Math.pow(2,20)*4,Ve=class extends Ee{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(t){super(),this.status="open",this.log=t.log,this.direction=t.direction??"outbound",this.inactivityTimeout=t.inactivityTimeout??12e4,this.maxReadBufferLength=t.maxReadBufferLength??Wm,this.maxWriteBufferLength=t.maxWriteBufferLength,this.maxMessageSize=t.maxMessageSize,this.readBuffer=new $,this.writeBuffer=new $,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(()=>{this.processSendQueue()})),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);let n=o=>{this.onDrainPromise?.reject(o.error??new hs)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(t){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),we(this.onDrainPromise.promise,t?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let t=Gr(),r=s=>{t.push(s.data)};this.addEventListener("message",r);let n=s=>{t.end(s.error)};this.addEventListener("close",n);let o=()=>{t.end()};this.addEventListener("remoteCloseWrite",o);try{yield*t}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(t){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Jt(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",t.byteLength),this.writeBuffer.append(t),this.processSendQueue()}abort(t){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",t),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(t)}catch(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new mo(t))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Jt("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 Jt("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Jt(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.append(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Jt(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.prepend(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(t){if(t.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(t),this.dispatchReadBuffer()}}addEventListener(...t){super.addEventListener.apply(this,t),t[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 t=new wr;this.dispatchEvent(new go(t))}onTransportClosed(t){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"),t!=null?this.abort(t):(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 xr))}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;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let t=!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){t=!1;break}let s=this.writeBuffer.sublist(0,o),i=new $(s);this.writeBuffer.consume(s.byteLength);let a=this.sendData(s);if(t=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!t)break}return t||(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"),t}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 t=this.readBuffer.sublist();this.readBuffer.consume(t.byteLength),this.dispatchEvent(new po(t))}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 ds=class extends Ve{remoteAddr;metricPrefix;metrics;constructor(t){super(t),this.metricPrefix=t.metricPrefix??"",this.metrics=t.metrics,this.remoteAddr=t.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(t){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 At(this,"idle",{...t,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 At(this,"drain",{...t,rejectionEvents:["close"]})),await this.sendClose(t),this.onTransportClosed())}};function Tl(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var ps=class extends Ee{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(t,r){super(),this.maConn=t,this.protocol=r.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=t.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(t){let r=this.maConn.send(t);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(t){this.status==="closed"||this.status==="closing"||(this.status="closing",await we(Promise.all([...this.streams].map(async r=>{await r.close(t)})),t?.signal),this.status="closed")}abort(t){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(r=>{r.abort(t)}),this.status="closed")}onTransportClosed(t){this.status="closing";try{[...this.streams].forEach(r=>{r.onTransportClosed(t)})}catch(r){this.abort(r)}this.status="closed"}async createStream(t){if(this.status!=="open")throw new co;let r=this.onCreateStream({...this.streamOptions,...t});return Tl(r)&&(r=await r),this.streams.push(r),this.cleanUpStream(r),r}onRemoteStream(t){if(this.streams.push(t),this.cleanUpStream(t),this.listenerCount("stream")===0){this.earlyStreams.push(t),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new ls(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:t})}cleanUpStream(t){let r=n=>{let o=this.streams.findIndex(s=>s===t);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${t.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${t.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${t.direction}_stream_end`]:!0})};t.addEventListener("close",r),this.metrics?.increment({[`${t.direction}_stream`]:!0})}addEventListener(...t){super.addEventListener.apply(this,t),t[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(r=>{this.safeDispatchEvent("stream",{detail:r})}),this.earlyStreams=[]})}};var ms=class extends Ve{id;protocol;constructor(t){super(t),this.id=t.id,this.protocol=t.protocol??""}async close(t){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 At(this,"idle",{...t,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 At(this,"drain",{...t,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(t),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(t){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(t),this.readStatus="closed",this.log("closed readable end gracefully"))}};var Ym=4194304,gs=class extends Error{static name="UnwrappedError";name="UnwrappedError"},zn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},fc=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},uc=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Xm(e){return typeof e?.closeRead=="function"}function Zm(e){return typeof e?.close=="function"}function cc(e){return Xm(e)?e.remoteWriteStatus!=="writable"&&e.readBufferLength===0:Zm(e)?e.status!=="open":!1}function Qm(e){return e?.addEventListener!=null&&e?.removeEventListener!=null&&e?.send!=null&&e?.push!=null&&e?.log!=null}function Jm(e,t){let r=t?.maxBufferSize??Ym,n=new $,o,s=!1;if(!Qm(e))throw new G("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()};e.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};e.addEventListener("close",a);let c=()=>{o?.resolve()};e.addEventListener("remoteCloseWrite",c);let f={readBuffer:n,async read(u){if(s===!0)throw new gs("Stream was unwrapped");if(cc(e)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw e.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new lr(`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 we(o.promise,u?.signal),cc(e)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let p=u?.bytes??n.byteLength;if(n.byteLength<p){if(cc(e))throw e.log.error("closed while reading %d/%d bytes",n.byteLength,p),new lr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${p} bytes`);return f.read(u)}let d=n.sublist(0,p);return n.consume(p),d},async write(u,l){if(s===!0)throw new gs("Stream was unwrapped");e.send(u)||await At(e,"drain",{signal:l?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,e.removeEventListener("message",i),e.removeEventListener("close",a),e.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(e.log("stream unwrapped with %d unread bytes",n.byteLength),e.push(n))),e}};return f}function ys(e,t={}){let r=Jm(e,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=rt(t.maxDataLength));let n=t?.lengthDecoder??me,o=t?.lengthEncoder??Ko;return{async read(i){let a=-1,c=new $;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 zn("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new uc(`Message length length too long - ${c.byteLength} > ${t.maxLengthLength}`);if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new fc(`Message length too long - ${a} > ${t.maxDataLength}`);let f=await r.read({...i,bytes:a});if(f==null)throw e.log.error("tried to read %d bytes but the stream closed",a),new lr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(f.byteLength!==a)throw e.log.error("read %d/%d bytes before the stream closed",f.byteLength,a),new lr(`Unexpected EOF - read ${f.byteLength}/${a} bytes before the stream closed`);return f},async write(i,a){await r.write(new $(o(i.byteLength),i),a)},async writeV(i,a){let c=new $(...i.flatMap(f=>[o(f.byteLength),f]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function bs(e,t){let r=ys(e,t),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 t0=1024*1024*4,e0=1024*1024*4,ws=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(t={}){this.buffer=new $,this.maxBufferSize=t.maxBufferSize??t0,this.maxDataLength=t.maxDataLength??e0,this.lengthDecoder=t.lengthDecoder??me,this.encodingLength=t.encodingLength??rt}*decode(t){if(this.buffer.append(t),this.buffer.byteLength>this.maxBufferSize)throw new G(`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 zn("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}}};var xs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Wr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Es=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},qn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Ss(e){return e[Symbol.asyncIterator]!=null}function Il(e,t){if(e.byteLength>t)throw new Wr("Message length too long")}var vs=e=>{let t=rt(e),r=at(t);return Ko(e,r),vs.bytes=t,r};vs.bytes=0;function jn(e,t){t=t??{};let r=t.lengthEncoder??vs,n=t?.maxDataLength??4194304;function*o(s){Il(s,n);let i=r(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Ss(e)?(async function*(){for await(let s of e)yield*o(s)})():(function*(){for(let s of e)yield*o(s)})()}jn.single=(e,t)=>{t=t??{};let r=t.lengthEncoder??vs,n=t?.maxDataLength??4194304;return Il(e,n),new $(r(e.byteLength),e)};var hr;(function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(hr||(hr={}));var lc=e=>{let t=me(e);return lc.bytes=rt(t),t};lc.bytes=0;function Gn(e,t){let r=new $,n=hr.LENGTH,o=-1,s=t?.lengthDecoder??lc,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===hr.LENGTH)try{if(o=s(r),o<0)throw new xs("Invalid message length");if(o>a)throw new Wr("Message length too long");let f=s.bytes;r.consume(f),t?.onLength!=null&&t.onLength(o),n=hr.DATA}catch(f){if(f instanceof RangeError){if(r.byteLength>i)throw new Es("Message length length too long");break}throw f}if(n===hr.DATA){if(r.byteLength<o)break;let f=r.sublist(0,o);r.consume(o),t?.onData!=null&&t.onData(f),yield f,n=hr.LENGTH}}}return Ss(e)?(async function*(){for await(let f of e)r.append(f),yield*c();if(r.byteLength>0)throw new qn("Unexpected end of input")})():(function*(){for(let f of e)r.append(f),yield*c();if(r.byteLength>0)throw new qn("Unexpected end of input")})()}Gn.fromReader=(e,t)=>{let r=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await e.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 Gn(n,{...t??{},onLength:s=>{r=s}})};var hc=class extends ms{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(t){super({...t,maxMessageSize:(t.maxMessageSize??qr)-_l}),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=Gr(),this.maxBufferedAmount=t.maxBufferedAmount??vl,this.finAckTimeout=t.finAckTimeout??Cl,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 Gn(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),At(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(t){if(this.channel.readyState!=="open")throw new Jt(`Invalid datachannel state - ${this.channel.readyState}`);this.log.trace('sending message, channel state "%s"',this.channel.readyState);try{for(let r of t)this.channel.send(r)}catch(r){this.log.error("error sending datachannel message - %e",r),this.abort(r)}}sendData(t){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(jn.single(It.encode({message:t.subarray()}))),{sentBytes:t.byteLength,canSendMore:this.channel.bufferedAmount<this.maxBufferedAmount})}sendReset(t){try{this.log.error("sending reset - %e",t),this._sendFlag(It.Flag.RESET),this.receivedFinAck?.reject(t)}catch(r){this.log.error("failed to send reset - %e",r)}}async sendCloseWrite(t){this._sendFlag(It.Flag.FIN),t?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let r=t?.signal??AbortSignal.timeout(this.finAckTimeout),n=[At(this.channel,"close",{signal:r}),At(this.channel,"error",{signal:r})];await Promise.any([we(this.receivedFinAck.promise,r),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(t){this._sendFlag(It.Flag.STOP_SENDING),t?.signal?.throwIfAborted()}processIncomingProtobuf(t){let r=It.decode(t);r.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new $(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===It.Flag.FIN&&(this._sendFlag(It.Flag.FIN_ACK),this.onRemoteCloseWrite()),r.flag===It.Flag.RESET&&(this.receivedFinAck?.reject(new wr("The stream was reset")),this.onRemoteReset()),r.flag===It.Flag.STOP_SENDING&&this.onRemoteCloseRead(),r.flag===It.Flag.FIN_ACK&&this.receivedFinAck?.resolve())}_sendFlag(t){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',t.toString(),this.channel.readyState),!1;this.log.trace("sending flag %s",t.toString());let r=It.encode({flag:t}),n=jn.single(r);try{return this._sendMessage(n),!0}catch(o){this.log.error("could not send flag %s - %e",t.toString(),o)}return!1}sendPause(){}sendResume(){}};function Wn(e){let{channel:t,direction:r,isHandshake:n}=e;return new hc({...e,id:`${t.id}`,log:e.log.newScope(`${n===!0?"handshake":r}:${t.id}`),protocol:""})}var $e=class{protocol;peerConnection;metrics;dataChannelOptions;earlyDataChannels;constructor(t){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=t.peerConnection,this.metrics=t.metrics,this.protocol=t.protocol??nc,this.dataChannelOptions=t.dataChannelOptions??{},this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(t){this.earlyDataChannels.push(t.channel)}createStreamMuxer(t){return this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new dc(t,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,earlyDataChannels:this.earlyDataChannels})}},dc=class extends ps{peerConnection;dataChannelOptions;constructor(t,r){super(t,{...r,name:"muxer"}),this.peerConnection=r.peerConnection,this.protocol=r.protocol??nc,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(t){if(this.log("incoming datachannel with channel id %d, protocol %s and status %s",t.id,t.protocol,t.readyState),t.label==="init"){this.log.trace("closing init channel %d",t.id),t.close();return}let r=Wn({...this.streamOptions,...this.dataChannelOptions,channel:t,direction:"inbound",log:this.log});this.onRemoteStream(r)}async onCreateStream(t){let r=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",r.id,t?.protocol),Wn({...t,...this.dataChannelOptions,channel:r,direction:"outbound",log:this.log})}onData(){}};var pc=class extends ds{peerConnection;constructor(t){super(t),this.peerConnection=t.peerConnection;let r=t.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(t){return{sentBytes:t.byteLength,canSendMore:!0}}async sendClose(t){this.peerConnection.close(),t?.signal?.throwIfAborted()}sendReset(){this.peerConnection.close()}sendPause(){}sendResume(){}},Yn=e=>new pc(e);async function mc(e){return e=e??{},typeof e=="function"&&(e=await e()),e.iceServers=e.iceServers??Sl.map(t=>({urls:[t]})),e}var Bl=(e=32)=>Al+[...Array(e)].map(()=>rc.at(Math.floor(Math.random()*rc.length))).join("");var _s=globalThis.RTCPeerConnection,Cs=globalThis.RTCSessionDescription,Dl=globalThis.RTCIceCandidate;var Mt=class extends Event{type;detail;constructor(t,r){super(t),this.type=t,this.detail=r}};var ze=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},Vt=class extends ze{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var Ls=class extends ze{constructor(t,r){super(`Invalid fingerprint "${t}" within ${r}`),this.name="WebRTC/InvalidFingerprintError"}};var Ts=class extends ze{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Is=class extends ze{constructor(t){super(`unsupported hash algorithm code: ${t} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var Nt;(function(e){let t;(function(a){a.SDP_OFFER="SDP_OFFER",a.SDP_ANSWER="SDP_ANSWER",a.ICE_CANDIDATE="ICE_CANDIDATE"})(t=e.Type||(e.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=()=>cr(r)})(t=e.Type||(e.Type={}));let n;e.codec=()=>(n==null&&(n=Me((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),e.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 p=a.uint32();switch(p>>>3){case 1:{u.type=e.Type.codec().decode(a);break}case 2:{u.data=a.string();break}default:{a.skipType(p&7);break}}}return u},function*(a,c,f,u={}){let l=c==null?a.len:a.pos+c;for(;a.pos<l;){let p=a.uint32();switch(p>>>3){case 1:{yield{field:`${f}.type`,value:e.Type.codec().decode(a)};break}case 2:{yield{field:`${f}.data`,value:a.string()};break}default:{a.skipType(p&7);break}}}})),n);function o(a){return Fe(a,e.codec())}e.encode=o;function s(a,c){return Ue(a,e.codec(),c)}e.decode=s;function i(a,c){return ke(a,e.codec(),c)}e.stream=i})(Nt||(Nt={}));var Bs=async(e,t,r)=>{try{let n=Promise.withResolvers();for(o0(e,n);;){let o=await Promise.race([n.promise,t.read({signal:r.signal})]);if(o==null){r.signal?.throwIfAborted();break}if(o.type!==Nt.Type.ICE_CANDIDATE)throw new ho("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){r.onProgress?.(new Mt("webrtc:end-of-ice-candidates")),r.log.trace("end-of-candidates received");continue}let i=new Dl(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{r.onProgress?.(new Mt("webrtc:add-ice-candidate",i.candidate)),await e.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&&e.connectionState!=="connected")throw n}};function o0(e,t){if(e.connectionState==="connected"){t.resolve();return}e.onconnectionstatechange=r=>{switch(e.connectionState){case"connected":t.resolve();break;case"failed":case"closed":t.reject(new ao(`RTCPeerConnection connection state became "${e.connectionState}"`));break;default:break}}}function Ds(e){let t;for(let r of e.getComponents())r.name==="p2p"&&(t=kr(r.value??""));if(t==null)throw new fo("Remote peerId must be present in multiaddr");return t}async function Rl({rtcConfiguration:e,dataChannel:t,signal:r,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:f}){let{circuitAddress:u,targetPeer:l}=Pl(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing circuit address: %a",u);let p=s.getConnections(l),d;p.length===0?(f?.(new Mt("webrtc:dial-relay")),d=await i.dial(u,{signal:r,onProgress:f})):(f?.(new Mt("webrtc:reuse-relay-connection")),d=p[0]),f?.(new Mt("webrtc:open-signaling-stream"));let g=await d.newStream($n,{signal:r,runOnLimitedConnection:!0}),S=bs(g).pb(Nt),h=new _s(e);h.addEventListener("connectionstatechange",()=>{h.connectionState==="closed"&&h.close()});let y=new $e({peerConnection:h,dataChannelOptions:t});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 R=JSON.stringify(P?.toJSON()??null);a.trace("initiator sending ICE candidate %o",P),S.write({type:Nt.Type.ICE_CANDIDATE,data:R},{signal:r}).catch(I=>{a.error("error sending ICE candidate - %e",I)})},h.onicecandidateerror=P=>{a.error("initiator ICE candidate error",P)};let L=await h.createOffer().catch(P=>{throw a.error("could not execute createOffer - %e",P),new Vt("Failed to set createOffer")});a.trace("initiator send SDP offer %s",L.sdp),f?.(new Mt("webrtc:send-sdp-offer")),await S.write({type:Nt.Type.SDP_OFFER,data:L.sdp},{signal:r}),await h.setLocalDescription(L).catch(P=>{throw a.error("could not execute setLocalDescription - %e",P),new Vt("Failed to set localDescription")}),f?.(new Mt("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let O=await S.read({signal:r});if(O.type!==Nt.Type.SDP_ANSWER)throw new Vt("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",O.data);let D=new Cs({type:"answer",sdp:O.data});return await h.setRemoteDescription(D).catch(P=>{throw a.error("could not execute setRemoteDescription - %e",P),new Vt("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),f?.(new Mt("webrtc:read-ice-candidates")),await Bs(h,S,{direction:"initiator",signal:r,log:a,onProgress:f}),a.trace("initiator connected"),v.readyState!=="open"&&(a.trace("wait for init channel to open"),await At(v,"open",{signal:r})),a.trace("closing init channel"),v.close(),a.trace("waiting for init channel to close"),await At(v,"close",{signal:r}),f?.(new Mt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await g.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(),g.abort(v),v}finally{h.onicecandidate=null,h.onicecandidateerror=null}}var Ol=ot(xl.matchers[0],nt(290)),Rs=class e extends Ee{transportManager;shutdownController;events;constructor(t,r){super(),this.transportManager=t.transportManager,this.events=t.events,this.shutdownController=r.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(t){t.detail.getAddrs().filter(n=>Ol.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(t=>!(t instanceof e)).map(t=>t.getAddrs().filter(r=>Ol.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 Nl(e,t,{peerConnection:r,signal:n,log:o}){o.trace("new inbound signaling stream");let s=bs(e).pb(Nt);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 p=JSON.stringify(l?.toJSON()??null);o.trace("recipient sending ICE candidate %s",p),s.write({type:Nt.Type.ICE_CANDIDATE,data:p},{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!==Nt.Type.SDP_OFFER)throw new Vt(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let f=new Cs({type:"offer",sdp:c.data});await r.setRemoteDescription(f).catch(l=>{throw o.error("could not execute setRemoteDescription - %e",l),new Vt("Failed to set remoteDescription")});let u=await r.createAnswer().catch(l=>{throw o.error("could not execute createAnswer - %e",l),new Vt("Failed to create answer")});o.trace("recipient send SDP answer %s",u.sdp),await s.write({type:Nt.Type.SDP_ANSWER,data:u.sdp},{signal:n}),await r.setLocalDescription(u).catch(l=>{throw o.error("could not execute setLocalDescription - %e",l),new Vt("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await Bs(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",t.remoteAddr,c),r.close(),c;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",t.remoteAddr,c)}let i=Ds(t.remoteAddr),a=$r(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var Ps=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,r={}){this.components=t,this.init=r,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[yo]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Er]=["@libp2p/transport"];[Qc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle($n,(t,r)=>{let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(t,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($n),this._started=!1}createListener(t){return new Rs(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(El.exactMatch)}dialFilter(t){return this.listenFilter(t)}async dial(t,r){this.log.trace("dialing address: %a",t);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await Rl({rtcConfiguration:await mc(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:t,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=Yn({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:Ds(t),muxerFactory:s,onProgress:r.onProgress,signal:r.signal});return this._closeOnShutdown(o,i),a}async _onProtocol(t,r,n){let o=new _s(await mc(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{o.connectionState==="closed"&&o.close()});let s=new $e({peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i,remotePeer:a}=await Nl(t,r,{peerConnection:o,signal:n,log:this.log});await t.close({signal:n});let c=Yn({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(),t.abort(i),i}}_closeOnShutdown(t,r){let n=()=>{r.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection - %e",o)})};this.shutdownController.signal.addEventListener("abort",n),t.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function Pl(e){let t=e.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(t==null)throw new G("Destination peer id was missing");return{circuitAddress:$r(e.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:kr(t)}}var Yr=!!globalThis.process?.env?.DUMP_SESSION_KEYS,gc=16;function s0(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Os(e){if(typeof e!="boolean")throw new TypeError(`boolean expected, not ${e}`)}function Xr(e){if(typeof e!="number")throw new TypeError("number expected, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError("positive integer expected, got "+e)}function gt(e,t,r=""){let n=s0(e),o=e?.length,s=t!==void 0;if(!n||s&&o!==t){let i=r&&`"${r}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return e}function yc(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ul(e,t,r=!1){gt(e,void 0,"output");let n=t.outputLen;if(e.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(r&&!Zr(e))throw new Error("invalid output, must be aligned")}function se(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Zt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function i0(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var dr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,a0=e=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255;var c0=e=>{for(let t=0;t<e.length;t++)e[t]=a0(e[t]);return e},xe=dr?e=>e:c0;function Fl(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function kl(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function Ml(e,t,r){let n=t,o=r||(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(e),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}var Kl=(e,t)=>{function r(n,...o){if(gt(n,void 0,"key"),e.nonceLength!==void 0){let u=o[0];gt(u,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let s=e.tagLength;s&&o[1]!==void 0&&gt(o[1],void 0,"AAD");let i=t(n,...o),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");gt(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,gt(u),a(i.encrypt.length,l),i.encrypt(u,l)},decrypt(u,l){if(gt(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,e),r};function Xn(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if(gt(t,void 0,"output"),t.length!==e)throw new Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&!Zr(t))throw new Error("invalid output, must be aligned");return t}function Hl(e,t,r){Xr(e),Xr(t),Os(r);let n=new Uint8Array(16),o=i0(n);return o.setBigUint64(0,BigInt(t),r),o.setBigUint64(8,BigInt(e),r),n}function Zr(e){return e.byteOffset%4===0}function Qr(e){return Uint8Array.from(gt(e))}var $l=e=>Uint8Array.from(e.split(""),t=>t.charCodeAt(0)),f0=xe(se($l("expand 16-byte k"))),u0=xe(se($l("expand 32-byte k")));function W(e,t){return e<<t|e>>>32-t}var Zn=64,l0=16,bc=2**32-1,Vl=Uint32Array.of();function h0(e,t,r,n,o,s,i,a){let c=o.length,f=new Uint8Array(Zn),u=se(f),l=dr&&Zr(o)&&Zr(s),p=l?se(o):Vl,d=l?se(s):Vl;if(!dr){for(let g=0;g<c;i++){if(e(t,r,n,u,i,a),xe(u),i>=bc)throw new Error("arx: counter overflow");let S=Math.min(Zn,c-g);for(let h=0,y;h<S;h++)y=g+h,s[y]=o[y]^f[h];g+=S}return}for(let g=0;g<c;i++){if(e(t,r,n,u,i,a),i>=bc)throw new Error("arx: counter overflow");let S=Math.min(Zn,c-g);if(l&&S===Zn){let h=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let y=0,v;y<l0;y++)v=h+y,d[v]=p[v]^u[y];g+=Zn;continue}for(let h=0,y;h<S;h++)y=g+h,s[y]=o[y]^f[h];g+=S}}function zl(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Fl({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return Xr(o),Xr(i),Os(s),Os(r),(a,c,f,u,l=0)=>{gt(a,void 0,"key"),gt(c,void 0,"nonce"),gt(f,void 0,"data");let p=f.length;if(u=Xn(p,u,!1),Xr(l),l<0||l>=bc)throw new Error("arx: counter overflow");let d=[],g=a.length,S,h;if(g===32)d.push(S=Qr(a)),h=u0;else if(g===16&&r)S=new Uint8Array(32),S.set(a),S.set(a,16),h=f0,d.push(S);else throw gt(a,32,"arx key"),new Error("invalid key size");(!dr||!Zr(c))&&d.push(c=Qr(c));let y=se(S);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let O=c.subarray(0,16);if(dr)n(h,y,se(O),y);else{let D=xe(Uint32Array.from(h));n(D,y,se(O),y),Zt(D),xe(y)}c=c.subarray(16)}else dr||xe(y);let v=16-o;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let O=new Uint8Array(12);O.set(c,s?0:12-c.length),c=O,d.push(c)}let L=xe(se(c));try{return h0(e,h,y,L,f,u,l,i),u}finally{Zt(...d)}}}function vt(e,t){return e[t++]&255|(e[t++]&255)<<8}var wc=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(t){t=Qr(gt(t,32,"key"));let r=vt(t,0),n=vt(t,2),o=vt(t,4),s=vt(t,6),i=vt(t,8),a=vt(t,10),c=vt(t,12),f=vt(t,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]=vt(t,16+2*u)}process(t,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],p=i[5],d=i[6],g=i[7],S=i[8],h=i[9],y=vt(t,r+0),v=vt(t,r+2),L=vt(t,r+4),O=vt(t,r+6),D=vt(t,r+8),P=vt(t,r+10),R=vt(t,r+12),I=vt(t,r+14),N=s[0]+(y&8191),k=s[1]+((y>>>13|v<<3)&8191),U=s[2]+((v>>>10|L<<6)&8191),m=s[3]+((L>>>7|O<<9)&8191),A=s[4]+((O>>>4|D<<12)&8191),E=s[5]+(D>>>1&8191),w=s[6]+((D>>>14|P<<2)&8191),b=s[7]+((P>>>11|R<<5)&8191),_=s[8]+((R>>>8|I<<8)&8191),C=s[9]+(I>>>5|o),x=0,T=x+N*a+k*(5*h)+U*(5*S)+m*(5*g)+A*(5*d);x=T>>>13,T&=8191,T+=E*(5*p)+w*(5*l)+b*(5*u)+_*(5*f)+C*(5*c),x+=T>>>13,T&=8191;let B=x+N*c+k*a+U*(5*h)+m*(5*S)+A*(5*g);x=B>>>13,B&=8191,B+=E*(5*d)+w*(5*p)+b*(5*l)+_*(5*u)+C*(5*f),x+=B>>>13,B&=8191;let F=x+N*f+k*c+U*a+m*(5*h)+A*(5*S);x=F>>>13,F&=8191,F+=E*(5*g)+w*(5*d)+b*(5*p)+_*(5*l)+C*(5*u),x+=F>>>13,F&=8191;let H=x+N*u+k*f+U*c+m*a+A*(5*h);x=H>>>13,H&=8191,H+=E*(5*S)+w*(5*g)+b*(5*d)+_*(5*p)+C*(5*l),x+=H>>>13,H&=8191;let K=x+N*l+k*u+U*f+m*c+A*a;x=K>>>13,K&=8191,K+=E*(5*h)+w*(5*S)+b*(5*g)+_*(5*d)+C*(5*p),x+=K>>>13,K&=8191;let J=x+N*p+k*l+U*u+m*f+A*c;x=J>>>13,J&=8191,J+=E*a+w*(5*h)+b*(5*S)+_*(5*g)+C*(5*d),x+=J>>>13,J&=8191;let tt=x+N*d+k*p+U*l+m*u+A*f;x=tt>>>13,tt&=8191,tt+=E*c+w*a+b*(5*h)+_*(5*S)+C*(5*g),x+=tt>>>13,tt&=8191;let et=x+N*g+k*d+U*p+m*l+A*u;x=et>>>13,et&=8191,et+=E*f+w*c+b*a+_*(5*h)+C*(5*S),x+=et>>>13,et&=8191;let Y=x+N*S+k*g+U*d+m*p+A*l;x=Y>>>13,Y&=8191,Y+=E*u+w*f+b*c+_*a+C*(5*h),x+=Y>>>13,Y&=8191;let it=x+N*h+k*S+U*g+m*d+A*p;x=it>>>13,it&=8191,it+=E*l+w*u+b*f+_*c+C*a,x+=it>>>13,it&=8191,x=(x<<2)+x|0,x=x+T|0,T=x&8191,x=x>>>13,B+=x,s[0]=T,s[1]=B,s[2]=F,s[3]=H,s[4]=K,s[5]=J,s[6]=tt,s[7]=et,s[8]=Y,s[9]=it}finalize(){let{h:t,pad:r}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[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++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+r[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+r[a]|0)+(i>>>16)|0,t[a]=i&65535;Zt(n)}update(t){yc(this),gt(t),t=Qr(t);let{buffer:r,blockLen:n}=this,o=t.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(t,s);continue}r.set(t.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,Zt(this.h,this.r,this.buffer,this.pad)}digestInto(t){yc(this),Ul(t,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++)t[s++]=n[i]>>>0,t[s++]=n[i]>>>8}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}},ql=Ml(32,e=>new wc(e));function d0(e,t,r,n,o,s=20){let i=e[0],a=e[1],c=e[2],f=e[3],u=t[0],l=t[1],p=t[2],d=t[3],g=t[4],S=t[5],h=t[6],y=t[7],v=o,L=r[0],O=r[1],D=r[2],P=i,R=a,I=c,N=f,k=u,U=l,m=p,A=d,E=g,w=S,b=h,_=y,C=v,x=L,T=O,B=D;for(let H=0;H<s;H+=2)P=P+k|0,C=W(C^P,16),E=E+C|0,k=W(k^E,12),P=P+k|0,C=W(C^P,8),E=E+C|0,k=W(k^E,7),R=R+U|0,x=W(x^R,16),w=w+x|0,U=W(U^w,12),R=R+U|0,x=W(x^R,8),w=w+x|0,U=W(U^w,7),I=I+m|0,T=W(T^I,16),b=b+T|0,m=W(m^b,12),I=I+m|0,T=W(T^I,8),b=b+T|0,m=W(m^b,7),N=N+A|0,B=W(B^N,16),_=_+B|0,A=W(A^_,12),N=N+A|0,B=W(B^N,8),_=_+B|0,A=W(A^_,7),P=P+U|0,B=W(B^P,16),b=b+B|0,U=W(U^b,12),P=P+U|0,B=W(B^P,8),b=b+B|0,U=W(U^b,7),R=R+m|0,C=W(C^R,16),_=_+C|0,m=W(m^_,12),R=R+m|0,C=W(C^R,8),_=_+C|0,m=W(m^_,7),I=I+A|0,x=W(x^I,16),E=E+x|0,A=W(A^E,12),I=I+A|0,x=W(x^I,8),E=E+x|0,A=W(A^E,7),N=N+k|0,T=W(T^N,16),w=w+T|0,k=W(k^w,12),N=N+k|0,T=W(T^N,8),w=w+T|0,k=W(k^w,7);let F=0;n[F++]=i+P|0,n[F++]=a+R|0,n[F++]=c+I|0,n[F++]=f+N|0,n[F++]=u+k|0,n[F++]=l+U|0,n[F++]=p+m|0,n[F++]=d+A|0,n[F++]=g+E|0,n[F++]=S+w|0,n[F++]=h+b|0,n[F++]=y+_|0,n[F++]=v+C|0,n[F++]=L+x|0,n[F++]=O+T|0,n[F++]=D+B|0}var p0=zl(d0,{counterRight:!1,counterLength:4,allowShortKeys:!1});var m0=new Uint8Array(16),jl=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(m0.subarray(r))},g0=new Uint8Array(32);function Gl(e,t,r,n,o){o!==void 0&&gt(o,void 0,"AAD");let s=e(t,r,g0),i=Hl(n.length,o?o.length:0,!0),a=ql.create(s);o&&jl(a,o),jl(a,n),a.update(i);let c=a.digest();return Zt(s,i),c}var y0=e=>(t,r,n)=>({encrypt(s,i){let a=s.length;i=Xn(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);e(t,r,c,c,1);let f=Gl(e,t,r,c,n);return i.set(f,a),Zt(f),i},decrypt(s,i){i=Xn(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),f=Gl(e,t,r,a,n);if(!kl(c,f))throw Zt(f),new Error("invalid tag");return i.set(s.subarray(0,-16)),e(t,r,i,i,1),Zt(f),i}}),xc=Kl({blockSize:64,nonceLength:12,tagLength:16},y0(p0));function Yl(e,t,r){return Xe(e),r===void 0&&(r=new Uint8Array(e.outputLen)),On(e,r,t)}var Ec=Uint8Array.of(0),Wl=Uint8Array.of();function Xl(e,t,r,n=32){Xe(e),te(n,"length"),_t(t,void 0,"prk");let o=e.outputLen;if(t.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=Wl:_t(r,void 0,"info");let i=new Uint8Array(s*o),a=On.create(e,t),c=a._cloneInto(),f=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)Ec[0]=u+1,c.update(u===0?Wl:f).update(r).update(Ec).digestInto(f),i.set(f,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),qt(f,Ec),i.slice(0,n)}var Sc={hashSHA256(e){return re(e.subarray())},getHKDF(e,t){let r=Yl(re,t,e),o=Xl(re,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 e=_n.utils.randomSecretKey();return{publicKey:_n.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed(e){return{publicKey:_n.getPublicKey(e),privateKey:e}},generateX25519SharedKey(e,t){return _n.getSharedSecret(e.subarray(),t.subarray())},chaCha20Poly1305Encrypt(e,t,r,n){return xc(n,t,r).encrypt(e.subarray())},chaCha20Poly1305Decrypt(e,t,r,n,o){return xc(n,t,r).decrypt(e.subarray(),o)}};var Zl=Sc;function Ql(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}var Jr=e=>{let t=at(2);return t[0]=e>>8,t[1]=e,t};Jr.bytes=2;var tn=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};tn.bytes=2;function Jl(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Ac(e,t){!t.enabled||!Yr||(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${V(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${V(e.privateKey,"hex")}`)):t("Missing local static keys."))}function vc(e,t){!t.enabled||!Yr||(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${V(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${V(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function th(e,t){!t.enabled||!Yr||t(e?`REMOTE_STATIC_PUBLIC_KEY ${V(e.subarray(),"hex")}`:"Missing remote static public key.")}function _c(e,t){!t.enabled||!Yr||t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${V(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Cc(e,t,r){!r.enabled||!Yr||(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&V(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&V(t.k,"hex")}`))}var en=class e extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=e.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var b0=0,w0=4294967295,x0="Cipherstate has reached maximum n, a new handshake must be performed",Ns=class{n;bytes;view;constructor(t=b0){this.n=t,this.bytes=pt(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>w0)throw new Error(x0)}};var pr=pt(0),rn=class{k;n;crypto;constructor(t,r=void 0,n=0){this.crypto=t,this.k=r,this.n=new Ns(n)}hasKey(){return!!this.k}encryptWithAd(t,r){if(!this.hasKey())return r;this.n.assertValue();let n=this.crypto.encrypt(r,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,r,n){if(!this.hasKey())return r;this.n.assertValue();let o=this.crypto.decrypt(r,this.n.getBytes(),t,this.k,n);return this.n.increment(),o}},Lc=class{cs;ck;h;crypto;constructor(t,r){this.crypto=t;let n=q(r,"utf-8");this.h=E0(t,n),this.ck=this.h,this.cs=new rn(t)}mixKey(t){let[r,n]=this.crypto.hkdf(this.ck,t);this.ck=r,this.cs=new rn(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new $(this.h,t))}encryptAndHash(t){let r=this.cs.encryptWithAd(this.h,t);return this.mixHash(r),r}decryptAndHash(t){let r=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),r}split(){let[t,r]=this.crypto.hkdf(this.ck,pr);return[new rn(this.crypto,t),new rn(this.crypto,r)]}},Tc=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:r,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:f}=t;this.crypto=r,this.ss=new Lc(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 t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.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(t,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<r+32)throw new Error("message is not long enough");this.re=t.sublist(r,r+32),this.ss.mixHash(this.re)}readS(t,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(t.byteLength<r+n)throw new Error("message is not long enough");let o=t.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Qn=class extends Tc{writeMessageA(t){return new $(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let r=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new $(r,n,this.ss.encryptAndHash(t))}writeMessageC(t){let r=this.writeS();return this.writeSE(),new $(r,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(r){throw new en(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let r=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+r))}catch(r){throw new en(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(t){try{let r=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(r))}catch(r){throw new en(`handshake stage 2 validation fail: ${r.message}`)}}};function E0(e,t){if(t.length<=32){let r=pt(32);return r.set(t),r}else return e.hash(t)}var Ic=new Float32Array([-0]),qe=new Uint8Array(Ic.buffer);function eh(e,t,r){Ic[0]=e,t[r]=qe[0],t[r+1]=qe[1],t[r+2]=qe[2],t[r+3]=qe[3]}function rh(e,t){return qe[0]=e[t],qe[1]=e[t+1],qe[2]=e[t+2],qe[3]=e[t+3],Ic[0]}var Bc=new Float64Array([-0]),Bt=new Uint8Array(Bc.buffer);function nh(e,t,r){Bc[0]=e,t[r]=Bt[0],t[r+1]=Bt[1],t[r+2]=Bt[2],t[r+3]=Bt[3],t[r+4]=Bt[4],t[r+5]=Bt[5],t[r+6]=Bt[6],t[r+7]=Bt[7]}function oh(e,t){return Bt[0]=e[t],Bt[1]=e[t+1],Bt[2]=e[t+2],Bt[3]=e[t+3],Bt[4]=e[t+4],Bt[5]=e[t+5],Bt[6]=e[t+6],Bt[7]=e[t+7],Bc[0]}var S0=BigInt(Number.MAX_SAFE_INTEGER),A0=BigInt(Number.MIN_SAFE_INTEGER),Kt=class e{lo;hi;constructor(t,r){this.lo=t|0,this.hi=r|0}toNumber(t=!1){if(!t&&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(t=!1){if(t)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(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return mr;if(t<S0&&t>A0)return this.fromNumber(Number(t));let r=t<0n;r&&(t=-t);let n=t>>32n,o=t-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>sh&&(o=0n,++n>sh&&(n=0n))),new e(Number(o),Number(n))}static fromNumber(t){if(t===0)return mr;let r=t<0;r&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new e(n,o)}static from(t){return typeof t=="number"?e.fromNumber(t):typeof t=="bigint"?e.fromBigInt(t):typeof t=="string"?e.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new e(t.low>>>0,t.high>>>0):mr}},mr=new Kt(0,0);mr.toBigInt=function(){return 0n};mr.zzEncode=mr.zzDecode=function(){return this};mr.length=function(){return 1};var sh=4294967296n;function ih(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:(r&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function ah(e,t,r){if(r-t<1)return"";let o,s=[],i=0,a;for(;t<r;)a=e[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&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 Dc(e,t,r){let n=r,o,s;for(let i=0;i<e.length;++i)o=e.charCodeAt(i),o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=o&63|128):(o&64512)===55296&&((s=e.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=o&63|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=o&63|128);return r-n}function Qt(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Us(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}var Rc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Qt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Qt(this,4);return Us(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Qt(this,4);return Us(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Qt(this,4);let t=rh(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Qt(this,4);let t=oh(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw Qt(this,t);return this.pos+=t,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let t=this.bytes();return ah(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Qt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Qt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Kt(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw Qt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,t}if(this.len-this.pos>4){for(;r<5;++r)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;r<5;++r){if(this.pos>=this.len)throw Qt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Qt(this,8);let t=Us(this.buf,this.pos+=4),r=Us(this.buf,this.pos+=4);return new Kt(t,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Ln(this.buf,this.pos);return this.pos+=rt(t),t}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 Pc(e){return new Rc(e instanceof Uint8Array?e:e.subarray())}function Fs(e,t,r){let n=Pc(e);return t.decode(n,void 0,r)}function Oc(e){let t=e??8192,r=t>>>1,n,o=t;return function(i){if(i<1||i>r)return at(i);o+i>t&&(n=at(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var gr=class{fn;len;next;val;constructor(t,r,n){this.fn=t,this.len=r,this.next=void 0,this.val=n}};function Nc(){}var Fc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},v0=Oc();function _0(e){return globalThis.Buffer!=null?at(e):v0(e)}var to=class{len;head;tail;states;constructor(){this.len=0,this.head=new gr(Nc,0,0),this.tail=this.head,this.states=null}_push(t,r,n){return this.tail=this.tail.next=new gr(t,r,n),this.len+=r,this}uint32(t){return this.len+=(this.tail=this.tail.next=new kc((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(ks,10,Kt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let r=Kt.fromBigInt(t);return this._push(ks,r.length(),r)}uint64Number(t){return this._push(Oe,rt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let r=Kt.fromBigInt(t).zzEncode();return this._push(ks,r.length(),r)}sint64Number(t){let r=Kt.fromNumber(t).zzEncode();return this._push(ks,r.length(),r)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Uc,1,t?1:0)}fixed32(t){return this._push(Jn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let r=Kt.fromBigInt(t);return this._push(Jn,4,r.lo)._push(Jn,4,r.hi)}fixed64Number(t){let r=Kt.fromNumber(t);return this._push(Jn,4,r.lo)._push(Jn,4,r.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(eh,4,t)}double(t){return this._push(nh,8,t)}bytes(t){let r=t.length>>>0;return r===0?this._push(Uc,1,0):this.uint32(r)._push(L0,r,t)}string(t){let r=ih(t);return r!==0?this.uint32(r)._push(Dc,r,t):this._push(Uc,1,0)}fork(){return this.states=new Fc(this),this.head=this.tail=new gr(Nc,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 gr(Nc,0,0),this.len=0),this}ldelim(){let t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=r,this.len+=n),this}finish(){let t=this.head.next,r=_0(this.len),n=0;for(;t!=null;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}};function Uc(e,t,r){t[r]=e&255}function C0(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}var kc=class extends gr{next;constructor(t,r){super(C0,t,r),this.next=void 0}};function ks(e,t,r){for(;e.hi!==0;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}function Jn(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function L0(e,t,r){t.set(e,r)}globalThis.Buffer!=null&&(to.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(T0,t,e),this},to.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(I0,t,e),this});function T0(e,t,r){t.set(e,r)}function I0(e,t,r){e.length<40?Dc(e,t,r):t.utf8Write!=null?t.utf8Write(e,r):t.set(q(e),r)}function Mc(){return new to}function Ms(e,t){let r=Mc();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var eo;(function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(eo||(eo={}));function Kc(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function Ks(e,t){return Kc("message",eo.LENGTH_DELIMITED,e,t)}var ro=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Hs;(function(e){let t;e.codec=()=>(t==null&&(t=Ks((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 ro('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 ro('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(r.string());break}default:{r.skipType(a&7);break}}}return s})),t),e.encode=r=>Ms(r,e.codec()),e.decode=(r,n)=>Fs(r,e.codec(),n)})(Hs||(Hs={}));var no;(function(e){let t;e.codec=()=>(t==null&&(t=Ks((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),Hs.codec().encode(r.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={identityKey:pt(0),identitySig:pt(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=Hs.codec().decode(r,r.uint32(),{limits:o.limits?.extensions});break}default:{r.skipType(a&7);break}}}return s})),t),e.encode=r=>Ms(r,e.codec()),e.decode=(r,n)=>Fs(r,e.codec(),n)})(no||(no={}));async function Vc(e,t,r){let n=await e.sign(uh(t));return no.encode({identityKey:_e(e.publicKey),identitySig:n,extensions:r})}async function $c(e,t,r){try{let n=no.decode(e),o=Nn(n.identityKey);if(r?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${r}`);if(!t)throw new Error("Remote static does not exist");let s=uh(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new so(n.message)}}function uh(e){let t=q("noise-libp2p-static-key:");return e instanceof Uint8Array?Pt([t,e],t.length+e.length):(e.prepend(t),e)}var Hc=class extends Ve{stream;handshake;metrics;decoder;constructor(t,r,n){super({log:t.log,inactivityTimeout:t.inactivityTimeout,maxReadBufferLength:t.maxReadBufferLength,direction:t.direction}),this.stream=t,this.handshake=r,this.metrics=n,this.decoder=new ws({lengthDecoder:tn,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(t){let r=new $;for(let n=0;n<t.byteLength;n+=65519){let o=n+65519;o>t.byteLength&&(o=t.byteLength);let s;t instanceof Uint8Array?s=this.handshake.encrypt(t.subarray(n,o)):s=this.handshake.encrypt(t.sublist(n,o)),this.metrics?.encryptedPackets.increment(),r.append(Jr(s.byteLength)),r.append(s)}return r}decrypt(t){let r=new $;for(let n=0;n<t.byteLength;n+=65535){let o=n+65535;if(o>t.byteLength&&(o=t.byteLength),o-gc<n)throw new Error("Invalid chunk");let s;t instanceof Uint8Array?s=t.subarray(n,o):s=t.sublist(n,o);let i=t.subarray(n,o-gc);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(t){return this.stream.close(t)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(t){this.stream.abort(t)}sendData(t){return{sentBytes:t.byteLength,canSendMore:this.stream.send(this.encrypt(t))}}};function zc(e,t,r){return new Hc(e,t,r)}async function lh(e,t){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=e,u=await Vc(s,a.publicKey,f),l=new Qn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Ac(l.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(l.writeMessageA(pr),t),r.trace("Stage 0 - Initiator finished sending first message."),vc(l.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");let p=l.readMessageB(await n.read(t));r.trace("Stage 1 - Initiator received the message."),_c(l.re,r),th(l.rs,r),r.trace("Initiator going to check remote's signature...");let d=await $c(p,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),t),r.trace("Stage 2 - Initiator sent message with signed payload.");let[g,S]=l.ss.split();return Cc(g,S,r),{payload:d,encrypt:h=>g.encryptWithAd(pr,h),decrypt:(h,y)=>S.decryptWithAd(pr,h,y)}}async function hh(e,t){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=e,u=await Vc(s,a.publicKey,f),l=new Qn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Ac(l.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),l.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),_c(l.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(l.writeMessageB(u),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),vc(l.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");let p=l.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");let d=await $c(p,l.rs,c),[g,S]=l.ss.split();return Cc(g,S,r),{payload:d,encrypt:h=>S.encryptWithAd(pr,h),decrypt:(h,y)=>g.decryptWithAd(pr,h,y)}}var Vs=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(t,r={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=r,{metrics:a}=t;this.components=t,this.log=t.logger.forComponent("libp2p:noise");let c=s??Zl;this.crypto=Ql(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Jl(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??pt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Er]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,r){let n=t.log?.newScope("noise")??this.log,o=ys(t,{lengthEncoder:Jr,lengthDecoder:tn,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=Nn(s.payload.identityKey);return{connection:zc(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:La(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(t){if(t==null||t.length===0)return;let r=this.components.upgrader.getStreamMuxers();if(r!=null)for(let n of t){let o=r.get(n);if(o!=null)return o}if(t.length)throw new io("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(t,r){let n=t.log?.newScope("noise")??this.log,o=ys(t,{lengthEncoder:Jr,lengthDecoder:tn,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=Nn(s.payload.identityKey);return{connection:zc(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:La(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(t,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await lh({connection:t,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(t,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await hh({connection:t,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 dh(e={}){return t=>new Vs(t,e)}var qc=Object.values(Ye).map(e=>e.decoder).reduce((e,t)=>e.or(t)),B0=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function ph(e){return e?.match(B0)?.groups?.fingerprint}function jc(e){let r=e.getComponents().find(n=>n.code===466)?.value;if(r===void 0||r==="")throw new G(`Couldn't find a certhash component of multiaddr: ${e.toString()}`);return r}function D0(e){return $t.decode(qc.decode(e))}function R0(e){let t=D0(jc(e)),r=P0(t.code),n=t.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new Ls(n,e.toString());return`${r} ${o.join(":").toUpperCase()}`}function mh(e){let t=e.split(":").map(o=>parseInt(o,16)),r=Uint8Array.from(t),n=Rt(ce.code,r);return $r(`/certhash/${ln.encode(n.bytes)}`)}function P0(e){switch(e){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new Is(e)}}function gh(e,t){let{host:r,port:n,type:o}=oc(e);if(o!=="ip4"&&o!=="ip6")throw new G(`Multiaddr ${e} was not an IPv4 or IPv6 address`);let s=R0(e);return{type:"answer",sdp:`v=0
2
+ "use strict";var Libp2PWebrtc=(()=>{var zs=Object.defineProperty;var Sh=Object.getOwnPropertyDescriptor;var Ah=Object.getOwnPropertyNames;var vh=Object.prototype.hasOwnProperty;var Dt=(e,t)=>{for(var r in t)zs(e,r,{get:t[r],enumerable:!0})},_h=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ah(t))!vh.call(e,o)&&o!==r&&zs(e,o,{get:()=>t[o],enumerable:!(n=Sh(t,o))||n.enumerable});return e};var Ch=e=>_h(zs({},"__esModule",{value:!0}),e);var k0={};Dt(k0,{webRTC:()=>F0,webRTCDirect:()=>U0});var so=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}},io=class extends Error{static name="InvalidCryptoExchangeError";constructor(t="Invalid crypto exchange"){super(t),this.name="InvalidCryptoExchangeError"}},G=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},br=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var ao=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}},co=class extends Error{static name="MuxerClosedError";constructor(t="The muxer is closed"){super(t),this.name="MuxerClosedError"}},wr=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}};var Jt=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}},sn=class extends Error{static name="StreamBufferError";constructor(t="The stream buffer was full"){super(t),this.name="StreamBufferError"}};var fo=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},uo=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},lo=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var ho=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var Ge=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var po=class extends Event{data;constructor(t,r){super("message",r),this.data=t}},xr=class extends Event{error;local;constructor(t,r,n){super("close",n),this.error=r,this.local=t}},mo=class extends xr{constructor(t,r){super(!0,t,r)}},go=class extends xr{constructor(t,r){super(!1,t,r)}};var qs=Symbol.for("@libp2p/peer-id");var yo=Symbol.for("@libp2p/transport");var Zc;(function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(Zc||(Zc={}));function Lh(e){return typeof e?.handleEvent=="function"}function Th(e){return(e!==!0&&e!==!1&&e?.once)??!1}var Ee=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let r=this.#t.get(t);return r==null?0:r.length}addEventListener(t,r,n){let o=Th(n);super.addEventListener(t,i=>{if(o){let a=this.#t.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==r),this.#t.set(i.type,a))}Lh(r)?r.handleEvent(i):r(i)},n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:r,once:o})}removeEventListener(t,r,n){super.removeEventListener(t.toString(),r??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==r),this.#t.set(t,o))}safeDispatchEvent(t,r={}){return this.dispatchEvent(new CustomEvent(t,r))}};var Er=Symbol.for("@libp2p/service-capabilities"),Qc=Symbol.for("@libp2p/service-dependencies");var Xs={};Dt(Xs,{base58btc:()=>lt,base58flickr:()=>Nh});var gg=new Uint8Array(0);function Jc(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function ae(e){if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}function tf(e){return new TextEncoder().encode(e)}function ef(e){return new TextDecoder().decode(e)}function Ih(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<e.length;o++){var s=e.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=e.length,c=e.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function l(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var S=0,h=0,y=0,v=g.length;y!==v&&g[y]===0;)y++,S++;for(var L=(v-y)*u+1>>>0,O=new Uint8Array(L);y!==v;){for(var D=g[y],P=0,R=L-1;(D!==0||P<h)&&R!==-1;R--,P++)D+=256*O[R]>>>0,O[R]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");h=P,y++}for(var I=L-h;I!==L&&O[I]===0;)I++;for(var N=c.repeat(S);I<L;++I)N+=e.charAt(O[I]);return N}function p(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var S=0;if(g[S]!==" "){for(var h=0,y=0;g[S]===c;)h++,S++;for(var v=(g.length-S)*f+1>>>0,L=new Uint8Array(v);g[S];){var O=r[g.charCodeAt(S)];if(O===255)return;for(var D=0,P=v-1;(O!==0||D<y)&&P!==-1;P--,D++)O+=a*L[P]>>>0,L[P]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");y=D,S++}if(g[S]!==" "){for(var R=v-y;R!==v&&L[R]===0;)R++;for(var I=new Uint8Array(h+(v-R)),N=h;R!==v;)I[N++]=L[R++];return I}}}function d(g){var S=p(g);if(S)return S;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:p,decode:d}}var Bh=Ih,Dh=Bh,nf=Dh;var js=class{name;prefix;baseEncode;constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Gs=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,r,n){this.name=t,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(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return of(this,t)}},Ws=class{decoders;constructor(t){this.decoders=t}or(t){return of(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function of(e,t){return new Ws({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var Ys=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new js(t,r,n),this.decoder=new Gs(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Sr({name:e,prefix:t,encode:r,decode:n}){return new Ys(e,t,r,n)}function Se({name:e,prefix:t,alphabet:r}){let{encode:n,decode:o}=nf(r,e);return Sr({prefix:t,name:e,encode:n,decode:s=>ae(o(s))})}function Rh(e,t,r,n){let o=e.length;for(;e[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=t[e[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 Ph(e,t,r){let n=t[t.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],i+=8;i>r;)i-=r,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function Oh(e){let t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}function ut({name:e,prefix:t,bitsPerChar:r,alphabet:n}){let o=Oh(n);return Sr({prefix:t,name:e,encode(s){return Ph(s,n,r)},decode(s){return Rh(s,o,r,e)}})}var lt=Se({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Nh=Se({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Zs={};Dt(Zs,{base32:()=>Ae,base32hex:()=>Mh,base32hexpad:()=>Hh,base32hexpadupper:()=>Vh,base32hexupper:()=>Kh,base32pad:()=>Fh,base32padupper:()=>kh,base32upper:()=>Uh,base32z:()=>$h});var Ae=ut({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Uh=ut({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Fh=ut({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),kh=ut({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Mh=ut({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kh=ut({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Hh=ut({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Vh=ut({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),$h=ut({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Qs={};Dt(Qs,{base36:()=>an,base36upper:()=>zh});var an=Se({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),zh=Se({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var $t={};Dt($t,{Digest:()=>We,create:()=>Rt,decode:()=>_r,equals:()=>ti,hasCode:()=>fd});var qh=cf,sf=128,jh=127,Gh=~jh,Wh=Math.pow(2,31);function cf(e,t,r){t=t||[],r=r||0;for(var n=r;e>=Wh;)t[r++]=e&255|sf,e/=128;for(;e&Gh;)t[r++]=e&255|sf,e>>>=7;return t[r]=e|0,cf.bytes=r-n+1,t}var Yh=Js,Xh=128,af=127;function Js(e,n){var r=0,n=n||0,o=0,s=n,i,a=e.length;do{if(s>=a)throw Js.bytes=0,new RangeError("Could not decode varint");i=e[s++],r+=o<28?(i&af)<<o:(i&af)*Math.pow(2,o),o+=7}while(i>=Xh);return Js.bytes=s-n,r}var Zh=Math.pow(2,7),Qh=Math.pow(2,14),Jh=Math.pow(2,21),td=Math.pow(2,28),ed=Math.pow(2,35),rd=Math.pow(2,42),nd=Math.pow(2,49),od=Math.pow(2,56),sd=Math.pow(2,63),id=function(e){return e<Zh?1:e<Qh?2:e<Jh?3:e<td?4:e<ed?5:e<rd?6:e<nd?7:e<od?8:e<sd?9:10},ad={encode:qh,decode:Yh,encodingLength:id},cd=ad,cn=cd;function fn(e,t=0){return[cn.decode(e,t),cn.decode.bytes]}function Ar(e,t,r=0){return cn.encode(e,t,r),t}function vr(e){return cn.encodingLength(e)}function Rt(e,t){let r=t.byteLength,n=vr(e),o=n+vr(r),s=new Uint8Array(o+r);return Ar(e,s,0),Ar(r,s,n),s.set(t,o),new We(e,r,t,s)}function _r(e){let t=ae(e),[r,n]=fn(t),[o,s]=fn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new We(r,o,i,t)}function ti(e,t){if(e===t)return!0;{let r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&Jc(e.bytes,r.bytes)}}var We=class{code;size;digest;bytes;constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}};function fd(e,t){return e.code===t}function ff(e,t){let{bytes:r,version:n}=e;return n===0?ld(r,ei(e),t??lt.encoder):hd(r,ei(e),t??Ae.encoder)}var uf=new WeakMap;function ei(e){let t=uf.get(e);if(t==null){let r=new Map;return uf.set(e,r),r}return t}var dt=class e{code;version;multihash;bytes;"/";constructor(t,r,n,o){this.code=r,this.version=t,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:t,multihash:r}=this;if(t!==un)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==dd)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.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:t,digest:r}=this.multihash,n=Rt(t,r);return e.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(t){return e.equals(this,t)}static equals(t,r){let n=r;return n!=null&&t.code===n.code&&t.version===n.version&&ti(t.multihash,n.multihash)}toString(t){return ff(this,t)}toJSON(){return{"/":ff(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let r=t;if(r instanceof e)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new e(n,o,s,i??lf(n,o,s.bytes))}else if(r[pd]===!0){let{version:n,multihash:o,code:s}=r,i=_r(o);return e.create(n,s,i)}else return null}static create(t,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(t){case 0:{if(r!==un)throw new Error(`Version 0 CID must use dag-pb (code: ${un}) block encoding`);return new e(t,r,n,n.bytes)}case 1:{let o=lf(t,r,n.bytes);return new e(t,r,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,un,t)}static createV1(t,r){return e.create(1,t,r)}static decode(t){let[r,n]=e.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=e.inspectBytes(t),n=r.size-r.multihashSize,o=ae(t.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 We(r.multihashCode,r.digestSize,s,o);return[r.version===0?e.createV0(i):e.createV1(r.codec,i),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[l,p]=fn(t.subarray(r));return r+=p,l},o=n(),s=un;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(t,r){let[n,o]=ud(t,r),s=e.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ei(s).set(n,t),s}};function ud(e,t){switch(e[0]){case"Q":{let r=t??lt;return[lt.prefix,r.decode(`${lt.prefix}${e}`)]}case lt.prefix:{let r=t??lt;return[lt.prefix,r.decode(e)]}case Ae.prefix:{let r=t??Ae;return[Ae.prefix,r.decode(e)]}case an.prefix:{let r=t??an;return[an.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function ld(e,t,r){let{prefix:n}=r;if(n!==lt.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=t.get(n);if(o==null){let s=r.encode(e).slice(1);return t.set(n,s),s}else return o}function hd(e,t,r){let{prefix:n}=r,o=t.get(n);if(o==null){let s=r.encode(e);return t.set(n,s),s}else return o}var un=112,dd=18;function lf(e,t,r){let n=vr(e),o=n+vr(t),s=new Uint8Array(o+r.byteLength);return Ar(e,s,0),Ar(t,s,n),s.set(r,o),s}var pd=Symbol.for("@ipld/js-cid/CID");var ri={};Dt(ri,{identity:()=>zt});var hf=0,md="identity",df=ae;function gd(e,t){if(t?.truncate!=null&&t.truncate!==e.byteLength){if(t.truncate<0||t.truncate>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,t.truncate)}return Rt(hf,df(e))}var zt={code:hf,name:md,encode:df,digest:gd};function wt(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}async function pf(e,t,r,n){let o=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,r.subarray());return n?.signal?.throwIfAborted(),s}function pt(e=0){return new Uint8Array(e)}function at(e=0){return new Uint8Array(e)}function Pt(e,t){t==null&&(t=e.reduce((o,s)=>o+s.length,0));let r=at(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}var gf=Symbol.for("@achingbrain/uint8arraylist");function mf(e,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let r=0;for(let n of e){let o=r+n.byteLength;if(t<o)return{buf:n,index:t-r};r=o}throw new RangeError("index is out of bounds")}function wo(e){return!!e?.[gf]}var $=class e{bufs;length;[gf]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let r=0;for(let n of t)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(wo(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(...t){this.prependAll(t)}prependAll(t){let r=0;for(let n of t.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(wo(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(t){let r=mf(this.bufs,t);return r.buf[r.index]}set(t,r){let n=mf(this.bufs,t);n.buf[n.index]=r}write(t,r=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(r+n,t[n]);else if(wo(t))for(let n=0;n<t.length;n++)this.set(r+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,r){let{bufs:n,length:o}=this._subList(t,r);return Pt(n,o)}subarray(t,r){let{bufs:n,length:o}=this._subList(t,r);return n.length===1?n[0]:Pt(n,o)}sublist(t,r){let{bufs:n,length:o}=this._subList(t,r),s=new e;return s.length=o,s.bufs=n,s}_subList(t,r){if(t=t??0,r=r??this.length,t<0&&(t=this.length+t),r<0&&(r=this.length+r),t<0||r>this.length)throw new RangeError("index is out of bounds");if(t===r)return{bufs:[],length:0};if(t===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,t>=c)continue;let f=t>=a&&t<c,u=r>a&&r<=c;if(f&&u){if(t===a&&r===c){n.push(i);break}let l=t-a;n.push(i.subarray(l,l+(r-t)));break}if(f){if(t===0){n.push(i);continue}n.push(i.subarray(t-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-t}}indexOf(t,r=0){if(!wo(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),t.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 p=f;p>=0;p--){let d=this.get(l+p);if(n[p]!==d){u=Math.max(1,p-a[d]);break}}if(u===0)return l}return-1}getInt8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(t,r){let n=at(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,t)}getInt16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(t,r,n){let o=pt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,t)}getInt32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(t,r,n){let o=pt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,t)}getBigInt64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(t,r,n){let o=pt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,t)}getUint8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(t,r){let n=at(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,t)}getUint16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(t,r,n){let o=pt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,t)}getUint32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(t,r,n){let o=pt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,t)}getBigUint64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(t,r,n){let o=pt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,t)}getFloat32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(t,r,n){let o=pt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,t)}getFloat64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(t,r,n){let o=pt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof e)||t.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!wt(this.bufs[r],t.bufs[r]))return!1;return!0}static fromUint8Arrays(t,r){let n=new e;return n.bufs=t,r==null&&(r=t.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}};var ni={};Dt(ni,{base10:()=>bd});var bd=Se({prefix:"9",name:"base10",alphabet:"0123456789"});var oi={};Dt(oi,{base16:()=>wd,base16upper:()=>xd});var wd=ut({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),xd=ut({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var si={};Dt(si,{base2:()=>Ed});var Ed=ut({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ii={};Dt(ii,{base256emoji:()=>Cd});var yf=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}"),Sd=yf.reduce((e,t,r)=>(e[r]=t,e),[]),Ad=yf.reduce((e,t,r)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return e[n]=r,e},[]);function vd(e){return e.reduce((t,r)=>(t+=Sd[r],t),"")}function _d(e){let t=[];for(let r of e){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=Ad[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);t.push(o)}return new Uint8Array(t)}var Cd=Sr({prefix:"\u{1F680}",name:"base256emoji",encode:vd,decode:_d});var ai={};Dt(ai,{base64:()=>Ld,base64pad:()=>Td,base64url:()=>ln,base64urlpad:()=>Id});var Ld=ut({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Td=ut({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ln=ut({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Id=ut({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ci={};Dt(ci,{base8:()=>Bd});var Bd=ut({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var fi={};Dt(fi,{identity:()=>Dd});var Dd=Sr({prefix:"\0",name:"identity",encode:e=>ef(e),decode:e=>tf(e)});var Jg=new TextEncoder,ty=new TextDecoder;var hi={};Dt(hi,{sha256:()=>ce,sha512:()=>Nd});var Od=20;function li({name:e,code:t,encode:r,minDigestLength:n,maxDigestLength:o}){return new ui(e,t,r,n,o)}var ui=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,r,n,o,s){this.name=t,this.code=r,this.encode=n,this.minDigestLength=o??Od,this.maxDigestLength=s}digest(t,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(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?bf(n,this.code,r?.truncate):n.then(o=>bf(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function bf(e,t,r){if(r!=null&&r!==e.byteLength){if(r>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,r)}return Rt(t,e)}function xf(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}var ce=li({name:"sha2-256",code:18,encode:xf("SHA-256")}),Nd=li({name:"sha2-512",code:19,encode:xf("SHA-512")});var Ye={...fi,...si,...ci,...ni,...oi,...Zs,...Qs,...Xs,...ai,...ii},hy={...hi,...ri};function Sf(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var Ef=Sf("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),di=Sf("ascii","a",e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},e=>{e=e.substring(1);let t=at(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}),Ud={utf8:Ef,"utf-8":Ef,hex:Ye.base16,latin1:di,ascii:di,binary:di,...Ye},xo=Ud;function q(e,t="utf8"){let r=xo[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}function V(e,t="utf8"){let r=xo[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}var Fd=parseInt("11111",2),pi=parseInt("10000000",2),kd=parseInt("01111111",2),Af={0:hn,1:hn,2:Md,3:Vd,4:$d,5:Hd,6:Kd,16:hn,22:hn,48:hn};function fe(e,t={offset:0}){let r=e[t.offset]&Fd;if(t.offset++,Af[r]!=null)return Af[r](e,t);throw new Error("No decoder for tag "+r)}function dn(e,t){let r=0;if((e[t.offset]&pi)===pi){let n=e[t.offset]&kd,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(o,16)}else r=e[t.offset],t.offset++;return r}function hn(e,t){dn(e,t);let r=[];for(;!(t.offset>=e.byteLength);){let n=fe(e,t);if(n===null)break;r.push(n)}return r}function Md(e,t){let r=dn(e,t),n=t.offset,o=t.offset+r,s=[];for(let i=n;i<o;i++)i===n&&e[i]===0||s.push(e[i]);return t.offset+=r,Uint8Array.from(s)}function Kd(e,t){let r=dn(e,t),n=t.offset+r,o=e[t.offset];t.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(;t.offset<n;){let f=e[t.offset];if(t.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 Hd(e,t){return t.offset++,null}function Vd(e,t){let r=dn(e,t),n=e[t.offset];t.offset++;let o=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function $d(e,t){let r=dn(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n}function zd(e){let t=e.toString(16);t.length%2===1&&(t="0"+t);let r=new $;for(let n=0;n<t.length;n+=2)r.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return r}function mi(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);let t=zd(e.byteLength);return new $(Uint8Array.from([t.byteLength|pi]),t)}function Ot(e){let t=new $,r=128;return(e.subarray()[0]&r)===r&&t.append(Uint8Array.from([0])),t.append(e),new $(Uint8Array.from([2]),mi(t),t)}function Eo(e){let t=Uint8Array.from([0]),r=new $(t,e);return new $(Uint8Array.from([3]),mi(r),r)}function ve(e,t=48){let r=new $;for(let n of e)r.append(n);return new $(Uint8Array.from([t]),mi(r),r)}var qd=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),jd=Uint8Array.from([6,5,43,129,4,0,34]),Gd=Uint8Array.from([6,5,43,129,4,0,35]),Wd={ext:!0,kty:"EC",crv:"P-256"},Yd={ext:!0,kty:"EC",crv:"P-384"},Xd={ext:!0,kty:"EC",crv:"P-521"},gi=32,yi=48,bi=66;function wi(e){let t=fe(e);return vf(t)}function vf(e){let t=e[1][1][0],r=1,n,o;if(t.byteLength===gi*2+1)return n=V(t.subarray(r,r+gi),"base64url"),o=V(t.subarray(r+gi),"base64url"),new Cr({...Wd,key_ops:["verify"],x:n,y:o});if(t.byteLength===yi*2+1)return n=V(t.subarray(r,r+yi),"base64url"),o=V(t.subarray(r+yi),"base64url"),new Cr({...Yd,key_ops:["verify"],x:n,y:o});if(t.byteLength===bi*2+1)return n=V(t.subarray(r,r+bi),"base64url"),o=V(t.subarray(r+bi),"base64url"),new Cr({...Xd,key_ops:["verify"],x:n,y:o});throw new G(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function _f(e){return ve([Ot(Uint8Array.from([1])),ve([Zd(e.crv)],160),ve([Eo(new $(Uint8Array.from([4]),q(e.x??"","base64url"),q(e.y??"","base64url")))],161)]).subarray()}function Zd(e){if(e==="P-256")return qd;if(e==="P-384")return jd;if(e==="P-521")return Gd;throw new G(`Invalid curve ${e}`)}var Cr=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=_f(this.jwk)),this._raw}toMultihash(){return zt.digest(_e(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return lt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}async verify(t,r,n){return pf(this.jwk,r,t,n)}};function xi(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function te(e,t=""){if(typeof e!="number"){let r=t&&`"${t}" `;throw new TypeError(`${r}expected number, got ${typeof e}`)}if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw new RangeError(`${r}expected integer >= 0, got ${e}`)}}function _t(e,t,r=""){let n=xi(e),o=e?.length,s=t!==void 0;if(!n||s&&o!==t){let i=r&&`"${r}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return e}function Xe(e){if(typeof e!="function"||typeof e.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(te(e.outputLen),te(e.blockLen),e.outputLen<1)throw new Error('"outputLen" must be >= 1');if(e.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Lr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function So(e,t){_t(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function qt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ao(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function jt(e,t){return e<<32-t|e>>>t}var Lf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qd=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function vo(e){if(_t(e),Lf)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Qd[e[r]];return t}var ue={_0:48,_9:57,A:65,F:70,a:97,f:102};function Cf(e){if(e>=ue._0&&e<=ue._9)return e-ue._0;if(e>=ue.A&&e<=ue.F)return e-(ue.A-10);if(e>=ue.a&&e<=ue.f)return e-(ue.a-10)}function pn(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(Lf)try{return Uint8Array.fromHex(e)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let t=e.length,r=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=Cf(e.charCodeAt(s)),a=Cf(e.charCodeAt(s+1));if(i===void 0||a===void 0){let c=e[s]+e[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ei(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];_t(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let s=e[n];r.set(s,o),o+=s.length}return r}function Si(e,t={}){let r=(o,s)=>e(s).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>e(o),Object.assign(r,t),Object.freeze(r)}function Tf(e=32){te(e,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var Ai=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function If(e,t,r){return e&t^~e&r}function Bf(e,t,r){return e&t^e&r^t&r}var mn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,r,n,o){this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Ao(this.buffer)}update(t){Lr(this),_t(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Ao(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Lr(this),So(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,qt(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=Ao(t),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:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},le=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var _o=BigInt(4294967295),Df=BigInt(32);function Jd(e,t=!1){return t?{h:Number(e&_o),l:Number(e>>Df&_o)}:{h:Number(e>>Df&_o)|0,l:Number(e&_o)|0}}function Rf(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=Jd(e[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var vi=(e,t,r)=>e>>>r,_i=(e,t,r)=>e<<32-r|t>>>r,Ze=(e,t,r)=>e>>>r|t<<32-r,Qe=(e,t,r)=>e<<32-r|t>>>r,gn=(e,t,r)=>e<<64-r|t>>>r-32,yn=(e,t,r)=>e>>>r-32|t<<64-r;function ee(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var Pf=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Of=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,Nf=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Uf=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,Ff=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),kf=(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0;var ep=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]),Ce=new Uint32Array(64),Ci=class extends mn{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,r,n,o,s,i,a,c]}set(t,r,n,o,s,i,a,c){this.A=t|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(t,r){for(let l=0;l<16;l++,r+=4)Ce[l]=t.getUint32(r,!1);for(let l=16;l<64;l++){let p=Ce[l-15],d=Ce[l-2],g=jt(p,7)^jt(p,18)^p>>>3,S=jt(d,17)^jt(d,19)^d>>>10;Ce[l]=S+Ce[l-7]+g+Ce[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 p=jt(a,6)^jt(a,11)^jt(a,25),d=u+p+If(a,c,f)+ep[l]+Ce[l]|0,S=(jt(n,2)^jt(n,13)^jt(n,22))+Bf(n,o,s)|0;u=f,f=c,c=a,a=i+d|0,i=s,s=o,o=n,n=d+S|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(){qt(Ce)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),qt(this.buffer)}},Li=class extends Ci{A=le[0]|0;B=le[1]|0;C=le[2]|0;D=le[3]|0;E=le[4]|0;F=le[5]|0;G=le[6]|0;H=le[7]|0;constructor(){super(32)}};var Mf=Rf(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),rp=Mf[0],np=Mf[1],Le=new Uint32Array(80),Te=new Uint32Array(80),Ti=class extends mn{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:u,Fh:l,Fl:p,Gh:d,Gl:g,Hh:S,Hl:h}=this;return[t,r,n,o,s,i,a,c,f,u,l,p,d,g,S,h]}set(t,r,n,o,s,i,a,c,f,u,l,p,d,g,S,h){this.Ah=t|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=p|0,this.Gh=d|0,this.Gl=g|0,this.Hh=S|0,this.Hl=h|0}process(t,r){for(let L=0;L<16;L++,r+=4)Le[L]=t.getUint32(r),Te[L]=t.getUint32(r+=4);for(let L=16;L<80;L++){let O=Le[L-15]|0,D=Te[L-15]|0,P=Ze(O,D,1)^Ze(O,D,8)^vi(O,D,7),R=Qe(O,D,1)^Qe(O,D,8)^_i(O,D,7),I=Le[L-2]|0,N=Te[L-2]|0,k=Ze(I,N,19)^gn(I,N,61)^vi(I,N,6),U=Qe(I,N,19)^yn(I,N,61)^_i(I,N,6),m=Nf(R,U,Te[L-7],Te[L-16]),A=Uf(m,P,k,Le[L-7],Le[L-16]);Le[L]=A|0,Te[L]=m|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:l,El:p,Fh:d,Fl:g,Gh:S,Gl:h,Hh:y,Hl:v}=this;for(let L=0;L<80;L++){let O=Ze(l,p,14)^Ze(l,p,18)^gn(l,p,41),D=Qe(l,p,14)^Qe(l,p,18)^yn(l,p,41),P=l&d^~l&S,R=p&g^~p&h,I=Ff(v,D,R,np[L],Te[L]),N=kf(I,y,O,P,rp[L],Le[L]),k=I|0,U=Ze(n,o,28)^gn(n,o,34)^gn(n,o,39),m=Qe(n,o,28)^yn(n,o,34)^yn(n,o,39),A=n&s^n&a^s&a,E=o&i^o&c^i&c;y=S|0,v=h|0,S=d|0,h=g|0,d=l|0,g=p|0,{h:l,l:p}=ee(f|0,u|0,N|0,k|0),f=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let w=Pf(k,m,E);n=Of(w,N,U,A),o=w|0}({h:n,l:o}=ee(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ee(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ee(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=ee(this.Dh|0,this.Dl|0,f|0,u|0),{h:l,l:p}=ee(this.Eh|0,this.El|0,l|0,p|0),{h:d,l:g}=ee(this.Fh|0,this.Fl|0,d|0,g|0),{h:S,l:h}=ee(this.Gh|0,this.Gl|0,S|0,h|0),{h:y,l:v}=ee(this.Hh|0,this.Hl|0,y|0,v|0),this.set(n,o,s,i,a,c,f,u,l,p,d,g,S,h,y,v)}roundClean(){qt(Le,Te)}destroy(){this.destroyed=!0,qt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ii=class extends Ti{Ah=xt[0]|0;Al=xt[1]|0;Bh=xt[2]|0;Bl=xt[3]|0;Ch=xt[4]|0;Cl=xt[5]|0;Dh=xt[6]|0;Dl=xt[7]|0;Eh=xt[8]|0;El=xt[9]|0;Fh=xt[10]|0;Fl=xt[11]|0;Gh=xt[12]|0;Gl=xt[13]|0;Hh=xt[14]|0;Hl=xt[15]|0;constructor(){super(64)}};var re=Si(()=>new Li,Ai(1));var Co=Si(()=>new Ii,Ai(3));var z=(e,t,r)=>_t(e,t,r),Di=te,Tr=vo,mt=(...e)=>Ei(...e),Ir=e=>pn(e),Je=xi,tr=e=>Tf(e),To=BigInt(0),Bi=BigInt(1);function Gt(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}" `;throw new TypeError(r+"expected boolean, got type="+typeof e)}return e}function Io(e){if(typeof e=="bigint"){if(!Lo(e))throw new RangeError("positive bigint expected, got "+e)}else Di(e);return e}function Wt(e,t=""){if(typeof e!="number"){let r=t&&`"${t}" `;throw new TypeError(r+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let r=t&&`"${t}" `;throw new RangeError(r+"expected safe integer, got "+e)}}function bn(e){let t=Io(e).toString(16);return t.length&1?"0"+t:t}function Kf(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?To:BigInt("0x"+e)}function er(e){return Kf(vo(e))}function Ut(e){return Kf(vo(Ie(_t(e)).reverse()))}function Bo(e,t){if(te(t),t===0)throw new RangeError("zero length");e=Io(e);let r=e.toString(16);if(r.length>t*2)throw new RangeError("number too large");return pn(r.padStart(t*2,"0"))}function wn(e,t){return Bo(e,t).reverse()}function Hf(e,t){if(e=z(e),t=z(t),e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function Ie(e){return Uint8Array.from(z(e))}function Do(e){if(typeof e!="string")throw new TypeError("ascii string expected, got "+typeof e);return Uint8Array.from(e,(t,r)=>{let n=t.charCodeAt(0);if(t.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${e[r]}" with code ${n} at position ${r}`);return n})}var Lo=e=>typeof e=="bigint"&&To<=e;function op(e,t,r){return Lo(e)&&Lo(t)&&Lo(r)&&t<=e&&e<r}function he(e,t,r,n){if(!op(t,r,n))throw new RangeError("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Br(e){if(e<To)throw new Error("expected non-negative bigint, got "+e);let t;for(t=0;e>To;e>>=Bi,t+=1);return t}var xn=e=>(Bi<<BigInt(e))-Bi;function Vf(e,t,r){if(te(e,"hashLen"),te(t,"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(e),f=n(e),u=0,l=()=>{c.fill(1),f.fill(0),u=0},p=(...h)=>r(f,mt(c,...h)),d=(h=o)=>{f=p(s,h),c=p(),h.length!==0&&(f=p(i,h),c=p())},g=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let h=0,y=[];for(;h<t;){c=p();let v=c.slice();y.push(v),h+=c.length}return mt(...y)};return(h,y)=>{l(),d(h);let v;for(;(v=y(g()))===void 0;)d();return l(),v}}function Ft(e,t={},r={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(e,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=e[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(t,!1),o(r,!0)}var Ri=()=>{throw new Error("not implemented")};var Et=BigInt(0),ht=BigInt(1),rr=BigInt(2),jf=BigInt(3),Gf=BigInt(4),Wf=BigInt(5),sp=BigInt(7),Yf=BigInt(8),ip=BigInt(9),Xf=BigInt(16);function ct(e,t){if(t<=Et)throw new Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=Et?r:t+r}function st(e,t,r){if(t<Et)throw new Error("pow2: expected non-negative exponent, got "+t);let n=e;for(;t-- >Et;)n*=n,n%=r;return n}function $f(e,t){if(e===Et)throw new Error("invert: expected non-zero number");if(t<=Et)throw new Error("invert: expected positive modulus, got "+t);let r=ct(e,t),n=t,o=Et,s=ht,i=ht,a=Et;for(;r!==Et;){let f=n/r,u=n-r*f,l=o-i*f,p=s-a*f;n=r,r=u,o=i,s=a,i=l,a=p}if(n!==ht)throw new Error("invert: does not exist");return ct(o,t)}function Pi(e,t,r){let n=e;if(!n.eql(n.sqr(t),r))throw new Error("Cannot find square root")}function Zf(e,t){let r=e,n=(r.ORDER+ht)/Gf,o=r.pow(t,n);return Pi(r,o,t),o}function ap(e,t){let r=e,n=(r.ORDER-Wf)/Yf,o=r.mul(t,rr),s=r.pow(o,n),i=r.mul(t,s),a=r.mul(r.mul(i,rr),s),c=r.mul(i,r.sub(a,r.ONE));return Pi(r,c,t),c}function cp(e){let t=Dr(e),r=Qf(e),n=r(t,t.neg(t.ONE)),o=r(t,n),s=r(t,t.neg(n)),i=(e+sp)/Xf;return((a,c)=>{let f=a,u=f.pow(c,i),l=f.mul(u,n),p=f.mul(u,o),d=f.mul(u,s),g=f.eql(f.sqr(l),c),S=f.eql(f.sqr(p),c);u=f.cmov(u,l,g),l=f.cmov(d,p,S);let h=f.eql(f.sqr(l),c),y=f.cmov(u,l,h);return Pi(f,y,c),y})}function Qf(e){if(e<jf)throw new Error("sqrt is not defined for small field");let t=e-ht,r=0;for(;t%rr===Et;)t/=rr,r++;let n=rr,o=Dr(e);for(;zf(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Zf;let s=o.pow(n,t),i=(t+ht)/rr;return function(c,f){let u=c;if(u.is0(f))return f;if(zf(u,f)!==1)throw new Error("Cannot find square root");let l=r,p=u.mul(u.ONE,s),d=u.pow(f,t),g=u.pow(f,i);for(;!u.eql(d,u.ONE);){if(u.is0(d))return u.ZERO;let S=1,h=u.sqr(d);for(;!u.eql(h,u.ONE);)if(S++,h=u.sqr(h),S===l)throw new Error("Cannot find square root");let y=ht<<BigInt(l-S-1),v=u.pow(p,y);l=S,p=u.sqr(v),d=u.mul(d,p),g=u.mul(g,v)}return g}}function fp(e){return e%Gf===jf?Zf:e%Yf===Wf?ap:e%Xf===ip?cp(e):Qf(e)}var de=(e,t)=>(ct(e,t)&ht)===ht,up=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Oi(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=up.reduce((n,o)=>(n[o]="function",n),t);if(Ft(e,r),Wt(e.BYTES,"BYTES"),Wt(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=ht)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function lp(e,t,r){let n=e;if(r<Et)throw new Error("invalid exponent, negatives unsupported");if(r===Et)return n.ONE;if(r===ht)return t;let o=n.ONE,s=t;for(;r>Et;)r&ht&&(o=n.mul(o,s)),s=n.sqr(s),r>>=ht;return o}function En(e,t,r=!1){let n=e,o=new Array(t.length).fill(r?n.ZERO:void 0),s=t.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return t.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),i),o}function zf(e,t){let r=e,n=(r.ORDER-ht)/rr,o=r.pow(t,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 hp(e,t){if(t!==void 0&&Di(t),e<=Et)throw new Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);let r=Br(e);if(t!==void 0&&t<r)throw new Error(`invalid n length: expected bit length (${r}) >= n.length (${t})`);let n=t!==void 0?t:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var qf=new WeakMap,Ro=class{ORDER;BITS;BYTES;isLE;ZERO=Et;ONE=ht;_lengths;_mod;constructor(t,r={}){if(t<=ht)throw new Error("invalid field: expected ORDER > 1, got "+t);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}=hp(t,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(t){return ct(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return Et<=t&&t<this.ORDER}is0(t){return t===Et}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&ht)===ht}neg(t){return ct(-t,this.ORDER)}eql(t,r){return t===r}sqr(t){return ct(t*t,this.ORDER)}add(t,r){return ct(t+r,this.ORDER)}sub(t,r){return ct(t-r,this.ORDER)}mul(t,r){return ct(t*r,this.ORDER)}pow(t,r){return lp(this,t,r)}div(t,r){return ct(t*$f(r,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,r){return t+r}subN(t,r){return t-r}mulN(t,r){return t*r}inv(t){return $f(t,this.ORDER)}sqrt(t){let r=qf.get(this);return r||qf.set(this,r=fp(this.ORDER)),r(this,t)}toBytes(t){return this.isLE?wn(t,this.BYTES):Bo(t,this.BYTES)}fromBytes(t,r=!1){z(t);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(t.length<1||!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let f=new Uint8Array(o);f.set(t,s?0:f.length-t.length),t=f}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?Ut(t):er(t);if(a&&(c=ct(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return En(this,t)}cmov(t,r,n){return Gt(n,"condition"),n?r:t}};Object.freeze(Ro.prototype);function Dr(e,t={}){return new Ro(e,t)}function Jf(e){if(typeof e!="bigint")throw new Error("field order must be bigint");if(e<=ht)throw new Error("field order must be greater than 1");let t=Br(e-ht);return Math.ceil(t/8)}function Ni(e){let t=Jf(e);return t+Math.ceil(t/2)}function Ui(e,t,r=!1){z(e);let n=e.length,o=Jf(t),s=Math.max(Ni(t),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?Ut(e):er(e),a=ct(i,t-ht)+ht;return r?wn(a,o):Bo(a,o)}var Rr=BigInt(0),nr=BigInt(1);function Sn(e,t){let r=t.negate();return e?r:t}function or(e,t){let r=En(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function nu(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Fi(e,t){nu(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=xn(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function tu(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=nr);let f=t*n,u=f+Math.abs(a)-1,l=a===0,p=a<0,d=t%2!==0;return{nextN:c,offset:u,isZero:l,isNeg:p,isNegF:d,offsetF:f}}var ki=new WeakMap,ou=new WeakMap;function Mi(e){return ou.get(e)||1}function eu(e){if(e!==Rr)throw new Error("invalid wNAF")}var Pr=class{BASE;ZERO;Fn;bits;constructor(t,r){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=r}_unsafeLadder(t,r,n=this.ZERO){let o=t;for(;r>Rr;)r&nr&&(n=n.add(o)),o=o.double(),r>>=nr;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=Fi(r,this.bits),s=[],i=t,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(t,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Fi(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:u,isNeg:l,isNegF:p,offsetF:d}=tu(n,a,i);n=c,u?s=s.add(Sn(p,r[d])):o=o.add(Sn(l,r[f]))}return eu(n),{p:o,f:s}}wNAFUnsafe(t,r,n,o=this.ZERO){let s=Fi(t,this.bits);for(let i=0;i<s.windows&&n!==Rr;i++){let{nextN:a,offset:c,isZero:f,isNeg:u}=tu(n,i,s);if(n=a,!f){let l=r[c];o=o.add(u?l.negate():l)}}return eu(n),o}getPrecomputes(t,r,n){let o=ki.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&(typeof n=="function"&&(o=n(o)),ki.set(r,o))),o}cached(t,r,n){let o=Mi(t);return this.wNAF(o,this.getPrecomputes(o,t,n),r)}unsafe(t,r,n,o){let s=Mi(t);return s===1?this._unsafeLadder(t,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),r,o)}createCache(t,r){nu(r,this.bits),ou.set(t,r),ki.delete(t)}hasCache(t){return Mi(t)!==1}};function su(e,t,r,n){let o=t,s=e.ZERO,i=e.ZERO;for(;r>Rr||n>Rr;)r&nr&&(s=s.add(o)),n&nr&&(i=i.add(o)),o=o.double(),r>>=nr,n>>=nr;return{p1:s,p2:i}}function ru(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Oi(t),t}else return Dr(e,{isLE:r})}function Po(e,t,r={},n){if(n===void 0&&(n=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let f=t[c];if(!(typeof f=="bigint"&&f>Rr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=ru(t.p,r.Fp,n),s=ru(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function Or(e,t){return function(n){let o=e(n);return{secretKey:o,publicKey:t(o)}}}var Be=BigInt(0),yt=BigInt(1),Ki=BigInt(2),dp=BigInt(8);function pp(e,t,r,n){let o=e.sqr(r),s=e.sqr(n),i=e.add(e.mul(t.a,o),s),a=e.add(e.ONE,e.mul(t.d,e.mul(o,s)));return e.eql(i,a)}function iu(e,t={}){let r=t,n=Po("edwards",e,r,r.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;Ft(r,{},{uvRatio:"function"});let c=Ki<<BigInt(s.BYTES*8)-yt,f=S=>o.create(S),u=r.uvRatio===void 0?(S,h)=>{try{return{isValid:!0,value:o.sqrt(o.div(S,h))}}catch{return{isValid:!1,value:Be}}}:r.uvRatio;if(!pp(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function l(S,h,y=!1){let v=y?yt:Be;return he("coordinate "+S,h,v,c),h}function p(S){if(!(S instanceof d))throw new Error("EdwardsPoint expected")}class d{static BASE=new d(i.Gx,i.Gy,yt,f(i.Gx*i.Gy));static ZERO=new d(Be,yt,yt,Be);static Fp=o;static Fn=s;X;Y;Z;T;constructor(h,y,v,L){this.X=l("x",h),this.Y=l("y",y),this.Z=l("z",v,!0),this.T=l("t",L),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,yt,f(y*v))}static fromBytes(h,y=!1){let v=o.BYTES,{a:L,d:O}=i;h=Ie(z(h,v,"point")),Gt(y,"zip215");let D=Ie(h),P=h[v-1];D[v-1]=P&-129;let R=Ut(D),I=y?c:o.ORDER;he("point.y",R,Be,I);let N=f(R*R),k=f(N-yt),U=f(O*N-L),{isValid:m,value:A}=u(k,U);if(!m)throw new Error("bad point: invalid y coordinate");let E=(A&yt)===yt,w=(P&128)!==0;if(!y&&A===Be&&w)throw new Error("bad point: x=0 and x_0=1");return w!==E&&(A=f(-A)),d.fromAffine({x:A,y:R})}static fromHex(h,y=!1){return d.fromBytes(Ir(h),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,y=!0){return g.createCache(this,h),y||this.multiply(Ki),this}assertValidity(){let h=this,{a:y,d:v}=i;if(h.is0())throw new Error("bad point: ZERO");let{X:L,Y:O,Z:D,T:P}=h,R=f(L*L),I=f(O*O),N=f(D*D),k=f(N*N),U=f(R*y),m=f(N*f(U+I)),A=f(k+f(v*f(R*I)));if(m!==A)throw new Error("bad point: equation left != right (1)");let E=f(L*O),w=f(D*P);if(E!==w)throw new Error("bad point: equation left != right (2)")}equals(h){p(h);let{X:y,Y:v,Z:L}=this,{X:O,Y:D,Z:P}=h,R=f(y*P),I=f(O*L),N=f(v*P),k=f(D*L);return R===I&&N===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:L}=this,O=f(y*y),D=f(v*v),P=f(Ki*f(L*L)),R=f(h*O),I=y+v,N=f(f(I*I)-O-D),k=R+D,U=k-P,m=R-D,A=f(N*U),E=f(k*m),w=f(N*m),b=f(U*k);return new d(A,E,b,w)}add(h){p(h);let{a:y,d:v}=i,{X:L,Y:O,Z:D,T:P}=this,{X:R,Y:I,Z:N,T:k}=h,U=f(L*R),m=f(O*I),A=f(P*v*k),E=f(D*N),w=f((L+O)*(R+I)-U-m),b=E-A,_=E+A,C=f(m-y*U),x=f(w*b),T=f(_*C),B=f(w*C),F=f(b*_);return new d(x,T,F,B)}subtract(h){return p(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}=g.cached(this,h,L=>or(d,L));return or(d,[y,v])[0]}multiplyUnsafe(h){if(!s.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===Be?d.ZERO:this.is0()||h===yt?this:g.unsafe(this,h,y=>or(d,y))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return g.unsafe(this,i.n).is0()}toAffine(h){let y=this,v=h,{X:L,Y:O,Z:D}=y,P=y.is0();v==null&&(v=P?dp:o.inv(D));let R=f(L*v),I=f(O*v),N=o.mul(D,v);if(P)return{x:Be,y:yt};if(N!==yt)throw new Error("invZ was invalid");return{x:R,y:I}}clearCofactor(){return a===yt?this:this.multiplyUnsafe(a)}toBytes(){let{x:h,y}=this.toAffine(),v=o.toBytes(y);return v[v.length-1]|=h&yt?128:0,v}toHex(){return Tr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new Pr(d,s.BITS);return s.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var Oo=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){this.ep=t}static fromBytes(t){Ri()}static fromHex(t){Ri()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return Tr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,r){return this.ep.precompute(t,r),this}};function au(e,t,r={}){if(typeof t!="function")throw new Error('"hash" function param is required');let n=t,o=r;Ft(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=e,f=n.outputLen,u=2*a.BYTES;if(f!==void 0&&(Wt(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let l=o.randomBytes===void 0?tr:o.randomBytes,p=o.adjustScalarBytes===void 0?m=>m:o.adjustScalarBytes,d=o.domain===void 0?(m,A,E)=>{if(Gt(E,"phflag"),A.length||E)throw new Error("Contexts/pre-hash are not supported");return m}:o.domain;function g(m){return c.create(Ut(m))}function S(m){let A=R.secretKey;z(m,R.secretKey,"secretKey");let E=z(n(m),2*A,"hashedSecretKey"),w=p(E.slice(0,A)),b=E.slice(A,2*A),_=g(w);return{head:w,prefix:b,scalar:_}}function h(m){let{head:A,prefix:E,scalar:w}=S(m),b=i.multiply(w),_=b.toBytes();return{head:A,prefix:E,scalar:w,point:b,pointBytes:_}}function y(m){return h(m).pointBytes}function v(m=Uint8Array.of(),...A){let E=mt(...A);return g(n(d(E,z(m,void 0,"context"),!!s)))}function L(m,A,E={}){m=z(m,void 0,"message"),s&&(m=s(m));let{prefix:w,scalar:b,pointBytes:_}=h(A),C=v(E.context,w,m),x=i.multiply(C).toBytes(),T=v(E.context,x,_,m),B=c.create(C+T*b);if(!c.isValid(B))throw new Error("sign failed: invalid s");let F=mt(x,c.toBytes(B));return z(F,R.signature,"result")}let O={zip215:o.zip215};function D(m,A,E,w=O){let{context:b}=w,_=w.zip215===void 0?!!O.zip215:w.zip215,C=R.signature;m=z(m,C,"signature"),A=z(A,void 0,"message"),E=z(E,R.publicKey,"publicKey"),_!==void 0&&Gt(_,"zip215"),s&&(A=s(A));let x=C/2,T=m.subarray(0,x),B=Ut(m.subarray(x,C)),F,H,K;try{F=e.fromBytes(E,_),H=e.fromBytes(T,_),K=i.multiplyUnsafe(B)}catch{return!1}if(!_&&F.isSmallOrder())return!1;let J=v(b,T,E,A);return H.add(F.multiplyUnsafe(J)).subtract(K).clearCofactor().is0()}let P=a.BYTES,R={secretKey:P,publicKey:P,signature:2*P,seed:P};function I(m){return m=m===void 0?l(R.seed):m,z(m,R.seed,"seed")}function N(m){return Je(m)&&m.length===R.secretKey}function k(m,A){try{return!!e.fromBytes(m,A===void 0?O.zip215:A)}catch{return!1}}let U={getExtendedPublicKey:h,randomSecretKey:I,isValidSecretKey:N,isValidPublicKey:k,toMontgomery(m){let{y:A}=e.fromBytes(m),E=R.publicKey,w=E===32;if(!w&&E!==57)throw new Error("only defined for 25519 and 448");let b=w?a.div(yt+A,yt-A):a.div(A-yt,A+yt);return a.toBytes(b)},toMontgomerySecret(m){let A=R.secretKey;z(m,A);let E=n(m.subarray(0,A));return p(E).subarray(0,A)}};return Object.freeze(R),Object.freeze(U),Object.freeze({keygen:Or(I,y),getPublicKey:y,sign:L,verify:D,utils:U,Point:e,lengths:R})}function An(e,t){if(Wt(e),Wt(t),t<0||t>4)throw new Error("invalid I2OSP length: "+t);if(e<0||e>2**(8*t)-1)throw new Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)r[n]=e&255,e>>>=8;return new Uint8Array(r)}function mp(e,t){let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n]^t[n];return r}function gp(e){if(!Je(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or ascii string");let t=typeof e=="string"?Do(e):e;if(t.length===0)throw new Error("DST must be non-empty");return t}function Hi(e,t,r,n){z(e),Wt(r),t=gp(t),t.length>255&&(t=n(mt(Do("H2C-OVERSIZE-DST-"),t)));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=mt(t,An(t.length,1)),c=new Uint8Array(s),f=An(r,2),u=new Array(i),l=n(mt(c,e,f,An(0,1),a));u[0]=n(mt(l,An(1,1),a));for(let d=1;d<i;d++){let g=[mp(l,u[d-1]),An(d+1,1),a];u[d]=n(mt(...g))}return mt(...u).slice(0,r)}var cu="HashToScalar-";var vn=BigInt(0),Nr=BigInt(1),No=BigInt(2);function yp(e){return Ft(e,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...e})}function fu(e){let t=yp(e),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=t,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i===void 0?tr:i,f=a?255:448,u=a?32:56,l=BigInt(a?9:5),p=BigInt(a?121665:39081),d=a?No**BigInt(254):No**BigInt(447),g=a?BigInt(8)*No**BigInt(251)-Nr:BigInt(4)*No**BigInt(445)-Nr,S=d+g+Nr,h=E=>ct(E,r),y=v(l);function v(E){return wn(h(E),u)}function L(E){let w=Ie(z(E,u,"uCoordinate"));return a&&(w[31]&=127),h(Ut(w))}function O(E){return Ut(o(Ie(z(E,u,"scalar"))))}function D(E,w){let b=k(L(w),O(E));if(b===vn)throw new Error("invalid private or public key received");return v(b)}function P(E){return D(E,y)}let R=P,I=D;function N(E,w,b){let _=h(E*(w-b));return w=h(w-_),b=h(b+_),{x_2:w,x_3:b}}function k(E,w){he("u",E,vn,r),he("scalar",w,d,S);let b=w,_=E,C=Nr,x=vn,T=E,B=Nr,F=vn;for(let K=BigInt(f-1);K>=vn;K--){let J=b>>K&Nr;F^=J,{x_2:C,x_3:T}=N(F,C,T),{x_2:x,x_3:B}=N(F,x,B),F=J;let tt=C+x,et=h(tt*tt),Y=C-x,it=h(Y*Y),ie=et-it,je=T+B,yr=T-B,nn=h(yr*tt),on=h(je*Y),Yc=nn+on,Xc=nn-on;T=h(Yc*Yc),B=h(_*h(Xc*Xc)),C=h(et*it),x=h(ie*(et+h(p*ie)))}({x_2:C,x_3:T}=N(F,C,T)),{x_2:x,x_3:B}=N(F,x,B);let H=s(x);return h(C*H)}let U={secretKey:u,publicKey:u,seed:u},m=E=>(E=E===void 0?c(u):E,z(E,U.seed,"seed"),E),A={randomSecretKey:m};return Object.freeze(U),Object.freeze(A),Object.freeze({keygen:Or(m,R),getSharedSecret:I,getPublicKey:R,scalarMult:D,scalarMultBase:P,utils:A,GuBytes:y.slice(),lengths:U})}var bp=BigInt(0),pe=BigInt(1),uu=BigInt(2),wp=BigInt(3),xp=BigInt(5),Ep=BigInt(8),sr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),qi={p:sr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ep,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function du(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=sr,a=e*e%s*e%s,c=st(a,uu,s)*a%s,f=st(c,pe,s)*e%s,u=st(f,xp,s)*f%s,l=st(u,t,s)*u%s,p=st(l,r,s)*l%s,d=st(p,n,s)*p%s,g=st(d,o,s)*d%s,S=st(g,o,s)*d%s,h=st(S,t,s)*u%s;return{pow_p_5_8:st(h,uu,s)*e%s,b2:a}}function pu(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var Vi=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ji(e,t){let r=sr,n=ct(t*t*t,r),o=ct(n*n*t,r),s=du(e*o).pow_p_5_8,i=ct(e*n*s,r),a=ct(t*i*i,r),c=i,f=ct(i*Vi,r),u=a===e,l=a===ct(-e,r),p=a===ct(-e*Vi,r);return u&&(i=c),(l||p)&&(i=f),de(i,r)&&(i=ct(-i,r)),{isValid:u||l,value:i}}var Re=iu(qi,{uvRatio:ji}),De=Re.Fp,mu=Re.Fn;function Sp(e){return au(Re,Co,Object.assign({adjustScalarBytes:pu,zip215:!0},e))}var gu=Sp({});var _n=(()=>{let e=sr;return fu({P:e,type:"x25519",powPminus2:t=>{let{pow_p_5_8:r,b2:n}=du(t);return ct(st(r,wp,e)*n,e)},adjustScalarBytes:pu})})();var $i=Vi,Ap=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),vp=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),_p=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Cp=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),lu=e=>ji(pe,e),Lp=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),zi=e=>De.create(Ut(e)&Lp);function hu(e){let{d:t}=qi,r=sr,n=y=>De.create(y),o=n($i*e*e),s=n((o+pe)*_p),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:f}=ji(s,a),u=n(f*e);de(u,r)||(u=n(-u)),c||(f=u),c||(i=o);let l=n(i*(o-pe)*Cp-a),p=f*f,d=n((f+f)*a),g=n(l*Ap),S=n(pe-p),h=n(pe+p);return new Re(n(d*h),n(S*g),n(g*h),n(d*S))}var Pe=class e extends Oo{static BASE=new e(Re.BASE);static ZERO=new e(Re.ZERO);static Fp=De;static Fn=mu;constructor(t){super(t)}static fromAffine(t){return new e(Re.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoPoint expected")}init(t){return new e(t)}static fromBytes(t){_t(t,32);let{a:r,d:n}=qi,o=sr,s=O=>De.create(O),i=zi(t);if(!Hf(De.toBytes(i),t)||de(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(pe+r*a),f=s(pe-r*a),u=s(c*c),l=s(f*f),p=s(r*n*u-l),{isValid:d,value:g}=lu(s(p*l)),S=s(g*f),h=s(g*S*p),y=s((i+i)*S);de(y,o)&&(y=s(-y));let v=s(c*h),L=s(y*v);if(!d||de(L,o)||v===bp)throw new Error("invalid ristretto255 encoding 2");return new e(new Re(y,v,pe,L))}static fromHex(t){return e.fromBytes(pn(t))}toBytes(){let{X:t,Y:r,Z:n,T:o}=this.ep,s=sr,i=h=>De.create(h),a=i(i(n+r)*i(n-r)),c=i(t*r),f=i(c*c),{value:u}=lu(i(a*f)),l=i(u*a),p=i(u*c),d=i(l*p*o),g;if(de(o*d,s)){let h=i(r*$i),y=i(t*$i);t=h,r=y,g=i(l*vp)}else g=p;de(t*d,s)&&(r=i(-r));let S=i((n-r)*g);return de(S,s)&&(S=i(-S)),De.toBytes(S)}equals(t){this.assertSame(t);let{X:r,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=f=>De.create(f),a=i(r*s)===i(n*o),c=i(n*s)===i(r*o);return a||c}is0(){return this.equals(e.ZERO)}};Object.freeze(Pe.BASE);Object.freeze(Pe.ZERO);Object.freeze(Pe.prototype);Object.freeze(Pe);var Tp=Object.freeze({Point:Pe,hashToCurve(e,t){let r=t?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":t.DST,n=Hi(e,r,64,Co);return Tp.deriveToCurve(n)},hashToScalar(e,t={DST:cu}){let r=Hi(e,t.DST,64,Co);return mu.create(Ut(r))},deriveToCurve(e){_t(e,64);let t=zi(e.subarray(0,32)),r=hu(t),n=zi(e.subarray(32,64)),o=hu(n);return new Pe(r.add(o))}});var Cn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Uo=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var yu={get(e=globalThis){let t=e.crypto;if(t?.subtle==null)throw new Uo("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Ht=yu;var Fo=32;var Gi,Ip=(async()=>{try{return await Ht.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Bp(e,t,r){if(e.buffer instanceof ArrayBuffer){let n=await Ht.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Ht.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Dp(e,t,r){return gu.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}async function bu(e,t,r){return Gi==null&&(Gi=await Ip),Gi?Bp(e,t,r):Dp(e,t,r)}function ko(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var Mo=class{type="Ed25519";raw;constructor(t){this.raw=Wi(t,Fo)}toMultihash(){return zt.digest(_e(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return lt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}verify(t,r,n){n?.signal?.throwIfAborted();let o=bu(this.raw,r,t);return ko(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Yi(e){return e=Wi(e,Fo),new Mo(e)}function Wi(e,t){if(e=Uint8Array.from(e??[]),e.length!==t)throw new G(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var Pp=Math.pow(2,7),Op=Math.pow(2,14),Np=Math.pow(2,21),Xi=Math.pow(2,28),Zi=Math.pow(2,35),Qi=Math.pow(2,42),Ji=Math.pow(2,49),Z=128,Ct=127;function rt(e){if(e<Pp)return 1;if(e<Op)return 2;if(e<Np)return 3;if(e<Xi)return 4;if(e<Zi)return 5;if(e<Qi)return 6;if(e<Ji)return 7;if(Number.MAX_SAFE_INTEGER!=null&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Oe(e,t,r=0){switch(rt(e)){case 8:t[r++]=e&255|Z,e/=128;case 7:t[r++]=e&255|Z,e/=128;case 6:t[r++]=e&255|Z,e/=128;case 5:t[r++]=e&255|Z,e/=128;case 4:t[r++]=e&255|Z,e>>>=7;case 3:t[r++]=e&255|Z,e>>>=7;case 2:t[r++]=e&255|Z,e>>>=7;case 1:{t[r++]=e&255,e>>>=7;break}default:throw new Error("unreachable")}return t}function Up(e,t,r=0){switch(rt(e)){case 8:t.set(r++,e&255|Z),e/=128;case 7:t.set(r++,e&255|Z),e/=128;case 6:t.set(r++,e&255|Z),e/=128;case 5:t.set(r++,e&255|Z),e/=128;case 4:t.set(r++,e&255|Z),e>>>=7;case 3:t.set(r++,e&255|Z),e>>>=7;case 2:t.set(r++,e&255|Z),e>>>=7;case 1:{t.set(r++,e&255),e>>>=7;break}default:throw new Error("unreachable")}return t}function Ln(e,t){let r=e[t],n=0;if(n+=r&Ct,r<Z||(r=e[t+1],n+=(r&Ct)<<7,r<Z)||(r=e[t+2],n+=(r&Ct)<<14,r<Z)||(r=e[t+3],n+=(r&Ct)<<21,r<Z)||(r=e[t+4],n+=(r&Ct)*Xi,r<Z)||(r=e[t+5],n+=(r&Ct)*Zi,r<Z)||(r=e[t+6],n+=(r&Ct)*Qi,r<Z)||(r=e[t+7],n+=(r&Ct)*Ji,r<Z))return n;throw new RangeError("Could not decode varint")}function Fp(e,t){let r=e.get(t),n=0;if(n+=r&Ct,r<Z||(r=e.get(t+1),n+=(r&Ct)<<7,r<Z)||(r=e.get(t+2),n+=(r&Ct)<<14,r<Z)||(r=e.get(t+3),n+=(r&Ct)<<21,r<Z)||(r=e.get(t+4),n+=(r&Ct)*Xi,r<Z)||(r=e.get(t+5),n+=(r&Ct)*Zi,r<Z)||(r=e.get(t+6),n+=(r&Ct)*Qi,r<Z)||(r=e.get(t+7),n+=(r&Ct)*Ji,r<Z))return n;throw new RangeError("Could not decode varint")}function Ko(e,t,r=0){return t==null&&(t=at(rt(e))),t instanceof Uint8Array?Oe(e,t,r):Up(e,t,r)}function me(e,t=0){return e instanceof Uint8Array?Ln(e,t):Fp(e,t)}var ta=new Float32Array([-0]),Ne=new Uint8Array(ta.buffer);function xu(e,t,r){ta[0]=e,t[r]=Ne[0],t[r+1]=Ne[1],t[r+2]=Ne[2],t[r+3]=Ne[3]}function Eu(e,t){return Ne[0]=e[t],Ne[1]=e[t+1],Ne[2]=e[t+2],Ne[3]=e[t+3],ta[0]}var ea=new Float64Array([-0]),Lt=new Uint8Array(ea.buffer);function Su(e,t,r){ea[0]=e,t[r]=Lt[0],t[r+1]=Lt[1],t[r+2]=Lt[2],t[r+3]=Lt[3],t[r+4]=Lt[4],t[r+5]=Lt[5],t[r+6]=Lt[6],t[r+7]=Lt[7]}function Au(e,t){return Lt[0]=e[t],Lt[1]=e[t+1],Lt[2]=e[t+2],Lt[3]=e[t+3],Lt[4]=e[t+4],Lt[5]=e[t+5],Lt[6]=e[t+6],Lt[7]=e[t+7],ea[0]}var kp=BigInt(Number.MAX_SAFE_INTEGER),Mp=BigInt(Number.MIN_SAFE_INTEGER),kt=class e{lo;hi;constructor(t,r){this.lo=t|0,this.hi=r|0}toNumber(t=!1){if(!t&&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(t=!1){if(t)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(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return ir;if(t<kp&&t>Mp)return this.fromNumber(Number(t));let r=t<0n;r&&(t=-t);let n=t>>32n,o=t-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>vu&&(o=0n,++n>vu&&(n=0n))),new e(Number(o),Number(n))}static fromNumber(t){if(t===0)return ir;let r=t<0;r&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new e(n,o)}static from(t){return typeof t=="number"?e.fromNumber(t):typeof t=="bigint"?e.fromBigInt(t):typeof t=="string"?e.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new e(t.low>>>0,t.high>>>0):ir}},ir=new kt(0,0);ir.toBigInt=function(){return 0n};ir.zzEncode=ir.zzDecode=function(){return this};ir.length=function(){return 1};var vu=4294967296n;function _u(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:(r&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Cu(e,t,r){if(r-t<1)return"";let o,s=[],i=0,a;for(;t<r;)a=e[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&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 ra(e,t,r){let n=r,o,s;for(let i=0;i<e.length;++i)o=e.charCodeAt(i),o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=o&63|128):(o&64512)===55296&&((s=e.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=o&63|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=o&63|128);return r-n}function Yt(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Ho(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}var na=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Yt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Yt(this,4);return Ho(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Yt(this,4);return Ho(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Yt(this,4);let t=Eu(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Yt(this,4);let t=Au(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw Yt(this,t);return this.pos+=t,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let t=this.bytes();return Cu(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Yt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Yt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new kt(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw Yt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,t}if(this.len-this.pos>4){for(;r<5;++r)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;r<5;++r){if(this.pos>=this.len)throw Yt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Yt(this,8);let t=Ho(this.buf,this.pos+=4),r=Ho(this.buf,this.pos+=4);return new kt(t,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Ln(this.buf,this.pos);return this.pos+=rt(t),t}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 In(e){return new na(e instanceof Uint8Array?e:e.subarray())}function Ue(e,t,r){let n=In(e);return t.decode(n,void 0,r)}function oa(e){let t=e??8192,r=t>>>1,n,o=t;return function(i){if(i<1||i>r)return at(i);o+i>t&&(n=at(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var ar=class{fn;len;next;val;constructor(t,r,n){this.fn=t,this.len=r,this.next=void 0,this.val=n}};function sa(){}var aa=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Kp=oa();function Hp(e){return globalThis.Buffer!=null?at(e):Kp(e)}var Dn=class{len;head;tail;states;constructor(){this.len=0,this.head=new ar(sa,0,0),this.tail=this.head,this.states=null}_push(t,r,n){return this.tail=this.tail.next=new ar(t,r,n),this.len+=r,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ca((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Vo,10,kt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let r=kt.fromBigInt(t);return this._push(Vo,r.length(),r)}uint64Number(t){return this._push(Oe,rt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let r=kt.fromBigInt(t).zzEncode();return this._push(Vo,r.length(),r)}sint64Number(t){let r=kt.fromNumber(t).zzEncode();return this._push(Vo,r.length(),r)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ia,1,t?1:0)}fixed32(t){return this._push(Bn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let r=kt.fromBigInt(t);return this._push(Bn,4,r.lo)._push(Bn,4,r.hi)}fixed64Number(t){let r=kt.fromNumber(t);return this._push(Bn,4,r.lo)._push(Bn,4,r.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(xu,4,t)}double(t){return this._push(Su,8,t)}bytes(t){let r=t.length>>>0;return r===0?this._push(ia,1,0):this.uint32(r)._push($p,r,t)}string(t){let r=_u(t);return r!==0?this.uint32(r)._push(ra,r,t):this._push(ia,1,0)}fork(){return this.states=new aa(this),this.head=this.tail=new ar(sa,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 ar(sa,0,0),this.len=0),this}ldelim(){let t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=r,this.len+=n),this}finish(){let t=this.head.next,r=Hp(this.len),n=0;for(;t!=null;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}};function ia(e,t,r){t[r]=e&255}function Vp(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}var ca=class extends ar{next;constructor(t,r){super(Vp,t,r),this.next=void 0}};function Vo(e,t,r){for(;e.hi!==0;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}function Bn(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function $p(e,t,r){t.set(e,r)}globalThis.Buffer!=null&&(Dn.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(zp,t,e),this},Dn.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(qp,t,e),this});function zp(e,t,r){t.set(e,r)}function qp(e,t,r){e.length<40?ra(e,t,r):t.utf8Write!=null?t.utf8Write(e,r):t.set(q(e),r)}function fa(){return new Dn}function Fe(e,t){let r=fa();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}function*ke(e,t,r){let n=In(e);yield*t.stream(n,void 0,"$",r)}var $o={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function zo(e,t,r,n,o){return{name:e,type:t,encode:r,decode:n,stream:o}}function cr(e){function t(s){if(e[s.toString()]==null)throw new Error("Invalid enum value");return e[s]}let r=function(i,a){let c=t(i);a.int32(c)},n=function(i){let a=i.int32();return t(a)},o=function*(i){let a=i.int32();yield t(a)};return zo("enum",$o.VARINT,r,n,o)}function Me(e,t,r){return zo("message",$o.LENGTH_DELIMITED,e,t,r)}var ft;(function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(ft||(ft={}));var ua;(function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(ua||(ua={}));(function(e){e.codec=()=>cr(ua)})(ft||(ft={}));var ne;(function(e){let t;e.codec=()=>(t==null&&(t=Me((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ft.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=ft.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:ft.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),t);function r(s){return Fe(s,e.codec())}e.encode=r;function n(s,i){return Ue(s,e.codec(),i)}e.decode=n;function o(s,i){return ke(s,e.codec(),i)}e.stream=o})(ne||(ne={}));var la;(function(e){let t;e.codec=()=>(t==null&&(t=Me((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ft.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=ft.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:ft.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),t);function r(s){return Fe(s,e.codec())}e.encode=r;function n(s,i){return Ue(s,e.codec(),i)}e.decode=n;function o(s,i){return ke(s,e.codec(),i)}e.stream=o})(la||(la={}));var Pn={};Dt(Pn,{MAX_RSA_KEY_SIZE:()=>ha,generateRSAKeyPair:()=>Ru,jwkToJWKKeyPair:()=>Pu,jwkToPkcs1:()=>Yp,jwkToPkix:()=>ga,jwkToRSAPrivateKey:()=>xa,pkcs1MessageToJwk:()=>pa,pkcs1MessageToRSAPrivateKey:()=>ya,pkcs1ToJwk:()=>Wp,pkcs1ToRSAPrivateKey:()=>Du,pkixMessageToJwk:()=>ma,pkixMessageToRSAPublicKey:()=>wa,pkixToJwk:()=>Xp,pkixToRSAPublicKey:()=>ba});var Ur=class{type="RSA";jwk;_raw;_multihash;constructor(t,r){this.jwk=t,this._multihash=r}get raw(){return this._raw==null&&(this._raw=Pn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return dt.createV1(114,this._multihash)}toString(){return lt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}verify(t,r,n){return Bu(this.jwk,r,t,n)}},Rn=class{type="RSA";jwk;_raw;publicKey;constructor(t,r){this.jwk=t,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=Pn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}sign(t,r){return Iu(this.jwk,t,r)}};var ha=8192,da=18,jp=1062,Gp=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Wp(e){let t=fe(e);return pa(t)}function pa(e){return{n:V(e[1],"base64url"),e:V(e[2],"base64url"),d:V(e[3],"base64url"),p:V(e[4],"base64url"),q:V(e[5],"base64url"),dp:V(e[6],"base64url"),dq:V(e[7],"base64url"),qi:V(e[8],"base64url"),kty:"RSA"}}function Yp(e){if(e.n==null||e.e==null||e.d==null||e.p==null||e.q==null||e.dp==null||e.dq==null||e.qi==null)throw new G("JWK was missing components");return ve([Ot(Uint8Array.from([0])),Ot(q(e.n,"base64url")),Ot(q(e.e,"base64url")),Ot(q(e.d,"base64url")),Ot(q(e.p,"base64url")),Ot(q(e.q,"base64url")),Ot(q(e.dp,"base64url")),Ot(q(e.dq,"base64url")),Ot(q(e.qi,"base64url"))]).subarray()}function Xp(e){let t=fe(e,{offset:0});return ma(t)}function ma(e){let t=fe(e[1],{offset:0});return{kty:"RSA",n:V(t[0],"base64url"),e:V(t[1],"base64url")}}function ga(e){if(e.n==null||e.e==null)throw new G("JWK was missing components");return ve([Gp,Eo(ve([Ot(q(e.n,"base64url")),Ot(q(e.e,"base64url"))]))]).subarray()}function Du(e){let t=fe(e);return ya(t)}function ya(e){let t=pa(e);return xa(t)}function ba(e,t){if(e.byteLength>=jp)throw new br("Key size is too large");let r=fe(e,{offset:0});return wa(r,e,t)}function wa(e,t,r){let n=ma(e);if(r==null){let o=re(ne.encode({Type:ft.RSA,Data:t}));r=Rt(da,o)}return new Ur(n,r)}function xa(e){if(Nu(e)>ha)throw new G("Key size is too large");let t=Pu(e),r=re(ne.encode({Type:ft.RSA,Data:ga(t.publicKey)})),n=Rt(da,r);return new Rn(t.privateKey,new Ur(t.publicKey,n))}async function Ru(e){if(e>ha)throw new G("Key size is too large");let t=await Ou(e),r=re(ne.encode({Type:ft.RSA,Data:ga(t.publicKey)})),n=Rt(da,r);return new Rn(t.privateKey,new Ur(t.publicKey,n))}function Pu(e){if(e==null)throw new G("Missing key parameter");return{privateKey:e,publicKey:{kty:e.kty,n:e.n,e:e.e}}}async function Ou(e,t){let r=await Ht.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);t?.signal?.throwIfAborted();let n=await Zp(r,t);return{privateKey:n[0],publicKey:n[1]}}async function Iu(e,t,r){let n=await Ht.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let o=await Ht.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,t instanceof Uint8Array?t:t.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Bu(e,t,r,n){let o=await Ht.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ht.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),s}async function Zp(e,t){if(e.privateKey==null||e.publicKey==null)throw new G("Private and public key are required");let r=await Promise.all([Ht.get().subtle.exportKey("jwk",e.privateKey),Ht.get().subtle.exportKey("jwk",e.publicKey)]);return t?.signal?.throwIfAborted(),r}function Nu(e){if(e.kty!=="RSA")throw new G("invalid key type");if(e.n==null)throw new G("invalid key modulus");return q(e.n,"base64url").length*8}var qo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,r){if(Xe(t),_t(r,void 0,"key"),this.iHash=t.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?t.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),qt(o)}update(t){return Lr(this),this.iHash.update(t),this}digestInto(t){Lr(this),So(t,this),this.finished=!0;let r=t.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},On=(()=>{let e=((t,r,n)=>new qo(t,r).update(n).digest());return e.create=(t,r)=>new qo(t,r),e})();var Uu=(e,t)=>(e+(e>=0?t:-t)/Fu)/t;function Qp(e,t,r){he("scalar",e,oe,r);let[[n,o],[s,i]]=t,a=Uu(i*e,r),c=Uu(-o*e,r),f=e-a*n-c*s,u=-a*o-c*i,l=f<oe,p=u<oe;l&&(f=-f),p&&(u=-u);let d=xn(Math.ceil(Br(r)/2))+Ke;if(f<oe||f>=d||u<oe||u>=d)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:l,k1:f,k2neg:p,k2:u}}function Sa(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Ea(e,t){Ft(e);let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];return Gt(r.lowS,"lowS"),Gt(r.prehash,"prehash"),r.format!==void 0&&Sa(r.format),r}var Aa=class extends Error{constructor(t=""){super(t)}},Xt={Err:Aa,_tlv:{encode:(e,t)=>{let{Err:r}=Xt;if(Wt(e,"tag"),e<0||e>255)throw new r("tlv.encode: wrong tag");if(typeof t!="string")throw new TypeError('"data" expected string, got type='+typeof t);if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=bn(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?bn(o.length/2|128):"";return bn(e)+s+o+t},decode(e,t){let{Err:r}=Xt;t=z(t,void 0,"DER data");let n=0;if(e<0||e>255)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[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=t.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=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=Xt;if(Io(e),e<oe)throw new t("integer: negative integers are not allowed");let r=bn(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=Xt;if(e.length<1)throw new t("invalid signature integer: empty");if(e[0]&128)throw new t("invalid signature integer: negative");if(e.length>1&&e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return er(e)}},toSig(e){let{Err:t,_int:r,_tlv:n}=Xt,o=z(e,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("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 t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(f)}},hexFromSig(e){let{_tlv:t,_int:r}=Xt,n=t.encode(2,r.encode(e.r)),o=t.encode(2,r.encode(e.s)),s=n+o;return t.encode(48,s)}};Object.freeze(Xt._tlv);Object.freeze(Xt._int);Object.freeze(Xt);var oe=BigInt(0),Ke=BigInt(1),Fu=BigInt(2),jo=BigInt(3),Jp=BigInt(4);function ku(e,t={}){let r=Po("weierstrass",e,t),n=r.Fp,o=r.Fn,s=r.CURVE,{h:i,n:a}=s;Ft(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:f}=t;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=Ku(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(U,m,A){if(f&&m.is0())return Uint8Array.of(0);let{x:E,y:w}=m.toAffine(),b=n.toBytes(E);if(Gt(A,"isCompressed"),A){l();let _=!n.isOdd(w);return mt(Mu(_),b)}else return mt(Uint8Array.of(4),b,n.toBytes(w))}function d(U){z(U,void 0,"Point");let{publicKey:m,publicKeyUncompressed:A}=u,E=U.length,w=U[0],b=U.subarray(1);if(f&&E===1&&w===0)return{x:n.ZERO,y:n.ZERO};if(E===m&&(w===2||w===3)){let _=n.fromBytes(b);if(!n.isValid(_))throw new Error("bad point: is not on curve, wrong x");let C=h(_),x;try{x=n.sqrt(C)}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(x);return(w&1)===1!==T&&(x=n.neg(x)),{x:_,y:x}}else if(E===A&&w===4){let _=n.BYTES,C=n.fromBytes(b.subarray(0,_)),x=n.fromBytes(b.subarray(_,_*2));if(!y(C,x))throw new Error("bad point: is not on curve");return{x:C,y:x}}else throw new Error(`bad point: got length ${E}, expected compressed=${m} or uncompressed=${A}`)}let g=t.toBytes===void 0?p:t.toBytes,S=t.fromBytes===void 0?d:t.fromBytes;function h(U){let m=n.sqr(U),A=n.mul(m,U);return n.add(n.add(A,n.mul(U,s.a)),s.b)}function y(U,m){let A=n.sqr(m),E=h(U);return n.eql(A,E)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,jo),Jp),L=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,L)))throw new Error("bad curve params: a or b");function O(U,m,A=!1){if(!n.isValid(m)||A&&n.is0(m))throw new Error(`bad point coordinate ${U}`);return m}function D(U){if(!(U instanceof I))throw new Error("Weierstrass Point expected")}function P(U){if(!c||!c.basises)throw new Error("no endo");return Qp(U,c.basises,o.ORDER)}function R(U,m,A,E,w){return A=new I(n.mul(A.X,U),A.Y,A.Z),m=Sn(E,m),A=Sn(w,A),m.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(m,A,E){this.X=O("x",m),this.Y=O("y",A,!0),this.Z=O("z",E),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){let{x:A,y:E}=m||{};if(!m||!n.isValid(A)||!n.isValid(E))throw new Error("invalid affine point");if(m instanceof I)throw new Error("projective point not allowed");return n.is0(A)&&n.is0(E)?I.ZERO:new I(A,E,n.ONE)}static fromBytes(m){let A=I.fromAffine(S(z(m,void 0,"point")));return A.assertValidity(),A}static fromHex(m){return I.fromBytes(Ir(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,A=!0){return k.createCache(this,m),A||this.multiply(jo),this}assertValidity(){let m=this;if(m.is0()){if(t.allowInfinityPoint&&n.is0(m.X)&&n.eql(m.Y,n.ONE)&&n.is0(m.Z))return;throw new Error("bad point: ZERO")}let{x:A,y:E}=m.toAffine();if(!n.isValid(A)||!n.isValid(E))throw new Error("bad point: x or y not field elements");if(!y(A,E))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(m)}equals(m){D(m);let{X:A,Y:E,Z:w}=this,{X:b,Y:_,Z:C}=m,x=n.eql(n.mul(A,C),n.mul(b,w)),T=n.eql(n.mul(E,C),n.mul(_,w));return x&&T}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:m,b:A}=s,E=n.mul(A,jo),{X:w,Y:b,Z:_}=this,C=n.ZERO,x=n.ZERO,T=n.ZERO,B=n.mul(w,w),F=n.mul(b,b),H=n.mul(_,_),K=n.mul(w,b);return K=n.add(K,K),T=n.mul(w,_),T=n.add(T,T),C=n.mul(m,T),x=n.mul(E,H),x=n.add(C,x),C=n.sub(F,x),x=n.add(F,x),x=n.mul(C,x),C=n.mul(K,C),T=n.mul(E,T),H=n.mul(m,H),K=n.sub(B,H),K=n.mul(m,K),K=n.add(K,T),T=n.add(B,B),B=n.add(T,B),B=n.add(B,H),B=n.mul(B,K),x=n.add(x,B),H=n.mul(b,_),H=n.add(H,H),B=n.mul(H,K),C=n.sub(C,B),T=n.mul(H,F),T=n.add(T,T),T=n.add(T,T),new I(C,x,T)}add(m){D(m);let{X:A,Y:E,Z:w}=this,{X:b,Y:_,Z:C}=m,x=n.ZERO,T=n.ZERO,B=n.ZERO,F=s.a,H=n.mul(s.b,jo),K=n.mul(A,b),J=n.mul(E,_),tt=n.mul(w,C),et=n.add(A,E),Y=n.add(b,_);et=n.mul(et,Y),Y=n.add(K,J),et=n.sub(et,Y),Y=n.add(A,w);let it=n.add(b,C);return Y=n.mul(Y,it),it=n.add(K,tt),Y=n.sub(Y,it),it=n.add(E,w),x=n.add(_,C),it=n.mul(it,x),x=n.add(J,tt),it=n.sub(it,x),B=n.mul(F,Y),x=n.mul(H,tt),B=n.add(x,B),x=n.sub(J,B),B=n.add(J,B),T=n.mul(x,B),J=n.add(K,K),J=n.add(J,K),tt=n.mul(F,tt),Y=n.mul(H,Y),J=n.add(J,tt),tt=n.sub(K,tt),tt=n.mul(F,tt),Y=n.add(Y,tt),K=n.mul(J,Y),T=n.add(T,K),K=n.mul(it,Y),x=n.mul(et,x),x=n.sub(x,K),K=n.mul(et,J),B=n.mul(it,B),B=n.add(B,K),new I(x,T,B)}subtract(m){return D(m),this.add(m.negate())}is0(){return this.equals(I.ZERO)}multiply(m){let{endo:A}=t;if(!o.isValidNot0(m))throw new RangeError("invalid scalar: out of range");let E,w,b=_=>k.cached(this,_,C=>or(I,C));if(A){let{k1neg:_,k1:C,k2neg:x,k2:T}=P(m),{p:B,f:F}=b(C),{p:H,f:K}=b(T);w=F.add(K),E=R(A.beta,B,H,_,x)}else{let{p:_,f:C}=b(m);E=_,w=C}return or(I,[E,w])[0]}multiplyUnsafe(m){let{endo:A}=t,E=this,w=m;if(!o.isValid(w))throw new RangeError("invalid scalar: out of range");if(w===oe||E.is0())return I.ZERO;if(w===Ke)return E;if(k.hasCache(this))return this.multiply(w);if(A){let{k1neg:b,k1:_,k2neg:C,k2:x}=P(w),{p1:T,p2:B}=su(I,E,_,x);return R(A.beta,T,B,b,C)}else return k.unsafe(E,w)}toAffine(m){let A=this,E=m,{X:w,Y:b,Z:_}=A;if(n.eql(_,n.ONE))return{x:w,y:b};let C=A.is0();E==null&&(E=C?n.ONE:n.inv(_));let x=n.mul(w,E),T=n.mul(b,E),B=n.mul(_,E);if(C)return{x:n.ZERO,y:n.ZERO};if(!n.eql(B,n.ONE))throw new Error("invZ was invalid");return{x,y:T}}isTorsionFree(){let{isTorsionFree:m}=t;return i===Ke?!0:m?m(I,this):k.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:m}=t;return i===Ke?this:m?m(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Ke?this.is0():this.clearCofactor().is0()}toBytes(m=!0){return Gt(m,"isCompressed"),this.assertValidity(),g(I,this,m)}toHex(m=!0){return Tr(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,k=new Pr(I,t.endo?Math.ceil(N/2):N);return N>=8&&I.BASE.precompute(8),Object.freeze(I.prototype),Object.freeze(I),I}function Mu(e){return Uint8Array.of(e?2:3)}function Ku(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function tm(e,t={}){let{Fn:r}=e,n=t.randomBytes===void 0?tr:t.randomBytes,o=Object.assign(Ku(e.Fp,r),{seed:Math.max(Ni(r.ORDER),16)});function s(d){try{let g=r.fromBytes(d);return r.isValidNot0(g)}catch{return!1}}function i(d,g){let{publicKey:S,publicKeyUncompressed:h}=o;try{let y=d.length;return g===!0&&y!==S||g===!1&&y!==h?!1:!!e.fromBytes(d)}catch{return!1}}function a(d){return d=d===void 0?n(o.seed):d,Ui(z(d,o.seed,"seed"),r.ORDER)}function c(d,g=!0){return e.BASE.multiply(r.fromBytes(d)).toBytes(g)}function f(d){let{secretKey:g,publicKey:S,publicKeyUncompressed:h}=o,y=r._lengths;if(!Je(d))return;let v=z(d,void 0,"key").length,L=v===S||v===h,O=v===g||!!y?.includes(v);if(!(L&&O))return L}function u(d,g,S=!0){if(f(d)===!0)throw new Error("first arg must be private key");if(f(g)===!1)throw new Error("second arg must be public key");let h=r.fromBytes(d);return e.fromBytes(g).multiply(h).toBytes(S)}let l={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},p=Or(a,c);return Object.freeze(l),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:e,utils:l,lengths:o})}function Hu(e,t,r={}){let n=t;Xe(n),Ft(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let o=r.randomBytes===void 0?tr:r.randomBytes,s=r.hmac===void 0?(w,b)=>On(n,w,b):r.hmac,{Fp:i,Fn:a}=e,{ORDER:c,BITS:f}=a,{keygen:u,getPublicKey:l,getSharedSecret:p,utils:d,lengths:g}=tm(e,r),S={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},h=c*Fu+Ke<i.ORDER;function y(w){let b=c>>Ke;return w>b}function v(w,b){if(!a.isValidNot0(b))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return b}function L(){if(h)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function O(w,b){Sa(b);let _=g.signature,C=b==="compact"?_:b==="recovered"?_+1:void 0;return z(w,C)}class D{r;s;recovery;constructor(b,_,C){if(this.r=v("r",b),this.s=v("s",_),C!=null){if(L(),![0,1,2,3].includes(C))throw new Error("invalid recovery id");this.recovery=C}Object.freeze(this)}static fromBytes(b,_=S.format){O(b,_);let C;if(_==="der"){let{r:F,s:H}=Xt.toSig(z(b));return new D(F,H)}_==="recovered"&&(C=b[0],_="compact",b=b.subarray(1));let x=g.signature/2,T=b.subarray(0,x),B=b.subarray(x,x*2);return new D(a.fromBytes(T),a.fromBytes(B),C)}static fromHex(b,_){return this.fromBytes(Ir(b),_)}assertRecovery(){let{recovery:b}=this;if(b==null)throw new Error("invalid recovery id: must be present");return b}addRecoveryBit(b){return new D(this.r,this.s,b)}recoverPublicKey(b){let{r:_,s:C}=this,x=this.assertRecovery(),T=x===2||x===3?_+c:_;if(!i.isValid(T))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let B=i.toBytes(T),F=e.fromBytes(mt(Mu((x&1)===0),B)),H=a.inv(T),K=R(z(b,void 0,"msgHash")),J=a.create(-K*H),tt=a.create(C*H),et=e.BASE.multiplyUnsafe(J).add(F.multiplyUnsafe(tt));if(et.is0())throw new Error("invalid recovery: point at infinify");return et.assertValidity(),et}hasHighS(){return y(this.s)}toBytes(b=S.format){if(Sa(b),b==="der")return Ir(Xt.hexFromSig(this));let{r:_,s:C}=this,x=a.toBytes(_),T=a.toBytes(C);return b==="recovered"?(L(),mt(Uint8Array.of(this.assertRecovery()),x,T)):mt(x,T)}toHex(b){return Tr(this.toBytes(b))}}Object.freeze(D.prototype),Object.freeze(D);let P=r.bits2int===void 0?function(b){if(b.length>8192)throw new Error("input is too large");let _=er(b),C=b.length*8-f;return C>0?_>>BigInt(C):_}:r.bits2int,R=r.bits2int_modN===void 0?function(b){return a.create(P(b))}:r.bits2int_modN,I=xn(f);function N(w){return he("num < 2^"+f,w,oe,I),a.toBytes(w)}function k(w,b){return z(w,void 0,"message"),b?z(n(w),void 0,"prehashed message"):w}function U(w,b,_){let{lowS:C,prehash:x,extraEntropy:T}=Ea(_,S);w=k(w,x);let B=R(w),F=a.fromBytes(b);if(!a.isValidNot0(F))throw new Error("invalid private key");let H=[N(F),N(B)];if(T!=null&&T!==!1){let et=T===!0?o(g.secretKey):T;H.push(z(et,void 0,"extraEntropy"))}let K=mt(...H),J=B;function tt(et){let Y=P(et);if(!a.isValidNot0(Y))return;let it=a.inv(Y),ie=e.BASE.multiply(Y).toAffine(),je=a.create(ie.x);if(je===oe)return;let yr=a.create(it*a.create(J+je*F));if(yr===oe)return;let nn=(ie.x===je?0:2)|Number(ie.y&Ke),on=yr;return C&&y(yr)&&(on=a.neg(yr),nn^=1),new D(je,on,h?void 0:nn)}return{seed:K,k2sig:tt}}function m(w,b,_={}){let{seed:C,k2sig:x}=U(w,b,_);return Vf(n.outputLen,a.BYTES,s)(C,x).toBytes(_.format)}function A(w,b,_,C={}){let{lowS:x,prehash:T,format:B}=Ea(C,S);if(_=z(_,void 0,"publicKey"),b=k(b,T),!Je(w)){let F=w instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+F)}O(w,B);try{let F=D.fromBytes(w,B),H=e.fromBytes(_);if(x&&F.hasHighS())return!1;let{r:K,s:J}=F,tt=R(b),et=a.inv(J),Y=a.create(tt*et),it=a.create(K*et),ie=e.BASE.multiplyUnsafe(Y).add(H.multiplyUnsafe(it));return ie.is0()?!1:a.create(ie.x)===K}catch{return!1}}function E(w,b,_={}){let{prehash:C}=Ea(_,S);return b=k(b,C),D.fromBytes(w,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:p,utils:d,lengths:g,Point:e,sign:m,verify:A,recoverPublicKey:E,Signature:D,hash:n})}var _a={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},em={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Vu=BigInt(2);function rm(e){let t=_a.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=e*e*e%t,u=f*f*e%t,l=st(u,r,t)*u%t,p=st(l,r,t)*u%t,d=st(p,Vu,t)*f%t,g=st(d,o,t)*d%t,S=st(g,s,t)*g%t,h=st(S,a,t)*S%t,y=st(h,c,t)*h%t,v=st(y,a,t)*S%t,L=st(v,r,t)*u%t,O=st(L,i,t)*g%t,D=st(O,n,t)*f%t,P=st(D,Vu,t);if(!va.eql(va.sqr(P),e))throw new Error("Cannot find square root");return P}var va=Dr(_a.p,{sqrt:rm}),nm=ku(_a,{Fp:va,endo:em}),Fr=Hu(nm,re);function $u(e,t,r,n){let o=ce.digest(r instanceof Uint8Array?r:r.subarray());if(ko(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Fr.verify(t,s,e,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Cn(String(s))});try{return n?.signal?.throwIfAborted(),Fr.verify(t,o.digest,e,{prehash:!1,format:"der"})}catch(s){throw new Cn(String(s))}}var Go=class{type="secp256k1";raw;_key;constructor(t){this._key=qu(t),this.raw=zu(this._key)}toMultihash(){return zt.digest(_e(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return lt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}verify(t,r,n){return $u(this._key,r,t,n)}};function Ca(e){return new Go(e)}function zu(e){return Fr.Point.fromBytes(e).toBytes()}function qu(e){try{return Fr.Point.fromBytes(e),e}catch(t){throw new br(String(t))}}function Nn(e,t){let{Type:r,Data:n}=ne.decode(e),o=n??new Uint8Array;switch(r){case ft.RSA:return ba(o,t);case ft.Ed25519:return Yi(o);case ft.secp256k1:return Ca(o);case ft.ECDSA:return wi(o);default:throw new Ge}}function ju(e){let{Type:t,Data:r}=ne.decode(e.digest),n=r??new Uint8Array;switch(t){case ft.Ed25519:return Yi(n);case ft.secp256k1:return Ca(n);case ft.ECDSA:return wi(n);default:throw new Ge}}function _e(e){return ne.encode({Type:ft[e.type],Data:e.raw})}var Gu=Symbol.for("nodejs.util.inspect.custom"),om=114,Un=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[qs]=!0;toString(){return this.string==null&&(this.string=lt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return dt.createV1(om,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return wt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return wt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Gu](){return`PeerId(${this.toString()})`}},Fn=class extends Un{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},kn=class extends Un{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Mn=class extends Un{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},sm=2336,Kn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=zt.digest(q(this.url))}[Gu](){return`PeerId(${this.url})`}[qs]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return dt.createV1(sm,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=V(t)),t.toString()===this.toString())}};var im=114,Wu=2336;function kr(e,t){let r;if(e.charAt(0)==="1"||e.charAt(0)==="Q")r=_r(lt.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return am(dt.parse(e));if(t==null)throw new G('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=_r(t.decode(e))}return Yu(r)}function La(e){if(e.type==="Ed25519")return new kn({multihash:e.toCID().multihash,publicKey:e});if(e.type==="secp256k1")return new Mn({multihash:e.toCID().multihash,publicKey:e});if(e.type==="RSA")return new Fn({multihash:e.toCID().multihash,publicKey:e});throw new Ge}function Yu(e){if(fm(e))return new Fn({multihash:e});if(cm(e))try{let t=ju(e);if(t.type==="Ed25519")return new kn({multihash:e,publicKey:t});if(t.type==="secp256k1")return new Mn({multihash:e,publicKey:t})}catch{let r=V(e.digest);return new Kn(new URL(r))}throw new lo("Supplied PeerID Multihash is invalid")}function am(e){if(e?.multihash==null||e.version==null||e.version===1&&e.code!==im&&e.code!==Wu)throw new uo("Supplied PeerID CID is invalid");if(e.code===Wu){let t=V(e.multihash.digest);return new Kn(new URL(t))}return Yu(e.multihash)}function cm(e){return e.code===zt.code}function fm(e){return e.code===ce.code}var St=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ge=class extends Error{static name="ValidationError";name="ValidationError"},Wo=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Yo=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Xo=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let r=this.index,n=t();return n===void 0&&(this.index=r),n}parseWith(t){let r=t();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(t){return this.readAtomically(()=>{let r=this.readChar();if(r===t)return r})}readSeparator(t,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,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 p=Number.parseInt(l,t);if(!Number.isNaN(p))return p});if(u===void 0)break;if(s*=t,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 t=new Uint8Array(4);for(let r=0;r<t.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[r]=n}return t})}readIPv6Addr(){let t=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]=t(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]=t(s.subarray(0,i));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var um=45,lm=15,Zo=new Xo;function Xu(e){if(!(e.length>lm))return Zo.new(e).parseWith(()=>Zo.readIPv4Addr())}function Zu(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>um))return Zo.new(e).parseWith(()=>Zo.readIPv6Addr())}function Qo(e){return!!Xu(e)}function Qu(e){return!!Zu(e)}function Ia(e){return t=>V(t,e)}function Ba(e){return t=>q(t,e)}function Mr(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function fr(e){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof e=="string"?parseInt(e):e),new Uint8Array(t)}function Ju(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let r=q(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=fr(n);return Pt([r,o],r.length+o.length)}function tl(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let r=Ae.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=fr(n);return Pt([r,o],r.length+o.length)}function Da(e){let t=e.subarray(0,e.length-2),r=e.subarray(e.length-2),n=V(t,"base32"),o=Mr(r);return`${n}:${o}`}var Ra=function(e){e=e.toString().trim();let t=new Uint8Array(4);return e.split(/\./g).forEach((r,n)=>{let o=parseInt(r,10);if(isNaN(o)||o<0||o>255)throw new St("Invalid byte value in IP address");t[n]=o}),t},el=function(e){let t=0;e=e.toString().trim();let r=e.split(":",8),n;for(n=0;n<r.length;n++){let s=Qo(r[n]),i;s&&(i=Ra(r[n]),r[n]=V(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,V(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(t+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 St("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},rl=function(e){if(e.byteLength!==4)throw new St("IPv4 address was incorrect length");let t=[];for(let r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},nl=function(e){if(e.byteLength!==16)throw new St("IPv6 address was incorrect length");let t=[];for(let n=0;n<e.byteLength;n+=2){let o=e[n],s=e[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}let r=t.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new St(`Invalid IPv6 address "${r}"`)}};function ol(e){try{let t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new St(`Invalid IPv6 address "${e}"`)}}var Ta=Object.values(Ye).map(e=>e.decoder),hm=(function(){let e=Ta[0].or(Ta[1]);return Ta.slice(2).forEach(t=>e=e.or(t)),e})();function sl(e){return hm.decode(e)}function il(e){return t=>e.encoder.encode(t)}function dm(e){if(parseInt(e).toString()!==e)throw new ge("Value must be an integer")}function pm(e){if(e<0)throw new ge("Value must be a positive integer, or zero")}function mm(e){return t=>{if(t>e)throw new ge(`Value must be smaller than or equal to ${e}`)}}function gm(...e){return t=>{for(let r of e)r(t)}}var Hn=gm(dm,pm,mm(65535));var bt=-1,Pa=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let r;if(typeof t=="string"?r=this.protocolsByName.get(t):r=this.protocolsByCode.get(t),r==null)throw new Yo(`Protocol ${t} was unknown`);return r}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(r=>{this.protocolsByName.set(r,t)})}removeProtocol(t){let r=this.protocolsByCode.get(t);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},be=new Pa,Bm=[{code:4,name:"ip4",size:32,valueToBytes:Ra,bytesToValue:rl,validate:e=>{if(!Qo(e))throw new ge(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:fr,bytesToValue:Mr,validate:Hn},{code:273,name:"udp",size:16,valueToBytes:fr,bytesToValue:Mr,validate:Hn},{code:33,name:"dccp",size:16,valueToBytes:fr,bytesToValue:Mr,validate:Hn},{code:41,name:"ip6",size:128,valueToBytes:el,bytesToValue:nl,stringToValue:ol,validate:e=>{if(!Qu(e))throw new ge(`Invalid IPv6 address "${e}"`)}},{code:42,name:"ip6zone",size:bt},{code:43,name:"ipcidr",size:8,bytesToValue:Ia("base10"),valueToBytes:Ba("base10")},{code:53,name:"dns",size:bt},{code:54,name:"dns4",size:bt},{code:55,name:"dns6",size:bt},{code:56,name:"dnsaddr",size:bt},{code:132,name:"sctp",size:16,valueToBytes:fr,bytesToValue:Mr,validate:Hn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:bt,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:bt,bytesToValue:Ia("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?Ba("base58btc")(e):dt.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Da,valueToBytes:Ju},{code:445,name:"onion3",size:296,bytesToValue:Da,valueToBytes:tl},{code:446,name:"garlic64",size:bt},{code:447,name:"garlic32",size:bt},{code:448,name:"tls"},{code:449,name:"sni",size:bt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:bt,bytesToValue:il(ln),valueToBytes:sl},{code:480,name:"http"},{code:481,name:"http-path",size:bt,stringToValue:e=>`/${decodeURIComponent(e)}`,valueToString:e=>encodeURIComponent(e.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:bt}];Bm.forEach(e=>{be.addProtocol(e)});function al(e){let t=[],r=0;for(;r<e.length;){let n=me(e,r),o=be.getProtocol(n),s=rt(n),i=Dm(o,e,r+s),a=0;i>0&&o.size===bt&&(a=rt(i));let c=s+a+i,f={code:n,name:o.name,bytes:e.subarray(r,r+c)};if(i>0){let u=r+s+a,l=e.subarray(u,u+i);f.value=o.bytesToValue?.(l)??V(l)}t.push(f),r+=c}return t}function cl(e){let t=0,r=[];for(let n of e){if(n.bytes==null){let o=be.getProtocol(n.code),s=rt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??q(n.value),a=i.byteLength,o.size===bt&&(c=rt(a)));let f=new Uint8Array(s+c+a),u=0;Oe(n.code,f,u),u+=s,i!=null&&(o.size===bt&&(Oe(a,f,u),u+=c),f.set(i,u)),n.bytes=f}r.push(n.bytes),t+=n.bytes.byteLength}return Pt(r,t)}function fl(e){if(e.charAt(0)!=="/")throw new St('String multiaddr must start with "/"');let t=[],r="protocol",n="",o="";for(let s=1;s<e.length;s++){let i=e.charAt(s);i!=="/"&&(r==="protocol"?o+=e.charAt(s):n+=e.charAt(s));let a=s===e.length-1;if(i==="/"||a){let c=be.getProtocol(o);if(r==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",r="protocol";continue}else if(a)throw new St(`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 St(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}t.push(f),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new St("Incomplete multiaddr");return t}function ul(e){return`/${e.flatMap(t=>{if(t.value==null)return t.name;let r=be.getProtocol(t.code);if(r==null)throw new St(`Unknown protocol code ${t.code}`);return[t.name,r.valueToString?.(t.value)??t.value]}).join("/")}`}function Dm(e,t,r){return e.size==null||e.size===0?0:e.size>0?e.size/8:me(t,r)}var Rm=Symbol.for("nodejs.util.inspect.custom"),Xa=Symbol.for("@multiformats/multiaddr");function Pm(e){if(e==null&&(e="/"),ll(e))return e.getComponents();if(e instanceof Uint8Array)return al(e);if(typeof e=="string")return e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),e===""&&(e="/"),fl(e);if(Array.isArray(e))return e;throw new St("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ns=class e{[Xa]=!0;#t;#e;#r;constructor(t="/",r={}){this.#t=Pm(t),r.validate!==!1&&Om(this)}get bytes(){return this.#r==null&&(this.#r=cl(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=ul(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let r=new e(t);return new e([...this.#t,...r.getComponents()],{validate:!1})}decapsulate(t){let r=t.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new Wo(`Address ${this.toString()} does not contain subaddress: ${r}`);return new e(n.slice(0,o),{validate:!1})}decapsulateCode(t){let r;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){r=n;break}return new e(this.#t.slice(0,r),{validate:!1})}equals(t){return wt(this.bytes,t.bytes)}[Rm](){return`Multiaddr(${this.toString()})`}};function Om(e){e.getComponents().forEach(t=>{let r=be.getProtocol(t.code);t.value!=null&&r.validate?.(t.value)})}function ll(e){return!!e?.[Xa]}function $r(e){return new ns(e)}var nt=e=>({match:t=>{let r=t[0];return r==null||r.code!==e||r.value!=null?!1:t.slice(1)}}),M=(e,t)=>({match:r=>{let n=r[0];return n?.code!==e||n.value==null||t!=null&&n.value!==t?!1:r.slice(1)}}),hl=e=>({match:t=>e.match(t)===!1?t:!1}),j=e=>({match:t=>{let r=e.match(t);return r===!1?t:r}}),Tt=(...e)=>({match:t=>{let r;for(let n of e){let o=n.match(t);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1}}),X=(...e)=>({match:t=>{for(let r of e){let n=r.match(t);if(n===!1)return!1;t=n}return t}});function ot(...e){function t(o){if(o==null)return!1;let s=o.getComponents();for(let i of e){let a=i.match(s);if(a===!1)return!1;s=a}return s}function r(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:e,matches:r,exactMatch:n}}var Nm=M(421),Q1=ot(Nm),ss=M(54),is=M(55),as=M(56),Qa=M(53),J1=ot(ss,j(M(421))),t2=ot(is,j(M(421))),e2=ot(as,j(M(421))),r2=ot(Tt(Qa,as,ss,is),j(M(421))),dl=X(M(4),j(M(43))),pl=X(j(M(42)),M(41),j(M(43))),Ja=Tt(dl,pl),zr=Tt(Ja,Qa,ss,is,as),n2=ot(Tt(Ja,X(Tt(Qa,as,ss,is),j(M(421))))),o2=ot(dl),s2=ot(pl),i2=ot(Ja),tc=X(zr,M(6)),Vn=X(zr,M(273)),a2=ot(X(tc,j(M(421)))),c2=ot(Vn),ec=X(Vn,nt(460),j(M(421))),cs=X(Vn,nt(461),j(M(421))),Um=Tt(ec,cs),f2=ot(ec),u2=ot(cs),Za=Tt(zr,tc,Vn,ec,cs),ml=Tt(X(Za,nt(477),j(M(421)))),l2=ot(ml),gl=Tt(X(Za,nt(478),j(M(421))),X(Za,nt(448),j(M(449)),nt(477),j(M(421)))),h2=ot(gl),yl=X(Vn,nt(280),j(M(466)),j(M(466)),j(M(421))),bl=ot(yl),wl=X(cs,nt(465),j(M(466)),j(M(466)),j(M(421))),d2=ot(wl),os=Tt(ml,gl,X(tc,j(M(421))),X(Um,j(M(421))),X(zr,j(M(421))),yl,wl,M(421)),xl=ot(os),Fm=X(j(os),nt(290),hl(nt(281)),j(M(421))),p2=ot(Fm),km=Tt(X(os,nt(290),nt(281),j(M(421))),X(os,nt(281),j(M(421))),X(nt(281),j(M(421)))),El=ot(km),Mm=X(zr,Tt(X(M(6,"80")),X(M(6),nt(480)),nt(480)),j(M(481)),j(M(421))),m2=ot(Mm),Km=X(zr,Tt(X(M(6,"443")),X(M(6,"443"),nt(480)),X(M(6),nt(443)),X(M(6),nt(448),nt(480)),X(nt(448),nt(480)),nt(448),nt(443)),j(M(481)),j(M(421))),g2=ot(Km),Hm=Tt(X(M(777),j(M(421)))),y2=ot(Hm),Vm=Tt(X(M(400),j(M(421)))),b2=ot(Vm);var It;(function(e){let t;(function(a){a.FIN="FIN",a.STOP_SENDING="STOP_SENDING",a.RESET="RESET",a.FIN_ACK="FIN_ACK"})(t=e.Flag||(e.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=()=>cr(r)})(t=e.Flag||(e.Flag={}));let n;e.codec=()=>(n==null&&(n=Me((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.flag!=null&&(c.uint32(8),e.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 p=a.uint32();switch(p>>>3){case 1:{u.flag=e.Flag.codec().decode(a);break}case 2:{u.message=a.bytes();break}default:{a.skipType(p&7);break}}}return u},function*(a,c,f,u={}){let l=c==null?a.len:a.pos+c;for(;a.pos<l;){let p=a.uint32();switch(p>>>3){case 1:{yield{field:`${f}.flag`,value:e.Flag.codec().decode(a)};break}case 2:{yield{field:`${f}.message`,value:a.bytes()};break}default:{a.skipType(p&7);break}}}})),n);function o(a){return Fe(a,e.codec())}e.encode=o;function s(a,c){return Ue(a,e.codec(),c)}e.decode=s;function i(a,c){return ke(a,e.codec(),c)}e.stream=i})(It||(It={}));var Sl=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],rc=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Al="libp2p+webrtc+v1/",vl=2*1024*1024,qr=16*1024;function $m(e=qr){let t=rt(e-rt(e)),r=1+rt(Object.keys(It.Flag).length-1),n=1,o=e-t-r-n,s=rt(o);return t+r+n+s}var _l=$m();var Cl=1e4,nc="/webrtc",$n="/webrtc-signaling/0.0.1";function zm(e){let t=e.getComponents(),r={},n=0;return t[n]?.name==="ip6zone"&&(r.zone=`${t[n].value}`,n++),t[n]?.name==="ip4"||t[n]?.name==="ip6"||t[n]?.name==="dns"||t[n]?.name==="dns4"||t[n]?.name==="dns6"?(r.type=t[n].name,r.host=t[n].value,n++):t[n]?.name==="dnsaddr"&&(r.type=t[n].name,r.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(r.protocol=t[n].name==="tcp"?"tcp":"udp",r.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(r.type==="ip4"?r.cidr=parseInt(`${t[n].value}`):r.type==="ip6"&&(r.cidr=`${t[n].value}`),n++),r.type==null||r.host==null?null:(t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(r.sni=t[n+1].value,n+=2),r)}function oc(e){let t=zm(e);if(t==null)throw new G(`Multiaddr ${e} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t}function fs(){let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}var us=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},jr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new us(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let r=this.head;this.head=r.next=new us(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var sc=class extends Error{type;code;constructor(t,r){super(t??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Gr(e={}){return qm(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}},e)}function qm(e,t){t=t??{};let r=t.onEnd,n=new jr,o,s,i,a=fs(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,y)=>{s=v=>{s=null,n.push(v);try{h(e(n))}catch(L){y(L)}return o}}):e(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=fs()})}},f=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new jr,s!=null?s({error:h}):(n.push({error:h}),o)),l=h=>{if(i)return o;if(t?.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})},p=h=>i?o:(i=!0,h!=null?u(h):f({done:!0})),d=()=>(n=new jr,p(),{done:!0}),g=h=>(p(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:g,push:l,end:p,get readableLength(){return n.size},onEmpty:async h=>{let y=h?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let v,L;y!=null&&(v=new Promise((O,D)=>{L=()=>{D(new sc)},y.addEventListener("abort",L)}));try{await Promise.race([a.promise,v])}finally{L!=null&&y!=null&&y?.removeEventListener("abort",L)}}},r==null)return o;let S=o;return o={[Symbol.asyncIterator](){return this},next(){return S.next()},throw(h){return S.throw(h),r!=null&&(r(h),r=void 0),{done:!0}},return(){return S.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(h){return S.end(h),r!=null&&(r(h),r=void 0),o},get readableLength(){return S.readableLength},onEmpty:h=>S.onEmpty(h)},o}var ic=class e extends Error{name="TimeoutError";constructor(t,r){super(t,r),Error.captureStackTrace?.(this,e)}},Ll=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function ac(e,t){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=t,a,c,u=new Promise((l,p)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){p(Ll(i));return}if(i&&(c=()=>{p(Ll(i))},i.addEventListener("abort",c,{once:!0})),e.then(l,p),r===Number.POSITIVE_INFINITY)return;let d=new ic;a=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(g){p(g)}return}typeof e.cancel=="function"&&e.cancel(),o===!1?l():o instanceof Error?p(o):(d.message=o??`Promise timed out after ${r} milliseconds`,p(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 jm=e=>{let t=e.addEventListener||e.on||e.addListener,r=e.removeEventListener||e.off||e.removeListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}};function Gm(e,t,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=[t].flat(),c=[],{addListener:f,removeListener:u}=jm(e),l=async(...d)=>{let g=r.multiArgs?d:d[0];if(r.filter)try{if(!await r.filter(g))return}catch(S){n(),i(S);return}c.push(g),r.count===c.length&&(n(),s(c))},p=(...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,p)};for(let d of a)f(d,l);for(let d of r.rejectionEvents)a.includes(d)||f(d,p);r.signal&&r.signal.addEventListener("abort",()=>{p(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){let s=ac(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function At(e,t,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Gm(e,t,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var lr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},ls=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},hs=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Wm(e){return e.reason}async function we(e,t,r){if(t==null)return e;let n=r?.translateError??Wm;if(t.aborted)return e.catch(()=>{}),Promise.reject(n(t));let o;try{return await Promise.race([e,new Promise((s,i)=>{o=()=>{i(n(t))},t.addEventListener("abort",o)})])}finally{o!=null&&t.removeEventListener("abort",o)}}var Ym=Math.pow(2,20)*4,Ve=class extends Ee{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(t){super(),this.status="open",this.log=t.log,this.direction=t.direction??"outbound",this.inactivityTimeout=t.inactivityTimeout??12e4,this.maxReadBufferLength=t.maxReadBufferLength??Ym,this.maxWriteBufferLength=t.maxWriteBufferLength,this.maxMessageSize=t.maxMessageSize,this.readBuffer=new $,this.writeBuffer=new $,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(()=>{this.processSendQueue()})),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);let n=o=>{this.onDrainPromise?.reject(o.error??new hs)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(t){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),we(this.onDrainPromise.promise,t?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let t=Gr(),r=s=>{t.push(s.data)};this.addEventListener("message",r);let n=s=>{t.end(s.error)};this.addEventListener("close",n);let o=()=>{t.end()};this.addEventListener("remoteCloseWrite",o);try{yield*t}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(t){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Jt(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",t.byteLength),this.writeBuffer.append(t),this.processSendQueue()}abort(t){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",t),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(t)}catch(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new mo(t))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Jt("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 Jt("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Jt(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.append(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Jt(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.prepend(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(t){if(t.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(t),this.dispatchReadBuffer()}}addEventListener(...t){super.addEventListener.apply(this,t),t[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 t=new wr;this.dispatchEvent(new go(t))}onTransportClosed(t){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"),t!=null?this.abort(t):(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 xr))}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;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let t=!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){t=!1;break}let s=this.writeBuffer.sublist(0,o),i=new $(s);this.writeBuffer.consume(s.byteLength);let a=this.sendData(s);if(t=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!t)break}return t||(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"),t}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 t=this.readBuffer.sublist();this.readBuffer.consume(t.byteLength),this.dispatchEvent(new po(t))}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 ds=class extends Ve{remoteAddr;metricPrefix;metrics;constructor(t){super(t),this.metricPrefix=t.metricPrefix??"",this.metrics=t.metrics,this.remoteAddr=t.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(t){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 At(this,"idle",{...t,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 At(this,"drain",{...t,rejectionEvents:["close"]})),await this.sendClose(t),this.onTransportClosed())}};function Tl(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var ps=class extends Ee{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(t,r){super(),this.maConn=t,this.protocol=r.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=t.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(t){let r=this.maConn.send(t);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(t){this.status==="closed"||this.status==="closing"||(this.status="closing",await we(Promise.all([...this.streams].map(async r=>{await r.close(t)})),t?.signal),this.status="closed")}abort(t){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(r=>{r.abort(t)}),this.status="closed")}onTransportClosed(t){this.status="closing";try{[...this.streams].forEach(r=>{r.onTransportClosed(t)})}catch(r){this.abort(r)}this.status="closed"}async createStream(t){if(this.status!=="open")throw new co;let r=this.onCreateStream({...this.streamOptions,...t});return Tl(r)&&(r=await r),this.streams.push(r),this.cleanUpStream(r),r}onRemoteStream(t){if(this.streams.push(t),this.cleanUpStream(t),this.listenerCount("stream")===0){this.earlyStreams.push(t),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new ls(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:t})}cleanUpStream(t){let r=n=>{let o=this.streams.findIndex(s=>s===t);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${t.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${t.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${t.direction}_stream_end`]:!0})};t.addEventListener("close",r),this.metrics?.increment({[`${t.direction}_stream`]:!0})}addEventListener(...t){super.addEventListener.apply(this,t),t[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(r=>{this.safeDispatchEvent("stream",{detail:r})}),this.earlyStreams=[]})}};var ms=class extends Ve{id;protocol;constructor(t){super(t),this.id=t.id,this.protocol=t.protocol??""}async close(t){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 At(this,"idle",{...t,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 At(this,"drain",{...t,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(t),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(t){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(t),this.readStatus="closed",this.log("closed readable end gracefully"))}};var Xm=4194304,gs=class extends Error{static name="UnwrappedError";name="UnwrappedError"},zn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},fc=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},uc=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Zm(e){return typeof e?.closeRead=="function"}function Qm(e){return typeof e?.close=="function"}function cc(e){return Zm(e)?e.remoteWriteStatus!=="writable"&&e.readBufferLength===0:Qm(e)?e.status!=="open":!1}function Jm(e){return e?.addEventListener!=null&&e?.removeEventListener!=null&&e?.send!=null&&e?.push!=null&&e?.log!=null}function t0(e,t){let r=t?.maxBufferSize??Xm,n=new $,o,s=!1;if(!Jm(e))throw new G("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()};e.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};e.addEventListener("close",a);let c=()=>{o?.resolve()};e.addEventListener("remoteCloseWrite",c);let f={readBuffer:n,async read(u){if(s===!0)throw new gs("Stream was unwrapped");if(cc(e)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw e.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new lr(`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 we(o.promise,u?.signal),cc(e)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let p=u?.bytes??n.byteLength;if(n.byteLength<p){if(cc(e))throw e.log.error("closed while reading %d/%d bytes",n.byteLength,p),new lr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${p} bytes`);return f.read(u)}let d=n.sublist(0,p);return n.consume(p),d},async write(u,l){if(s===!0)throw new gs("Stream was unwrapped");e.send(u)||await At(e,"drain",{signal:l?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,e.removeEventListener("message",i),e.removeEventListener("close",a),e.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(e.log("stream unwrapped with %d unread bytes",n.byteLength),e.push(n))),e}};return f}function ys(e,t={}){let r=t0(e,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=rt(t.maxDataLength));let n=t?.lengthDecoder??me,o=t?.lengthEncoder??Ko;return{async read(i){let a=-1,c=new $;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 zn("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new uc(`Message length length too long - ${c.byteLength} > ${t.maxLengthLength}`);if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new fc(`Message length too long - ${a} > ${t.maxDataLength}`);let f=await r.read({...i,bytes:a});if(f==null)throw e.log.error("tried to read %d bytes but the stream closed",a),new lr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(f.byteLength!==a)throw e.log.error("read %d/%d bytes before the stream closed",f.byteLength,a),new lr(`Unexpected EOF - read ${f.byteLength}/${a} bytes before the stream closed`);return f},async write(i,a){await r.write(new $(o(i.byteLength),i),a)},async writeV(i,a){let c=new $(...i.flatMap(f=>[o(f.byteLength),f]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function bs(e,t){let r=ys(e,t),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 e0=1024*1024*4,r0=1024*1024*4,ws=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(t={}){this.buffer=new $,this.maxBufferSize=t.maxBufferSize??e0,this.maxDataLength=t.maxDataLength??r0,this.lengthDecoder=t.lengthDecoder??me,this.encodingLength=t.encodingLength??rt}*decode(t){if(this.buffer.append(t),this.buffer.byteLength>this.maxBufferSize)throw new G(`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 zn("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}}};var xs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Wr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Es=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},qn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Ss(e){return e[Symbol.asyncIterator]!=null}function Il(e,t){if(e.byteLength>t)throw new Wr("Message length too long")}var vs=e=>{let t=rt(e),r=at(t);return Ko(e,r),vs.bytes=t,r};vs.bytes=0;function jn(e,t){t=t??{};let r=t.lengthEncoder??vs,n=t?.maxDataLength??4194304;function*o(s){Il(s,n);let i=r(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Ss(e)?(async function*(){for await(let s of e)yield*o(s)})():(function*(){for(let s of e)yield*o(s)})()}jn.single=(e,t)=>{t=t??{};let r=t.lengthEncoder??vs,n=t?.maxDataLength??4194304;return Il(e,n),new $(r(e.byteLength),e)};var hr;(function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(hr||(hr={}));var lc=e=>{let t=me(e);return lc.bytes=rt(t),t};lc.bytes=0;function Gn(e,t){let r=new $,n=hr.LENGTH,o=-1,s=t?.lengthDecoder??lc,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===hr.LENGTH)try{if(o=s(r),o<0)throw new xs("Invalid message length");if(o>a)throw new Wr("Message length too long");let f=s.bytes;r.consume(f),t?.onLength!=null&&t.onLength(o),n=hr.DATA}catch(f){if(f instanceof RangeError){if(r.byteLength>i)throw new Es("Message length length too long");break}throw f}if(n===hr.DATA){if(r.byteLength<o)break;let f=r.sublist(0,o);r.consume(o),t?.onData!=null&&t.onData(f),yield f,n=hr.LENGTH}}}return Ss(e)?(async function*(){for await(let f of e)r.append(f),yield*c();if(r.byteLength>0)throw new qn("Unexpected end of input")})():(function*(){for(let f of e)r.append(f),yield*c();if(r.byteLength>0)throw new qn("Unexpected end of input")})()}Gn.fromReader=(e,t)=>{let r=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await e.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 Gn(n,{...t??{},onLength:s=>{r=s}})};var hc=class extends ms{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(t){super({...t,maxMessageSize:(t.maxMessageSize??qr)-_l}),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=Gr(),this.maxBufferedAmount=t.maxBufferedAmount??vl,this.finAckTimeout=t.finAckTimeout??Cl,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 Gn(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),At(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(t){if(this.channel.readyState!=="open")throw new Jt(`Invalid datachannel state - ${this.channel.readyState}`);this.log.trace('sending message, channel state "%s"',this.channel.readyState);try{for(let r of t)this.channel.send(r)}catch(r){this.log.error("error sending datachannel message - %e",r),this.abort(r)}}sendData(t){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(jn.single(It.encode({message:t.subarray()}))),{sentBytes:t.byteLength,canSendMore:this.channel.bufferedAmount<this.maxBufferedAmount})}sendReset(t){try{this.log.error("sending reset - %e",t),this._sendFlag(It.Flag.RESET),this.receivedFinAck?.reject(t)}catch(r){this.log.error("failed to send reset - %e",r)}}async sendCloseWrite(t){this._sendFlag(It.Flag.FIN),t?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let r=t?.signal??AbortSignal.timeout(this.finAckTimeout),n=[At(this.channel,"close",{signal:r}),At(this.channel,"error",{signal:r})];await Promise.any([we(this.receivedFinAck.promise,r),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(t){this._sendFlag(It.Flag.STOP_SENDING),t?.signal?.throwIfAborted()}processIncomingProtobuf(t){let r=It.decode(t);r.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new $(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===It.Flag.FIN&&(this._sendFlag(It.Flag.FIN_ACK),this.onRemoteCloseWrite()),r.flag===It.Flag.RESET&&(this.receivedFinAck?.reject(new wr("The stream was reset")),this.onRemoteReset()),r.flag===It.Flag.STOP_SENDING&&this.onRemoteCloseRead(),r.flag===It.Flag.FIN_ACK&&this.receivedFinAck?.resolve())}_sendFlag(t){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',t.toString(),this.channel.readyState),!1;this.log.trace("sending flag %s",t.toString());let r=It.encode({flag:t}),n=jn.single(r);try{return this._sendMessage(n),!0}catch(o){this.log.error("could not send flag %s - %e",t.toString(),o)}return!1}sendPause(){}sendResume(){}};function Wn(e){let{channel:t,direction:r,isHandshake:n}=e;return new hc({...e,id:`${t.id}`,log:e.log.newScope(`${n===!0?"handshake":r}:${t.id}`),protocol:""})}var $e=class{protocol;peerConnection;metrics;dataChannelOptions;earlyDataChannels;constructor(t){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=t.peerConnection,this.metrics=t.metrics,this.protocol=t.protocol??nc,this.dataChannelOptions=t.dataChannelOptions??{},this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(t){this.earlyDataChannels.push(t.channel)}createStreamMuxer(t){return this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new dc(t,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,earlyDataChannels:this.earlyDataChannels})}},dc=class extends ps{peerConnection;dataChannelOptions;constructor(t,r){super(t,{...r,name:"muxer"}),this.peerConnection=r.peerConnection,this.protocol=r.protocol??nc,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(t){if(this.log("incoming datachannel with channel id %d, protocol %s and status %s",t.id,t.protocol,t.readyState),t.label==="init"){this.log.trace("closing init channel %d",t.id),t.close();return}let r=Wn({...this.streamOptions,...this.dataChannelOptions,channel:t,direction:"inbound",log:this.log});this.onRemoteStream(r)}async onCreateStream(t){let r=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",r.id,t?.protocol),Wn({...t,...this.dataChannelOptions,channel:r,direction:"outbound",log:this.log})}onData(){}};var pc=class extends ds{peerConnection;constructor(t){super(t),this.peerConnection=t.peerConnection;let r=t.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(t){return{sentBytes:t.byteLength,canSendMore:!0}}async sendClose(t){this.peerConnection.close(),t?.signal?.throwIfAborted()}sendReset(){this.peerConnection.close()}sendPause(){}sendResume(){}},Yn=e=>new pc(e);async function mc(e){return e=e??{},typeof e=="function"&&(e=await e()),e.iceServers=e.iceServers??Sl.map(t=>({urls:[t]})),e}var Bl=(e=32)=>Al+[...Array(e)].map(()=>rc.at(Math.floor(Math.random()*rc.length))).join("");var _s=globalThis.RTCPeerConnection,Cs=globalThis.RTCSessionDescription,Dl=globalThis.RTCIceCandidate;var Mt=class extends Event{type;detail;constructor(t,r){super(t),this.type=t,this.detail=r}};var ze=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},Vt=class extends ze{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var Ls=class extends ze{constructor(t,r){super(`Invalid fingerprint "${t}" within ${r}`),this.name="WebRTC/InvalidFingerprintError"}};var Ts=class extends ze{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Is=class extends ze{constructor(t){super(`unsupported hash algorithm code: ${t} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var Nt;(function(e){let t;(function(a){a.SDP_OFFER="SDP_OFFER",a.SDP_ANSWER="SDP_ANSWER",a.ICE_CANDIDATE="ICE_CANDIDATE"})(t=e.Type||(e.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=()=>cr(r)})(t=e.Type||(e.Type={}));let n;e.codec=()=>(n==null&&(n=Me((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),e.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 p=a.uint32();switch(p>>>3){case 1:{u.type=e.Type.codec().decode(a);break}case 2:{u.data=a.string();break}default:{a.skipType(p&7);break}}}return u},function*(a,c,f,u={}){let l=c==null?a.len:a.pos+c;for(;a.pos<l;){let p=a.uint32();switch(p>>>3){case 1:{yield{field:`${f}.type`,value:e.Type.codec().decode(a)};break}case 2:{yield{field:`${f}.data`,value:a.string()};break}default:{a.skipType(p&7);break}}}})),n);function o(a){return Fe(a,e.codec())}e.encode=o;function s(a,c){return Ue(a,e.codec(),c)}e.decode=s;function i(a,c){return ke(a,e.codec(),c)}e.stream=i})(Nt||(Nt={}));var Bs=async(e,t,r)=>{try{let n=Promise.withResolvers();for(s0(e,n);;){let o=await Promise.race([n.promise,t.read({signal:r.signal})]);if(o==null){r.signal?.throwIfAborted();break}if(o.type!==Nt.Type.ICE_CANDIDATE)throw new ho("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){r.onProgress?.(new Mt("webrtc:end-of-ice-candidates")),r.log.trace("end-of-candidates received");continue}let i=new Dl(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{r.onProgress?.(new Mt("webrtc:add-ice-candidate",i.candidate)),await e.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&&e.connectionState!=="connected")throw n}};function s0(e,t){if(e.connectionState==="connected"){t.resolve();return}e.onconnectionstatechange=r=>{switch(e.connectionState){case"connected":t.resolve();break;case"failed":case"closed":t.reject(new ao(`RTCPeerConnection connection state became "${e.connectionState}"`));break;default:break}}}function Ds(e){let t;for(let r of e.getComponents())r.name==="p2p"&&(t=kr(r.value??""));if(t==null)throw new fo("Remote peerId must be present in multiaddr");return t}async function Rl({rtcConfiguration:e,dataChannel:t,signal:r,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:f}){let{circuitAddress:u,targetPeer:l}=Pl(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing circuit address: %a",u);let p=s.getConnections(l),d;p.length===0?(f?.(new Mt("webrtc:dial-relay")),d=await i.dial(u,{signal:r,onProgress:f})):(f?.(new Mt("webrtc:reuse-relay-connection")),d=p[0]),f?.(new Mt("webrtc:open-signaling-stream"));let g=await d.newStream($n,{signal:r,runOnLimitedConnection:!0}),S=bs(g).pb(Nt),h=new _s(e);h.addEventListener("connectionstatechange",()=>{h.connectionState==="closed"&&h.close()});let y=new $e({peerConnection:h,dataChannelOptions:t});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 R=JSON.stringify(P?.toJSON()??null);a.trace("initiator sending ICE candidate %o",P),S.write({type:Nt.Type.ICE_CANDIDATE,data:R},{signal:r}).catch(I=>{a.error("error sending ICE candidate - %e",I)})},h.onicecandidateerror=P=>{a.error("initiator ICE candidate error",P)};let L=await h.createOffer().catch(P=>{throw a.error("could not execute createOffer - %e",P),new Vt("Failed to set createOffer")});a.trace("initiator send SDP offer %s",L.sdp),f?.(new Mt("webrtc:send-sdp-offer")),await S.write({type:Nt.Type.SDP_OFFER,data:L.sdp},{signal:r}),await h.setLocalDescription(L).catch(P=>{throw a.error("could not execute setLocalDescription - %e",P),new Vt("Failed to set localDescription")}),f?.(new Mt("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let O=await S.read({signal:r});if(O.type!==Nt.Type.SDP_ANSWER)throw new Vt("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",O.data);let D=new Cs({type:"answer",sdp:O.data});return await h.setRemoteDescription(D).catch(P=>{throw a.error("could not execute setRemoteDescription - %e",P),new Vt("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),f?.(new Mt("webrtc:read-ice-candidates")),await Bs(h,S,{direction:"initiator",signal:r,log:a,onProgress:f}),a.trace("initiator connected"),v.readyState!=="open"&&(a.trace("wait for init channel to open"),await At(v,"open",{signal:r})),a.trace("closing init channel"),v.close(),a.trace("waiting for init channel to close"),await At(v,"close",{signal:r}),f?.(new Mt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await g.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(),g.abort(v),v}finally{h.onicecandidate=null,h.onicecandidateerror=null}}var Ol=ot(xl.matchers[0],nt(290)),Rs=class e extends Ee{transportManager;shutdownController;events;constructor(t,r){super(),this.transportManager=t.transportManager,this.events=t.events,this.shutdownController=r.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(t){t.detail.getAddrs().filter(n=>Ol.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(t=>!(t instanceof e)).map(t=>t.getAddrs().filter(r=>Ol.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 Nl(e,t,{peerConnection:r,signal:n,log:o}){o.trace("new inbound signaling stream");let s=bs(e).pb(Nt);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 p=JSON.stringify(l?.toJSON()??null);o.trace("recipient sending ICE candidate %s",p),s.write({type:Nt.Type.ICE_CANDIDATE,data:p},{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!==Nt.Type.SDP_OFFER)throw new Vt(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let f=new Cs({type:"offer",sdp:c.data});await r.setRemoteDescription(f).catch(l=>{throw o.error("could not execute setRemoteDescription - %e",l),new Vt("Failed to set remoteDescription")});let u=await r.createAnswer().catch(l=>{throw o.error("could not execute createAnswer - %e",l),new Vt("Failed to create answer")});o.trace("recipient send SDP answer %s",u.sdp),await s.write({type:Nt.Type.SDP_ANSWER,data:u.sdp},{signal:n}),await r.setLocalDescription(u).catch(l=>{throw o.error("could not execute setLocalDescription - %e",l),new Vt("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await Bs(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",t.remoteAddr,c),r.close(),c;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",t.remoteAddr,c)}let i=Ds(t.remoteAddr),a=$r(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var Ps=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,r={}){this.components=t,this.init=r,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[yo]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Er]=["@libp2p/transport"];[Qc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle($n,(t,r)=>{let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(t,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($n),this._started=!1}createListener(t){return new Rs(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(El.exactMatch)}dialFilter(t){return this.listenFilter(t)}async dial(t,r){this.log.trace("dialing address: %a",t);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await Rl({rtcConfiguration:await mc(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:t,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=Yn({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:Ds(t),muxerFactory:s,onProgress:r.onProgress,signal:r.signal});return this._closeOnShutdown(o,i),a}async _onProtocol(t,r,n){let o=new _s(await mc(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{o.connectionState==="closed"&&o.close()});let s=new $e({peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i,remotePeer:a}=await Nl(t,r,{peerConnection:o,signal:n,log:this.log});await t.close({signal:n});let c=Yn({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(),t.abort(i),i}}_closeOnShutdown(t,r){let n=()=>{r.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection - %e",o)})};this.shutdownController.signal.addEventListener("abort",n),t.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function Pl(e){let t=e.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(t==null)throw new G("Destination peer id was missing");return{circuitAddress:$r(e.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:kr(t)}}var Yr=!!globalThis.process?.env?.DUMP_SESSION_KEYS,gc=16;function i0(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Os(e){if(typeof e!="boolean")throw new TypeError(`boolean expected, not ${e}`)}function Xr(e){if(typeof e!="number")throw new TypeError("number expected, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError("positive integer expected, got "+e)}function gt(e,t,r=""){let n=i0(e),o=e?.length,s=t!==void 0;if(!n||s&&o!==t){let i=r&&`"${r}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return e}function yc(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ul(e,t,r=!1){gt(e,void 0,"output");let n=t.outputLen;if(e.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(r&&!Zr(e))throw new Error("invalid output, must be aligned")}function se(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Zt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function a0(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var dr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,c0=e=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255;var f0=e=>{for(let t=0;t<e.length;t++)e[t]=c0(e[t]);return e},xe=dr?e=>e:f0;function Fl(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function kl(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function Ml(e,t,r){let n=t,o=r||(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(e),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}var Kl=(e,t)=>{function r(n,...o){if(gt(n,void 0,"key"),e.nonceLength!==void 0){let u=o[0];gt(u,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let s=e.tagLength;s&&o[1]!==void 0&&gt(o[1],void 0,"AAD");let i=t(n,...o),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");gt(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,gt(u),a(i.encrypt.length,l),i.encrypt(u,l)},decrypt(u,l){if(gt(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,e),r};function Xn(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if(gt(t,void 0,"output"),t.length!==e)throw new Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&!Zr(t))throw new Error("invalid output, must be aligned");return t}function Hl(e,t,r){Xr(e),Xr(t),Os(r);let n=new Uint8Array(16),o=a0(n);return o.setBigUint64(0,BigInt(t),r),o.setBigUint64(8,BigInt(e),r),n}function Zr(e){return e.byteOffset%4===0}function Qr(e){return Uint8Array.from(gt(e))}var $l=e=>Uint8Array.from(e.split(""),t=>t.charCodeAt(0)),u0=xe(se($l("expand 16-byte k"))),l0=xe(se($l("expand 32-byte k")));function W(e,t){return e<<t|e>>>32-t}var Zn=64,h0=16,bc=2**32-1,Vl=Uint32Array.of();function d0(e,t,r,n,o,s,i,a){let c=o.length,f=new Uint8Array(Zn),u=se(f),l=dr&&Zr(o)&&Zr(s),p=l?se(o):Vl,d=l?se(s):Vl;if(!dr){for(let g=0;g<c;i++){if(e(t,r,n,u,i,a),xe(u),i>=bc)throw new Error("arx: counter overflow");let S=Math.min(Zn,c-g);for(let h=0,y;h<S;h++)y=g+h,s[y]=o[y]^f[h];g+=S}return}for(let g=0;g<c;i++){if(e(t,r,n,u,i,a),i>=bc)throw new Error("arx: counter overflow");let S=Math.min(Zn,c-g);if(l&&S===Zn){let h=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let y=0,v;y<h0;y++)v=h+y,d[v]=p[v]^u[y];g+=Zn;continue}for(let h=0,y;h<S;h++)y=g+h,s[y]=o[y]^f[h];g+=S}}function zl(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Fl({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return Xr(o),Xr(i),Os(s),Os(r),(a,c,f,u,l=0)=>{gt(a,void 0,"key"),gt(c,void 0,"nonce"),gt(f,void 0,"data");let p=f.length;if(u=Xn(p,u,!1),Xr(l),l<0||l>=bc)throw new Error("arx: counter overflow");let d=[],g=a.length,S,h;if(g===32)d.push(S=Qr(a)),h=l0;else if(g===16&&r)S=new Uint8Array(32),S.set(a),S.set(a,16),h=u0,d.push(S);else throw gt(a,32,"arx key"),new Error("invalid key size");(!dr||!Zr(c))&&d.push(c=Qr(c));let y=se(S);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let O=c.subarray(0,16);if(dr)n(h,y,se(O),y);else{let D=xe(Uint32Array.from(h));n(D,y,se(O),y),Zt(D),xe(y)}c=c.subarray(16)}else dr||xe(y);let v=16-o;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let O=new Uint8Array(12);O.set(c,s?0:12-c.length),c=O,d.push(c)}let L=xe(se(c));try{return d0(e,h,y,L,f,u,l,i),u}finally{Zt(...d)}}}function vt(e,t){return e[t++]&255|(e[t++]&255)<<8}var wc=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(t){t=Qr(gt(t,32,"key"));let r=vt(t,0),n=vt(t,2),o=vt(t,4),s=vt(t,6),i=vt(t,8),a=vt(t,10),c=vt(t,12),f=vt(t,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]=vt(t,16+2*u)}process(t,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],p=i[5],d=i[6],g=i[7],S=i[8],h=i[9],y=vt(t,r+0),v=vt(t,r+2),L=vt(t,r+4),O=vt(t,r+6),D=vt(t,r+8),P=vt(t,r+10),R=vt(t,r+12),I=vt(t,r+14),N=s[0]+(y&8191),k=s[1]+((y>>>13|v<<3)&8191),U=s[2]+((v>>>10|L<<6)&8191),m=s[3]+((L>>>7|O<<9)&8191),A=s[4]+((O>>>4|D<<12)&8191),E=s[5]+(D>>>1&8191),w=s[6]+((D>>>14|P<<2)&8191),b=s[7]+((P>>>11|R<<5)&8191),_=s[8]+((R>>>8|I<<8)&8191),C=s[9]+(I>>>5|o),x=0,T=x+N*a+k*(5*h)+U*(5*S)+m*(5*g)+A*(5*d);x=T>>>13,T&=8191,T+=E*(5*p)+w*(5*l)+b*(5*u)+_*(5*f)+C*(5*c),x+=T>>>13,T&=8191;let B=x+N*c+k*a+U*(5*h)+m*(5*S)+A*(5*g);x=B>>>13,B&=8191,B+=E*(5*d)+w*(5*p)+b*(5*l)+_*(5*u)+C*(5*f),x+=B>>>13,B&=8191;let F=x+N*f+k*c+U*a+m*(5*h)+A*(5*S);x=F>>>13,F&=8191,F+=E*(5*g)+w*(5*d)+b*(5*p)+_*(5*l)+C*(5*u),x+=F>>>13,F&=8191;let H=x+N*u+k*f+U*c+m*a+A*(5*h);x=H>>>13,H&=8191,H+=E*(5*S)+w*(5*g)+b*(5*d)+_*(5*p)+C*(5*l),x+=H>>>13,H&=8191;let K=x+N*l+k*u+U*f+m*c+A*a;x=K>>>13,K&=8191,K+=E*(5*h)+w*(5*S)+b*(5*g)+_*(5*d)+C*(5*p),x+=K>>>13,K&=8191;let J=x+N*p+k*l+U*u+m*f+A*c;x=J>>>13,J&=8191,J+=E*a+w*(5*h)+b*(5*S)+_*(5*g)+C*(5*d),x+=J>>>13,J&=8191;let tt=x+N*d+k*p+U*l+m*u+A*f;x=tt>>>13,tt&=8191,tt+=E*c+w*a+b*(5*h)+_*(5*S)+C*(5*g),x+=tt>>>13,tt&=8191;let et=x+N*g+k*d+U*p+m*l+A*u;x=et>>>13,et&=8191,et+=E*f+w*c+b*a+_*(5*h)+C*(5*S),x+=et>>>13,et&=8191;let Y=x+N*S+k*g+U*d+m*p+A*l;x=Y>>>13,Y&=8191,Y+=E*u+w*f+b*c+_*a+C*(5*h),x+=Y>>>13,Y&=8191;let it=x+N*h+k*S+U*g+m*d+A*p;x=it>>>13,it&=8191,it+=E*l+w*u+b*f+_*c+C*a,x+=it>>>13,it&=8191,x=(x<<2)+x|0,x=x+T|0,T=x&8191,x=x>>>13,B+=x,s[0]=T,s[1]=B,s[2]=F,s[3]=H,s[4]=K,s[5]=J,s[6]=tt,s[7]=et,s[8]=Y,s[9]=it}finalize(){let{h:t,pad:r}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[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++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+r[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+r[a]|0)+(i>>>16)|0,t[a]=i&65535;Zt(n)}update(t){yc(this),gt(t),t=Qr(t);let{buffer:r,blockLen:n}=this,o=t.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(t,s);continue}r.set(t.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,Zt(this.h,this.r,this.buffer,this.pad)}digestInto(t){yc(this),Ul(t,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++)t[s++]=n[i]>>>0,t[s++]=n[i]>>>8}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}},ql=Ml(32,e=>new wc(e));function p0(e,t,r,n,o,s=20){let i=e[0],a=e[1],c=e[2],f=e[3],u=t[0],l=t[1],p=t[2],d=t[3],g=t[4],S=t[5],h=t[6],y=t[7],v=o,L=r[0],O=r[1],D=r[2],P=i,R=a,I=c,N=f,k=u,U=l,m=p,A=d,E=g,w=S,b=h,_=y,C=v,x=L,T=O,B=D;for(let H=0;H<s;H+=2)P=P+k|0,C=W(C^P,16),E=E+C|0,k=W(k^E,12),P=P+k|0,C=W(C^P,8),E=E+C|0,k=W(k^E,7),R=R+U|0,x=W(x^R,16),w=w+x|0,U=W(U^w,12),R=R+U|0,x=W(x^R,8),w=w+x|0,U=W(U^w,7),I=I+m|0,T=W(T^I,16),b=b+T|0,m=W(m^b,12),I=I+m|0,T=W(T^I,8),b=b+T|0,m=W(m^b,7),N=N+A|0,B=W(B^N,16),_=_+B|0,A=W(A^_,12),N=N+A|0,B=W(B^N,8),_=_+B|0,A=W(A^_,7),P=P+U|0,B=W(B^P,16),b=b+B|0,U=W(U^b,12),P=P+U|0,B=W(B^P,8),b=b+B|0,U=W(U^b,7),R=R+m|0,C=W(C^R,16),_=_+C|0,m=W(m^_,12),R=R+m|0,C=W(C^R,8),_=_+C|0,m=W(m^_,7),I=I+A|0,x=W(x^I,16),E=E+x|0,A=W(A^E,12),I=I+A|0,x=W(x^I,8),E=E+x|0,A=W(A^E,7),N=N+k|0,T=W(T^N,16),w=w+T|0,k=W(k^w,12),N=N+k|0,T=W(T^N,8),w=w+T|0,k=W(k^w,7);let F=0;n[F++]=i+P|0,n[F++]=a+R|0,n[F++]=c+I|0,n[F++]=f+N|0,n[F++]=u+k|0,n[F++]=l+U|0,n[F++]=p+m|0,n[F++]=d+A|0,n[F++]=g+E|0,n[F++]=S+w|0,n[F++]=h+b|0,n[F++]=y+_|0,n[F++]=v+C|0,n[F++]=L+x|0,n[F++]=O+T|0,n[F++]=D+B|0}var m0=zl(p0,{counterRight:!1,counterLength:4,allowShortKeys:!1});var g0=new Uint8Array(16),jl=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(g0.subarray(r))},y0=new Uint8Array(32);function Gl(e,t,r,n,o){o!==void 0&&gt(o,void 0,"AAD");let s=e(t,r,y0),i=Hl(n.length,o?o.length:0,!0),a=ql.create(s);o&&jl(a,o),jl(a,n),a.update(i);let c=a.digest();return Zt(s,i),c}var b0=e=>(t,r,n)=>({encrypt(s,i){let a=s.length;i=Xn(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);e(t,r,c,c,1);let f=Gl(e,t,r,c,n);return i.set(f,a),Zt(f),i},decrypt(s,i){i=Xn(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),f=Gl(e,t,r,a,n);if(!kl(c,f))throw Zt(f),new Error("invalid tag");return i.set(s.subarray(0,-16)),e(t,r,i,i,1),Zt(f),i}}),xc=Kl({blockSize:64,nonceLength:12,tagLength:16},b0(m0));function Yl(e,t,r){return Xe(e),r===void 0&&(r=new Uint8Array(e.outputLen)),On(e,r,t)}var Ec=Uint8Array.of(0),Wl=Uint8Array.of();function Xl(e,t,r,n=32){Xe(e),te(n,"length"),_t(t,void 0,"prk");let o=e.outputLen;if(t.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=Wl:_t(r,void 0,"info");let i=new Uint8Array(s*o),a=On.create(e,t),c=a._cloneInto(),f=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)Ec[0]=u+1,c.update(u===0?Wl:f).update(r).update(Ec).digestInto(f),i.set(f,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),qt(f,Ec),i.slice(0,n)}var Sc={hashSHA256(e){return re(e.subarray())},getHKDF(e,t){let r=Yl(re,t,e),o=Xl(re,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 e=_n.utils.randomSecretKey();return{publicKey:_n.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed(e){return{publicKey:_n.getPublicKey(e),privateKey:e}},generateX25519SharedKey(e,t){return _n.getSharedSecret(e.subarray(),t.subarray())},chaCha20Poly1305Encrypt(e,t,r,n){return xc(n,t,r).encrypt(e.subarray())},chaCha20Poly1305Decrypt(e,t,r,n,o){return xc(n,t,r).decrypt(e.subarray(),o)}};var Zl=Sc;function Ql(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}var Jr=e=>{let t=at(2);return t[0]=e>>8,t[1]=e,t};Jr.bytes=2;var tn=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};tn.bytes=2;function Jl(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Ac(e,t){!t.enabled||!Yr||(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${V(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${V(e.privateKey,"hex")}`)):t("Missing local static keys."))}function vc(e,t){!t.enabled||!Yr||(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${V(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${V(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function th(e,t){!t.enabled||!Yr||t(e?`REMOTE_STATIC_PUBLIC_KEY ${V(e.subarray(),"hex")}`:"Missing remote static public key.")}function _c(e,t){!t.enabled||!Yr||t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${V(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Cc(e,t,r){!r.enabled||!Yr||(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&V(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&V(t.k,"hex")}`))}var en=class e extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=e.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var w0=0,x0=4294967295,E0="Cipherstate has reached maximum n, a new handshake must be performed",Ns=class{n;bytes;view;constructor(t=w0){this.n=t,this.bytes=pt(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>x0)throw new Error(E0)}};var pr=pt(0),rn=class{k;n;crypto;constructor(t,r=void 0,n=0){this.crypto=t,this.k=r,this.n=new Ns(n)}hasKey(){return!!this.k}encryptWithAd(t,r){if(!this.hasKey())return r;this.n.assertValue();let n=this.crypto.encrypt(r,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,r,n){if(!this.hasKey())return r;this.n.assertValue();let o=this.crypto.decrypt(r,this.n.getBytes(),t,this.k,n);return this.n.increment(),o}},Lc=class{cs;ck;h;crypto;constructor(t,r){this.crypto=t;let n=q(r,"utf-8");this.h=S0(t,n),this.ck=this.h,this.cs=new rn(t)}mixKey(t){let[r,n]=this.crypto.hkdf(this.ck,t);this.ck=r,this.cs=new rn(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new $(this.h,t))}encryptAndHash(t){let r=this.cs.encryptWithAd(this.h,t);return this.mixHash(r),r}decryptAndHash(t){let r=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),r}split(){let[t,r]=this.crypto.hkdf(this.ck,pr);return[new rn(this.crypto,t),new rn(this.crypto,r)]}},Tc=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:r,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:f}=t;this.crypto=r,this.ss=new Lc(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 t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.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(t,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<r+32)throw new Error("message is not long enough");this.re=t.sublist(r,r+32),this.ss.mixHash(this.re)}readS(t,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(t.byteLength<r+n)throw new Error("message is not long enough");let o=t.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Qn=class extends Tc{writeMessageA(t){return new $(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let r=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new $(r,n,this.ss.encryptAndHash(t))}writeMessageC(t){let r=this.writeS();return this.writeSE(),new $(r,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(r){throw new en(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let r=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+r))}catch(r){throw new en(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(t){try{let r=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(r))}catch(r){throw new en(`handshake stage 2 validation fail: ${r.message}`)}}};function S0(e,t){if(t.length<=32){let r=pt(32);return r.set(t),r}else return e.hash(t)}var Ic=new Float32Array([-0]),qe=new Uint8Array(Ic.buffer);function eh(e,t,r){Ic[0]=e,t[r]=qe[0],t[r+1]=qe[1],t[r+2]=qe[2],t[r+3]=qe[3]}function rh(e,t){return qe[0]=e[t],qe[1]=e[t+1],qe[2]=e[t+2],qe[3]=e[t+3],Ic[0]}var Bc=new Float64Array([-0]),Bt=new Uint8Array(Bc.buffer);function nh(e,t,r){Bc[0]=e,t[r]=Bt[0],t[r+1]=Bt[1],t[r+2]=Bt[2],t[r+3]=Bt[3],t[r+4]=Bt[4],t[r+5]=Bt[5],t[r+6]=Bt[6],t[r+7]=Bt[7]}function oh(e,t){return Bt[0]=e[t],Bt[1]=e[t+1],Bt[2]=e[t+2],Bt[3]=e[t+3],Bt[4]=e[t+4],Bt[5]=e[t+5],Bt[6]=e[t+6],Bt[7]=e[t+7],Bc[0]}var A0=BigInt(Number.MAX_SAFE_INTEGER),v0=BigInt(Number.MIN_SAFE_INTEGER),Kt=class e{lo;hi;constructor(t,r){this.lo=t|0,this.hi=r|0}toNumber(t=!1){if(!t&&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(t=!1){if(t)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(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return mr;if(t<A0&&t>v0)return this.fromNumber(Number(t));let r=t<0n;r&&(t=-t);let n=t>>32n,o=t-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>sh&&(o=0n,++n>sh&&(n=0n))),new e(Number(o),Number(n))}static fromNumber(t){if(t===0)return mr;let r=t<0;r&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new e(n,o)}static from(t){return typeof t=="number"?e.fromNumber(t):typeof t=="bigint"?e.fromBigInt(t):typeof t=="string"?e.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new e(t.low>>>0,t.high>>>0):mr}},mr=new Kt(0,0);mr.toBigInt=function(){return 0n};mr.zzEncode=mr.zzDecode=function(){return this};mr.length=function(){return 1};var sh=4294967296n;function ih(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:(r&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function ah(e,t,r){if(r-t<1)return"";let o,s=[],i=0,a;for(;t<r;)a=e[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&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 Dc(e,t,r){let n=r,o,s;for(let i=0;i<e.length;++i)o=e.charCodeAt(i),o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=o&63|128):(o&64512)===55296&&((s=e.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=o&63|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=o&63|128);return r-n}function Qt(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Us(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}var Rc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Qt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Qt(this,4);return Us(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Qt(this,4);return Us(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Qt(this,4);let t=rh(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Qt(this,4);let t=oh(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw Qt(this,t);return this.pos+=t,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let t=this.bytes();return ah(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Qt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Qt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Kt(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw Qt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,t}if(this.len-this.pos>4){for(;r<5;++r)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;r<5;++r){if(this.pos>=this.len)throw Qt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Qt(this,8);let t=Us(this.buf,this.pos+=4),r=Us(this.buf,this.pos+=4);return new Kt(t,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Ln(this.buf,this.pos);return this.pos+=rt(t),t}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 Pc(e){return new Rc(e instanceof Uint8Array?e:e.subarray())}function Fs(e,t,r){let n=Pc(e);return t.decode(n,void 0,r)}function Oc(e){let t=e??8192,r=t>>>1,n,o=t;return function(i){if(i<1||i>r)return at(i);o+i>t&&(n=at(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var gr=class{fn;len;next;val;constructor(t,r,n){this.fn=t,this.len=r,this.next=void 0,this.val=n}};function Nc(){}var Fc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},_0=Oc();function C0(e){return globalThis.Buffer!=null?at(e):_0(e)}var to=class{len;head;tail;states;constructor(){this.len=0,this.head=new gr(Nc,0,0),this.tail=this.head,this.states=null}_push(t,r,n){return this.tail=this.tail.next=new gr(t,r,n),this.len+=r,this}uint32(t){return this.len+=(this.tail=this.tail.next=new kc((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(ks,10,Kt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let r=Kt.fromBigInt(t);return this._push(ks,r.length(),r)}uint64Number(t){return this._push(Oe,rt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let r=Kt.fromBigInt(t).zzEncode();return this._push(ks,r.length(),r)}sint64Number(t){let r=Kt.fromNumber(t).zzEncode();return this._push(ks,r.length(),r)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Uc,1,t?1:0)}fixed32(t){return this._push(Jn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let r=Kt.fromBigInt(t);return this._push(Jn,4,r.lo)._push(Jn,4,r.hi)}fixed64Number(t){let r=Kt.fromNumber(t);return this._push(Jn,4,r.lo)._push(Jn,4,r.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(eh,4,t)}double(t){return this._push(nh,8,t)}bytes(t){let r=t.length>>>0;return r===0?this._push(Uc,1,0):this.uint32(r)._push(T0,r,t)}string(t){let r=ih(t);return r!==0?this.uint32(r)._push(Dc,r,t):this._push(Uc,1,0)}fork(){return this.states=new Fc(this),this.head=this.tail=new gr(Nc,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 gr(Nc,0,0),this.len=0),this}ldelim(){let t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=r,this.len+=n),this}finish(){let t=this.head.next,r=C0(this.len),n=0;for(;t!=null;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}};function Uc(e,t,r){t[r]=e&255}function L0(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}var kc=class extends gr{next;constructor(t,r){super(L0,t,r),this.next=void 0}};function ks(e,t,r){for(;e.hi!==0;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}function Jn(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function T0(e,t,r){t.set(e,r)}globalThis.Buffer!=null&&(to.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(I0,t,e),this},to.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(B0,t,e),this});function I0(e,t,r){t.set(e,r)}function B0(e,t,r){e.length<40?Dc(e,t,r):t.utf8Write!=null?t.utf8Write(e,r):t.set(q(e),r)}function Mc(){return new to}function Ms(e,t){let r=Mc();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var eo;(function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(eo||(eo={}));function Kc(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function Ks(e,t){return Kc("message",eo.LENGTH_DELIMITED,e,t)}var ro=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Hs;(function(e){let t;e.codec=()=>(t==null&&(t=Ks((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 ro('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 ro('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(r.string());break}default:{r.skipType(a&7);break}}}return s})),t),e.encode=r=>Ms(r,e.codec()),e.decode=(r,n)=>Fs(r,e.codec(),n)})(Hs||(Hs={}));var no;(function(e){let t;e.codec=()=>(t==null&&(t=Ks((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),Hs.codec().encode(r.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={identityKey:pt(0),identitySig:pt(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=Hs.codec().decode(r,r.uint32(),{limits:o.limits?.extensions});break}default:{r.skipType(a&7);break}}}return s})),t),e.encode=r=>Ms(r,e.codec()),e.decode=(r,n)=>Fs(r,e.codec(),n)})(no||(no={}));async function Vc(e,t,r){let n=await e.sign(uh(t));return no.encode({identityKey:_e(e.publicKey),identitySig:n,extensions:r})}async function $c(e,t,r){try{let n=no.decode(e),o=Nn(n.identityKey);if(r?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${r}`);if(!t)throw new Error("Remote static does not exist");let s=uh(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new so(n.message)}}function uh(e){let t=q("noise-libp2p-static-key:");return e instanceof Uint8Array?Pt([t,e],t.length+e.length):(e.prepend(t),e)}var Hc=class extends Ve{stream;handshake;metrics;decoder;constructor(t,r,n){super({log:t.log,inactivityTimeout:t.inactivityTimeout,maxReadBufferLength:t.maxReadBufferLength,direction:t.direction}),this.stream=t,this.handshake=r,this.metrics=n,this.decoder=new ws({lengthDecoder:tn,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(t){let r=new $;for(let n=0;n<t.byteLength;n+=65519){let o=n+65519;o>t.byteLength&&(o=t.byteLength);let s;t instanceof Uint8Array?s=this.handshake.encrypt(t.subarray(n,o)):s=this.handshake.encrypt(t.sublist(n,o)),this.metrics?.encryptedPackets.increment(),r.append(Jr(s.byteLength)),r.append(s)}return r}decrypt(t){let r=new $;for(let n=0;n<t.byteLength;n+=65535){let o=n+65535;if(o>t.byteLength&&(o=t.byteLength),o-gc<n)throw new Error("Invalid chunk");let s;t instanceof Uint8Array?s=t.subarray(n,o):s=t.sublist(n,o);let i=t.subarray(n,o-gc);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(t){return this.stream.close(t)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(t){this.stream.abort(t)}sendData(t){return{sentBytes:t.byteLength,canSendMore:this.stream.send(this.encrypt(t))}}};function zc(e,t,r){return new Hc(e,t,r)}async function lh(e,t){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=e,u=await Vc(s,a.publicKey,f),l=new Qn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Ac(l.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(l.writeMessageA(pr),t),r.trace("Stage 0 - Initiator finished sending first message."),vc(l.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");let p=l.readMessageB(await n.read(t));r.trace("Stage 1 - Initiator received the message."),_c(l.re,r),th(l.rs,r),r.trace("Initiator going to check remote's signature...");let d=await $c(p,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),t),r.trace("Stage 2 - Initiator sent message with signed payload.");let[g,S]=l.ss.split();return Cc(g,S,r),{payload:d,encrypt:h=>g.encryptWithAd(pr,h),decrypt:(h,y)=>S.decryptWithAd(pr,h,y)}}async function hh(e,t){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=e,u=await Vc(s,a.publicKey,f),l=new Qn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Ac(l.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),l.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),_c(l.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(l.writeMessageB(u),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),vc(l.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");let p=l.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");let d=await $c(p,l.rs,c),[g,S]=l.ss.split();return Cc(g,S,r),{payload:d,encrypt:h=>S.encryptWithAd(pr,h),decrypt:(h,y)=>g.decryptWithAd(pr,h,y)}}var Vs=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(t,r={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=r,{metrics:a}=t;this.components=t,this.log=t.logger.forComponent("libp2p:noise");let c=s??Zl;this.crypto=Ql(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Jl(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??pt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Er]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,r){let n=t.log?.newScope("noise")??this.log,o=ys(t,{lengthEncoder:Jr,lengthDecoder:tn,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=Nn(s.payload.identityKey);return{connection:zc(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:La(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(t){if(t==null||t.length===0)return;let r=this.components.upgrader.getStreamMuxers();if(r!=null)for(let n of t){let o=r.get(n);if(o!=null)return o}if(t.length)throw new io("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(t,r){let n=t.log?.newScope("noise")??this.log,o=ys(t,{lengthEncoder:Jr,lengthDecoder:tn,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=Nn(s.payload.identityKey);return{connection:zc(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:La(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(t,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await lh({connection:t,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(t,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await hh({connection:t,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 dh(e={}){return t=>new Vs(t,e)}var qc=Object.values(Ye).map(e=>e.decoder).reduce((e,t)=>e.or(t)),D0=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function ph(e){return e?.match(D0)?.groups?.fingerprint}function jc(e){let r=e.getComponents().find(n=>n.code===466)?.value;if(r===void 0||r==="")throw new G(`Couldn't find a certhash component of multiaddr: ${e.toString()}`);return r}function R0(e){return $t.decode(qc.decode(e))}function P0(e){let t=R0(jc(e)),r=O0(t.code),n=t.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new Ls(n,e.toString());return`${r} ${o.join(":").toUpperCase()}`}function mh(e){let t=e.split(":").map(o=>parseInt(o,16)),r=Uint8Array.from(t),n=Rt(ce.code,r);return $r(`/certhash/${ln.encode(n.bytes)}`)}function O0(e){switch(e){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new Is(e)}}function gh(e,t){let{host:r,port:n,type:o}=oc(e);if(o!=="ip4"&&o!=="ip6")throw new G(`Multiaddr ${e} was not an IPv4 or IPv6 address`);let s=P0(e);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
@@ -37,7 +37,7 @@ a=end-of-candidates
37
37
  `:`
38
38
  `;try{e.sdp=e.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
39
39
  a=ice-ufrag:`+t+r).replace(/\na=ice-pwd:[^\n]*\n/,`
40
- a=ice-pwd:`+t+r)}catch{}return e}var Wc=q("libp2p-webrtc-noise:");function wh(e,t,r){let n=e.trim().toLowerCase().replaceAll(":",""),o=q(n,"hex"),s=Rt(ce.code,o),i=qc.decode(jc(t)),a=Wc.byteLength+s.bytes.byteLength+i.byteLength;return r==="server"?Pt([Wc,i,s.bytes],a):Pt([Wc,s.bytes,i],a)}function O0(e,t){return e.role==="server"}async function xh(e,t,r,n){let o=e.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let l=await e.createOffer();n.log.trace("client created local offer %s",l.sdp);let p=Gc(l,r);n.log.trace("client setting local offer %s",p.sdp),await e.setLocalDescription(p);let d=gh(n.remoteAddr,r);n.log.trace("client setting server description %s",d.sdp),await e.setRemoteDescription(d)}else{let l=yh(n.remoteAddr,r);n.log.trace("server setting client %s %s",l.type,l.sdp),await e.setRemoteDescription(l),n.log.trace("server creating local answer");let p=await e.createAnswer();n.log.trace("server created local answer");let d=Gc(p,r);n.log.trace("server setting local description %s",p.sdp),await e.setLocalDescription(d)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await At(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),O0(n,e)){let l=e.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(mh(l))}let s=ph(e.localDescription?.sdp);if(s==null)throw new ze("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=wh(s,n.remoteAddr,n.role),a=dh({prologueBytes:i})(n),c=Wn({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),f=Yn({peerConnection:e,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(e.addEventListener("connectionstatechange",()=>{switch(e.connectionState){case"failed":case"disconnected":case"closed":f.close().catch(l=>{n.log.error("error closing connection - %e",l),f.abort(l)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let l=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:l.remotePeer,muxerFactory:t,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:t,signal:n.signal})}catch(s){throw o.close(),e.close(),s}}async function Eh(e,t,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 $e({peerConnection:s,metrics:r.events,dataChannelOptions:r.dataChannel});return{peerConnection:s,muxerFactory:i}}var $s=class{log;metrics;components;init;constructor(t,r={}){this.log=t.logger.forComponent("libp2p:webrtc-direct"),this.components=t,this.init=r,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[yo]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Er]=["@libp2p/transport"];async dial(t,r){this.log("dial %a",t),r.signal.throwIfAborted();let n,o=t.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=kr(o));let s=Bl(),{peerConnection:i,muxerFactory:a}=await Eh("client",s,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await xh(i,a,s,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:r.signal,remoteAddr:t,dataChannel:this.init.dataChannel,upgrader:r.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw i.close(),c}}createListener(t){throw new Ts("WebRTCDirectTransport.createListener")}listenFilter(t){return[]}dialFilter(t){return t.filter(bl.exactMatch)}};function N0(e){return t=>new $s(t,e)}function U0(e){return t=>new Ps(t,e)}return Ch(F0);})();
40
+ a=ice-pwd:`+t+r)}catch{}return e}var Wc=q("libp2p-webrtc-noise:");function wh(e,t,r){let n=e.trim().toLowerCase().replaceAll(":",""),o=q(n,"hex"),s=Rt(ce.code,o),i=qc.decode(jc(t)),a=Wc.byteLength+s.bytes.byteLength+i.byteLength;return r==="server"?Pt([Wc,i,s.bytes],a):Pt([Wc,s.bytes,i],a)}function N0(e,t){return e.role==="server"}async function xh(e,t,r,n){let o=e.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let l=await e.createOffer();n.log.trace("client created local offer %s",l.sdp);let p=Gc(l,r);n.log.trace("client setting local offer %s",p.sdp),await e.setLocalDescription(p);let d=gh(n.remoteAddr,r);n.log.trace("client setting server description %s",d.sdp),await e.setRemoteDescription(d)}else{let l=yh(n.remoteAddr,r);n.log.trace("server setting client %s %s",l.type,l.sdp),await e.setRemoteDescription(l),n.log.trace("server creating local answer");let p=await e.createAnswer();n.log.trace("server created local answer");let d=Gc(p,r);n.log.trace("server setting local description %s",p.sdp),await e.setLocalDescription(d)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await At(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),N0(n,e)){let l=e.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(mh(l))}let s=ph(e.localDescription?.sdp);if(s==null)throw new ze("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=wh(s,n.remoteAddr,n.role),a=dh({prologueBytes:i})(n),c=Wn({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),f=Yn({peerConnection:e,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(e.addEventListener("connectionstatechange",()=>{switch(e.connectionState){case"failed":case"disconnected":case"closed":f.close().catch(l=>{n.log.error("error closing connection - %e",l),f.abort(l)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let l=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:l.remotePeer,muxerFactory:t,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:t,signal:n.signal})}catch(s){throw o.close(),e.close(),s}}async function Eh(e,t,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 $e({peerConnection:s,metrics:r.events,dataChannelOptions:r.dataChannel});return{peerConnection:s,muxerFactory:i}}var $s=class{log;metrics;components;init;constructor(t,r={}){this.log=t.logger.forComponent("libp2p:webrtc-direct"),this.components=t,this.init=r,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[yo]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Er]=["@libp2p/transport"];async dial(t,r){this.log("dial %a",t),r.signal.throwIfAborted();let n,o=t.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=kr(o));let s=Bl(),{peerConnection:i,muxerFactory:a}=await Eh("client",s,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await xh(i,a,s,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:r.signal,remoteAddr:t,dataChannel:this.init.dataChannel,upgrader:r.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw i.close(),c}}createListener(t){throw new Ts("WebRTCDirectTransport.createListener")}listenFilter(t){return[]}dialFilter(t){return t.filter(bl.exactMatch)}};function U0(e){return t=>new $s(t,e)}function F0(e){return t=>new Ps(t,e)}return Ch(k0);})();
41
41
  /*! Bundled license information:
42
42
 
43
43
  @noble/curves/utils.js: