@libp2p/webrtc 5.0.18 → 5.0.19-6ddc1b80e
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/index.min.js +1 -1
- package/package.json +8 -8
- package/dist/typedoc-urls.json +0 -12
package/dist/index.min.js
CHANGED
@@ -3,7 +3,7 @@
|
|
3
3
|
`).map(o=>` ${o}`).join(`
|
4
4
|
`));let e=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return t.length?`${e} :
|
5
5
|
${t.join(`
|
6
|
-
`)}`:`${e} :`}};Ml=$e;D.Constructed=Ml;$e.NAME="CONSTRUCTED";var Ao=class extends Nt{fromBER(t,e,n){return e}toBER(t){return ne}};Ao.override="EndOfContentValueBlock";var Vl,So=class extends St{constructor(t={}){super(t,Ao),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Vl=So;D.EndOfContent=Vl;So.NAME=dn;var Fl,Nr=class extends St{constructor(t={}){super(t,Nt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(t,e,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,e+n>t.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):e+n}toBER(t,e){let n=new ArrayBuffer(2);if(!t){let o=new Uint8Array(n);o[0]=5,o[1]=0}return e&&e.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Fl=Nr;D.Null=Fl;Nr.NAME="NULL";var Bo=class extends Se(Nt){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=z.BufferSourceConverter.toUint8Array(e.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}get value(){for(let t of this.valueHexView)if(t>0)return!0;return!1}set value(t){this.valueHexView[0]=t?255:0}fromBER(t,e,n){let o=z.BufferSourceConverter.toUint8Array(t);return Ae(this,o,e,n)?(this.valueHexView=o.subarray(e,e+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,ua.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Bo.NAME="BooleanValueBlock";var Kl,Io=class extends St{constructor(t={}){super(t,Bo),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Kl=Io;D.Boolean=Kl;Io.NAME="BOOLEAN";var Co=class extends Se(ae){constructor({isConstructed:t=!1,...e}={}){super(e),this.isConstructed=t}fromBER(t,e,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=ae.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===dn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Dl)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(t,e,n),this.blockLength=n;return o}toBER(t,e){return this.isConstructed?ae.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Co.NAME="OctetStringValueBlock";var $l,ko=class r extends St{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Co),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(t,e,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),e;if(!this.valueBlock.isConstructed){let s=(t instanceof ArrayBuffer?new Uint8Array(t):t).subarray(e,e+n);try{if(s.byteLength){let i=rs(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(t,e,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?$e.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${z.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let t=[];for(let e of this.valueBlock.value)e instanceof r&&t.push(e.valueBlock.valueHexView);return z.BufferSourceConverter.concat(t)}};$l=ko;D.OctetString=$l;ko.NAME=Dl;var To=class extends Se(ae){constructor({unusedBits:t=0,isConstructed:e=!1,...n}={}){super(n),this.unusedBits=t,this.isConstructed=e,this.blockLength=this.valueHexView.byteLength}fromBER(t,e,n){if(!n)return e;let o=-1;if(this.isConstructed){if(o=ae.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===dn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Pl)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let s=z.BufferSourceConverter.toUint8Array(t);if(!Ae(this,s,e,n))return-1;let i=s.subarray(e,e+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=rs(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,e+n}toBER(t,e){if(this.isConstructed)return ae.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ne;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};To.NAME="BitStringValueBlock";var Wl,Lr=class extends St{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},To),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(t,e,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(t,e,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return $e.prototype.onAsciiEncoding.call(this);{let t=[],e=this.valueBlock.valueHexView;for(let o of e)t.push(o.toString(2).padStart(8,"0"));let n=t.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Wl=Lr;D.BitString=Wl;Lr.NAME=Pl;var ql;function um(r,t){let e=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<i?i:c,f=0;for(let d=u;d>=0;d--,f++){switch(!0){case f<a.length:l=s[i-f]+a[c-f]+e[0];break;default:l=s[i-f]+e[0]}switch(e[0]=l/10,!0){case f>=s.length:s=go(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return e[0]>0&&(s=go(e,s)),s}function Ul(r){if(r>=fn.length)for(let t=fn.length;t<=r;t++){let e=new Uint8Array([0]),n=fn[t-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+e[0]]);e[0]=s[0]/10,n[o]=s[0]%10}e[0]>0&&(n=go(e,n)),fn.push(n)}return fn[r]}function fm(r,t){let e=0,n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=s[i-u]-a[c-u]-e,!0){case l<0:e=1,s[i-u]=l+10;break;default:e=0,s[i-u]=l}if(e>0)for(let f=i-c+1;f>=0;f--,u++)if(l=s[i-u]-e,l<0)e=1,s[i-u]=l+10;else{e=0,s[i-u]=l;break}return s.slice()}var pn=class extends Se(Nt){constructor({value:t,...e}={}){super(e),this._valueDec=0,e.valueHex&&this.setValueHex(),t!==void 0&&(this.valueDec=t)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=ua.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Ll(t))}get valueDec(){return this._valueDec}fromDER(t,e,n,o=0){let s=this.fromBER(t,e,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(t=!1){let e=this.valueHexView;switch(!0){case(e[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(e,1),this.valueHexView=n}break;case(e[0]===0&&(e[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(t)}fromBER(t,e,n){let o=super.fromBER(t,e,n);return o===-1||this.setValueHex(),o}toBER(t){return t?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let t=this.valueHexView.length*8-1,e=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case t:e=fm(Ul(n),e),i="-";break;default:e=um(e,Ul(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=Rl.charAt(e[c]));return a===!1&&(i+=Rl.charAt(0)),i}};ql=pn;pn.NAME="IntegerValueBlock";Object.defineProperty(ql.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var zl,Bt=class r extends St{constructor(t={}){super(t,pn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return yo(),BigInt(this.valueBlock.toString())}static fromBigInt(t){yo();let e=BigInt(t),n=new hn,o=e.toString(16).replace(/^-/,""),s=new Uint8Array(z.Convert.FromHex(o));if(e<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${z.Convert.ToHex(a)}`)+e,u=z.BufferSourceConverter.toUint8Array(z.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let t=new r({valueHex:this.valueBlock.valueHexView});return t.valueBlock.toDER(),t}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};zl=Bt;D.Integer=zl;Bt.NAME="INTEGER";var Gl,No=class extends Bt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Gl=No;D.Enumerated=Gl;No.NAME="ENUMERATED";var mn=class extends Se(Nt){constructor({valueDec:t=-1,isFirstSid:e=!1,...n}={}){super(n),this.valueDec=t,this.isFirstSid=e}fromBER(t,e,n){if(!n)return e;let o=z.BufferSourceConverter.toUint8Array(t);if(!Ae(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=ir(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){yo();let e=BigInt(t).toString(2);for(;e.length%7;)e="0"+e;let n=new Uint8Array(e.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(e.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=Ke(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",ne;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let t="";if(this.isHexOnly)t=z.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let e=this.valueDec;this.valueDec<=39?t="0.":this.valueDec<=79?(t="1.",e-=40):(t="2.",e-=80),t+=e.toString()}else t=this.valueDec.toString();return t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};mn.NAME="sidBlock";var Lo=class extends Nt{constructor({value:t=Rr,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new mn;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t){let e=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(t);if(o.byteLength===0)return this.error=this.value[n].error,ne;e.push(o)}return fa(e)}fromString(t){this.value=[];let e=0,n=0,o="",s=!1;do if(n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new mn;if(o>Number.MAX_SAFE_INTEGER){yo();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e?(o=`{${o}}`,this.value[n].isFirstSid?t=`2.{${o} - 80}`:t+=o):t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Lo.NAME="ObjectIdentifierValueBlock";var jl,_r=class extends St{constructor(t={}){super(t,Lo),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};jl=_r;D.ObjectIdentifier=jl;_r.NAME="OBJECT IDENTIFIER";var gn=class extends Se(xe){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=z.BufferSourceConverter.toUint8Array(t);if(!Ae(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=ir(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=Ke(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",ne;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let t="";return this.isHexOnly?t=z.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};gn.NAME="relativeSidBlock";var _o=class extends Nt{constructor({value:t=Rr,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new gn;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t,e){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(t);if(s.byteLength===0)return this.error=this.value[o].error,ne;n.push(s)}return fa(n)}fromString(t){this.value=[];let e=0,n=0,o="";do{n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1;let s=new gn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e&&(o=`{${o}}`),t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};_o.NAME="RelativeObjectIdentifierValueBlock";var Zl,Ro=class extends St{constructor(t={}){super(t,_o),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Zl=Ro;D.RelativeObjectIdentifier=Zl;Ro.NAME="RelativeObjectIdentifier";var Xl,Ee=class extends $e{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Xl=Ee;D.Sequence=Xl;Ee.NAME="SEQUENCE";var Yl,Uo=class extends $e{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Yl=Uo;D.Set=Yl;Uo.NAME="SET";var Do=class extends Se(Nt){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=Rr}toJSON(){return{...super.toJSON(),value:this.value}}};Do.NAME="StringValueBlock";var Po=class extends Do{};Po.NAME="SimpleStringValueBlock";var Ut=class extends xo{constructor({...t}={}){super(t,Po)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,z.BufferSourceConverter.toUint8Array(t))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);this.valueBlock.value=t}};Ut.NAME="SIMPLE STRING";var Oo=class extends Ut{fromBuffer(t){this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=z.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=z.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf8String(t)),this.valueBlock.value=t}};Oo.NAME="Utf8StringValueBlock";var Jl,ve=class extends Oo{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Jl=ve;D.Utf8String=Jl;ve.NAME="UTF8String";var Ho=class extends Ut{fromBuffer(t){this.valueBlock.value=z.Convert.ToUtf16String(t),this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf16String(t))}};Ho.NAME="BmpStringValueBlock";var Ql,Mo=class extends Ho{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Ql=Mo;D.BmpString=Ql;Mo.NAME="BMPString";var Vo=class extends Ut{fromBuffer(t){let e=ArrayBuffer.isView(t)?t.slice().buffer:t.slice(0),n=new Uint8Array(e);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(e))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e*4);for(let o=0;o<e;o++){let s=Ke(t.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=t}};Vo.NAME="UniversalStringValueBlock";var tu,Fo=class extends Vo{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};tu=Fo;D.UniversalString=tu;Fo.NAME="UniversalString";var eu,Ko=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};eu=Ko;D.NumericString=eu;Ko.NAME="NumericString";var ru,$o=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};ru=$o;D.PrintableString=ru;$o.NAME="PrintableString";var nu,Wo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};nu=Wo;D.TeletexString=nu;Wo.NAME="TeletexString";var ou,qo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};ou=qo;D.VideotexString=ou;qo.NAME="VideotexString";var su,zo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};su=zo;D.IA5String=su;zo.NAME="IA5String";var iu,Go=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};iu=Go;D.GraphicString=iu;Go.NAME="GraphicString";var au,yn=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};au=yn;D.VisibleString=au;yn.NAME="VisibleString";var cu,jo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};cu=jo;D.GeneralString=cu;jo.NAME="GeneralString";var lu,Zo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};lu=Zo;D.CharacterString=lu;Zo.NAME="CharacterString";var uu,wn=class extends yn{constructor({value:t,valueDate:e,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,t){this.fromString(t),this.valueBlock.valueHexView=new Uint8Array(t.length);for(let o=0;o<t.length;o++)this.valueBlock.valueHexView[o]=t.charCodeAt(o)}e&&(this.fromDate(e),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(t){this.fromString(String.fromCharCode.apply(null,z.BufferSourceConverter.toUint8Array(t)))}toBuffer(){let t=this.toString(),e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return e}fromDate(t){this.year=t.getUTCFullYear(),this.month=t.getUTCMonth()+1,this.day=t.getUTCDate(),this.hour=t.getUTCHours(),this.minute=t.getUTCMinutes(),this.second=t.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(t){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(t);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(t="iso"){if(t==="iso"){let e=new Array(7);return e[0]=Mt(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Mt(this.month,2),e[2]=Mt(this.day,2),e[3]=Mt(this.hour,2),e[4]=Mt(this.minute,2),e[5]=Mt(this.second,2),e[6]="Z",e.join("")}return super.toString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};uu=wn;D.UTCTime=uu;wn.NAME="UTCTime";var fu,Xo=class extends wn{constructor(t={}){var e;super(t),(e=this.millisecond)!==null&&e!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(t){super.fromDate(t),this.millisecond=t.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(t){let e=!1,n="",o="",s=0,i,a=0,c=0;if(t[t.length-1]==="Z")n=t.substring(0,t.length-1),e=!0;else{let f=new Number(t[t.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=t}if(e){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,d=n.indexOf("+"),m="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(m=n.substring(d+1),n=n.substring(0,d),m.length!==2&&m.length!==4)throw new Error("Wrong input string for conversion");let x=parseInt(m.substring(0,2),10);if(isNaN(x.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*x,m.length===4){if(x=parseInt(m.substring(2,4),10),isNaN(x.valueOf()))throw new Error("Wrong input string for conversion");c=f*x}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");s=f.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*s;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(e===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(t="iso"){if(t==="iso"){let e=[];return e.push(Mt(this.year,4)),e.push(Mt(this.month,2)),e.push(Mt(this.day,2)),e.push(Mt(this.hour,2)),e.push(Mt(this.minute,2)),e.push(Mt(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(Mt(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};fu=Xo;D.GeneralizedTime=fu;Xo.NAME="GeneralizedTime";var hu,Yo=class extends ve{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};hu=Yo;D.DATE=hu;Yo.NAME="DATE";var du,Jo=class extends ve{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};du=Jo;D.TimeOfDay=du;Jo.NAME="TimeOfDay";var pu,Qo=class extends ve{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};pu=Qo;D.DateTime=pu;Qo.NAME="DateTime";var mu,ts=class extends ve{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};mu=ts;D.Duration=mu;ts.NAME="Duration";var gu,es=class extends ve{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};gu=es;D.TIME=gu;es.NAME="TIME";function J(r,t="utf8"){let e=uo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var bn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},ns=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var yu={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new ns("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 We=yu;async function wu(r){let t=await We.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await dm(t);return{privateKey:e[0],publicKey:e[1]}}async function bu(r,t){let e=await We.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await We.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function xu(r,t,e){let n=await We.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return We.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function dm(r){if(r.privateKey==null||r.publicKey==null)throw new tt("Private and public key are required");return Promise.all([We.get().subtle.exportKey("jwk",r.privateKey),We.get().subtle.exportKey("jwk",r.publicKey)])}function pa(r){if(r.kty!=="RSA")throw new tt("invalid key type");if(r.n==null)throw new tt("invalid key modulus");return et(r.n,"base64url").length*8}var Ur=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=xn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return vt.createV1(114,this._multihash)}toString(){return nt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Rt(this.raw,t.raw)}verify(t,e){return xu(this._key,e,t)}},En=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=xn.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Rt(this.raw,t.raw)}sign(t){return bu(this._key,t)}};var os=8192,ma=18;function Eu(r){let{result:t}=da(r),e=t.valueBlock.value;return{n:ce(e[1]),e:ce(e[2]),d:ce(e[3]),p:ce(e[4]),q:ce(e[5]),dp:ce(e[6]),dq:ce(e[7]),qi:ce(e[8]),kty:"RSA",alg:"RS256"}}function pm(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new tt("JWK was missing components");let e=new Ee({value:[new Bt({value:0}),Bt.fromBigInt(le(et(r.n,"base64url"))),Bt.fromBigInt(le(et(r.e,"base64url"))),Bt.fromBigInt(le(et(r.d,"base64url"))),Bt.fromBigInt(le(et(r.p,"base64url"))),Bt.fromBigInt(le(et(r.q,"base64url"))),Bt.fromBigInt(le(et(r.dp,"base64url"))),Bt.fromBigInt(le(et(r.dq,"base64url"))),Bt.fromBigInt(le(et(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function vu(r){let{result:t}=da(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:ce(e[0]),e:ce(e[1])}}function ga(r){if(r.n==null||r.e==null)throw new tt("JWK was missing components");let e=new Ee({value:[new Ee({value:[new _r({value:"1.2.840.113549.1.1.1"}),new Nr]}),new Lr({valueHex:new Ee({value:[Bt.fromBigInt(le(et(r.n,"base64url"))),Bt.fromBigInt(le(et(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function ce(r){let t=r.valueBlock.valueHexView;for(;t[0]===0;)t=t.subarray(1);return J(t,"base64url")}function le(r){let t=[];return r.forEach(function(e){let n=e.toString(16);n.length%2>0&&(n=`0${n}`),t.push(n)}),BigInt("0x"+t.join(""))}function Au(r){let t=Eu(r);return Su(t)}function ya(r){let t=vu(r);if(pa(t)>os)throw new gr("Key size is too large");let e=ie(se.encode({Type:bt.RSA,Data:r})),n=Ot(ma,e);return new Ur(t,n)}function Su(r){if(pa(r)>os)throw new tt("Key size is too large");let t=Iu(r),e=ie(se.encode({Type:bt.RSA,Data:ga(t.publicKey)})),n=Ot(ma,e);return new En(t.privateKey,new Ur(t.publicKey,n))}async function Bu(r){if(r>os)throw new tt("Key size is too large");let t=await wu(r),e=ie(se.encode({Type:bt.RSA,Data:ga(t.publicKey)})),n=Ot(ma,e);return new En(t.privateKey,new Ur(t.publicKey,n))}function Iu(r){if(r==null)throw new tt("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var ss=class extends Ar{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Qr(t);let n=Re(e);if(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 o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return vr(this),this.iHash.update(t),this}digestInto(t){vr(this),Er(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,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=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Dr=(r,t,e)=>new ss(r,t).update(e).digest();Dr.create=(r,t)=>new ss(r,t);function Cu(r){r.lowS!==void 0&&Zt("lowS",r.lowS),r.prehash!==void 0&&Zt("prehash",r.prehash)}function mm(r){let t=nn(r);Wt(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:gm,hexToBytes:ym}=ro,Be={Err:class extends Error{constructor(t=""){super(t)}},_tlv:{encode:(r,t)=>{let{Err:e}=Be;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=Je(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Je(o.length/2|128):"";return`${Je(r)}${s}${o}${t}`},decode(r,t){let{Err:e}=Be,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("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 e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=Be;if(r<Ie)throw new t("integer: negative integers are not allowed");let e=Je(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected assertion");return e},decode(r){let{Err:t}=Be;if(r[0]&128)throw new t("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return gm(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Be,o=typeof r=="string"?ym(r):r;Br(o);let{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:l,l:u}=n.decode(2,c);if(u.length)throw new t("Invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=Be,n=`${t.encode(2,e.encode(r.r))}${t.encode(2,e.encode(r.s))}`;return t.encode(48,n)}},Ie=BigInt(0),xt=BigInt(1),qb=BigInt(2),ku=BigInt(3),zb=BigInt(4);function wm(r){let t=mm(r),{Fp:e}=t,n=He(t.n,t.nBitLength),o=t.toBytes||((g,h,y)=>{let b=h.toAffine();return we(Uint8Array.from([4]),e.toBytes(b.x),e.toBytes(b.y))}),s=t.fromBytes||(g=>{let h=g.subarray(1),y=e.fromBytes(h.subarray(0,e.BYTES)),b=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:y,y:b}});function i(g){let{a:h,b:y}=t,b=e.sqr(g),p=e.mul(b,g);return e.add(e.add(p,e.mul(g,h)),y)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return en(g,xt,t.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:y,wrapPrivateKey:b,n:p}=t;if(h&&typeof g!="bigint"){if(Pe(g)&&(g=me(g)),typeof g!="string"||!h.includes(g.length))throw new Error("Invalid key");g=g.padStart(y*2,"0")}let B;try{B=typeof g=="bigint"?g:ge(it("private key",g,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof g}`)}return b&&(B=Z(B,p)),At("private key",B,xt,p),B}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=tr((g,h)=>{let{px:y,py:b,pz:p}=g;if(e.eql(p,e.ONE))return{x:y,y:b};let B=g.is0();h==null&&(h=B?e.ONE:e.inv(p));let L=e.mul(y,h),N=e.mul(b,h),S=e.mul(p,h);if(B)return{x:e.ZERO,y:e.ZERO};if(!e.eql(S,e.ONE))throw new Error("invZ was invalid");return{x:L,y:N}}),f=tr(g=>{if(g.is0()){if(t.allowInfinityPoint&&!e.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:h,y}=g.toAffine();if(!e.isValid(h)||!e.isValid(y))throw new Error("bad point: x or y not FE");let b=e.sqr(y),p=i(h);if(!e.eql(b,p))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,y,b){if(this.px=h,this.py=y,this.pz=b,h==null||!e.isValid(h))throw new Error("x required");if(y==null||!e.isValid(y))throw new Error("y required");if(b==null||!e.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:y,y:b}=h||{};if(!h||!e.isValid(y)||!e.isValid(b))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let p=B=>e.eql(B,e.ZERO);return p(y)&&p(b)?d.ZERO:new d(y,b,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let y=e.invertBatch(h.map(b=>b.pz));return h.map((b,p)=>b.toAffine(y[p])).map(d.fromAffine)}static fromHex(h){let y=d.fromAffine(s(it("pointHex",h)));return y.assertValidity(),y}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,y){return so(d,n,h,y)}_setWindowSize(h){x.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:y,py:b,pz:p}=this,{px:B,py:L,pz:N}=h,S=e.eql(e.mul(y,N),e.mul(B,p)),k=e.eql(e.mul(b,N),e.mul(L,p));return S&&k}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:y}=t,b=e.mul(y,ku),{px:p,py:B,pz:L}=this,N=e.ZERO,S=e.ZERO,k=e.ZERO,I=e.mul(p,p),M=e.mul(B,B),_=e.mul(L,L),O=e.mul(p,B);return O=e.add(O,O),k=e.mul(p,L),k=e.add(k,k),N=e.mul(h,k),S=e.mul(b,_),S=e.add(N,S),N=e.sub(M,S),S=e.add(M,S),S=e.mul(N,S),N=e.mul(O,N),k=e.mul(b,k),_=e.mul(h,_),O=e.sub(I,_),O=e.mul(h,O),O=e.add(O,k),k=e.add(I,I),I=e.add(k,I),I=e.add(I,_),I=e.mul(I,O),S=e.add(S,I),_=e.mul(B,L),_=e.add(_,_),I=e.mul(_,O),N=e.sub(N,I),k=e.mul(_,M),k=e.add(k,k),k=e.add(k,k),new d(N,S,k)}add(h){l(h);let{px:y,py:b,pz:p}=this,{px:B,py:L,pz:N}=h,S=e.ZERO,k=e.ZERO,I=e.ZERO,M=t.a,_=e.mul(t.b,ku),O=e.mul(y,B),V=e.mul(b,L),C=e.mul(p,N),T=e.add(y,b),E=e.add(B,L);T=e.mul(T,E),E=e.add(O,V),T=e.sub(T,E),E=e.add(y,p);let w=e.add(B,N);return E=e.mul(E,w),w=e.add(O,C),E=e.sub(E,w),w=e.add(b,p),S=e.add(L,N),w=e.mul(w,S),S=e.add(V,C),w=e.sub(w,S),I=e.mul(M,E),S=e.mul(_,C),I=e.add(S,I),S=e.sub(V,I),I=e.add(V,I),k=e.mul(S,I),V=e.add(O,O),V=e.add(V,O),C=e.mul(M,C),E=e.mul(_,E),V=e.add(V,C),C=e.sub(O,C),C=e.mul(M,C),E=e.add(E,C),O=e.mul(V,E),k=e.add(k,O),O=e.mul(w,E),S=e.mul(T,S),S=e.sub(S,O),O=e.mul(T,V),I=e.mul(w,I),I=e.add(I,O),new d(S,k,I)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return x.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){At("scalar",h,Ie,t.n);let y=d.ZERO;if(h===Ie)return y;if(h===xt)return this;let{endo:b}=t;if(!b)return x.unsafeLadder(this,h);let{k1neg:p,k1:B,k2neg:L,k2:N}=b.splitScalar(h),S=y,k=y,I=this;for(;B>Ie||N>Ie;)B&xt&&(S=S.add(I)),N&xt&&(k=k.add(I)),I=I.double(),B>>=xt,N>>=xt;return p&&(S=S.negate()),L&&(k=k.negate()),k=new d(e.mul(k.px,b.beta),k.py,k.pz),S.add(k)}multiply(h){let{endo:y,n:b}=t;At("scalar",h,xt,b);let p,B;if(y){let{k1neg:L,k1:N,k2neg:S,k2:k}=y.splitScalar(h),{p:I,f:M}=this.wNAF(N),{p:_,f:O}=this.wNAF(k);I=x.constTimeNegate(L,I),_=x.constTimeNegate(S,_),_=new d(e.mul(_.px,y.beta),_.py,_.pz),p=I.add(_),B=M.add(O)}else{let{p:L,f:N}=this.wNAF(h);p=L,B=N}return d.normalizeZ([p,B])[0]}multiplyAndAddUnsafe(h,y,b){let p=d.BASE,B=(N,S)=>S===Ie||S===xt||!N.equals(p)?N.multiplyUnsafe(S):N.multiply(S),L=B(this,y).add(B(h,b));return L.is0()?void 0:L}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:y}=t;if(h===xt)return!0;if(y)return y(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:y}=t;return h===xt?this:y?y(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return Zt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return Zt("isCompressed",h),me(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let m=t.nBitLength,x=oo(d,t.endo?Math.ceil(m/2):m);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function bm(r){let t=nn(r);return Wt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Tu(r){let t=bm(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(C){return Z(C,n)}function a(C){return no(C,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=wm({...t,toBytes(C,T,E){let w=T.toAffine(),A=e.toBytes(w.x),v=we;return Zt("isCompressed",E),E?v(Uint8Array.from([T.hasEvenY()?2:3]),A):v(Uint8Array.from([4]),A,e.toBytes(w.y))},fromBytes(C){let T=C.length,E=C[0],w=C.subarray(1);if(T===o&&(E===2||E===3)){let A=ge(w);if(!en(A,xt,e.ORDER))throw new Error("Point is not on curve");let v=u(A),R;try{R=e.sqrt(v)}catch(F){let K=F instanceof Error?": "+F.message:"";throw new Error("Point is not on curve"+K)}let U=(R&xt)===xt;return(E&1)===1!==U&&(R=e.neg(R)),{x:A,y:R}}else if(T===s&&E===4){let A=e.fromBytes(w.subarray(0,e.BYTES)),v=e.fromBytes(w.subarray(e.BYTES,2*e.BYTES));return{x:A,y:v}}else throw new Error(`Point of length ${T} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),d=C=>me(Oe(C,t.nByteLength));function m(C){let T=n>>xt;return C>T}function x(C){return m(C)?i(-C):C}let g=(C,T,E)=>ge(C.slice(T,E));class h{constructor(T,E,w){this.r=T,this.s=E,this.recovery=w,this.assertValidity()}static fromCompact(T){let E=t.nByteLength;return T=it("compactSignature",T,E*2),new h(g(T,0,E),g(T,E,2*E))}static fromDER(T){let{r:E,s:w}=Be.toSig(it("DER",T));return new h(E,w)}assertValidity(){At("r",this.r,xt,n),At("s",this.s,xt,n)}addRecoveryBit(T){return new h(this.r,this.s,T)}recoverPublicKey(T){let{r:E,s:w,recovery:A}=this,v=N(it("msgHash",T));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let R=A===2||A===3?E+t.n:E;if(R>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=A&1?"03":"02",H=c.fromHex(U+d(R)),F=a(R),K=i(-v*F),W=i(w*F),j=c.BASE.multiplyAndAddUnsafe(H,K,W);if(!j)throw new Error("point at infinify");return j.assertValidity(),j}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return Qe(this.toDERHex())}toDERHex(){return Be.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Qe(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let y={isValidPrivateKey(C){try{return l(C),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let C=Bi(t.n);return sl(t.randomBytes(C),t.n)},precompute(C=8,T=c.BASE){return T._setWindowSize(C),T.multiply(BigInt(3)),T}};function b(C,T=!0){return c.fromPrivateKey(C).toRawBytes(T)}function p(C){let T=Pe(C),E=typeof C=="string",w=(T||E)&&C.length;return T?w===o||w===s:E?w===2*o||w===2*s:C instanceof c}function B(C,T,E=!0){if(p(C))throw new Error("first arg must be private key");if(!p(T))throw new Error("second arg must be public key");return c.fromHex(T).multiply(l(C)).toRawBytes(E)}let L=t.bits2int||function(C){let T=ge(C),E=C.length*8-t.nBitLength;return E>0?T>>BigInt(E):T},N=t.bits2int_modN||function(C){return i(L(C))},S=rn(t.nBitLength);function k(C){return At(`num < 2^${t.nBitLength}`,C,Ie,S),Oe(C,t.nByteLength)}function I(C,T,E=M){if(["recovered","canonical"].some(st=>st in E))throw new Error("sign() legacy options not supported");let{hash:w,randomBytes:A}=t,{lowS:v,prehash:R,extraEntropy:U}=E;v==null&&(v=!0),C=it("msgHash",C),Cu(E),R&&(C=it("prehashed msgHash",w(C)));let H=N(C),F=l(T),K=[k(F),k(H)];if(U!=null&&U!==!1){let st=U===!0?A(e.BYTES):U;K.push(it("extraEntropy",st))}let W=we(...K),j=H;function ot(st){let ut=L(st);if(!f(ut))return;let _t=a(ut),mt=c.BASE.multiply(ut).toAffine(),Pt=i(mt.x);if(Pt===Ie)return;let ue=i(_t*i(j+Pt*F));if(ue===Ie)return;let zr=(mt.x===Pt?0:2)|Number(mt.y&xt),Gr=ue;return v&&m(ue)&&(Gr=x(ue),zr^=1),new h(Pt,Gr,zr)}return{seed:W,k2sig:ot}}let M={lowS:t.lowS,prehash:!1},_={lowS:t.lowS,prehash:!1};function O(C,T,E=M){let{seed:w,k2sig:A}=I(C,T,E),v=t;return xi(v.hash.outputLen,v.nByteLength,v.hmac)(w,A)}c.BASE._setWindowSize(8);function V(C,T,E,w=_){let A=C;if(T=it("msgHash",T),E=it("publicKey",E),"strict"in w)throw new Error("options.strict was renamed to lowS");Cu(w);let{lowS:v,prehash:R}=w,U,H;try{if(typeof A=="string"||Pe(A))try{U=h.fromDER(A)}catch(mt){if(!(mt instanceof Be.Err))throw mt;U=h.fromCompact(A)}else if(typeof A=="object"&&typeof A.r=="bigint"&&typeof A.s=="bigint"){let{r:mt,s:Pt}=A;U=new h(mt,Pt)}else throw new Error("PARSE");H=c.fromHex(E)}catch(mt){if(mt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(v&&U.hasHighS())return!1;R&&(T=t.hash(T));let{r:F,s:K}=U,W=N(T),j=a(K),ot=i(W*j),st=i(F*j),ut=c.BASE.multiplyAndAddUnsafe(H,ot,st)?.toAffine();return ut?i(ut.x)===F:!1}return{CURVE:t,getPublicKey:b,getSharedSecret:B,sign:O,verify:V,ProjectivePoint:c,Signature:h,utils:y}}function xm(r){return{hash:r,hmac:(t,...e)=>Dr(r,t,hi(...e)),randomBytes:tn}}function Nu(r,t){let e=n=>Tu({...r,...xm(n)});return Object.freeze({...e(t),create:e})}var Ru=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Lu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Em=BigInt(1),wa=BigInt(2),_u=(r,t)=>(r+t/wa)/t;function vm(r){let t=Ru,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=at(u,e,t)*u%t,d=at(f,e,t)*u%t,m=at(d,wa,t)*l%t,x=at(m,o,t)*m%t,g=at(x,s,t)*x%t,h=at(g,a,t)*g%t,y=at(h,c,t)*h%t,b=at(y,a,t)*g%t,p=at(b,e,t)*u%t,B=at(p,i,t)*x%t,L=at(B,n,t)*l%t,N=at(L,wa,t);if(!ba.eql(ba.sqr(N),r))throw new Error("Cannot find square root");return N}var ba=He(Ru,void 0,void 0,{sqrt:vm}),ar=Nu({a:BigInt(0),b:BigInt(7),Fp:ba,n:Lu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Lu,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Em*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=_u(s*r,t),c=_u(-n*r,t),l=Z(r-a*e-c*o,t),u=Z(-a*n-c*s,t),f=l>i,d=u>i;if(f&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},ie),ex=BigInt(0);var rx=ar.ProjectivePoint;function Et(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=wt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}function Uu(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Du(r,t,e){let n=cn.digest(e instanceof Uint8Array?e:e.subarray());if(Uu(n))return n.then(({digest:o})=>ar.verify(t,o,r)).catch(o=>{throw new bn(String(o))});try{return ar.verify(t,n.digest,r)}catch(o){throw new bn(String(o))}}var is=class{type="secp256k1";raw;_key;constructor(t){this._key=Ou(t),this.raw=Pu(this._key)}toMultihash(){return de.digest(Cr(this))}toCID(){return vt.createV1(114,this.toMultihash())}toString(){return nt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Rt(this.raw,t.raw)}verify(t,e){return Du(this._key,e,t)}};function xa(r){return new is(r)}function Pu(r){return ar.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Ou(r){try{return ar.ProjectivePoint.fromHex(r),r}catch(t){throw new gr(String(t))}}function vn(r){let{Type:t,Data:e}=se.decode(r),n=e??new Uint8Array;switch(t){case bt.RSA:return ya(n);case bt.Ed25519:return Ni(n);case bt.secp256k1:return xa(n);default:throw new Ze}}function Hu(r){let{Type:t,Data:e}=se.decode(r.digest),n=e??new Uint8Array;switch(t){case bt.Ed25519:return Ni(n);case bt.secp256k1:return xa(n);default:throw new Ze}}function Cr(r){return se.encode({Type:bt[r.type],Data:r.raw})}var Mu=Symbol.for("nodejs.util.inspect.custom"),Sm=114,An=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()})`}[ti]=!0;toString(){return this.string==null&&(this.string=nt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return vt.createV1(Sm,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Rt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Rt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Mu](){return`PeerId(${this.toString()})`}},Sn=class extends An{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Bn=class extends An{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},In=class extends An{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Bm=2336,as=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=de.digest(et(this.url))}[Mu](){return`PeerId(${this.url})`}[ti]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return vt.createV1(Bm,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=J(t)),t.toString()===this.toString())}};function Pr(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=_e(nt.decode(`z${r}`));else{if(t==null)throw new tt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=_e(t.decode(r))}return Im(e)}function Ea(r){if(r.type==="Ed25519")return new Bn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new In({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Sn({multihash:r.toCID().multihash,publicKey:r});throw new Ze}function Im(r){if(km(r))return new Sn({multihash:r});if(Cm(r))try{let t=Hu(r);if(t.type==="Ed25519")return new Bn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new In({multihash:r,publicKey:t})}catch{let e=J(r.digest);return new as(new URL(e))}throw new zn("Supplied PeerID Multihash is invalid")}function Cm(r){return r.code===de.code}function km(r){return r.code===cn.code}var cs=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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 e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=t,s+=u,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[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];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;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 e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Vu=45,Tm=15,Or=new cs;function va(r){if(!(r.length>Tm))return Or.new(r).parseWith(()=>Or.readIPv4Addr())}function Aa(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Vu))return Or.new(r).parseWith(()=>Or.readIPv6Addr())}function ls(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Vu))return Or.new(r).parseWith(()=>Or.readIPAddr())}var y1=parseInt("0xFFFF",16),w1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function us(r){return!!va(r)}function fs(r){return!!Aa(r)}function hs(r){return!!ls(r)}var $u=us,Um=fs,Sa=function(r){let t=0;if(r=r.toString().trim(),$u(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Um(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=$u(e[n]),i;s&&(i=Sa(e[n]),e[n]=J(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,J(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},Wu=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Hr={},Ba={},Pm=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];Pm.forEach(r=>{let t=Om(...r);Ba[t.code]=t,Hr[t.name]=t});function Om(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function Q(r){if(typeof r=="number"){if(Ba[r]!=null)return Ba[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Hr[r]!=null)return Hr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var e2=Q("ip4"),r2=Q("ip6"),n2=Q("ipcidr");function Ta(r,t){switch(Q(r).code){case 4:case 41:return Mm(t);case 42:return ka(t);case 6:case 273:case 33:case 132:return Gu(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ka(t);case 421:return $m(t);case 444:return zu(t);case 445:return zu(t);case 466:return Km(t);case 481:return globalThis.encodeURIComponent(ka(t));default:return J(t,"base16")}}function Na(r,t){switch(Q(r).code){case 4:return qu(t);case 41:return qu(t);case 42:return Ca(t);case 6:case 273:case 33:case 132:return La(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ca(t);case 421:return Vm(t);case 444:return Wm(t);case 445:return qm(t);case 466:return Fm(t);case 481:return Ca(globalThis.decodeURIComponent(t));default:return et(t,"base16")}}var Ia=Object.values(nr).map(r=>r.decoder),Hm=function(){let r=Ia[0].or(Ia[1]);return Ia.slice(2).forEach(t=>r=r.or(t)),r}();function qu(r){if(!hs(r))throw new Error("invalid ip address");return Sa(r)}function Mm(r){let t=Wu(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!hs(t))throw new Error("invalid ip address");return t}function La(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Gu(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Ca(r){let t=et(r),e=Uint8Array.from(oe(t.length));return Et([e,t],e.length+t.length)}function ka(r){let t=Jt(r);if(r=r.slice(ct(t)),r.length!==t)throw new Error("inconsistent lengths");return J(r)}function Vm(r){let t;r[0]==="Q"||r[0]==="1"?t=_e(nt.decode(`z${r}`)).bytes:t=vt.parse(r).multihash.bytes;let e=Uint8Array.from(oe(t.length));return Et([e,t],e.length+t.length)}function Fm(r){let t=Hm.decode(r),e=Uint8Array.from(oe(t.length));return Et([e,t],e.length+t.length)}function Km(r){let t=Jt(r),e=r.slice(ct(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+J(e,"base64url")}function $m(r){let t=Jt(r),e=r.slice(ct(t));if(e.length!==t)throw new Error("inconsistent lengths");return J(e,"base58btc")}function Wm(r){let t=r.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 e=he.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=La(n);return Et([e,o],e.length+o.length)}function qm(r){let t=r.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 e=he.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=La(n);return Et([e,o],e.length+o.length)}function zu(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=J(t,"base32"),o=Gu(e);return`${n}:${o}`}function ju(r){r=_a(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=Q(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw Xu("invalid address: "+r);if(a.path===!0){n=_a(o.slice(s).join("/")),t.push([a.code,Na(a.code,n)]),e.push([a.code,n]);break}let c=Na(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Ta(a.code,c)])}return{string:Zu(e),bytes:Ua(t),tuples:t,stringTuples:e,path:n}}function Ra(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=Jt(r,o),i=ct(s),a=Q(s),c=zm(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Xu("Invalid address Uint8Array: "+J(r,"base16"));t.push([s,l]);let u=Ta(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Zu(e),tuples:t,stringTuples:e,path:n}}function Zu(r){let t=[];return r.map(e=>{let n=Q(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),_a(t.join("/"))}function Ua(r){return Et(r.map(t=>{let e=Q(t[0]),n=Uint8Array.from(oe(e.code));return t.length>1&&t[1]!=null&&(n=Et([n,t[1]])),n}))}function zm(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=Jt(t instanceof Uint8Array?t:Uint8Array.from(t));return e+ct(e)}}function _a(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function Xu(r){return new Error("Error parsing address: "+r)}var Gm=Symbol.for("nodejs.util.inspect.custom"),Pa=Symbol.for("@multiformats/js-multiaddr/multiaddr"),jm=[Q("dns").code,Q("dns4").code,Q("dns6").code,Q("dnsaddr").code],Da=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},ds=class r{bytes;#t;#e;#r;#n;[Pa]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Ra(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=ju(t)}else if(Ju(t))e=Ra(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="",i=Q("tcp"),a=Q("udp"),c=Q("ip4"),l=Q("ip6"),u=Q("dns6"),f=Q("ip6zone");for(let[m,x]of this.stringTuples())m===f.code&&(s=`%${x??""}`),jm.includes(m)&&(e=i.name,o=443,n=`${x??""}${s}`,t=m===u.code?6:4),(m===i.code||m===a.code)&&(e=Q(m).name,o=parseInt(x??"")),(m===c.code||m===l.code)&&(e=Q(m).name,n=`${x??""}${s}`,t=m===l.code?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},Q(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>Q(t).name)}tuples(){return this.#e}stringTuples(){return this.#r}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(Ua(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Hr.p2p.code&&t.push([n,o]),n===Hr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?J(nt.decode(`z${n}`),"base58btc"):J(vt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return Rt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=Yu.get(e.name);if(n==null)throw new Da(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>qe(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[Gm](){return`Multiaddr(${this.#t})`}};var Yu=new Map;function Ju(r){return!!r?.[Pa]}function qe(r){return new ds(r)}var Zm=r=>r.toString().split("/").slice(1),Mr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),q=r=>({match:t=>Mr(e=>e===r).match(t),pattern:r}),cr=()=>({match:r=>Mr(t=>typeof t=="string").match(r),pattern:"{string}"}),Cn=()=>({match:r=>Mr(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),rt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{nt.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),kn=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{zi.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),X=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Lt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),G=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function lt(...r){function t(o){let s=Zm(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var ms=G(q("dns4"),cr()),gs=G(q("dns6"),cr()),ys=G(q("dnsaddr"),cr()),Ha=G(q("dns"),cr()),_2=lt(ms,X(rt())),R2=lt(gs,X(rt())),U2=lt(ys,X(rt())),D2=lt(Lt(Ha,ys,ms,gs),X(rt())),Qu=G(q("ip4"),Mr(us)),tf=G(q("ip6"),Mr(fs)),Ma=Lt(Qu,tf),Ce=Lt(Ma,Ha,ms,gs,ys),P2=lt(Lt(Ma,G(Lt(Ha,ys,ms,gs),X(rt())))),O2=lt(Qu),H2=lt(tf),M2=lt(Ma),Va=G(Ce,q("tcp"),Cn()),Tn=G(Ce,q("udp"),Cn()),V2=lt(G(Va,X(rt()))),F2=lt(Tn),Fa=G(Tn,q("quic"),X(rt())),ws=G(Tn,q("quic-v1"),X(rt())),Xm=Lt(Fa,ws),K2=lt(Fa),$2=lt(ws),Oa=Lt(Ce,Va,Tn,Fa,ws),ef=Lt(G(Oa,q("ws"),X(rt()))),W2=lt(ef),rf=Lt(G(Oa,q("wss"),X(rt())),G(Oa,q("tls"),X(G(q("sni"),cr())),q("ws"),X(rt()))),q2=lt(rf),nf=G(Tn,q("webrtc-direct"),X(kn()),X(kn()),X(rt())),of=lt(nf),sf=G(ws,q("webtransport"),X(kn()),X(kn()),X(rt())),z2=lt(sf),ps=Lt(ef,rf,G(Va,X(rt())),G(Xm,X(rt())),G(Ce,X(rt())),nf,sf,rt()),af=lt(ps),Ym=G(ps,q("p2p-circuit"),rt()),G2=lt(Ym),Jm=Lt(G(ps,q("p2p-circuit"),q("webrtc"),X(rt())),G(ps,q("webrtc"),X(rt())),G(q("webrtc"),X(rt()))),cf=lt(Jm),Qm=Lt(G(Ce,q("tcp"),Cn(),q("http"),X(rt())),G(Ce,q("http"),X(rt()))),j2=lt(Qm),t0=Lt(G(Ce,q("tcp"),Lt(G(q("443"),q("http")),G(Cn(),q("https"))),X(rt())),G(Ce,q("tls"),q("http"),X(rt())),G(Ce,q("https"),X(rt()))),Z2=lt(t0),e0=Lt(G(q("memory"),cr(),X(rt()))),X2=lt(e0);var lf=function(r,t,e){if(e||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return r.concat(s||Array.prototype.slice.call(t))},r0=function(){function r(t,e,n){this.name=t,this.version=e,this.os=n,this.type="browser"}return r}();var n0=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var o0=function(){function r(t,e,n,o){this.name=t,this.version=e,this.os=n,this.bot=o,this.type="bot-device"}return r}();var s0=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var i0=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var a0=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,c0=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,uf=3,l0=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",a0]],ff=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function df(r){return r?hf(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new i0:typeof navigator<"u"?hf(navigator.userAgent):h0()}function u0(r){return r!==""&&l0.reduce(function(t,e){var n=e[0],o=e[1];if(t)return t;var s=o.exec(r);return!!s&&[n,s]},!1)}function hf(r){var t=u0(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new s0;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<uf&&(o=lf(lf([],o,!0),d0(uf-o.length),!0)):o=[];var s=o.join("."),i=f0(r),a=c0.exec(r);return a&&a[1]?new o0(e,s,i,a[1]):new r0(e,s,i)}function f0(r){for(var t=0,e=ff.length;t<e;t++){var n=ff[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function h0(){var r=typeof process<"u"&&process.version;return r?new n0(process.version.slice(1)):null}function d0(r){for(var t=[],e=0;e<r;e++)t.push("0");return t}function pt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Ka=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},$a=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},pf=r=>globalThis.DOMException===void 0?new $a(r):new DOMException(r),mf=r=>{let t=r.reason===void 0?pf("This operation was aborted."):r.reason;return t instanceof Error?t:pf(t)};function lr(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,c=new Promise((l,u)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:d}=t;d.aborted&&u(mf(d));let m=()=>{u(mf(d))};d.addEventListener("abort",m,{once:!0}),r.finally(()=>{d.removeEventListener("abort",m)})}if(e===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new Ka;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(d){u(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?u(o):(f.message=o??`Promise timed out after ${e} milliseconds`,u(f))},e),(async()=>{try{l(await r)}catch(d){u(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}var gf=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"];var yf=df(),Nn=yf!=null&&yf.name==="firefox",bs=async function*(){},xs=async r=>{},p0=30*1e3;function wf(r,t,e=p0,n){r.readyState==="open"&&Promise.resolve().then(async()=>{if(r.bufferedAmount>0){n.log("%s drain channel with %d buffered bytes",t,r.bufferedAmount);let o=pt(),s=!1;r.bufferedAmountLowThreshold=0;let i=()=>{s||(n.log("%s drain channel closed before drain",t),o.resolve())};r.addEventListener("close",i,{once:!0}),r.addEventListener("bufferedamountlow",()=>{s=!0,r.removeEventListener("close",i),o.resolve()}),await lr(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function Ln(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??gf.map(t=>({urls:[t]})),r}var ur=class{log;peerConnection;remoteAddr;timeline;metrics;source=bs();sink=xs;constructor(t,e){this.log=t.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=e.remoteAddr,this.timeline=e.timeline,this.peerConnection=e.peerConnection;let n=this.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",this.peerConnection.connectionState,"initial state",n),(this.peerConnection.connectionState==="disconnected"||this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.timeline.close=Date.now())}}async close(t){this.log.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(t){this.log.error("closing connection due to error",t),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}};var Es=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)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}},Vr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Es(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 e=this.head;this.head=e.next=new Es(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Wa=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function ze(r={}){return m0(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function m0(r,t){t=t??{};let e=t.onEnd,n=new Vr,o,s,i,a=pt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,y)=>{s=b=>{s=null,n.push(b);try{h(r(n))}catch(p){y(p)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=pt()})}},l=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new Vr,s!=null?s({error:h}):(n.push({error:h}),o)),f=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 l({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?u(h):l({done:!0})),m=()=>(n=new Vr,d(),{done:!0}),x=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:x,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let y=h?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let b,p;y!=null&&(b=new Promise((B,L)=>{p=()=>{L(new Wa)},y.addEventListener("abort",p)}));try{await Promise.race([a.promise,b])}finally{p!=null&&y!=null&&y?.removeEventListener("abort",p)}}},e==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(h){return g.throw(h),e!=null&&(e(h),e=void 0),{done:!0}},return(){return g.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(h){return g.end(h),e!=null&&(e(h),e=void 0),o},get readableLength(){return g.readableLength},onEmpty:h=>g.onEmpty(h)},o}var vs=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function ke(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new vs(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new vs(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var xf=Symbol.for("@achingbrain/uint8arraylist");function bf(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function As(r){return!!r?.[xf]}var ht=class r{bufs;length;[xf]=!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 e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(As(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(As(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=bf(this.bufs,t);return e.buf[e.index]}set(t,e){let n=bf(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(As(t))for(let n=0;n<t.length;n++)this.set(e+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,e){let{bufs:n,length:o}=this._subList(t,e);return Et(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Et(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===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 l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!As(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(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;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 f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let m=this.get(f+d);if(n[d]!==m){u=Math.max(1,d-a[m]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=wt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=yt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=yt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=yt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=wt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=yt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=yt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=yt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=yt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=yt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Rt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};function Ef(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function vf(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Af(r,t){let e=Ef(r).return?.();vf(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var g0=5e3;function qa(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ss=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(t){this.sinkController=new AbortController,this.sinkEnd=pt(),this.closed=pt(),this.log=t.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=t.id,this.metadata=t.metadata??{},this.direction=t.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=t.sendCloseWriteTimeout??g0,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=ze({onEnd:e=>{e!=null?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(t){if(this.writeStatus!=="ready")throw new je(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let e={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(e);qa(o)&&await o}let n=()=>{Af(t,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let o of t){o=o instanceof Uint8Array?new ht(o):o;let s=this.sendData(o,e);qa(s)&&(this.sendingData=pt(),await s,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",n)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(t){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(t){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(t){this.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await ke(Promise.all([this.closeWrite(t),this.closeRead(t),this.closed.promise]),t?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(t={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let e=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(t)),e==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(t={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await ke(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await ke(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await ke(this.sinkEnd.promise,t.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(t){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",t),this.log("try to send reset to remote");let e=this.sendReset();qa(e)&&e.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(t),this.onAbort?.(t)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let t=new qn("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(t),this.onReset?.()}_closeSinkAndSource(t){this._closeSink(t),this._closeSource(t)}_closeSink(t){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(t)}_closeSource(t){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(t))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(t){this.streamSource.push(t)}sourceReadableLength(){return this.streamSource.readableLength}};function Bs(r){return r[Symbol.asyncIterator]!=null}var Is=r=>{let t=ct(r),e=wt(t);return oe(r,e),Is.bytes=t,e};Is.bytes=0;function _n(r,t){t=t??{};let e=t.lengthEncoder??Is;function*n(o){let s=e(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Bs(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}_n.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Is;return new ht(e(r.byteLength),r)};var Cs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ks=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ts=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Rn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var y0=8,w0=1024*1024*4,fr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(fr||(fr={}));var za=r=>{let t=Jt(r);return za.bytes=ct(t),t};za.bytes=0;function hr(r,t){let e=new ht,n=fr.LENGTH,o=-1,s=t?.lengthDecoder??za,i=t?.maxLengthLength??y0,a=t?.maxDataLength??w0;function*c(){for(;e.byteLength>0;){if(n===fr.LENGTH)try{if(o=s(e),o<0)throw new Cs("Invalid message length");if(o>a)throw new ks("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=fr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Ts("Message length length too long");break}throw l}if(n===fr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=fr.LENGTH}}}return Bs(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Rn("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Rn("Unexpected end of input")}()}hr.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return hr(n,{...t??{},onLength:s=>{e=s}})};var x0=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function E0(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:u}=x0(r),f=(...m)=>{let x=e.multiArgs?m:m[0];e.filter&&!e.filter(x)||(c.push(x),e.count===c.length&&(n(),s(c)))},d=m=>{n(),i(m)};n=()=>{for(let m of a)u(m,f);for(let m of e.rejectionEvents)u(m,d)};for(let m of a)l(m,f);for(let m of e.rejectionEvents)l(m,d);e.signal&&e.signal.addEventListener("abort",()=>{d(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=lr(o,{milliseconds:e.timeout});return s.cancel=n,s}return o}function Ga(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=E0(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var Dt;(function(r){let t;(function(o){o.FIN="FIN",o.STOP_SENDING="STOP_SENDING",o.RESET="RESET",o.FIN_ACK="FIN_ACK"})(t=r.Flag||(r.Flag={}));let e;(function(o){o[o.FIN=0]="FIN",o[o.STOP_SENDING=1]="STOP_SENDING",o[o.RESET=2]="RESET",o[o.FIN_ACK=3]="FIN_ACK"})(e||(e={})),function(o){o.codec=()=>sr(e)}(t=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=re((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.flag!=null&&(s.uint32(8),r.Flag.codec().encode(o.flag,s)),o.message!=null&&(s.uint32(18),s.bytes(o.message)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.flag=r.Flag.codec().decode(o);break}case 2:{a.message=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ee(o,r.codec()),r.decode=(o,s)=>te(o,r.codec(),s)})(Dt||(Dt={}));var v0=2*1024*1024,A0=30*1e3,Ns=16*1024;function S0(r=Ns){let t=ct(r-ct(r)),e=1+ct(Object.keys(Dt.Flag).length-1),n=1,o=r-t-e-n,s=ct(o);return t+e+n+s}var B0=S0(),I0=5e3,C0=5e3,ja=class extends Ss{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;constructor(t){let e=t.onEnd;switch(t.onEnd=o=>{this.log.trace("readable and writeable ends closed",this.status),Promise.resolve(async()=>{if(!(this.timeline.abort!=null||this.timeline.reset!==null))try{await lr(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),e?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=ze(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??A0,this.maxBufferedAmount=t.maxBufferedAmount??v0,this.maxMessageSize=(t.maxMessageSize??Ns)-B0,this.receiveFinAck=pt(),this.finAckTimeout=t.closeTimeout??I0,this.openTimeout=t.openTimeout??C0,this.channel.readyState){case"open":this.timeline.open=new Date().getTime();break;case"closed":case"closing":(this.timeline.close===void 0||this.timeline.close===0)&&(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new je("Unknown datachannel state")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{let s=o.error;this.abort(s)},this.channel.onmessage=async o=>{let{data:s}=o;s===null||s.byteLength===0||this.incomingData.push(new Uint8Array(s,0,s.byteLength))};let n=this;Promise.resolve().then(async()=>{for await(let o of hr(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new ht(s))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(t,e=!0){if(e&&this.channel.bufferedAmount>this.maxBufferedAmount)try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await Ga(this.channel,"bufferedamountlow",{timeout:this.bufferedAmountLowEventTimeout})}catch(n){throw n instanceof jr?new jr(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`):n}if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new je(`Invalid datachannel state - ${this.channel.readyState}`);this.channel.readyState!=="open"&&(this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await Ga(this.channel,"open",{timeout:this.openTimeout}),this.log('channel state is now "%s", sending data',this.channel.readyState)),this.channel.send(t.subarray())}async sendData(t){for(t=t.sublist();t.byteLength>0;){let e=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,e),o=Dt.encode({message:n}),s=_n.single(o);await this._sendMessage(s),t.consume(e)}}async sendReset(){try{await this._sendFlag(Dt.Flag.RESET)}catch(t){this.log.error("failed to send reset - %e",t)}}async sendCloseWrite(t){if(await this._sendFlag(Dt.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await ke(this.receiveFinAck.promise,t?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(n){this.log.error("failed to await FIN_ACK",n)}}else this.log.trace("sending FIN failed, not awaiting FIN_ACK");this.receiveFinAck.resolve()}async sendCloseRead(){await this._sendFlag(Dt.Flag.STOP_SENDING)}processIncomingProtobuf(t){let e=Dt.decode(t);if(e.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',e.flag,this.writeStatus,this.readStatus),e.flag===Dt.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Dt.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),e.flag===Dt.Flag.RESET&&this.reset(),e.flag===Dt.Flag.STOP_SENDING&&this.remoteCloseRead(),e.flag===Dt.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),this.readStatus==="ready")return e.message}async _sendFlag(t){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',this.channel.readyState,t.toString()),!1;this.log.trace("sending flag %s",t.toString());let e=Dt.encode({flag:t}),n=_n.single(e);try{return await this._sendMessage(n,!1),!0}catch(o){this.log.error("could not send flag %s - %e",t.toString(),o)}return!1}};function Fr(r){let{channel:t,direction:e}=r;return new ja({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var Sf="/webrtc",Ge=class{protocol;peerConnection;bufferedStreams=[];metrics;dataChannelOptions;components;log;constructor(t,e){this.components=t,this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??Sf,this.dataChannelOptions=e.dataChannelOptions??{},this.log=t.logger.forComponent("libp2p:webrtc:datachannelmuxerfactory"),this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),n.label==="init"){this.log.trace("closing early init channel"),n.close();return}let o={},s=Fr({channel:n,direction:"inbound",onEnd:i=>{o.onEnd(i)},logger:t.logger,...this.dataChannelOptions});o.stream=s,o.channel=n,o.onEnd=()=>{this.bufferedStreams=this.bufferedStreams.filter(i=>i.stream.id!==s.id)},this.bufferedStreams.push(o)}}createStreamMuxer(t){return new Za(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},Za=class{init;streams;protocol;log;peerConnection;dataChannelOptions;metrics;logger;constructor(t,e){this.init=e,this.log=t.logger.forComponent("libp2p:webrtc:muxer"),this.logger=t.logger,this.streams=e.streams.map(n=>n.stream),this.peerConnection=e.peerConnection,this.protocol=e.protocol??Sf,this.metrics=e.metrics,this.dataChannelOptions=e.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace("incoming datachannel with channel id %d",n.id),n.label==="init"){this.log.trace("closing init channel"),n.close();return}let o=n.id,s=Fr({channel:n,direction:"inbound",onEnd:()=>{this.#t(s,n),this.log("incoming channel %s ended",o)},logger:this.logger,...this.dataChannelOptions});this.streams.push(s),this.metrics?.increment({incoming_stream:!0}),e?.onIncomingStream?.(s)},this.init.streams.length>0&&queueMicrotask(()=>{this.init.streams.forEach(n=>{n.onEnd=()=>{this.log("incoming early channel %s ended with state %s",n.channel.id,n.channel.readyState),this.#t(n.stream,n.channel)},this.metrics?.increment({incoming_stream:!0}),this.init?.onIncomingStream?.(n.stream)})})}#t(t,e){this.log.trace("stream %s %s %s onEnd",t.direction,t.id,t.protocol),wf(e,`${t.direction} ${t.id} ${t.protocol}`,this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter(n=>n.id!==t.id),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(t)}async close(t){try{await Promise.all(this.streams.map(async e=>e.close(t)))}catch(e){this.abort(e)}}abort(t){for(let e of this.streams)e.abort(t)}source=bs();sink=xs;newStream(){let t=this.peerConnection.createDataChannel(""),e=t.id;this.log.trace("opened outgoing datachannel with channel id %s",e);let n=Fr({channel:t,direction:"outbound",onEnd:()=>{this.#t(n,t),this.log("outgoing channel %s ended",e)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(n),this.metrics?.increment({outgoing_stream:!0}),n}};var dr=globalThis.RTCPeerConnection,Ls=globalThis.RTCSessionDescription,Bf=globalThis.RTCIceCandidate;var Xa=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=pt(),this.haveNext=pt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=pt(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=pt(),await ke(this.readNext.promise,e?.signal,e)}};function If(){return new Xa}var _s=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Ya=class extends Error{code;constructor(t,e){super(t),this.code=e}},Ja=class extends Ya{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Cf(r,t){let e=If();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new ht;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new Ja("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:d}=await Promise.race([n.next(),l]);return f===!0?new ht:d}for(;o.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),l]);if(d===!0)throw new _s("unexpected end of input");o.append(f)}let u=o.sublist(0,i);return o.consume(i),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Rs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Us=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ds=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Un(r,t={}){let e=Cf(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=ct(t.maxDataLength));let n=t?.lengthDecoder??Jt,o=t?.lengthEncoder??oe;return{read:async i=>{let a=-1,c=new ht;for(;;){c.append(await e.read(1,i));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Rs("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ds("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Us("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new ht(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new ht(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Ps(r,t){let e=Un(r,t),n={read:async(o,s)=>{let i=await e.read(s);return o.decode(i)},write:async(o,s,i)=>{await e.write(s.encode(o),i)},writeV:async(o,s,i)=>{await e.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:()=>e.unwrap()};return n}var $t=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var pr=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},zt=class extends pr{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var Dn=class extends pr{constructor(t,e){super(`[stream: ${t}] data channel error: ${e}`),this.name="WebRTC/DataChannelError"}};var Pn=class extends pr{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`),this.name="WebRTC/InvalidFingerprintError"}};var Os=class extends pr{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Hs=class extends pr{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 Vt;(function(r){let t;(function(o){o.SDP_OFFER="SDP_OFFER",o.SDP_ANSWER="SDP_ANSWER",o.ICE_CANDIDATE="ICE_CANDIDATE"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.SDP_OFFER=0]="SDP_OFFER",o[o.SDP_ANSWER=1]="SDP_ANSWER",o[o.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(e||(e={})),function(o){o.codec=()=>sr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=re((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.data!=null&&(s.uint32(18),s.string(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.data=o.string();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ee(o,r.codec()),r.decode=(o,s)=>te(o,r.codec(),s)})(Vt||(Vt={}));var Ms=async(r,t,e)=>{try{let n=pt();for(k0(r,n);;){let o=await Promise.race([n.promise,t.read({signal:e.signal}).catch(()=>{})]);if(o==null){e.signal?.throwIfAborted();break}if(o.type!==Vt.Type.ICE_CANDIDATE)throw new Gn("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){e.onProgress?.(new $t("webrtc:end-of-ice-candidates")),e.log.trace("end-of-candidates received");continue}let i=new Bf(s);e.log.trace("%s received new ICE candidate %o",e.direction,s);try{e.onProgress?.(new $t("webrtc:add-ice-candidate",i.candidate)),await r.addIceCandidate(i)}catch(a){e.log.error("%s bad candidate received",e.direction,s,a)}}}catch(n){if(e.log.error("%s error parsing ICE candidate",e.direction,n),e.signal?.aborted===!0&&Vs(r)!=="connected")throw n}};function Vs(r){return Nn?r.iceConnectionState:r.connectionState}function k0(r,t){r[Nn?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch(Vs(r)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new Wn("RTCPeerConnection was closed"));break;default:break}}}async function kf({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=Tf(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new tt("Relay peer was missing");let d=s.getConnections(Pr(f)),m,x=!1;d.length===0?(l?.(new $t("webrtc:dial-relay")),m=await i.dial(u,{signal:e,onProgress:l}),x=!0):(l?.(new $t("webrtc:reuse-relay-connection")),m=d[0]);try{l?.(new $t("webrtc:open-signaling-stream"));let g=await m.newStream(Fs,{signal:e,runOnLimitedConnection:!0}),h=Ps(g).pb(Vt),y=new dr(r),b=new Ge({logger:c},{peerConnection:y,dataChannelOptions:t});try{let p=y.createDataChannel("init");y.onicecandidate=({candidate:S})=>{let k=JSON.stringify(S?.toJSON()??null);a.trace("initiator sending ICE candidate %o",S),h.write({type:Vt.Type.ICE_CANDIDATE,data:k},{signal:e}).catch(I=>{a.error("error sending ICE candidate",I)})},y.onicecandidateerror=S=>{a.error("initiator ICE candidate error",S)};let B=await y.createOffer().catch(S=>{throw a.error("could not execute createOffer",S),new zt("Failed to set createOffer")});a.trace("initiator send SDP offer %s",B.sdp),l?.(new $t("webrtc:send-sdp-offer")),await h.write({type:Vt.Type.SDP_OFFER,data:B.sdp},{signal:e}),await y.setLocalDescription(B).catch(S=>{throw a.error("could not execute setLocalDescription",S),new zt("Failed to set localDescription")}),l?.(new $t("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let L=await h.read({signal:e});if(L.type!==Vt.Type.SDP_ANSWER)throw new zt("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",L.data);let N=new Ls({type:"answer",sdp:L.data});return await y.setRemoteDescription(N).catch(S=>{throw a.error("could not execute setRemoteDescription",S),new zt("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),l?.(new $t("webrtc:read-ice-candidates")),await Ms(y,h,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),p.close(),l?.(new $t("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await g.close({signal:e}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:y,muxerFactory:b}}catch(p){throw a.error("outgoing signaling error",p),y.close(),g.abort(p),p}finally{y.onicecandidate=null,y.onicecandidateerror=null}}finally{if(x)try{await m.close({signal:e})}catch(g){m.abort(g)}}}var T0=lt(af.matchers[0],q("p2p-circuit")),Ks=class extends Zn{transportManager;shutdownController;constructor(t,e){super(),this.transportManager=t.transportManager,this.shutdownController=e.shutdownController}async listen(){queueMicrotask(()=>{this.safeDispatchEvent("listening")})}getAddrs(){return this.transportManager.getListeners().filter(t=>t!==this).map(t=>t.getAddrs().filter(e=>T0.exactMatch(e)).map(e=>e.encapsulate("/webrtc"))).flat()}async close(){this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function Nf({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=Ps(t).pb(Vt);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Vt.Type.ICE_CANDIDATE,data:f},{signal:e}).catch(d=>{o.error("error sending ICE candidate",d)})},o.trace("recipient read SDP offer");let a=await s.read({signal:e});if(a.type!==Vt.Type.SDP_OFFER)throw new zt(`expected message type SDP_OFFER, received: ${a.type??"undefined"} `);o.trace("recipient received SDP offer %s",a.data);let c=new Ls({type:"offer",sdp:a.data});await r.setRemoteDescription(c).catch(u=>{throw o.error("could not execute setRemoteDescription",u),new zt("Failed to set remoteDescription")});let l=await r.createAnswer().catch(u=>{throw o.error("could not execute createAnswer",u),new zt("Failed to create answer")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:Vt.Type.SDP_ANSWER,data:l.sdp},{signal:e}),await r.setLocalDescription(l).catch(u=>{throw o.error("could not execute setLocalDescription",u),new zt("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await Ms(r,s,{direction:"recipient",signal:e,log:o})}catch(a){if(Vs(r)!=="connected")throw o.error("error while handling signaling stream from peer %a",n.remoteAddr,a),r.close(),a;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",n.remoteAddr,a)}let i=qe(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var N0="/webrtc",L0="/p2p-circuit",Fs="/webrtc-signaling/0.0.1",_0=30*1e3,$s=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,e={}){this.components=t,this.init=e,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,jn(1/0,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"})})}[Kn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[yr]=["@libp2p/transport"];[_c]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(Fs,t=>{this._onProtocol(t).catch(e=>{this.log.error("failed to handle incoming connect from %p",t.connection.remotePeer,e)})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(Fs),this._started=!1}createListener(t){return new Ks(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(cf.exactMatch)}dialFilter(t){return this.listenFilter(t)}async dial(t,e){this.log.trace("dialing address: %a",t);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await kf({rtcConfiguration:await Ln(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:t,dataChannelOptions:this.init.dataChannel,signal:e.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:e.onProgress}),i=new ur(this.components,{peerConnection:o,timeline:{open:Date.now()},remoteAddr:n,metrics:this.metrics?.dialerEvents}),a=await e.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,muxerFactory:s,onProgress:e.onProgress});return this._closeOnShutdown(o,i),a}async _onProtocol({connection:t,stream:e}){let n=AbortSignal.timeout(this.init.inboundConnectionTimeout??_0),o=new dr(await Ln(this.init.rtcConfiguration)),s=new Ge(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await Nf({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new ur(this.components,{peerConnection:o,timeline:{open:new Date().getTime()},remoteAddr:i,metrics:this.metrics?.listenerEvents});await this.components.upgrader.upgradeInbound(a,{skipEncryption:!0,skipProtection:!0,muxerFactory:s}),this._closeOnShutdown(o,a)}catch(i){throw this.log.error("incoming signaling error",i),o.close(),e.abort(i),i}}_closeOnShutdown(t,e){let n=()=>{e.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection",o)})};this.shutdownController.signal.addEventListener("abort",n),t.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function Tf(r){let t=r.toString().split(N0+"/");if(t.length!==2)throw new tt("webrtc protocol was not present in multiaddr");if(!t[0].includes(L0))throw new tt("p2p-circuit protocol was not present in multiaddr");let e=qe(t[0]),o=qe("/"+t[1]).getPeerId();if(o==null)throw new tt("destination peer id was missing");let s=e.protos().pop();if(s===void 0)throw new tt("invalid multiaddr");return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:Pr(o)}}function Qa(){let r=pt(),t=!1;return{sink:async e=>{if(t)throw new Error("already piped");t=!0,r.resolve(e)},source:async function*(){yield*await r.promise}()}}function Lf(){let r=Qa(),t=Qa();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}function R0(r){return r[Symbol.asyncIterator]!=null}function U0(...r){let t=[];for(let e of r)R0(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=ze({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var _f=U0;function Rf(r,...t){if(r==null)throw new Error("Empty pipeline");if(tc(r)){let n=r;r=()=>n.source}else if(Df(r)||Uf(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&tc(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)tc(e[n])&&(e[n]=P0(e[n]));return D0(...e)}var D0=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Uf=r=>r?.[Symbol.asyncIterator]!=null,Df=r=>r?.[Symbol.iterator]!=null,tc=r=>r==null?!1:r.sink!=null&&r.source!=null,P0=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=ze({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(Uf(s))o=async function*(){yield*s,n.end()};else if(Df(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return _f(n,o())}return r.source};var Kr=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function Ws(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function ec(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function rc(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Ft(r,...t){if(!rc(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function nc(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function Pf(r,t){Ft(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var Te=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),Of=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),O0=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!O0)throw new Error("Non little-endian hardware is not supported");function H0(r){if(typeof r!="string")throw new Error(`string expected, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function qs(r){if(typeof r=="string")r=H0(r);else if(rc(r))r=zs(r);else throw new Error(`Uint8Array expected, got ${typeof r}`);return r}function Hf(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function Mf(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}var oc=(r,t)=>(Object.assign(t,r),t);function sc(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}function zs(r){return Uint8Array.from(r)}function Ne(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}var Ff=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),M0=Ff("expand 16-byte k"),V0=Ff("expand 32-byte k"),F0=Te(M0),Kf=Te(V0),TA=Kf.slice();function P(r,t){return r<<t|r>>>32-t}function ic(r){return r.byteOffset%4===0}var Gs=64,K0=16,$f=2**32-1,Vf=new Uint32Array;function $0(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(Gs),u=Te(l),f=ic(o)&&ic(s),d=f?Te(o):Vf,m=f?Te(s):Vf;for(let x=0;x<c;i++){if(r(t,e,n,u,i,a),i>=$f)throw new Error("arx: counter overflow");let g=Math.min(Gs,c-x);if(f&&g===Gs){let h=x/4;if(x%4!==0)throw new Error("arx: invalid block position");for(let y=0,b;y<K0;y++)b=h+y,m[b]=d[b]^u[y];x+=Gs;continue}for(let h=0,y;h<g;h++)y=x+h,s[y]=o[y]^l[h];x+=g}}function ac(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Hf({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return Ws(o),Ws(i),ec(s),ec(e),(a,c,l,u,f=0)=>{Ft(a),Ft(c),Ft(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),Ft(u),Ws(f),f<0||f>=$f)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let m=[],x=a.length,g,h;if(x===32)m.push(g=zs(a)),h=Kf;else if(x===16&&e)g=new Uint8Array(32),g.set(a),g.set(a,16),h=F0,m.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${x}`);ic(c)||m.push(c=zs(c));let y=Te(g);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,y,Te(c.subarray(0,16)),y),c=c.subarray(16)}let b=16-o;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let B=new Uint8Array(12);B.set(c,s?0:12-c.length),c=B,m.push(c)}let p=Te(c);return $0(r,h,y,p,l,u,f,i),Ne(...m),u}}var It=(r,t)=>r[t++]&255|(r[t++]&255)<<8,cc=class{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=qs(t),Ft(t,32);let e=It(t,0),n=It(t,2),o=It(t,4),s=It(t,6),i=It(t,8),a=It(t,10),c=It(t,12),l=It(t,14);this.r[0]=e&8191,this.r[1]=(e>>>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|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=It(t,16+2*u)}process(t,e,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],d=i[5],m=i[6],x=i[7],g=i[8],h=i[9],y=It(t,e+0),b=It(t,e+2),p=It(t,e+4),B=It(t,e+6),L=It(t,e+8),N=It(t,e+10),S=It(t,e+12),k=It(t,e+14),I=s[0]+(y&8191),M=s[1]+((y>>>13|b<<3)&8191),_=s[2]+((b>>>10|p<<6)&8191),O=s[3]+((p>>>7|B<<9)&8191),V=s[4]+((B>>>4|L<<12)&8191),C=s[5]+(L>>>1&8191),T=s[6]+((L>>>14|N<<2)&8191),E=s[7]+((N>>>11|S<<5)&8191),w=s[8]+((S>>>8|k<<8)&8191),A=s[9]+(k>>>5|o),v=0,R=v+I*a+M*(5*h)+_*(5*g)+O*(5*x)+V*(5*m);v=R>>>13,R&=8191,R+=C*(5*d)+T*(5*f)+E*(5*u)+w*(5*l)+A*(5*c),v+=R>>>13,R&=8191;let U=v+I*c+M*a+_*(5*h)+O*(5*g)+V*(5*x);v=U>>>13,U&=8191,U+=C*(5*m)+T*(5*d)+E*(5*f)+w*(5*u)+A*(5*l),v+=U>>>13,U&=8191;let H=v+I*l+M*c+_*a+O*(5*h)+V*(5*g);v=H>>>13,H&=8191,H+=C*(5*x)+T*(5*m)+E*(5*d)+w*(5*f)+A*(5*u),v+=H>>>13,H&=8191;let F=v+I*u+M*l+_*c+O*a+V*(5*h);v=F>>>13,F&=8191,F+=C*(5*g)+T*(5*x)+E*(5*m)+w*(5*d)+A*(5*f),v+=F>>>13,F&=8191;let K=v+I*f+M*u+_*l+O*c+V*a;v=K>>>13,K&=8191,K+=C*(5*h)+T*(5*g)+E*(5*x)+w*(5*m)+A*(5*d),v+=K>>>13,K&=8191;let W=v+I*d+M*f+_*u+O*l+V*c;v=W>>>13,W&=8191,W+=C*a+T*(5*h)+E*(5*g)+w*(5*x)+A*(5*m),v+=W>>>13,W&=8191;let j=v+I*m+M*d+_*f+O*u+V*l;v=j>>>13,j&=8191,j+=C*c+T*a+E*(5*h)+w*(5*g)+A*(5*x),v+=j>>>13,j&=8191;let ot=v+I*x+M*m+_*d+O*f+V*u;v=ot>>>13,ot&=8191,ot+=C*l+T*c+E*a+w*(5*h)+A*(5*g),v+=ot>>>13,ot&=8191;let st=v+I*g+M*x+_*m+O*d+V*f;v=st>>>13,st&=8191,st+=C*u+T*l+E*c+w*a+A*(5*h),v+=st>>>13,st&=8191;let ut=v+I*h+M*g+_*x+O*m+V*d;v=ut>>>13,ut&=8191,ut+=C*f+T*u+E*l+w*c+A*a,v+=ut>>>13,ut&=8191,v=(v<<2)+v|0,v=v+R|0,R=v&8191,v=v>>>13,U+=v,s[0]=R,s[1]=U,s[2]=H,s[3]=F,s[4]=K,s[5]=W,s[6]=j,s[7]=ot,s[8]=st,s[9]=ut}finalize(){let{h:t,pad:e}=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]+e[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+e[a]|0)+(i>>>16)|0,t[a]=i&65535;Ne(n)}update(t){nc(this);let{buffer:e,blockLen:n}=this;t=qs(t);let 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}e.set(t.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(e,0,!1),this.pos=0)}return this}destroy(){Ne(this.h,this.r,this.buffer,this.pad)}digestInto(t){nc(this),Pf(t,this),this.finished=!0;let{buffer:e,h:n}=this,{pos:o}=this;if(o){for(e[o++]=1;o<16;o++)e[o]=0;this.process(e,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)t[s++]=n[i]>>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}};function W0(r){let t=(n,o)=>r(o).update(qs(n)).digest(),e=r(new Uint8Array(32));return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=n=>r(n),t}var Wf=W0(r=>new cc(r));function Gf(r,t,e,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=t[0],f=t[1],d=t[2],m=t[3],x=t[4],g=t[5],h=t[6],y=t[7],b=o,p=e[0],B=e[1],L=e[2],N=i,S=a,k=c,I=l,M=u,_=f,O=d,V=m,C=x,T=g,E=h,w=y,A=b,v=p,R=B,U=L;for(let F=0;F<s;F+=2)N=N+M|0,A=P(A^N,16),C=C+A|0,M=P(M^C,12),N=N+M|0,A=P(A^N,8),C=C+A|0,M=P(M^C,7),S=S+_|0,v=P(v^S,16),T=T+v|0,_=P(_^T,12),S=S+_|0,v=P(v^S,8),T=T+v|0,_=P(_^T,7),k=k+O|0,R=P(R^k,16),E=E+R|0,O=P(O^E,12),k=k+O|0,R=P(R^k,8),E=E+R|0,O=P(O^E,7),I=I+V|0,U=P(U^I,16),w=w+U|0,V=P(V^w,12),I=I+V|0,U=P(U^I,8),w=w+U|0,V=P(V^w,7),N=N+_|0,U=P(U^N,16),E=E+U|0,_=P(_^E,12),N=N+_|0,U=P(U^N,8),E=E+U|0,_=P(_^E,7),S=S+O|0,A=P(A^S,16),w=w+A|0,O=P(O^w,12),S=S+O|0,A=P(A^S,8),w=w+A|0,O=P(O^w,7),k=k+V|0,v=P(v^k,16),C=C+v|0,V=P(V^C,12),k=k+V|0,v=P(v^k,8),C=C+v|0,V=P(V^C,7),I=I+M|0,R=P(R^I,16),T=T+R|0,M=P(M^T,12),I=I+M|0,R=P(R^I,8),T=T+R|0,M=P(M^T,7);let H=0;n[H++]=i+N|0,n[H++]=a+S|0,n[H++]=c+k|0,n[H++]=l+I|0,n[H++]=u+M|0,n[H++]=f+_|0,n[H++]=d+O|0,n[H++]=m+V|0,n[H++]=x+C|0,n[H++]=g+T|0,n[H++]=h+E|0,n[H++]=y+w|0,n[H++]=b+A|0,n[H++]=p+v|0,n[H++]=B+R|0,n[H++]=L+U|0}function q0(r,t,e,n){let o=r[0],s=r[1],i=r[2],a=r[3],c=t[0],l=t[1],u=t[2],f=t[3],d=t[4],m=t[5],x=t[6],g=t[7],h=e[0],y=e[1],b=e[2],p=e[3];for(let L=0;L<20;L+=2)o=o+c|0,h=P(h^o,16),d=d+h|0,c=P(c^d,12),o=o+c|0,h=P(h^o,8),d=d+h|0,c=P(c^d,7),s=s+l|0,y=P(y^s,16),m=m+y|0,l=P(l^m,12),s=s+l|0,y=P(y^s,8),m=m+y|0,l=P(l^m,7),i=i+u|0,b=P(b^i,16),x=x+b|0,u=P(u^x,12),i=i+u|0,b=P(b^i,8),x=x+b|0,u=P(u^x,7),a=a+f|0,p=P(p^a,16),g=g+p|0,f=P(f^g,12),a=a+f|0,p=P(p^a,8),g=g+p|0,f=P(f^g,7),o=o+l|0,p=P(p^o,16),x=x+p|0,l=P(l^x,12),o=o+l|0,p=P(p^o,8),x=x+p|0,l=P(l^x,7),s=s+u|0,h=P(h^s,16),g=g+h|0,u=P(u^g,12),s=s+u|0,h=P(h^s,8),g=g+h|0,u=P(u^g,7),i=i+f|0,y=P(y^i,16),d=d+y|0,f=P(f^d,12),i=i+f|0,y=P(y^i,8),d=d+y|0,f=P(f^d,7),a=a+c|0,b=P(b^a,16),m=m+b|0,c=P(c^m,12),a=a+c|0,b=P(b^a,8),m=m+b|0,c=P(c^m,7);let B=0;n[B++]=o,n[B++]=s,n[B++]=i,n[B++]=a,n[B++]=h,n[B++]=y,n[B++]=b,n[B++]=p}var z0=ac(Gf,{counterRight:!1,counterLength:4,allowShortKeys:!1}),G0=ac(Gf,{counterRight:!1,counterLength:8,extendNonceFn:q0,allowShortKeys:!1});var j0=new Uint8Array(16),qf=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(j0.subarray(e))},Z0=new Uint8Array(32);function zf(r,t,e,n,o){let s=r(t,e,Z0),i=Wf.create(s);o&&qf(i,o),qf(i,n);let a=new Uint8Array(16),c=Of(a);sc(c,0,BigInt(o?o.length:0),!0),sc(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return Ne(s,a),l}var jf=r=>(t,e,n)=>(Ft(t,32),Ft(e),{encrypt(s,i){let a=s.length,c=a+16;i?Ft(i,c):i=new Uint8Array(c),r(t,e,s,i,1);let l=zf(r,t,e,i.subarray(0,-16),n);return i.set(l,a),Ne(l),i},decrypt(s,i){let a=s.length,c=a-16;if(a<16)throw new Error("encrypted data must be at least 16 bytes");i?Ft(i,c):i=new Uint8Array(c);let l=s.subarray(0,-16),u=s.subarray(-16),f=zf(r,t,e,l,n);if(!Mf(u,f))throw new Error("invalid tag");return r(t,e,l,i,1),Ne(f),i}}),lc=oc({blockSize:64,nonceLength:12,tagLength:16},jf(z0)),HA=oc({blockSize:64,nonceLength:24,tagLength:16},jf(G0));function Xf(r,t,e){return Qr(r),e===void 0&&(e=new Uint8Array(r.outputLen)),Dr(r,Re(e),Re(t))}var uc=new Uint8Array([0]),Zf=new Uint8Array;function Yf(r,t,e,n=32){if(Qr(r),Yn(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);e===void 0&&(e=Zf);let s=new Uint8Array(o*r.outputLen),i=Dr.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)uc[0]=l+1,a.update(l===0?Zf:c).update(e).update(uc).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),uc.fill(0),s.slice(0,n)}var fc={hashSHA256(r){return ie(r.subarray())},getHKDF(r,t){let e=Xf(ie,t,r),o=Yf(ie,e,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=sn.utils.randomPrivateKey();return{publicKey:sn.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:sn.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return sn.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return lc(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return lc(n,t,e).decrypt(r.subarray(),o)}};var Jf=fc;function Qf(r){return{generateKeypair:r.generateX25519KeyPair,dh:(t,e)=>r.generateX25519SharedKey(t.privateKey,e).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var $r=r=>{let t=wt(2);return t[0]=r>>8,t[1]=r,t};$r.bytes=2;var On=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let t=0;return t+=r[0]<<8,t+=r[1],t}return r.getUint16(0)};On.bytes=2;function th(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function hc(r,t){!t.enabled||!Kr||(r?(t(`LOCAL_STATIC_PUBLIC_KEY ${J(r.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${J(r.privateKey,"hex")}`)):t("Missing local static keys."))}function dc(r,t){!t.enabled||!Kr||(r?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${J(r.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${J(r.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function eh(r,t){!t.enabled||!Kr||t(r?`REMOTE_STATIC_PUBLIC_KEY ${J(r.subarray(),"hex")}`:"Missing remote static public key.")}function pc(r,t){!t.enabled||!Kr||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${J(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function mc(r,t,e){!e.enabled||!Kr||(e(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&J(r.k,"hex")}`),e(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&J(t.k,"hex")}`))}var Wr=class r extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var X0=0,Y0=4294967295,J0="Cipherstate has reached maximum n, a new handshake must be performed",js=class{n;bytes;view;constructor(t=X0){this.n=t,this.bytes=yt(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>Y0)throw new Error(J0)}};var mr=yt(0),qr=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new js(n)}hasKey(){return!!this.k}encryptWithAd(t,e){if(!this.hasKey())return e;this.n.assertValue();let n=this.crypto.encrypt(e,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,e,n){if(!this.hasKey())return e;this.n.assertValue();let o=this.crypto.decrypt(e,this.n.getBytes(),t,this.k,n);return this.n.increment(),o}},gc=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=et(e,"utf-8");this.h=Q0(t,n),this.ck=this.h,this.cs=new qr(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new qr(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new ht(this.h,t))}encryptAndHash(t){let e=this.cs.encryptWithAd(this.h,t);return this.mixHash(e),e}decryptAndHash(t){let e=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),e}split(){let[t,e]=this.crypto.hkdf(this.ck,mr);return[new qr(this.crypto,t),new qr(this.crypto,e)]}},yc=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:e,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=t;this.crypto=e,this.ss=new gc(e,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}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,e=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<e+32)throw new Error("message is not long enough");this.re=t.sublist(e,e+32),this.ss.mixHash(this.re)}readS(t,e=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<e+n)throw new Error("message is not long enough");let o=t.sublist(e,e+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Hn=class extends yc{writeMessageA(t){return new ht(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let e=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new ht(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){let e=this.writeS();return this.writeSE(),new ht(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(e){throw new Wr(`handshake stage 0 validation fail: ${e.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let e=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+e))}catch(e){throw new Wr(`handshake stage 1 validation fail: ${e.message}`)}}readMessageC(t){try{let e=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(e))}catch(e){throw new Wr(`handshake stage 2 validation fail: ${e.message}`)}}};function Q0(r,t){if(t.length<=32){let e=yt(32);return e.set(t),e}else return r.hash(t)}var Zs;(function(r){let t;r.codec=()=>(t==null&&(t=re((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.webtransportCerthashes!=null)for(let s of e.webtransportCerthashes)n.uint32(10),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={webtransportCerthashes:[]},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:{o.webtransportCerthashes.push(e.bytes());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>ee(e,r.codec()),r.decode=e=>te(e,r.codec())})(Zs||(Zs={}));var Mn;(function(r){let t;r.codec=()=>(t==null&&(t=re((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.identityKey!=null&&e.identityKey.byteLength>0&&(n.uint32(10),n.bytes(e.identityKey)),e.identitySig!=null&&e.identitySig.byteLength>0&&(n.uint32(18),n.bytes(e.identitySig)),e.extensions!=null&&(n.uint32(34),Zs.codec().encode(e.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={identityKey:yt(0),identitySig:yt(0)},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:{o.identityKey=e.bytes();break}case 2:{o.identitySig=e.bytes();break}case 4:{o.extensions=Zs.codec().decode(e,e.uint32());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>ee(e,r.codec()),r.decode=e=>te(e,r.codec())})(Mn||(Mn={}));async function wc(r,t,e){let n=await r.sign(rh(t));return Mn.encode({identityKey:Cr(r.publicKey),identitySig:n,extensions:e})}async function bc(r,t,e){try{let n=Mn.decode(r),o=vn(n.identityKey);if(e?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${e}`);if(!t)throw new Error("Remote static does not exist");let s=rh(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new $n(n.message)}}function rh(r){let t=et("noise-libp2p-static-key:");return r instanceof Uint8Array?Et([t,r],t.length+r.length):(r.prepend(t),r)}async function nh(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await wc(s,a.publicKey,l),f=new Hn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});hc(f.s,e),e.trace("Stage 0 - Initiator starting to send first message."),await n.write(f.writeMessageA(mr),t),e.trace("Stage 0 - Initiator finished sending first message."),dc(f.e,e),e.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=f.readMessageB(await n.read(t));e.trace("Stage 1 - Initiator received the message."),pc(f.re,e),eh(f.rs,e),e.trace("Initiator going to check remote's signature...");let m=await bc(d,f.rs,c);e.trace("All good with the signature!"),e.trace("Stage 2 - Initiator sending third handshake message."),await n.write(f.writeMessageC(u),t),e.trace("Stage 2 - Initiator sent message with signed payload.");let[x,g]=f.ss.split();return mc(x,g,e),{payload:m,encrypt:h=>x.encryptWithAd(mr,h),decrypt:(h,y)=>g.decryptWithAd(mr,h,y)}}async function oh(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await wc(s,a.publicKey,l),f=new Hn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});hc(f.s,e),e.trace("Stage 0 - Responder waiting to receive first message."),f.readMessageA(await n.read(t)),e.trace("Stage 0 - Responder received first message."),pc(f.re,e),e.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(f.writeMessageB(u),t),e.trace("Stage 1 - Responder sent the second handshake message with signed payload."),dc(f.e,e),e.trace("Stage 2 - Responder waiting for third handshake message...");let d=f.readMessageC(await n.read(t));e.trace("Stage 2 - Responder received the message, finished handshake.");let m=await bc(d,f.rs,c),[x,g]=f.ss.split();return mc(x,g,e),{payload:m,encrypt:h=>g.encryptWithAd(mr,h),decrypt:(h,y)=>x.decryptWithAd(mr,h,y)}}var ih=16;function ah(r,t){return async function*(e){for await(let n of e)for(let o=0;o<n.length;o+=65519){let s=o+65519;s>n.length&&(s=n.length);let i;n instanceof Uint8Array?i=r.encrypt(n.subarray(o,s)):i=r.encrypt(n.sublist(o,s)),t?.encryptedPackets.increment(),yield new ht($r(i.byteLength),i)}}}function ch(r,t){return async function*(e){for await(let n of e)for(let o=0;o<n.length;o+=65535){let s=o+65535;if(s>n.length&&(s=n.length),s-ih<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-ih);try{let c=r.decrypt(i,a);t?.decryptedPackets.increment(),yield c}catch(c){throw t?.decryptErrors.increment(),c}}}}var Xs=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(t,e={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=e,{metrics:a}=t;this.components=t;let c=s??Jf;this.crypto=Qf(c),this.extensions=o,this.metrics=a?th(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??yt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[yr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,e){let n=Un(t,{lengthEncoder:$r,lengthDecoder:On,maxDataLength:65535}),o=await this.performHandshakeInitiator(n,this.components.privateKey,e?.remotePeer?.publicKey,e),s=await this.createSecureConnection(n,o);t.source=s.source,t.sink=s.sink;let i=vn(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ea(i)}}async secureInbound(t,e){let n=Un(t,{lengthEncoder:$r,lengthDecoder:On,maxDataLength:65535}),o=await this.performHandshakeResponder(n,this.components.privateKey,e?.remotePeer?.publicKey,e),s=await this.createSecureConnection(n,o);t.source=s.source,t.sink=s.sink;let i=vn(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ea(i)}}async performHandshakeInitiator(t,e,n,o){let s;try{s=await nh({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async performHandshakeResponder(t,e,n,o){let s;try{s=await oh({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async createSecureConnection(t,e){let[n,o]=Lf(),s=t.unwrap();return await Rf(n,ah(e,this.metrics),s,i=>hr(i,{lengthDecoder:On}),ch(e,this.metrics),n),o}};function lh(r={}){return t=>new Xs(t,r)}var xc=Object.values(nr).map(r=>r.decoder).reduce((r,t)=>r.or(t));function uh(r,t){let e=r.getConfiguration().certificates?.at(0);if(e?.getFingerprints==null){t.log.trace("fetching fingerprint from local SDP");let o=r.localDescription;return o==null?void 0:eg(o.sdp)}if(t.log.trace("fetching fingerprint from local certificate"),e.getFingerprints().length===0)return;let n=e.getFingerprints()[0].value;if(n==null)throw new Pn("","no fingerprint on local certificate");return n}var tg=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function eg(r){return r.match(tg)?.groups?.fingerprint}function rg(r){for(let t of r.protoNames())if(t.startsWith("ip"))return t.toUpperCase();return"IP6"}function Ys(r){let e=r.stringTuples().filter(n=>n[0]===dh).map(n=>n[1])[0];if(e===void 0||e==="")throw new tt(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function Ec(r){return Gt.decode(xc.decode(r))}function ng(r){let t=Ec(Ys(r)),e=vc(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 Pn(n,r.toString());return[`${e} ${o.join(":").toUpperCase()}`,n]}function vc(r){switch(r){case 17:return"SHA-1";case 18:return"SHA-256";case 19:return"SHA-512";default:throw new Hs(r)}}function og(r,t){let{host:e,port:n}=r.toOptions(),o=rg(r),[s]=ng(r);return`v=0
|
6
|
+
`)}`:`${e} :`}};Ml=$e;D.Constructed=Ml;$e.NAME="CONSTRUCTED";var Ao=class extends Nt{fromBER(t,e,n){return e}toBER(t){return ne}};Ao.override="EndOfContentValueBlock";var Vl,So=class extends St{constructor(t={}){super(t,Ao),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Vl=So;D.EndOfContent=Vl;So.NAME=dn;var Fl,Nr=class extends St{constructor(t={}){super(t,Nt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(t,e,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,e+n>t.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):e+n}toBER(t,e){let n=new ArrayBuffer(2);if(!t){let o=new Uint8Array(n);o[0]=5,o[1]=0}return e&&e.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Fl=Nr;D.Null=Fl;Nr.NAME="NULL";var Bo=class extends Se(Nt){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=z.BufferSourceConverter.toUint8Array(e.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}get value(){for(let t of this.valueHexView)if(t>0)return!0;return!1}set value(t){this.valueHexView[0]=t?255:0}fromBER(t,e,n){let o=z.BufferSourceConverter.toUint8Array(t);return Ae(this,o,e,n)?(this.valueHexView=o.subarray(e,e+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,ua.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Bo.NAME="BooleanValueBlock";var Kl,Io=class extends St{constructor(t={}){super(t,Bo),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Kl=Io;D.Boolean=Kl;Io.NAME="BOOLEAN";var Co=class extends Se(ae){constructor({isConstructed:t=!1,...e}={}){super(e),this.isConstructed=t}fromBER(t,e,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=ae.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===dn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Dl)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(t,e,n),this.blockLength=n;return o}toBER(t,e){return this.isConstructed?ae.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Co.NAME="OctetStringValueBlock";var $l,ko=class r extends St{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Co),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(t,e,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),e;if(!this.valueBlock.isConstructed){let s=(t instanceof ArrayBuffer?new Uint8Array(t):t).subarray(e,e+n);try{if(s.byteLength){let i=rs(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(t,e,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?$e.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${z.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let t=[];for(let e of this.valueBlock.value)e instanceof r&&t.push(e.valueBlock.valueHexView);return z.BufferSourceConverter.concat(t)}};$l=ko;D.OctetString=$l;ko.NAME=Dl;var To=class extends Se(ae){constructor({unusedBits:t=0,isConstructed:e=!1,...n}={}){super(n),this.unusedBits=t,this.isConstructed=e,this.blockLength=this.valueHexView.byteLength}fromBER(t,e,n){if(!n)return e;let o=-1;if(this.isConstructed){if(o=ae.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===dn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Pl)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let s=z.BufferSourceConverter.toUint8Array(t);if(!Ae(this,s,e,n))return-1;let i=s.subarray(e,e+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=rs(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,e+n}toBER(t,e){if(this.isConstructed)return ae.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ne;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};To.NAME="BitStringValueBlock";var Wl,Lr=class extends St{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},To),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(t,e,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(t,e,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return $e.prototype.onAsciiEncoding.call(this);{let t=[],e=this.valueBlock.valueHexView;for(let o of e)t.push(o.toString(2).padStart(8,"0"));let n=t.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Wl=Lr;D.BitString=Wl;Lr.NAME=Pl;var ql;function um(r,t){let e=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<i?i:c,f=0;for(let d=u;d>=0;d--,f++){switch(!0){case f<a.length:l=s[i-f]+a[c-f]+e[0];break;default:l=s[i-f]+e[0]}switch(e[0]=l/10,!0){case f>=s.length:s=go(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return e[0]>0&&(s=go(e,s)),s}function Ul(r){if(r>=fn.length)for(let t=fn.length;t<=r;t++){let e=new Uint8Array([0]),n=fn[t-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+e[0]]);e[0]=s[0]/10,n[o]=s[0]%10}e[0]>0&&(n=go(e,n)),fn.push(n)}return fn[r]}function fm(r,t){let e=0,n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=s[i-u]-a[c-u]-e,!0){case l<0:e=1,s[i-u]=l+10;break;default:e=0,s[i-u]=l}if(e>0)for(let f=i-c+1;f>=0;f--,u++)if(l=s[i-u]-e,l<0)e=1,s[i-u]=l+10;else{e=0,s[i-u]=l;break}return s.slice()}var pn=class extends Se(Nt){constructor({value:t,...e}={}){super(e),this._valueDec=0,e.valueHex&&this.setValueHex(),t!==void 0&&(this.valueDec=t)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=ua.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Ll(t))}get valueDec(){return this._valueDec}fromDER(t,e,n,o=0){let s=this.fromBER(t,e,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(t=!1){let e=this.valueHexView;switch(!0){case(e[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(e,1),this.valueHexView=n}break;case(e[0]===0&&(e[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(t)}fromBER(t,e,n){let o=super.fromBER(t,e,n);return o===-1||this.setValueHex(),o}toBER(t){return t?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let t=this.valueHexView.length*8-1,e=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case t:e=fm(Ul(n),e),i="-";break;default:e=um(e,Ul(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=Rl.charAt(e[c]));return a===!1&&(i+=Rl.charAt(0)),i}};ql=pn;pn.NAME="IntegerValueBlock";Object.defineProperty(ql.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var zl,Bt=class r extends St{constructor(t={}){super(t,pn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return yo(),BigInt(this.valueBlock.toString())}static fromBigInt(t){yo();let e=BigInt(t),n=new hn,o=e.toString(16).replace(/^-/,""),s=new Uint8Array(z.Convert.FromHex(o));if(e<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${z.Convert.ToHex(a)}`)+e,u=z.BufferSourceConverter.toUint8Array(z.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let t=new r({valueHex:this.valueBlock.valueHexView});return t.valueBlock.toDER(),t}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};zl=Bt;D.Integer=zl;Bt.NAME="INTEGER";var Gl,No=class extends Bt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Gl=No;D.Enumerated=Gl;No.NAME="ENUMERATED";var mn=class extends Se(Nt){constructor({valueDec:t=-1,isFirstSid:e=!1,...n}={}){super(n),this.valueDec=t,this.isFirstSid=e}fromBER(t,e,n){if(!n)return e;let o=z.BufferSourceConverter.toUint8Array(t);if(!Ae(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=ir(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){yo();let e=BigInt(t).toString(2);for(;e.length%7;)e="0"+e;let n=new Uint8Array(e.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(e.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=Ke(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",ne;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let t="";if(this.isHexOnly)t=z.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let e=this.valueDec;this.valueDec<=39?t="0.":this.valueDec<=79?(t="1.",e-=40):(t="2.",e-=80),t+=e.toString()}else t=this.valueDec.toString();return t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};mn.NAME="sidBlock";var Lo=class extends Nt{constructor({value:t=Rr,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new mn;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t){let e=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(t);if(o.byteLength===0)return this.error=this.value[n].error,ne;e.push(o)}return fa(e)}fromString(t){this.value=[];let e=0,n=0,o="",s=!1;do if(n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new mn;if(o>Number.MAX_SAFE_INTEGER){yo();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e?(o=`{${o}}`,this.value[n].isFirstSid?t=`2.{${o} - 80}`:t+=o):t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Lo.NAME="ObjectIdentifierValueBlock";var jl,_r=class extends St{constructor(t={}){super(t,Lo),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};jl=_r;D.ObjectIdentifier=jl;_r.NAME="OBJECT IDENTIFIER";var gn=class extends Se(xe){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=z.BufferSourceConverter.toUint8Array(t);if(!Ae(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=ir(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=Ke(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",ne;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let t="";return this.isHexOnly?t=z.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};gn.NAME="relativeSidBlock";var _o=class extends Nt{constructor({value:t=Rr,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new gn;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t,e){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(t);if(s.byteLength===0)return this.error=this.value[o].error,ne;n.push(s)}return fa(n)}fromString(t){this.value=[];let e=0,n=0,o="";do{n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1;let s=new gn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e&&(o=`{${o}}`),t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};_o.NAME="RelativeObjectIdentifierValueBlock";var Zl,Ro=class extends St{constructor(t={}){super(t,_o),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Zl=Ro;D.RelativeObjectIdentifier=Zl;Ro.NAME="RelativeObjectIdentifier";var Xl,Ee=class extends $e{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Xl=Ee;D.Sequence=Xl;Ee.NAME="SEQUENCE";var Yl,Uo=class extends $e{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Yl=Uo;D.Set=Yl;Uo.NAME="SET";var Do=class extends Se(Nt){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=Rr}toJSON(){return{...super.toJSON(),value:this.value}}};Do.NAME="StringValueBlock";var Po=class extends Do{};Po.NAME="SimpleStringValueBlock";var Ut=class extends xo{constructor({...t}={}){super(t,Po)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,z.BufferSourceConverter.toUint8Array(t))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);this.valueBlock.value=t}};Ut.NAME="SIMPLE STRING";var Oo=class extends Ut{fromBuffer(t){this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=z.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=z.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf8String(t)),this.valueBlock.value=t}};Oo.NAME="Utf8StringValueBlock";var Jl,ve=class extends Oo{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Jl=ve;D.Utf8String=Jl;ve.NAME="UTF8String";var Ho=class extends Ut{fromBuffer(t){this.valueBlock.value=z.Convert.ToUtf16String(t),this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf16String(t))}};Ho.NAME="BmpStringValueBlock";var Ql,Mo=class extends Ho{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Ql=Mo;D.BmpString=Ql;Mo.NAME="BMPString";var Vo=class extends Ut{fromBuffer(t){let e=ArrayBuffer.isView(t)?t.slice().buffer:t.slice(0),n=new Uint8Array(e);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(e))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e*4);for(let o=0;o<e;o++){let s=Ke(t.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=t}};Vo.NAME="UniversalStringValueBlock";var tu,Fo=class extends Vo{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};tu=Fo;D.UniversalString=tu;Fo.NAME="UniversalString";var eu,Ko=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};eu=Ko;D.NumericString=eu;Ko.NAME="NumericString";var ru,$o=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};ru=$o;D.PrintableString=ru;$o.NAME="PrintableString";var nu,Wo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};nu=Wo;D.TeletexString=nu;Wo.NAME="TeletexString";var ou,qo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};ou=qo;D.VideotexString=ou;qo.NAME="VideotexString";var su,zo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};su=zo;D.IA5String=su;zo.NAME="IA5String";var iu,Go=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};iu=Go;D.GraphicString=iu;Go.NAME="GraphicString";var au,yn=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};au=yn;D.VisibleString=au;yn.NAME="VisibleString";var cu,jo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};cu=jo;D.GeneralString=cu;jo.NAME="GeneralString";var lu,Zo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};lu=Zo;D.CharacterString=lu;Zo.NAME="CharacterString";var uu,wn=class extends yn{constructor({value:t,valueDate:e,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,t){this.fromString(t),this.valueBlock.valueHexView=new Uint8Array(t.length);for(let o=0;o<t.length;o++)this.valueBlock.valueHexView[o]=t.charCodeAt(o)}e&&(this.fromDate(e),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(t){this.fromString(String.fromCharCode.apply(null,z.BufferSourceConverter.toUint8Array(t)))}toBuffer(){let t=this.toString(),e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return e}fromDate(t){this.year=t.getUTCFullYear(),this.month=t.getUTCMonth()+1,this.day=t.getUTCDate(),this.hour=t.getUTCHours(),this.minute=t.getUTCMinutes(),this.second=t.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(t){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(t);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(t="iso"){if(t==="iso"){let e=new Array(7);return e[0]=Mt(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Mt(this.month,2),e[2]=Mt(this.day,2),e[3]=Mt(this.hour,2),e[4]=Mt(this.minute,2),e[5]=Mt(this.second,2),e[6]="Z",e.join("")}return super.toString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};uu=wn;D.UTCTime=uu;wn.NAME="UTCTime";var fu,Xo=class extends wn{constructor(t={}){var e;super(t),(e=this.millisecond)!==null&&e!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(t){super.fromDate(t),this.millisecond=t.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(t){let e=!1,n="",o="",s=0,i,a=0,c=0;if(t[t.length-1]==="Z")n=t.substring(0,t.length-1),e=!0;else{let f=new Number(t[t.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=t}if(e){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,d=n.indexOf("+"),m="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(m=n.substring(d+1),n=n.substring(0,d),m.length!==2&&m.length!==4)throw new Error("Wrong input string for conversion");let x=parseInt(m.substring(0,2),10);if(isNaN(x.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*x,m.length===4){if(x=parseInt(m.substring(2,4),10),isNaN(x.valueOf()))throw new Error("Wrong input string for conversion");c=f*x}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");s=f.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*s;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(e===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(t="iso"){if(t==="iso"){let e=[];return e.push(Mt(this.year,4)),e.push(Mt(this.month,2)),e.push(Mt(this.day,2)),e.push(Mt(this.hour,2)),e.push(Mt(this.minute,2)),e.push(Mt(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(Mt(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};fu=Xo;D.GeneralizedTime=fu;Xo.NAME="GeneralizedTime";var hu,Yo=class extends ve{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};hu=Yo;D.DATE=hu;Yo.NAME="DATE";var du,Jo=class extends ve{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};du=Jo;D.TimeOfDay=du;Jo.NAME="TimeOfDay";var pu,Qo=class extends ve{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};pu=Qo;D.DateTime=pu;Qo.NAME="DateTime";var mu,ts=class extends ve{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};mu=ts;D.Duration=mu;ts.NAME="Duration";var gu,es=class extends ve{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};gu=es;D.TIME=gu;es.NAME="TIME";function J(r,t="utf8"){let e=uo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var bn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},ns=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var yu={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new ns("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 We=yu;async function wu(r){let t=await We.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await dm(t);return{privateKey:e[0],publicKey:e[1]}}async function bu(r,t){let e=await We.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await We.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function xu(r,t,e){let n=await We.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return We.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function dm(r){if(r.privateKey==null||r.publicKey==null)throw new tt("Private and public key are required");return Promise.all([We.get().subtle.exportKey("jwk",r.privateKey),We.get().subtle.exportKey("jwk",r.publicKey)])}function pa(r){if(r.kty!=="RSA")throw new tt("invalid key type");if(r.n==null)throw new tt("invalid key modulus");return et(r.n,"base64url").length*8}var Ur=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=xn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return vt.createV1(114,this._multihash)}toString(){return nt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Rt(this.raw,t.raw)}verify(t,e){return xu(this._key,e,t)}},En=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=xn.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Rt(this.raw,t.raw)}sign(t){return bu(this._key,t)}};var os=8192,ma=18;function Eu(r){let{result:t}=da(r),e=t.valueBlock.value;return{n:ce(e[1]),e:ce(e[2]),d:ce(e[3]),p:ce(e[4]),q:ce(e[5]),dp:ce(e[6]),dq:ce(e[7]),qi:ce(e[8]),kty:"RSA",alg:"RS256"}}function pm(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new tt("JWK was missing components");let e=new Ee({value:[new Bt({value:0}),Bt.fromBigInt(le(et(r.n,"base64url"))),Bt.fromBigInt(le(et(r.e,"base64url"))),Bt.fromBigInt(le(et(r.d,"base64url"))),Bt.fromBigInt(le(et(r.p,"base64url"))),Bt.fromBigInt(le(et(r.q,"base64url"))),Bt.fromBigInt(le(et(r.dp,"base64url"))),Bt.fromBigInt(le(et(r.dq,"base64url"))),Bt.fromBigInt(le(et(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function vu(r){let{result:t}=da(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:ce(e[0]),e:ce(e[1])}}function ga(r){if(r.n==null||r.e==null)throw new tt("JWK was missing components");let e=new Ee({value:[new Ee({value:[new _r({value:"1.2.840.113549.1.1.1"}),new Nr]}),new Lr({valueHex:new Ee({value:[Bt.fromBigInt(le(et(r.n,"base64url"))),Bt.fromBigInt(le(et(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function ce(r){let t=r.valueBlock.valueHexView;for(;t[0]===0;)t=t.subarray(1);return J(t,"base64url")}function le(r){let t=[];return r.forEach(function(e){let n=e.toString(16);n.length%2>0&&(n=`0${n}`),t.push(n)}),BigInt("0x"+t.join(""))}function Au(r){let t=Eu(r);return Su(t)}function ya(r){let t=vu(r);if(pa(t)>os)throw new gr("Key size is too large");let e=ie(se.encode({Type:bt.RSA,Data:r})),n=Ot(ma,e);return new Ur(t,n)}function Su(r){if(pa(r)>os)throw new tt("Key size is too large");let t=Iu(r),e=ie(se.encode({Type:bt.RSA,Data:ga(t.publicKey)})),n=Ot(ma,e);return new En(t.privateKey,new Ur(t.publicKey,n))}async function Bu(r){if(r>os)throw new tt("Key size is too large");let t=await wu(r),e=ie(se.encode({Type:bt.RSA,Data:ga(t.publicKey)})),n=Ot(ma,e);return new En(t.privateKey,new Ur(t.publicKey,n))}function Iu(r){if(r==null)throw new tt("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var ss=class extends Ar{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Qr(t);let n=Re(e);if(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 o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return vr(this),this.iHash.update(t),this}digestInto(t){vr(this),Er(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,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=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Dr=(r,t,e)=>new ss(r,t).update(e).digest();Dr.create=(r,t)=>new ss(r,t);function Cu(r){r.lowS!==void 0&&Zt("lowS",r.lowS),r.prehash!==void 0&&Zt("prehash",r.prehash)}function mm(r){let t=nn(r);Wt(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:gm,hexToBytes:ym}=ro,Be={Err:class extends Error{constructor(t=""){super(t)}},_tlv:{encode:(r,t)=>{let{Err:e}=Be;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=Je(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Je(o.length/2|128):"";return`${Je(r)}${s}${o}${t}`},decode(r,t){let{Err:e}=Be,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("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 e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=Be;if(r<Ie)throw new t("integer: negative integers are not allowed");let e=Je(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected assertion");return e},decode(r){let{Err:t}=Be;if(r[0]&128)throw new t("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return gm(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Be,o=typeof r=="string"?ym(r):r;Br(o);let{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:l,l:u}=n.decode(2,c);if(u.length)throw new t("Invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=Be,n=`${t.encode(2,e.encode(r.r))}${t.encode(2,e.encode(r.s))}`;return t.encode(48,n)}},Ie=BigInt(0),xt=BigInt(1),qb=BigInt(2),ku=BigInt(3),zb=BigInt(4);function wm(r){let t=mm(r),{Fp:e}=t,n=He(t.n,t.nBitLength),o=t.toBytes||((g,h,y)=>{let b=h.toAffine();return we(Uint8Array.from([4]),e.toBytes(b.x),e.toBytes(b.y))}),s=t.fromBytes||(g=>{let h=g.subarray(1),y=e.fromBytes(h.subarray(0,e.BYTES)),b=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:y,y:b}});function i(g){let{a:h,b:y}=t,b=e.sqr(g),p=e.mul(b,g);return e.add(e.add(p,e.mul(g,h)),y)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return en(g,xt,t.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:y,wrapPrivateKey:b,n:p}=t;if(h&&typeof g!="bigint"){if(Pe(g)&&(g=me(g)),typeof g!="string"||!h.includes(g.length))throw new Error("Invalid key");g=g.padStart(y*2,"0")}let B;try{B=typeof g=="bigint"?g:ge(it("private key",g,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof g}`)}return b&&(B=Z(B,p)),At("private key",B,xt,p),B}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=tr((g,h)=>{let{px:y,py:b,pz:p}=g;if(e.eql(p,e.ONE))return{x:y,y:b};let B=g.is0();h==null&&(h=B?e.ONE:e.inv(p));let L=e.mul(y,h),N=e.mul(b,h),S=e.mul(p,h);if(B)return{x:e.ZERO,y:e.ZERO};if(!e.eql(S,e.ONE))throw new Error("invZ was invalid");return{x:L,y:N}}),f=tr(g=>{if(g.is0()){if(t.allowInfinityPoint&&!e.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:h,y}=g.toAffine();if(!e.isValid(h)||!e.isValid(y))throw new Error("bad point: x or y not FE");let b=e.sqr(y),p=i(h);if(!e.eql(b,p))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,y,b){if(this.px=h,this.py=y,this.pz=b,h==null||!e.isValid(h))throw new Error("x required");if(y==null||!e.isValid(y))throw new Error("y required");if(b==null||!e.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:y,y:b}=h||{};if(!h||!e.isValid(y)||!e.isValid(b))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let p=B=>e.eql(B,e.ZERO);return p(y)&&p(b)?d.ZERO:new d(y,b,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let y=e.invertBatch(h.map(b=>b.pz));return h.map((b,p)=>b.toAffine(y[p])).map(d.fromAffine)}static fromHex(h){let y=d.fromAffine(s(it("pointHex",h)));return y.assertValidity(),y}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,y){return so(d,n,h,y)}_setWindowSize(h){x.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:y,py:b,pz:p}=this,{px:B,py:L,pz:N}=h,S=e.eql(e.mul(y,N),e.mul(B,p)),k=e.eql(e.mul(b,N),e.mul(L,p));return S&&k}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:y}=t,b=e.mul(y,ku),{px:p,py:B,pz:L}=this,N=e.ZERO,S=e.ZERO,k=e.ZERO,I=e.mul(p,p),M=e.mul(B,B),_=e.mul(L,L),O=e.mul(p,B);return O=e.add(O,O),k=e.mul(p,L),k=e.add(k,k),N=e.mul(h,k),S=e.mul(b,_),S=e.add(N,S),N=e.sub(M,S),S=e.add(M,S),S=e.mul(N,S),N=e.mul(O,N),k=e.mul(b,k),_=e.mul(h,_),O=e.sub(I,_),O=e.mul(h,O),O=e.add(O,k),k=e.add(I,I),I=e.add(k,I),I=e.add(I,_),I=e.mul(I,O),S=e.add(S,I),_=e.mul(B,L),_=e.add(_,_),I=e.mul(_,O),N=e.sub(N,I),k=e.mul(_,M),k=e.add(k,k),k=e.add(k,k),new d(N,S,k)}add(h){l(h);let{px:y,py:b,pz:p}=this,{px:B,py:L,pz:N}=h,S=e.ZERO,k=e.ZERO,I=e.ZERO,M=t.a,_=e.mul(t.b,ku),O=e.mul(y,B),V=e.mul(b,L),C=e.mul(p,N),T=e.add(y,b),E=e.add(B,L);T=e.mul(T,E),E=e.add(O,V),T=e.sub(T,E),E=e.add(y,p);let w=e.add(B,N);return E=e.mul(E,w),w=e.add(O,C),E=e.sub(E,w),w=e.add(b,p),S=e.add(L,N),w=e.mul(w,S),S=e.add(V,C),w=e.sub(w,S),I=e.mul(M,E),S=e.mul(_,C),I=e.add(S,I),S=e.sub(V,I),I=e.add(V,I),k=e.mul(S,I),V=e.add(O,O),V=e.add(V,O),C=e.mul(M,C),E=e.mul(_,E),V=e.add(V,C),C=e.sub(O,C),C=e.mul(M,C),E=e.add(E,C),O=e.mul(V,E),k=e.add(k,O),O=e.mul(w,E),S=e.mul(T,S),S=e.sub(S,O),O=e.mul(T,V),I=e.mul(w,I),I=e.add(I,O),new d(S,k,I)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return x.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){At("scalar",h,Ie,t.n);let y=d.ZERO;if(h===Ie)return y;if(h===xt)return this;let{endo:b}=t;if(!b)return x.unsafeLadder(this,h);let{k1neg:p,k1:B,k2neg:L,k2:N}=b.splitScalar(h),S=y,k=y,I=this;for(;B>Ie||N>Ie;)B&xt&&(S=S.add(I)),N&xt&&(k=k.add(I)),I=I.double(),B>>=xt,N>>=xt;return p&&(S=S.negate()),L&&(k=k.negate()),k=new d(e.mul(k.px,b.beta),k.py,k.pz),S.add(k)}multiply(h){let{endo:y,n:b}=t;At("scalar",h,xt,b);let p,B;if(y){let{k1neg:L,k1:N,k2neg:S,k2:k}=y.splitScalar(h),{p:I,f:M}=this.wNAF(N),{p:_,f:O}=this.wNAF(k);I=x.constTimeNegate(L,I),_=x.constTimeNegate(S,_),_=new d(e.mul(_.px,y.beta),_.py,_.pz),p=I.add(_),B=M.add(O)}else{let{p:L,f:N}=this.wNAF(h);p=L,B=N}return d.normalizeZ([p,B])[0]}multiplyAndAddUnsafe(h,y,b){let p=d.BASE,B=(N,S)=>S===Ie||S===xt||!N.equals(p)?N.multiplyUnsafe(S):N.multiply(S),L=B(this,y).add(B(h,b));return L.is0()?void 0:L}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:y}=t;if(h===xt)return!0;if(y)return y(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:y}=t;return h===xt?this:y?y(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return Zt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return Zt("isCompressed",h),me(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let m=t.nBitLength,x=oo(d,t.endo?Math.ceil(m/2):m);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function bm(r){let t=nn(r);return Wt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Tu(r){let t=bm(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(C){return Z(C,n)}function a(C){return no(C,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=wm({...t,toBytes(C,T,E){let w=T.toAffine(),A=e.toBytes(w.x),v=we;return Zt("isCompressed",E),E?v(Uint8Array.from([T.hasEvenY()?2:3]),A):v(Uint8Array.from([4]),A,e.toBytes(w.y))},fromBytes(C){let T=C.length,E=C[0],w=C.subarray(1);if(T===o&&(E===2||E===3)){let A=ge(w);if(!en(A,xt,e.ORDER))throw new Error("Point is not on curve");let v=u(A),R;try{R=e.sqrt(v)}catch(F){let K=F instanceof Error?": "+F.message:"";throw new Error("Point is not on curve"+K)}let U=(R&xt)===xt;return(E&1)===1!==U&&(R=e.neg(R)),{x:A,y:R}}else if(T===s&&E===4){let A=e.fromBytes(w.subarray(0,e.BYTES)),v=e.fromBytes(w.subarray(e.BYTES,2*e.BYTES));return{x:A,y:v}}else throw new Error(`Point of length ${T} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),d=C=>me(Oe(C,t.nByteLength));function m(C){let T=n>>xt;return C>T}function x(C){return m(C)?i(-C):C}let g=(C,T,E)=>ge(C.slice(T,E));class h{constructor(T,E,w){this.r=T,this.s=E,this.recovery=w,this.assertValidity()}static fromCompact(T){let E=t.nByteLength;return T=it("compactSignature",T,E*2),new h(g(T,0,E),g(T,E,2*E))}static fromDER(T){let{r:E,s:w}=Be.toSig(it("DER",T));return new h(E,w)}assertValidity(){At("r",this.r,xt,n),At("s",this.s,xt,n)}addRecoveryBit(T){return new h(this.r,this.s,T)}recoverPublicKey(T){let{r:E,s:w,recovery:A}=this,v=N(it("msgHash",T));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let R=A===2||A===3?E+t.n:E;if(R>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=A&1?"03":"02",H=c.fromHex(U+d(R)),F=a(R),K=i(-v*F),W=i(w*F),j=c.BASE.multiplyAndAddUnsafe(H,K,W);if(!j)throw new Error("point at infinify");return j.assertValidity(),j}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return Qe(this.toDERHex())}toDERHex(){return Be.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Qe(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let y={isValidPrivateKey(C){try{return l(C),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let C=Bi(t.n);return sl(t.randomBytes(C),t.n)},precompute(C=8,T=c.BASE){return T._setWindowSize(C),T.multiply(BigInt(3)),T}};function b(C,T=!0){return c.fromPrivateKey(C).toRawBytes(T)}function p(C){let T=Pe(C),E=typeof C=="string",w=(T||E)&&C.length;return T?w===o||w===s:E?w===2*o||w===2*s:C instanceof c}function B(C,T,E=!0){if(p(C))throw new Error("first arg must be private key");if(!p(T))throw new Error("second arg must be public key");return c.fromHex(T).multiply(l(C)).toRawBytes(E)}let L=t.bits2int||function(C){let T=ge(C),E=C.length*8-t.nBitLength;return E>0?T>>BigInt(E):T},N=t.bits2int_modN||function(C){return i(L(C))},S=rn(t.nBitLength);function k(C){return At(`num < 2^${t.nBitLength}`,C,Ie,S),Oe(C,t.nByteLength)}function I(C,T,E=M){if(["recovered","canonical"].some(st=>st in E))throw new Error("sign() legacy options not supported");let{hash:w,randomBytes:A}=t,{lowS:v,prehash:R,extraEntropy:U}=E;v==null&&(v=!0),C=it("msgHash",C),Cu(E),R&&(C=it("prehashed msgHash",w(C)));let H=N(C),F=l(T),K=[k(F),k(H)];if(U!=null&&U!==!1){let st=U===!0?A(e.BYTES):U;K.push(it("extraEntropy",st))}let W=we(...K),j=H;function ot(st){let ut=L(st);if(!f(ut))return;let _t=a(ut),mt=c.BASE.multiply(ut).toAffine(),Pt=i(mt.x);if(Pt===Ie)return;let ue=i(_t*i(j+Pt*F));if(ue===Ie)return;let zr=(mt.x===Pt?0:2)|Number(mt.y&xt),Gr=ue;return v&&m(ue)&&(Gr=x(ue),zr^=1),new h(Pt,Gr,zr)}return{seed:W,k2sig:ot}}let M={lowS:t.lowS,prehash:!1},_={lowS:t.lowS,prehash:!1};function O(C,T,E=M){let{seed:w,k2sig:A}=I(C,T,E),v=t;return xi(v.hash.outputLen,v.nByteLength,v.hmac)(w,A)}c.BASE._setWindowSize(8);function V(C,T,E,w=_){let A=C;if(T=it("msgHash",T),E=it("publicKey",E),"strict"in w)throw new Error("options.strict was renamed to lowS");Cu(w);let{lowS:v,prehash:R}=w,U,H;try{if(typeof A=="string"||Pe(A))try{U=h.fromDER(A)}catch(mt){if(!(mt instanceof Be.Err))throw mt;U=h.fromCompact(A)}else if(typeof A=="object"&&typeof A.r=="bigint"&&typeof A.s=="bigint"){let{r:mt,s:Pt}=A;U=new h(mt,Pt)}else throw new Error("PARSE");H=c.fromHex(E)}catch(mt){if(mt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(v&&U.hasHighS())return!1;R&&(T=t.hash(T));let{r:F,s:K}=U,W=N(T),j=a(K),ot=i(W*j),st=i(F*j),ut=c.BASE.multiplyAndAddUnsafe(H,ot,st)?.toAffine();return ut?i(ut.x)===F:!1}return{CURVE:t,getPublicKey:b,getSharedSecret:B,sign:O,verify:V,ProjectivePoint:c,Signature:h,utils:y}}function xm(r){return{hash:r,hmac:(t,...e)=>Dr(r,t,hi(...e)),randomBytes:tn}}function Nu(r,t){let e=n=>Tu({...r,...xm(n)});return Object.freeze({...e(t),create:e})}var Ru=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Lu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Em=BigInt(1),wa=BigInt(2),_u=(r,t)=>(r+t/wa)/t;function vm(r){let t=Ru,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=at(u,e,t)*u%t,d=at(f,e,t)*u%t,m=at(d,wa,t)*l%t,x=at(m,o,t)*m%t,g=at(x,s,t)*x%t,h=at(g,a,t)*g%t,y=at(h,c,t)*h%t,b=at(y,a,t)*g%t,p=at(b,e,t)*u%t,B=at(p,i,t)*x%t,L=at(B,n,t)*l%t,N=at(L,wa,t);if(!ba.eql(ba.sqr(N),r))throw new Error("Cannot find square root");return N}var ba=He(Ru,void 0,void 0,{sqrt:vm}),ar=Nu({a:BigInt(0),b:BigInt(7),Fp:ba,n:Lu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Lu,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Em*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=_u(s*r,t),c=_u(-n*r,t),l=Z(r-a*e-c*o,t),u=Z(-a*n-c*s,t),f=l>i,d=u>i;if(f&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},ie),ex=BigInt(0);var rx=ar.ProjectivePoint;function Et(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=wt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}function Uu(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Du(r,t,e){let n=cn.digest(e instanceof Uint8Array?e:e.subarray());if(Uu(n))return n.then(({digest:o})=>ar.verify(t,o,r)).catch(o=>{throw new bn(String(o))});try{return ar.verify(t,n.digest,r)}catch(o){throw new bn(String(o))}}var is=class{type="secp256k1";raw;_key;constructor(t){this._key=Ou(t),this.raw=Pu(this._key)}toMultihash(){return de.digest(Cr(this))}toCID(){return vt.createV1(114,this.toMultihash())}toString(){return nt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Rt(this.raw,t.raw)}verify(t,e){return Du(this._key,e,t)}};function xa(r){return new is(r)}function Pu(r){return ar.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Ou(r){try{return ar.ProjectivePoint.fromHex(r),r}catch(t){throw new gr(String(t))}}function vn(r){let{Type:t,Data:e}=se.decode(r),n=e??new Uint8Array;switch(t){case bt.RSA:return ya(n);case bt.Ed25519:return Ni(n);case bt.secp256k1:return xa(n);default:throw new Ze}}function Hu(r){let{Type:t,Data:e}=se.decode(r.digest),n=e??new Uint8Array;switch(t){case bt.Ed25519:return Ni(n);case bt.secp256k1:return xa(n);default:throw new Ze}}function Cr(r){return se.encode({Type:bt[r.type],Data:r.raw})}var Mu=Symbol.for("nodejs.util.inspect.custom"),Sm=114,An=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()})`}[ti]=!0;toString(){return this.string==null&&(this.string=nt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return vt.createV1(Sm,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Rt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Rt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Mu](){return`PeerId(${this.toString()})`}},Sn=class extends An{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Bn=class extends An{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},In=class extends An{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Bm=2336,as=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=de.digest(et(this.url))}[Mu](){return`PeerId(${this.url})`}[ti]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return vt.createV1(Bm,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=J(t)),t.toString()===this.toString())}};function Pr(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=_e(nt.decode(`z${r}`));else{if(t==null)throw new tt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=_e(t.decode(r))}return Im(e)}function Ea(r){if(r.type==="Ed25519")return new Bn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new In({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Sn({multihash:r.toCID().multihash,publicKey:r});throw new Ze}function Im(r){if(km(r))return new Sn({multihash:r});if(Cm(r))try{let t=Hu(r);if(t.type==="Ed25519")return new Bn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new In({multihash:r,publicKey:t})}catch{let e=J(r.digest);return new as(new URL(e))}throw new zn("Supplied PeerID Multihash is invalid")}function Cm(r){return r.code===de.code}function km(r){return r.code===cn.code}var cs=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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 e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=t,s+=u,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[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];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;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 e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Vu=45,Tm=15,Or=new cs;function va(r){if(!(r.length>Tm))return Or.new(r).parseWith(()=>Or.readIPv4Addr())}function Aa(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Vu))return Or.new(r).parseWith(()=>Or.readIPv6Addr())}function ls(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Vu))return Or.new(r).parseWith(()=>Or.readIPAddr())}var y1=parseInt("0xFFFF",16),w1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function us(r){return!!va(r)}function fs(r){return!!Aa(r)}function hs(r){return!!ls(r)}var $u=us,Um=fs,Sa=function(r){let t=0;if(r=r.toString().trim(),$u(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Um(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=$u(e[n]),i;s&&(i=Sa(e[n]),e[n]=J(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,J(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},Wu=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Hr={},Ba={},Pm=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];Pm.forEach(r=>{let t=Om(...r);Ba[t.code]=t,Hr[t.name]=t});function Om(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function Q(r){if(typeof r=="number"){if(Ba[r]!=null)return Ba[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Hr[r]!=null)return Hr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var e2=Q("ip4"),r2=Q("ip6"),n2=Q("ipcidr");function Ta(r,t){switch(Q(r).code){case 4:case 41:return Mm(t);case 42:return ka(t);case 6:case 273:case 33:case 132:return Gu(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ka(t);case 421:return $m(t);case 444:return zu(t);case 445:return zu(t);case 466:return Km(t);case 481:return globalThis.encodeURIComponent(ka(t));default:return J(t,"base16")}}function Na(r,t){switch(Q(r).code){case 4:return qu(t);case 41:return qu(t);case 42:return Ca(t);case 6:case 273:case 33:case 132:return La(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ca(t);case 421:return Vm(t);case 444:return Wm(t);case 445:return qm(t);case 466:return Fm(t);case 481:return Ca(globalThis.decodeURIComponent(t));default:return et(t,"base16")}}var Ia=Object.values(nr).map(r=>r.decoder),Hm=function(){let r=Ia[0].or(Ia[1]);return Ia.slice(2).forEach(t=>r=r.or(t)),r}();function qu(r){if(!hs(r))throw new Error("invalid ip address");return Sa(r)}function Mm(r){let t=Wu(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!hs(t))throw new Error("invalid ip address");return t}function La(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Gu(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Ca(r){let t=et(r),e=Uint8Array.from(oe(t.length));return Et([e,t],e.length+t.length)}function ka(r){let t=Jt(r);if(r=r.slice(ct(t)),r.length!==t)throw new Error("inconsistent lengths");return J(r)}function Vm(r){let t;r[0]==="Q"||r[0]==="1"?t=_e(nt.decode(`z${r}`)).bytes:t=vt.parse(r).multihash.bytes;let e=Uint8Array.from(oe(t.length));return Et([e,t],e.length+t.length)}function Fm(r){let t=Hm.decode(r),e=Uint8Array.from(oe(t.length));return Et([e,t],e.length+t.length)}function Km(r){let t=Jt(r),e=r.slice(ct(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+J(e,"base64url")}function $m(r){let t=Jt(r),e=r.slice(ct(t));if(e.length!==t)throw new Error("inconsistent lengths");return J(e,"base58btc")}function Wm(r){let t=r.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 e=he.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=La(n);return Et([e,o],e.length+o.length)}function qm(r){let t=r.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 e=he.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=La(n);return Et([e,o],e.length+o.length)}function zu(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=J(t,"base32"),o=Gu(e);return`${n}:${o}`}function ju(r){r=_a(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=Q(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw Xu("invalid address: "+r);if(a.path===!0){n=_a(o.slice(s).join("/")),t.push([a.code,Na(a.code,n)]),e.push([a.code,n]);break}let c=Na(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Ta(a.code,c)])}return{string:Zu(e),bytes:Ua(t),tuples:t,stringTuples:e,path:n}}function Ra(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=Jt(r,o),i=ct(s),a=Q(s),c=zm(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Xu("Invalid address Uint8Array: "+J(r,"base16"));t.push([s,l]);let u=Ta(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Zu(e),tuples:t,stringTuples:e,path:n}}function Zu(r){let t=[];return r.map(e=>{let n=Q(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),_a(t.join("/"))}function Ua(r){return Et(r.map(t=>{let e=Q(t[0]),n=Uint8Array.from(oe(e.code));return t.length>1&&t[1]!=null&&(n=Et([n,t[1]])),n}))}function zm(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=Jt(t instanceof Uint8Array?t:Uint8Array.from(t));return e+ct(e)}}function _a(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function Xu(r){return new Error("Error parsing address: "+r)}var Gm=Symbol.for("nodejs.util.inspect.custom"),Pa=Symbol.for("@multiformats/js-multiaddr/multiaddr"),jm=[Q("dns").code,Q("dns4").code,Q("dns6").code,Q("dnsaddr").code],Da=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},ds=class r{bytes;#t;#e;#r;#n;[Pa]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Ra(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=ju(t)}else if(Ju(t))e=Ra(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="",i=Q("tcp"),a=Q("udp"),c=Q("ip4"),l=Q("ip6"),u=Q("dns6"),f=Q("ip6zone");for(let[m,x]of this.stringTuples())m===f.code&&(s=`%${x??""}`),jm.includes(m)&&(e=i.name,o=443,n=`${x??""}${s}`,t=m===u.code?6:4),(m===i.code||m===a.code)&&(e=Q(m).name,o=parseInt(x??"")),(m===c.code||m===l.code)&&(e=Q(m).name,n=`${x??""}${s}`,t=m===l.code?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},Q(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>Q(t).name)}tuples(){return this.#e.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#r.map(([t,e])=>e==null?[t]:[t,e])}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(Ua(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Hr.p2p.code&&t.push([n,o]),n===Hr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?J(nt.decode(`z${n}`),"base58btc"):J(vt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return Rt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=Yu.get(e.name);if(n==null)throw new Da(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>qe(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[Gm](){return`Multiaddr(${this.#t})`}};var Yu=new Map;function Ju(r){return!!r?.[Pa]}function qe(r){return new ds(r)}var Zm=r=>r.toString().split("/").slice(1),Mr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),q=r=>({match:t=>Mr(e=>e===r).match(t),pattern:r}),cr=()=>({match:r=>Mr(t=>typeof t=="string").match(r),pattern:"{string}"}),Cn=()=>({match:r=>Mr(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),rt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{nt.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),kn=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{zi.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),X=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Lt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),G=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function lt(...r){function t(o){let s=Zm(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var ms=G(q("dns4"),cr()),gs=G(q("dns6"),cr()),ys=G(q("dnsaddr"),cr()),Ha=G(q("dns"),cr()),_2=lt(ms,X(rt())),R2=lt(gs,X(rt())),U2=lt(ys,X(rt())),D2=lt(Lt(Ha,ys,ms,gs),X(rt())),Qu=G(q("ip4"),Mr(us)),tf=G(q("ip6"),Mr(fs)),Ma=Lt(Qu,tf),Ce=Lt(Ma,Ha,ms,gs,ys),P2=lt(Lt(Ma,G(Lt(Ha,ys,ms,gs),X(rt())))),O2=lt(Qu),H2=lt(tf),M2=lt(Ma),Va=G(Ce,q("tcp"),Cn()),Tn=G(Ce,q("udp"),Cn()),V2=lt(G(Va,X(rt()))),F2=lt(Tn),Fa=G(Tn,q("quic"),X(rt())),ws=G(Tn,q("quic-v1"),X(rt())),Xm=Lt(Fa,ws),K2=lt(Fa),$2=lt(ws),Oa=Lt(Ce,Va,Tn,Fa,ws),ef=Lt(G(Oa,q("ws"),X(rt()))),W2=lt(ef),rf=Lt(G(Oa,q("wss"),X(rt())),G(Oa,q("tls"),X(G(q("sni"),cr())),q("ws"),X(rt()))),q2=lt(rf),nf=G(Tn,q("webrtc-direct"),X(kn()),X(kn()),X(rt())),of=lt(nf),sf=G(ws,q("webtransport"),X(kn()),X(kn()),X(rt())),z2=lt(sf),ps=Lt(ef,rf,G(Va,X(rt())),G(Xm,X(rt())),G(Ce,X(rt())),nf,sf,rt()),af=lt(ps),Ym=G(ps,q("p2p-circuit"),rt()),G2=lt(Ym),Jm=Lt(G(ps,q("p2p-circuit"),q("webrtc"),X(rt())),G(ps,q("webrtc"),X(rt())),G(q("webrtc"),X(rt()))),cf=lt(Jm),Qm=Lt(G(Ce,q("tcp"),Cn(),q("http"),X(rt())),G(Ce,q("http"),X(rt()))),j2=lt(Qm),t0=Lt(G(Ce,q("tcp"),Lt(G(q("443"),q("http")),G(Cn(),q("https"))),X(rt())),G(Ce,q("tls"),q("http"),X(rt())),G(Ce,q("https"),X(rt()))),Z2=lt(t0),e0=Lt(G(q("memory"),cr(),X(rt()))),X2=lt(e0);var lf=function(r,t,e){if(e||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return r.concat(s||Array.prototype.slice.call(t))},r0=function(){function r(t,e,n){this.name=t,this.version=e,this.os=n,this.type="browser"}return r}();var n0=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var o0=function(){function r(t,e,n,o){this.name=t,this.version=e,this.os=n,this.bot=o,this.type="bot-device"}return r}();var s0=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var i0=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var a0=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,c0=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,uf=3,l0=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",a0]],ff=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function df(r){return r?hf(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new i0:typeof navigator<"u"?hf(navigator.userAgent):h0()}function u0(r){return r!==""&&l0.reduce(function(t,e){var n=e[0],o=e[1];if(t)return t;var s=o.exec(r);return!!s&&[n,s]},!1)}function hf(r){var t=u0(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new s0;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<uf&&(o=lf(lf([],o,!0),d0(uf-o.length),!0)):o=[];var s=o.join("."),i=f0(r),a=c0.exec(r);return a&&a[1]?new o0(e,s,i,a[1]):new r0(e,s,i)}function f0(r){for(var t=0,e=ff.length;t<e;t++){var n=ff[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function h0(){var r=typeof process<"u"&&process.version;return r?new n0(process.version.slice(1)):null}function d0(r){for(var t=[],e=0;e<r;e++)t.push("0");return t}function pt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Ka=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},$a=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},pf=r=>globalThis.DOMException===void 0?new $a(r):new DOMException(r),mf=r=>{let t=r.reason===void 0?pf("This operation was aborted."):r.reason;return t instanceof Error?t:pf(t)};function lr(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,c=new Promise((l,u)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:d}=t;d.aborted&&u(mf(d));let m=()=>{u(mf(d))};d.addEventListener("abort",m,{once:!0}),r.finally(()=>{d.removeEventListener("abort",m)})}if(e===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new Ka;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(d){u(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?u(o):(f.message=o??`Promise timed out after ${e} milliseconds`,u(f))},e),(async()=>{try{l(await r)}catch(d){u(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}var gf=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"];var yf=df(),Nn=yf!=null&&yf.name==="firefox",bs=async function*(){},xs=async r=>{},p0=30*1e3;function wf(r,t,e=p0,n){r.readyState==="open"&&Promise.resolve().then(async()=>{if(r.bufferedAmount>0){n.log("%s drain channel with %d buffered bytes",t,r.bufferedAmount);let o=pt(),s=!1;r.bufferedAmountLowThreshold=0;let i=()=>{s||(n.log("%s drain channel closed before drain",t),o.resolve())};r.addEventListener("close",i,{once:!0}),r.addEventListener("bufferedamountlow",()=>{s=!0,r.removeEventListener("close",i),o.resolve()}),await lr(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function Ln(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??gf.map(t=>({urls:[t]})),r}var ur=class{log;peerConnection;remoteAddr;timeline;metrics;source=bs();sink=xs;constructor(t,e){this.log=t.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=e.remoteAddr,this.timeline=e.timeline,this.peerConnection=e.peerConnection;let n=this.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",this.peerConnection.connectionState,"initial state",n),(this.peerConnection.connectionState==="disconnected"||this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.timeline.close=Date.now())}}async close(t){this.log.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(t){this.log.error("closing connection due to error",t),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}};var Es=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)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}},Vr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Es(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 e=this.head;this.head=e.next=new Es(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Wa=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function ze(r={}){return m0(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function m0(r,t){t=t??{};let e=t.onEnd,n=new Vr,o,s,i,a=pt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,y)=>{s=b=>{s=null,n.push(b);try{h(r(n))}catch(p){y(p)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=pt()})}},l=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new Vr,s!=null?s({error:h}):(n.push({error:h}),o)),f=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 l({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?u(h):l({done:!0})),m=()=>(n=new Vr,d(),{done:!0}),x=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:x,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let y=h?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let b,p;y!=null&&(b=new Promise((B,L)=>{p=()=>{L(new Wa)},y.addEventListener("abort",p)}));try{await Promise.race([a.promise,b])}finally{p!=null&&y!=null&&y?.removeEventListener("abort",p)}}},e==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(h){return g.throw(h),e!=null&&(e(h),e=void 0),{done:!0}},return(){return g.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(h){return g.end(h),e!=null&&(e(h),e=void 0),o},get readableLength(){return g.readableLength},onEmpty:h=>g.onEmpty(h)},o}var vs=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function ke(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new vs(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new vs(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var xf=Symbol.for("@achingbrain/uint8arraylist");function bf(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function As(r){return!!r?.[xf]}var ht=class r{bufs;length;[xf]=!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 e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(As(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(As(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=bf(this.bufs,t);return e.buf[e.index]}set(t,e){let n=bf(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(As(t))for(let n=0;n<t.length;n++)this.set(e+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,e){let{bufs:n,length:o}=this._subList(t,e);return Et(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Et(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===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 l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!As(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(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;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 f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let m=this.get(f+d);if(n[d]!==m){u=Math.max(1,d-a[m]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=wt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=yt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=yt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=yt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=wt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=yt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=yt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=yt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=yt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=yt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Rt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};function Ef(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function vf(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Af(r,t){let e=Ef(r).return?.();vf(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var g0=5e3;function qa(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ss=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(t){this.sinkController=new AbortController,this.sinkEnd=pt(),this.closed=pt(),this.log=t.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=t.id,this.metadata=t.metadata??{},this.direction=t.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=t.sendCloseWriteTimeout??g0,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=ze({onEnd:e=>{e!=null?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(t){if(this.writeStatus!=="ready")throw new je(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let e={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(e);qa(o)&&await o}let n=()=>{Af(t,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let o of t){o=o instanceof Uint8Array?new ht(o):o;let s=this.sendData(o,e);qa(s)&&(this.sendingData=pt(),await s,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",n)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(t){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(t){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(t){this.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await ke(Promise.all([this.closeWrite(t),this.closeRead(t),this.closed.promise]),t?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(t={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let e=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(t)),e==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(t={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await ke(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await ke(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await ke(this.sinkEnd.promise,t.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(t){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",t),this.log("try to send reset to remote");let e=this.sendReset();qa(e)&&e.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(t),this.onAbort?.(t)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let t=new qn("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(t),this.onReset?.()}_closeSinkAndSource(t){this._closeSink(t),this._closeSource(t)}_closeSink(t){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(t)}_closeSource(t){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(t))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(t){this.streamSource.push(t)}sourceReadableLength(){return this.streamSource.readableLength}};function Bs(r){return r[Symbol.asyncIterator]!=null}var Is=r=>{let t=ct(r),e=wt(t);return oe(r,e),Is.bytes=t,e};Is.bytes=0;function _n(r,t){t=t??{};let e=t.lengthEncoder??Is;function*n(o){let s=e(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Bs(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}_n.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Is;return new ht(e(r.byteLength),r)};var Cs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ks=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ts=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Rn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var y0=8,w0=1024*1024*4,fr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(fr||(fr={}));var za=r=>{let t=Jt(r);return za.bytes=ct(t),t};za.bytes=0;function hr(r,t){let e=new ht,n=fr.LENGTH,o=-1,s=t?.lengthDecoder??za,i=t?.maxLengthLength??y0,a=t?.maxDataLength??w0;function*c(){for(;e.byteLength>0;){if(n===fr.LENGTH)try{if(o=s(e),o<0)throw new Cs("Invalid message length");if(o>a)throw new ks("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=fr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Ts("Message length length too long");break}throw l}if(n===fr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=fr.LENGTH}}}return Bs(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Rn("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Rn("Unexpected end of input")}()}hr.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return hr(n,{...t??{},onLength:s=>{e=s}})};var x0=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function E0(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:u}=x0(r),f=(...m)=>{let x=e.multiArgs?m:m[0];e.filter&&!e.filter(x)||(c.push(x),e.count===c.length&&(n(),s(c)))},d=m=>{n(),i(m)};n=()=>{for(let m of a)u(m,f);for(let m of e.rejectionEvents)u(m,d)};for(let m of a)l(m,f);for(let m of e.rejectionEvents)l(m,d);e.signal&&e.signal.addEventListener("abort",()=>{d(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=lr(o,{milliseconds:e.timeout});return s.cancel=n,s}return o}function Ga(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=E0(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var Dt;(function(r){let t;(function(o){o.FIN="FIN",o.STOP_SENDING="STOP_SENDING",o.RESET="RESET",o.FIN_ACK="FIN_ACK"})(t=r.Flag||(r.Flag={}));let e;(function(o){o[o.FIN=0]="FIN",o[o.STOP_SENDING=1]="STOP_SENDING",o[o.RESET=2]="RESET",o[o.FIN_ACK=3]="FIN_ACK"})(e||(e={})),function(o){o.codec=()=>sr(e)}(t=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=re((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.flag!=null&&(s.uint32(8),r.Flag.codec().encode(o.flag,s)),o.message!=null&&(s.uint32(18),s.bytes(o.message)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.flag=r.Flag.codec().decode(o);break}case 2:{a.message=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ee(o,r.codec()),r.decode=(o,s)=>te(o,r.codec(),s)})(Dt||(Dt={}));var v0=2*1024*1024,A0=30*1e3,Ns=16*1024;function S0(r=Ns){let t=ct(r-ct(r)),e=1+ct(Object.keys(Dt.Flag).length-1),n=1,o=r-t-e-n,s=ct(o);return t+e+n+s}var B0=S0(),I0=5e3,C0=5e3,ja=class extends Ss{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;constructor(t){let e=t.onEnd;switch(t.onEnd=o=>{this.log.trace("readable and writeable ends closed",this.status),Promise.resolve(async()=>{if(!(this.timeline.abort!=null||this.timeline.reset!==null))try{await lr(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),e?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=ze(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??A0,this.maxBufferedAmount=t.maxBufferedAmount??v0,this.maxMessageSize=(t.maxMessageSize??Ns)-B0,this.receiveFinAck=pt(),this.finAckTimeout=t.closeTimeout??I0,this.openTimeout=t.openTimeout??C0,this.channel.readyState){case"open":this.timeline.open=new Date().getTime();break;case"closed":case"closing":(this.timeline.close===void 0||this.timeline.close===0)&&(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new je("Unknown datachannel state")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{let s=o.error;this.abort(s)},this.channel.onmessage=async o=>{let{data:s}=o;s===null||s.byteLength===0||this.incomingData.push(new Uint8Array(s,0,s.byteLength))};let n=this;Promise.resolve().then(async()=>{for await(let o of hr(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new ht(s))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(t,e=!0){if(e&&this.channel.bufferedAmount>this.maxBufferedAmount)try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await Ga(this.channel,"bufferedamountlow",{timeout:this.bufferedAmountLowEventTimeout})}catch(n){throw n instanceof jr?new jr(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`):n}if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new je(`Invalid datachannel state - ${this.channel.readyState}`);this.channel.readyState!=="open"&&(this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await Ga(this.channel,"open",{timeout:this.openTimeout}),this.log('channel state is now "%s", sending data',this.channel.readyState)),this.channel.send(t.subarray())}async sendData(t){for(t=t.sublist();t.byteLength>0;){let e=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,e),o=Dt.encode({message:n}),s=_n.single(o);await this._sendMessage(s),t.consume(e)}}async sendReset(){try{await this._sendFlag(Dt.Flag.RESET)}catch(t){this.log.error("failed to send reset - %e",t)}}async sendCloseWrite(t){if(await this._sendFlag(Dt.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await ke(this.receiveFinAck.promise,t?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(n){this.log.error("failed to await FIN_ACK",n)}}else this.log.trace("sending FIN failed, not awaiting FIN_ACK");this.receiveFinAck.resolve()}async sendCloseRead(){await this._sendFlag(Dt.Flag.STOP_SENDING)}processIncomingProtobuf(t){let e=Dt.decode(t);if(e.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',e.flag,this.writeStatus,this.readStatus),e.flag===Dt.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Dt.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),e.flag===Dt.Flag.RESET&&this.reset(),e.flag===Dt.Flag.STOP_SENDING&&this.remoteCloseRead(),e.flag===Dt.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),this.readStatus==="ready")return e.message}async _sendFlag(t){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',this.channel.readyState,t.toString()),!1;this.log.trace("sending flag %s",t.toString());let e=Dt.encode({flag:t}),n=_n.single(e);try{return await this._sendMessage(n,!1),!0}catch(o){this.log.error("could not send flag %s - %e",t.toString(),o)}return!1}};function Fr(r){let{channel:t,direction:e}=r;return new ja({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var Sf="/webrtc",Ge=class{protocol;peerConnection;bufferedStreams=[];metrics;dataChannelOptions;components;log;constructor(t,e){this.components=t,this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??Sf,this.dataChannelOptions=e.dataChannelOptions??{},this.log=t.logger.forComponent("libp2p:webrtc:datachannelmuxerfactory"),this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),n.label==="init"){this.log.trace("closing early init channel"),n.close();return}let o={},s=Fr({channel:n,direction:"inbound",onEnd:i=>{o.onEnd(i)},logger:t.logger,...this.dataChannelOptions});o.stream=s,o.channel=n,o.onEnd=()=>{this.bufferedStreams=this.bufferedStreams.filter(i=>i.stream.id!==s.id)},this.bufferedStreams.push(o)}}createStreamMuxer(t){return new Za(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},Za=class{init;streams;protocol;log;peerConnection;dataChannelOptions;metrics;logger;constructor(t,e){this.init=e,this.log=t.logger.forComponent("libp2p:webrtc:muxer"),this.logger=t.logger,this.streams=e.streams.map(n=>n.stream),this.peerConnection=e.peerConnection,this.protocol=e.protocol??Sf,this.metrics=e.metrics,this.dataChannelOptions=e.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace("incoming datachannel with channel id %d",n.id),n.label==="init"){this.log.trace("closing init channel"),n.close();return}let o=n.id,s=Fr({channel:n,direction:"inbound",onEnd:()=>{this.#t(s,n),this.log("incoming channel %s ended",o)},logger:this.logger,...this.dataChannelOptions});this.streams.push(s),this.metrics?.increment({incoming_stream:!0}),e?.onIncomingStream?.(s)},this.init.streams.length>0&&queueMicrotask(()=>{this.init.streams.forEach(n=>{n.onEnd=()=>{this.log("incoming early channel %s ended with state %s",n.channel.id,n.channel.readyState),this.#t(n.stream,n.channel)},this.metrics?.increment({incoming_stream:!0}),this.init?.onIncomingStream?.(n.stream)})})}#t(t,e){this.log.trace("stream %s %s %s onEnd",t.direction,t.id,t.protocol),wf(e,`${t.direction} ${t.id} ${t.protocol}`,this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter(n=>n.id!==t.id),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(t)}async close(t){try{await Promise.all(this.streams.map(async e=>e.close(t)))}catch(e){this.abort(e)}}abort(t){for(let e of this.streams)e.abort(t)}source=bs();sink=xs;newStream(){let t=this.peerConnection.createDataChannel(""),e=t.id;this.log.trace("opened outgoing datachannel with channel id %s",e);let n=Fr({channel:t,direction:"outbound",onEnd:()=>{this.#t(n,t),this.log("outgoing channel %s ended",e)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(n),this.metrics?.increment({outgoing_stream:!0}),n}};var dr=globalThis.RTCPeerConnection,Ls=globalThis.RTCSessionDescription,Bf=globalThis.RTCIceCandidate;var Xa=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=pt(),this.haveNext=pt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=pt(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=pt(),await ke(this.readNext.promise,e?.signal,e)}};function If(){return new Xa}var _s=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Ya=class extends Error{code;constructor(t,e){super(t),this.code=e}},Ja=class extends Ya{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Cf(r,t){let e=If();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new ht;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new Ja("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:d}=await Promise.race([n.next(),l]);return f===!0?new ht:d}for(;o.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),l]);if(d===!0)throw new _s("unexpected end of input");o.append(f)}let u=o.sublist(0,i);return o.consume(i),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Rs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Us=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ds=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Un(r,t={}){let e=Cf(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=ct(t.maxDataLength));let n=t?.lengthDecoder??Jt,o=t?.lengthEncoder??oe;return{read:async i=>{let a=-1,c=new ht;for(;;){c.append(await e.read(1,i));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Rs("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ds("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Us("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new ht(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new ht(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Ps(r,t){let e=Un(r,t),n={read:async(o,s)=>{let i=await e.read(s);return o.decode(i)},write:async(o,s,i)=>{await e.write(s.encode(o),i)},writeV:async(o,s,i)=>{await e.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:()=>e.unwrap()};return n}var $t=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var pr=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},zt=class extends pr{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var Dn=class extends pr{constructor(t,e){super(`[stream: ${t}] data channel error: ${e}`),this.name="WebRTC/DataChannelError"}};var Pn=class extends pr{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`),this.name="WebRTC/InvalidFingerprintError"}};var Os=class extends pr{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Hs=class extends pr{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 Vt;(function(r){let t;(function(o){o.SDP_OFFER="SDP_OFFER",o.SDP_ANSWER="SDP_ANSWER",o.ICE_CANDIDATE="ICE_CANDIDATE"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.SDP_OFFER=0]="SDP_OFFER",o[o.SDP_ANSWER=1]="SDP_ANSWER",o[o.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(e||(e={})),function(o){o.codec=()=>sr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=re((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.data!=null&&(s.uint32(18),s.string(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.data=o.string();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ee(o,r.codec()),r.decode=(o,s)=>te(o,r.codec(),s)})(Vt||(Vt={}));var Ms=async(r,t,e)=>{try{let n=pt();for(k0(r,n);;){let o=await Promise.race([n.promise,t.read({signal:e.signal}).catch(()=>{})]);if(o==null){e.signal?.throwIfAborted();break}if(o.type!==Vt.Type.ICE_CANDIDATE)throw new Gn("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){e.onProgress?.(new $t("webrtc:end-of-ice-candidates")),e.log.trace("end-of-candidates received");continue}let i=new Bf(s);e.log.trace("%s received new ICE candidate %o",e.direction,s);try{e.onProgress?.(new $t("webrtc:add-ice-candidate",i.candidate)),await r.addIceCandidate(i)}catch(a){e.log.error("%s bad candidate received",e.direction,s,a)}}}catch(n){if(e.log.error("%s error parsing ICE candidate",e.direction,n),e.signal?.aborted===!0&&Vs(r)!=="connected")throw n}};function Vs(r){return Nn?r.iceConnectionState:r.connectionState}function k0(r,t){r[Nn?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch(Vs(r)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new Wn("RTCPeerConnection was closed"));break;default:break}}}async function kf({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=Tf(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new tt("Relay peer was missing");let d=s.getConnections(Pr(f)),m,x=!1;d.length===0?(l?.(new $t("webrtc:dial-relay")),m=await i.dial(u,{signal:e,onProgress:l}),x=!0):(l?.(new $t("webrtc:reuse-relay-connection")),m=d[0]);try{l?.(new $t("webrtc:open-signaling-stream"));let g=await m.newStream(Fs,{signal:e,runOnLimitedConnection:!0}),h=Ps(g).pb(Vt),y=new dr(r),b=new Ge({logger:c},{peerConnection:y,dataChannelOptions:t});try{let p=y.createDataChannel("init");y.onicecandidate=({candidate:S})=>{let k=JSON.stringify(S?.toJSON()??null);a.trace("initiator sending ICE candidate %o",S),h.write({type:Vt.Type.ICE_CANDIDATE,data:k},{signal:e}).catch(I=>{a.error("error sending ICE candidate",I)})},y.onicecandidateerror=S=>{a.error("initiator ICE candidate error",S)};let B=await y.createOffer().catch(S=>{throw a.error("could not execute createOffer",S),new zt("Failed to set createOffer")});a.trace("initiator send SDP offer %s",B.sdp),l?.(new $t("webrtc:send-sdp-offer")),await h.write({type:Vt.Type.SDP_OFFER,data:B.sdp},{signal:e}),await y.setLocalDescription(B).catch(S=>{throw a.error("could not execute setLocalDescription",S),new zt("Failed to set localDescription")}),l?.(new $t("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let L=await h.read({signal:e});if(L.type!==Vt.Type.SDP_ANSWER)throw new zt("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",L.data);let N=new Ls({type:"answer",sdp:L.data});return await y.setRemoteDescription(N).catch(S=>{throw a.error("could not execute setRemoteDescription",S),new zt("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),l?.(new $t("webrtc:read-ice-candidates")),await Ms(y,h,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),p.close(),l?.(new $t("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await g.close({signal:e}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:y,muxerFactory:b}}catch(p){throw a.error("outgoing signaling error",p),y.close(),g.abort(p),p}finally{y.onicecandidate=null,y.onicecandidateerror=null}}finally{if(x)try{await m.close({signal:e})}catch(g){m.abort(g)}}}var T0=lt(af.matchers[0],q("p2p-circuit")),Ks=class extends Zn{transportManager;shutdownController;constructor(t,e){super(),this.transportManager=t.transportManager,this.shutdownController=e.shutdownController}async listen(){queueMicrotask(()=>{this.safeDispatchEvent("listening")})}getAddrs(){return this.transportManager.getListeners().filter(t=>t!==this).map(t=>t.getAddrs().filter(e=>T0.exactMatch(e)).map(e=>e.encapsulate("/webrtc"))).flat()}async close(){this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function Nf({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=Ps(t).pb(Vt);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Vt.Type.ICE_CANDIDATE,data:f},{signal:e}).catch(d=>{o.error("error sending ICE candidate",d)})},o.trace("recipient read SDP offer");let a=await s.read({signal:e});if(a.type!==Vt.Type.SDP_OFFER)throw new zt(`expected message type SDP_OFFER, received: ${a.type??"undefined"} `);o.trace("recipient received SDP offer %s",a.data);let c=new Ls({type:"offer",sdp:a.data});await r.setRemoteDescription(c).catch(u=>{throw o.error("could not execute setRemoteDescription",u),new zt("Failed to set remoteDescription")});let l=await r.createAnswer().catch(u=>{throw o.error("could not execute createAnswer",u),new zt("Failed to create answer")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:Vt.Type.SDP_ANSWER,data:l.sdp},{signal:e}),await r.setLocalDescription(l).catch(u=>{throw o.error("could not execute setLocalDescription",u),new zt("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await Ms(r,s,{direction:"recipient",signal:e,log:o})}catch(a){if(Vs(r)!=="connected")throw o.error("error while handling signaling stream from peer %a",n.remoteAddr,a),r.close(),a;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",n.remoteAddr,a)}let i=qe(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var N0="/webrtc",L0="/p2p-circuit",Fs="/webrtc-signaling/0.0.1",_0=30*1e3,$s=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,e={}){this.components=t,this.init=e,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,jn(1/0,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"})})}[Kn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[yr]=["@libp2p/transport"];[_c]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(Fs,t=>{this._onProtocol(t).catch(e=>{this.log.error("failed to handle incoming connect from %p",t.connection.remotePeer,e)})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(Fs),this._started=!1}createListener(t){return new Ks(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(cf.exactMatch)}dialFilter(t){return this.listenFilter(t)}async dial(t,e){this.log.trace("dialing address: %a",t);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await kf({rtcConfiguration:await Ln(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:t,dataChannelOptions:this.init.dataChannel,signal:e.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:e.onProgress}),i=new ur(this.components,{peerConnection:o,timeline:{open:Date.now()},remoteAddr:n,metrics:this.metrics?.dialerEvents}),a=await e.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,muxerFactory:s,onProgress:e.onProgress});return this._closeOnShutdown(o,i),a}async _onProtocol({connection:t,stream:e}){let n=AbortSignal.timeout(this.init.inboundConnectionTimeout??_0),o=new dr(await Ln(this.init.rtcConfiguration)),s=new Ge(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await Nf({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new ur(this.components,{peerConnection:o,timeline:{open:new Date().getTime()},remoteAddr:i,metrics:this.metrics?.listenerEvents});await this.components.upgrader.upgradeInbound(a,{skipEncryption:!0,skipProtection:!0,muxerFactory:s}),this._closeOnShutdown(o,a)}catch(i){throw this.log.error("incoming signaling error",i),o.close(),e.abort(i),i}}_closeOnShutdown(t,e){let n=()=>{e.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection",o)})};this.shutdownController.signal.addEventListener("abort",n),t.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function Tf(r){let t=r.toString().split(N0+"/");if(t.length!==2)throw new tt("webrtc protocol was not present in multiaddr");if(!t[0].includes(L0))throw new tt("p2p-circuit protocol was not present in multiaddr");let e=qe(t[0]),o=qe("/"+t[1]).getPeerId();if(o==null)throw new tt("destination peer id was missing");let s=e.protos().pop();if(s===void 0)throw new tt("invalid multiaddr");return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:Pr(o)}}function Qa(){let r=pt(),t=!1;return{sink:async e=>{if(t)throw new Error("already piped");t=!0,r.resolve(e)},source:async function*(){yield*await r.promise}()}}function Lf(){let r=Qa(),t=Qa();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}function R0(r){return r[Symbol.asyncIterator]!=null}function U0(...r){let t=[];for(let e of r)R0(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=ze({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var _f=U0;function Rf(r,...t){if(r==null)throw new Error("Empty pipeline");if(tc(r)){let n=r;r=()=>n.source}else if(Df(r)||Uf(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&tc(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)tc(e[n])&&(e[n]=P0(e[n]));return D0(...e)}var D0=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Uf=r=>r?.[Symbol.asyncIterator]!=null,Df=r=>r?.[Symbol.iterator]!=null,tc=r=>r==null?!1:r.sink!=null&&r.source!=null,P0=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=ze({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(Uf(s))o=async function*(){yield*s,n.end()};else if(Df(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return _f(n,o())}return r.source};var Kr=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function Ws(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function ec(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function rc(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Ft(r,...t){if(!rc(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function nc(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function Pf(r,t){Ft(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var Te=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),Of=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),O0=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!O0)throw new Error("Non little-endian hardware is not supported");function H0(r){if(typeof r!="string")throw new Error(`string expected, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function qs(r){if(typeof r=="string")r=H0(r);else if(rc(r))r=zs(r);else throw new Error(`Uint8Array expected, got ${typeof r}`);return r}function Hf(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function Mf(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}var oc=(r,t)=>(Object.assign(t,r),t);function sc(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}function zs(r){return Uint8Array.from(r)}function Ne(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}var Ff=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),M0=Ff("expand 16-byte k"),V0=Ff("expand 32-byte k"),F0=Te(M0),Kf=Te(V0),TA=Kf.slice();function P(r,t){return r<<t|r>>>32-t}function ic(r){return r.byteOffset%4===0}var Gs=64,K0=16,$f=2**32-1,Vf=new Uint32Array;function $0(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(Gs),u=Te(l),f=ic(o)&&ic(s),d=f?Te(o):Vf,m=f?Te(s):Vf;for(let x=0;x<c;i++){if(r(t,e,n,u,i,a),i>=$f)throw new Error("arx: counter overflow");let g=Math.min(Gs,c-x);if(f&&g===Gs){let h=x/4;if(x%4!==0)throw new Error("arx: invalid block position");for(let y=0,b;y<K0;y++)b=h+y,m[b]=d[b]^u[y];x+=Gs;continue}for(let h=0,y;h<g;h++)y=x+h,s[y]=o[y]^l[h];x+=g}}function ac(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Hf({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return Ws(o),Ws(i),ec(s),ec(e),(a,c,l,u,f=0)=>{Ft(a),Ft(c),Ft(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),Ft(u),Ws(f),f<0||f>=$f)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let m=[],x=a.length,g,h;if(x===32)m.push(g=zs(a)),h=Kf;else if(x===16&&e)g=new Uint8Array(32),g.set(a),g.set(a,16),h=F0,m.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${x}`);ic(c)||m.push(c=zs(c));let y=Te(g);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,y,Te(c.subarray(0,16)),y),c=c.subarray(16)}let b=16-o;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let B=new Uint8Array(12);B.set(c,s?0:12-c.length),c=B,m.push(c)}let p=Te(c);return $0(r,h,y,p,l,u,f,i),Ne(...m),u}}var It=(r,t)=>r[t++]&255|(r[t++]&255)<<8,cc=class{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=qs(t),Ft(t,32);let e=It(t,0),n=It(t,2),o=It(t,4),s=It(t,6),i=It(t,8),a=It(t,10),c=It(t,12),l=It(t,14);this.r[0]=e&8191,this.r[1]=(e>>>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|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=It(t,16+2*u)}process(t,e,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],d=i[5],m=i[6],x=i[7],g=i[8],h=i[9],y=It(t,e+0),b=It(t,e+2),p=It(t,e+4),B=It(t,e+6),L=It(t,e+8),N=It(t,e+10),S=It(t,e+12),k=It(t,e+14),I=s[0]+(y&8191),M=s[1]+((y>>>13|b<<3)&8191),_=s[2]+((b>>>10|p<<6)&8191),O=s[3]+((p>>>7|B<<9)&8191),V=s[4]+((B>>>4|L<<12)&8191),C=s[5]+(L>>>1&8191),T=s[6]+((L>>>14|N<<2)&8191),E=s[7]+((N>>>11|S<<5)&8191),w=s[8]+((S>>>8|k<<8)&8191),A=s[9]+(k>>>5|o),v=0,R=v+I*a+M*(5*h)+_*(5*g)+O*(5*x)+V*(5*m);v=R>>>13,R&=8191,R+=C*(5*d)+T*(5*f)+E*(5*u)+w*(5*l)+A*(5*c),v+=R>>>13,R&=8191;let U=v+I*c+M*a+_*(5*h)+O*(5*g)+V*(5*x);v=U>>>13,U&=8191,U+=C*(5*m)+T*(5*d)+E*(5*f)+w*(5*u)+A*(5*l),v+=U>>>13,U&=8191;let H=v+I*l+M*c+_*a+O*(5*h)+V*(5*g);v=H>>>13,H&=8191,H+=C*(5*x)+T*(5*m)+E*(5*d)+w*(5*f)+A*(5*u),v+=H>>>13,H&=8191;let F=v+I*u+M*l+_*c+O*a+V*(5*h);v=F>>>13,F&=8191,F+=C*(5*g)+T*(5*x)+E*(5*m)+w*(5*d)+A*(5*f),v+=F>>>13,F&=8191;let K=v+I*f+M*u+_*l+O*c+V*a;v=K>>>13,K&=8191,K+=C*(5*h)+T*(5*g)+E*(5*x)+w*(5*m)+A*(5*d),v+=K>>>13,K&=8191;let W=v+I*d+M*f+_*u+O*l+V*c;v=W>>>13,W&=8191,W+=C*a+T*(5*h)+E*(5*g)+w*(5*x)+A*(5*m),v+=W>>>13,W&=8191;let j=v+I*m+M*d+_*f+O*u+V*l;v=j>>>13,j&=8191,j+=C*c+T*a+E*(5*h)+w*(5*g)+A*(5*x),v+=j>>>13,j&=8191;let ot=v+I*x+M*m+_*d+O*f+V*u;v=ot>>>13,ot&=8191,ot+=C*l+T*c+E*a+w*(5*h)+A*(5*g),v+=ot>>>13,ot&=8191;let st=v+I*g+M*x+_*m+O*d+V*f;v=st>>>13,st&=8191,st+=C*u+T*l+E*c+w*a+A*(5*h),v+=st>>>13,st&=8191;let ut=v+I*h+M*g+_*x+O*m+V*d;v=ut>>>13,ut&=8191,ut+=C*f+T*u+E*l+w*c+A*a,v+=ut>>>13,ut&=8191,v=(v<<2)+v|0,v=v+R|0,R=v&8191,v=v>>>13,U+=v,s[0]=R,s[1]=U,s[2]=H,s[3]=F,s[4]=K,s[5]=W,s[6]=j,s[7]=ot,s[8]=st,s[9]=ut}finalize(){let{h:t,pad:e}=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]+e[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+e[a]|0)+(i>>>16)|0,t[a]=i&65535;Ne(n)}update(t){nc(this);let{buffer:e,blockLen:n}=this;t=qs(t);let 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}e.set(t.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(e,0,!1),this.pos=0)}return this}destroy(){Ne(this.h,this.r,this.buffer,this.pad)}digestInto(t){nc(this),Pf(t,this),this.finished=!0;let{buffer:e,h:n}=this,{pos:o}=this;if(o){for(e[o++]=1;o<16;o++)e[o]=0;this.process(e,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)t[s++]=n[i]>>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}};function W0(r){let t=(n,o)=>r(o).update(qs(n)).digest(),e=r(new Uint8Array(32));return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=n=>r(n),t}var Wf=W0(r=>new cc(r));function Gf(r,t,e,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=t[0],f=t[1],d=t[2],m=t[3],x=t[4],g=t[5],h=t[6],y=t[7],b=o,p=e[0],B=e[1],L=e[2],N=i,S=a,k=c,I=l,M=u,_=f,O=d,V=m,C=x,T=g,E=h,w=y,A=b,v=p,R=B,U=L;for(let F=0;F<s;F+=2)N=N+M|0,A=P(A^N,16),C=C+A|0,M=P(M^C,12),N=N+M|0,A=P(A^N,8),C=C+A|0,M=P(M^C,7),S=S+_|0,v=P(v^S,16),T=T+v|0,_=P(_^T,12),S=S+_|0,v=P(v^S,8),T=T+v|0,_=P(_^T,7),k=k+O|0,R=P(R^k,16),E=E+R|0,O=P(O^E,12),k=k+O|0,R=P(R^k,8),E=E+R|0,O=P(O^E,7),I=I+V|0,U=P(U^I,16),w=w+U|0,V=P(V^w,12),I=I+V|0,U=P(U^I,8),w=w+U|0,V=P(V^w,7),N=N+_|0,U=P(U^N,16),E=E+U|0,_=P(_^E,12),N=N+_|0,U=P(U^N,8),E=E+U|0,_=P(_^E,7),S=S+O|0,A=P(A^S,16),w=w+A|0,O=P(O^w,12),S=S+O|0,A=P(A^S,8),w=w+A|0,O=P(O^w,7),k=k+V|0,v=P(v^k,16),C=C+v|0,V=P(V^C,12),k=k+V|0,v=P(v^k,8),C=C+v|0,V=P(V^C,7),I=I+M|0,R=P(R^I,16),T=T+R|0,M=P(M^T,12),I=I+M|0,R=P(R^I,8),T=T+R|0,M=P(M^T,7);let H=0;n[H++]=i+N|0,n[H++]=a+S|0,n[H++]=c+k|0,n[H++]=l+I|0,n[H++]=u+M|0,n[H++]=f+_|0,n[H++]=d+O|0,n[H++]=m+V|0,n[H++]=x+C|0,n[H++]=g+T|0,n[H++]=h+E|0,n[H++]=y+w|0,n[H++]=b+A|0,n[H++]=p+v|0,n[H++]=B+R|0,n[H++]=L+U|0}function q0(r,t,e,n){let o=r[0],s=r[1],i=r[2],a=r[3],c=t[0],l=t[1],u=t[2],f=t[3],d=t[4],m=t[5],x=t[6],g=t[7],h=e[0],y=e[1],b=e[2],p=e[3];for(let L=0;L<20;L+=2)o=o+c|0,h=P(h^o,16),d=d+h|0,c=P(c^d,12),o=o+c|0,h=P(h^o,8),d=d+h|0,c=P(c^d,7),s=s+l|0,y=P(y^s,16),m=m+y|0,l=P(l^m,12),s=s+l|0,y=P(y^s,8),m=m+y|0,l=P(l^m,7),i=i+u|0,b=P(b^i,16),x=x+b|0,u=P(u^x,12),i=i+u|0,b=P(b^i,8),x=x+b|0,u=P(u^x,7),a=a+f|0,p=P(p^a,16),g=g+p|0,f=P(f^g,12),a=a+f|0,p=P(p^a,8),g=g+p|0,f=P(f^g,7),o=o+l|0,p=P(p^o,16),x=x+p|0,l=P(l^x,12),o=o+l|0,p=P(p^o,8),x=x+p|0,l=P(l^x,7),s=s+u|0,h=P(h^s,16),g=g+h|0,u=P(u^g,12),s=s+u|0,h=P(h^s,8),g=g+h|0,u=P(u^g,7),i=i+f|0,y=P(y^i,16),d=d+y|0,f=P(f^d,12),i=i+f|0,y=P(y^i,8),d=d+y|0,f=P(f^d,7),a=a+c|0,b=P(b^a,16),m=m+b|0,c=P(c^m,12),a=a+c|0,b=P(b^a,8),m=m+b|0,c=P(c^m,7);let B=0;n[B++]=o,n[B++]=s,n[B++]=i,n[B++]=a,n[B++]=h,n[B++]=y,n[B++]=b,n[B++]=p}var z0=ac(Gf,{counterRight:!1,counterLength:4,allowShortKeys:!1}),G0=ac(Gf,{counterRight:!1,counterLength:8,extendNonceFn:q0,allowShortKeys:!1});var j0=new Uint8Array(16),qf=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(j0.subarray(e))},Z0=new Uint8Array(32);function zf(r,t,e,n,o){let s=r(t,e,Z0),i=Wf.create(s);o&&qf(i,o),qf(i,n);let a=new Uint8Array(16),c=Of(a);sc(c,0,BigInt(o?o.length:0),!0),sc(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return Ne(s,a),l}var jf=r=>(t,e,n)=>(Ft(t,32),Ft(e),{encrypt(s,i){let a=s.length,c=a+16;i?Ft(i,c):i=new Uint8Array(c),r(t,e,s,i,1);let l=zf(r,t,e,i.subarray(0,-16),n);return i.set(l,a),Ne(l),i},decrypt(s,i){let a=s.length,c=a-16;if(a<16)throw new Error("encrypted data must be at least 16 bytes");i?Ft(i,c):i=new Uint8Array(c);let l=s.subarray(0,-16),u=s.subarray(-16),f=zf(r,t,e,l,n);if(!Mf(u,f))throw new Error("invalid tag");return r(t,e,l,i,1),Ne(f),i}}),lc=oc({blockSize:64,nonceLength:12,tagLength:16},jf(z0)),HA=oc({blockSize:64,nonceLength:24,tagLength:16},jf(G0));function Xf(r,t,e){return Qr(r),e===void 0&&(e=new Uint8Array(r.outputLen)),Dr(r,Re(e),Re(t))}var uc=new Uint8Array([0]),Zf=new Uint8Array;function Yf(r,t,e,n=32){if(Qr(r),Yn(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);e===void 0&&(e=Zf);let s=new Uint8Array(o*r.outputLen),i=Dr.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)uc[0]=l+1,a.update(l===0?Zf:c).update(e).update(uc).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),uc.fill(0),s.slice(0,n)}var fc={hashSHA256(r){return ie(r.subarray())},getHKDF(r,t){let e=Xf(ie,t,r),o=Yf(ie,e,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=sn.utils.randomPrivateKey();return{publicKey:sn.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:sn.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return sn.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return lc(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return lc(n,t,e).decrypt(r.subarray(),o)}};var Jf=fc;function Qf(r){return{generateKeypair:r.generateX25519KeyPair,dh:(t,e)=>r.generateX25519SharedKey(t.privateKey,e).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var $r=r=>{let t=wt(2);return t[0]=r>>8,t[1]=r,t};$r.bytes=2;var On=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let t=0;return t+=r[0]<<8,t+=r[1],t}return r.getUint16(0)};On.bytes=2;function th(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function hc(r,t){!t.enabled||!Kr||(r?(t(`LOCAL_STATIC_PUBLIC_KEY ${J(r.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${J(r.privateKey,"hex")}`)):t("Missing local static keys."))}function dc(r,t){!t.enabled||!Kr||(r?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${J(r.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${J(r.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function eh(r,t){!t.enabled||!Kr||t(r?`REMOTE_STATIC_PUBLIC_KEY ${J(r.subarray(),"hex")}`:"Missing remote static public key.")}function pc(r,t){!t.enabled||!Kr||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${J(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function mc(r,t,e){!e.enabled||!Kr||(e(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&J(r.k,"hex")}`),e(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&J(t.k,"hex")}`))}var Wr=class r extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var X0=0,Y0=4294967295,J0="Cipherstate has reached maximum n, a new handshake must be performed",js=class{n;bytes;view;constructor(t=X0){this.n=t,this.bytes=yt(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>Y0)throw new Error(J0)}};var mr=yt(0),qr=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new js(n)}hasKey(){return!!this.k}encryptWithAd(t,e){if(!this.hasKey())return e;this.n.assertValue();let n=this.crypto.encrypt(e,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,e,n){if(!this.hasKey())return e;this.n.assertValue();let o=this.crypto.decrypt(e,this.n.getBytes(),t,this.k,n);return this.n.increment(),o}},gc=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=et(e,"utf-8");this.h=Q0(t,n),this.ck=this.h,this.cs=new qr(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new qr(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new ht(this.h,t))}encryptAndHash(t){let e=this.cs.encryptWithAd(this.h,t);return this.mixHash(e),e}decryptAndHash(t){let e=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),e}split(){let[t,e]=this.crypto.hkdf(this.ck,mr);return[new qr(this.crypto,t),new qr(this.crypto,e)]}},yc=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:e,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=t;this.crypto=e,this.ss=new gc(e,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}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,e=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<e+32)throw new Error("message is not long enough");this.re=t.sublist(e,e+32),this.ss.mixHash(this.re)}readS(t,e=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<e+n)throw new Error("message is not long enough");let o=t.sublist(e,e+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Hn=class extends yc{writeMessageA(t){return new ht(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let e=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new ht(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){let e=this.writeS();return this.writeSE(),new ht(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(e){throw new Wr(`handshake stage 0 validation fail: ${e.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let e=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+e))}catch(e){throw new Wr(`handshake stage 1 validation fail: ${e.message}`)}}readMessageC(t){try{let e=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(e))}catch(e){throw new Wr(`handshake stage 2 validation fail: ${e.message}`)}}};function Q0(r,t){if(t.length<=32){let e=yt(32);return e.set(t),e}else return r.hash(t)}var Zs;(function(r){let t;r.codec=()=>(t==null&&(t=re((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.webtransportCerthashes!=null)for(let s of e.webtransportCerthashes)n.uint32(10),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={webtransportCerthashes:[]},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:{o.webtransportCerthashes.push(e.bytes());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>ee(e,r.codec()),r.decode=e=>te(e,r.codec())})(Zs||(Zs={}));var Mn;(function(r){let t;r.codec=()=>(t==null&&(t=re((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.identityKey!=null&&e.identityKey.byteLength>0&&(n.uint32(10),n.bytes(e.identityKey)),e.identitySig!=null&&e.identitySig.byteLength>0&&(n.uint32(18),n.bytes(e.identitySig)),e.extensions!=null&&(n.uint32(34),Zs.codec().encode(e.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={identityKey:yt(0),identitySig:yt(0)},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:{o.identityKey=e.bytes();break}case 2:{o.identitySig=e.bytes();break}case 4:{o.extensions=Zs.codec().decode(e,e.uint32());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>ee(e,r.codec()),r.decode=e=>te(e,r.codec())})(Mn||(Mn={}));async function wc(r,t,e){let n=await r.sign(rh(t));return Mn.encode({identityKey:Cr(r.publicKey),identitySig:n,extensions:e})}async function bc(r,t,e){try{let n=Mn.decode(r),o=vn(n.identityKey);if(e?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${e}`);if(!t)throw new Error("Remote static does not exist");let s=rh(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new $n(n.message)}}function rh(r){let t=et("noise-libp2p-static-key:");return r instanceof Uint8Array?Et([t,r],t.length+r.length):(r.prepend(t),r)}async function nh(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await wc(s,a.publicKey,l),f=new Hn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});hc(f.s,e),e.trace("Stage 0 - Initiator starting to send first message."),await n.write(f.writeMessageA(mr),t),e.trace("Stage 0 - Initiator finished sending first message."),dc(f.e,e),e.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=f.readMessageB(await n.read(t));e.trace("Stage 1 - Initiator received the message."),pc(f.re,e),eh(f.rs,e),e.trace("Initiator going to check remote's signature...");let m=await bc(d,f.rs,c);e.trace("All good with the signature!"),e.trace("Stage 2 - Initiator sending third handshake message."),await n.write(f.writeMessageC(u),t),e.trace("Stage 2 - Initiator sent message with signed payload.");let[x,g]=f.ss.split();return mc(x,g,e),{payload:m,encrypt:h=>x.encryptWithAd(mr,h),decrypt:(h,y)=>g.decryptWithAd(mr,h,y)}}async function oh(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await wc(s,a.publicKey,l),f=new Hn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});hc(f.s,e),e.trace("Stage 0 - Responder waiting to receive first message."),f.readMessageA(await n.read(t)),e.trace("Stage 0 - Responder received first message."),pc(f.re,e),e.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(f.writeMessageB(u),t),e.trace("Stage 1 - Responder sent the second handshake message with signed payload."),dc(f.e,e),e.trace("Stage 2 - Responder waiting for third handshake message...");let d=f.readMessageC(await n.read(t));e.trace("Stage 2 - Responder received the message, finished handshake.");let m=await bc(d,f.rs,c),[x,g]=f.ss.split();return mc(x,g,e),{payload:m,encrypt:h=>g.encryptWithAd(mr,h),decrypt:(h,y)=>x.decryptWithAd(mr,h,y)}}var ih=16;function ah(r,t){return async function*(e){for await(let n of e)for(let o=0;o<n.length;o+=65519){let s=o+65519;s>n.length&&(s=n.length);let i;n instanceof Uint8Array?i=r.encrypt(n.subarray(o,s)):i=r.encrypt(n.sublist(o,s)),t?.encryptedPackets.increment(),yield new ht($r(i.byteLength),i)}}}function ch(r,t){return async function*(e){for await(let n of e)for(let o=0;o<n.length;o+=65535){let s=o+65535;if(s>n.length&&(s=n.length),s-ih<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-ih);try{let c=r.decrypt(i,a);t?.decryptedPackets.increment(),yield c}catch(c){throw t?.decryptErrors.increment(),c}}}}var Xs=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(t,e={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=e,{metrics:a}=t;this.components=t;let c=s??Jf;this.crypto=Qf(c),this.extensions=o,this.metrics=a?th(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??yt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[yr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,e){let n=Un(t,{lengthEncoder:$r,lengthDecoder:On,maxDataLength:65535}),o=await this.performHandshakeInitiator(n,this.components.privateKey,e?.remotePeer?.publicKey,e),s=await this.createSecureConnection(n,o);t.source=s.source,t.sink=s.sink;let i=vn(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ea(i)}}async secureInbound(t,e){let n=Un(t,{lengthEncoder:$r,lengthDecoder:On,maxDataLength:65535}),o=await this.performHandshakeResponder(n,this.components.privateKey,e?.remotePeer?.publicKey,e),s=await this.createSecureConnection(n,o);t.source=s.source,t.sink=s.sink;let i=vn(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ea(i)}}async performHandshakeInitiator(t,e,n,o){let s;try{s=await nh({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async performHandshakeResponder(t,e,n,o){let s;try{s=await oh({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async createSecureConnection(t,e){let[n,o]=Lf(),s=t.unwrap();return await Rf(n,ah(e,this.metrics),s,i=>hr(i,{lengthDecoder:On}),ch(e,this.metrics),n),o}};function lh(r={}){return t=>new Xs(t,r)}var xc=Object.values(nr).map(r=>r.decoder).reduce((r,t)=>r.or(t));function uh(r,t){let e=r.getConfiguration().certificates?.at(0);if(e?.getFingerprints==null){t.log.trace("fetching fingerprint from local SDP");let o=r.localDescription;return o==null?void 0:eg(o.sdp)}if(t.log.trace("fetching fingerprint from local certificate"),e.getFingerprints().length===0)return;let n=e.getFingerprints()[0].value;if(n==null)throw new Pn("","no fingerprint on local certificate");return n}var tg=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function eg(r){return r.match(tg)?.groups?.fingerprint}function rg(r){for(let t of r.protoNames())if(t.startsWith("ip"))return t.toUpperCase();return"IP6"}function Ys(r){let e=r.stringTuples().filter(n=>n[0]===dh).map(n=>n[1])[0];if(e===void 0||e==="")throw new tt(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function Ec(r){return Gt.decode(xc.decode(r))}function ng(r){let t=Ec(Ys(r)),e=vc(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 Pn(n,r.toString());return[`${e} ${o.join(":").toUpperCase()}`,n]}function vc(r){switch(r){case 17:return"SHA-1";case 18:return"SHA-256";case 19:return"SHA-512";default:throw new Hs(r)}}function og(r,t){let{host:e,port:n}=r.toOptions(),o=rg(r),[s]=ng(r);return`v=0
|
7
7
|
o=- 0 0 IN ${o} ${e}
|
8
8
|
s=-
|
9
9
|
c=IN ${o} ${e}
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@libp2p/webrtc",
|
3
|
-
"version": "5.0.
|
3
|
+
"version": "5.0.19-6ddc1b80e",
|
4
4
|
"description": "A libp2p transport using WebRTC connections",
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
6
6
|
"homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/transport-webrtc#readme",
|
@@ -51,10 +51,10 @@
|
|
51
51
|
},
|
52
52
|
"dependencies": {
|
53
53
|
"@chainsafe/libp2p-noise": "^16.0.0",
|
54
|
-
"@libp2p/interface": "
|
55
|
-
"@libp2p/interface-internal": "
|
56
|
-
"@libp2p/peer-id": "
|
57
|
-
"@libp2p/utils": "
|
54
|
+
"@libp2p/interface": "2.2.1-6ddc1b80e",
|
55
|
+
"@libp2p/interface-internal": "2.1.1-6ddc1b80e",
|
56
|
+
"@libp2p/peer-id": "5.0.8-6ddc1b80e",
|
57
|
+
"@libp2p/utils": "6.2.1-6ddc1b80e",
|
58
58
|
"@multiformats/multiaddr": "^12.2.3",
|
59
59
|
"@multiformats/multiaddr-matcher": "^1.2.1",
|
60
60
|
"detect-browser": "^5.3.0",
|
@@ -76,9 +76,9 @@
|
|
76
76
|
"uint8arrays": "^5.1.0"
|
77
77
|
},
|
78
78
|
"devDependencies": {
|
79
|
-
"@libp2p/crypto": "
|
80
|
-
"@libp2p/interface-compliance-tests": "
|
81
|
-
"@libp2p/logger": "
|
79
|
+
"@libp2p/crypto": "5.0.7-6ddc1b80e",
|
80
|
+
"@libp2p/interface-compliance-tests": "6.1.11-6ddc1b80e",
|
81
|
+
"@libp2p/logger": "5.1.4-6ddc1b80e",
|
82
82
|
"@types/sinon": "^17.0.3",
|
83
83
|
"aegir": "^44.0.1",
|
84
84
|
"delay": "^6.0.0",
|
package/dist/typedoc-urls.json
DELETED
@@ -1,12 +0,0 @@
|
|
1
|
-
{
|
2
|
-
"DataChannelOptions": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_webrtc.DataChannelOptions.html",
|
3
|
-
".:DataChannelOptions": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_webrtc.DataChannelOptions.html",
|
4
|
-
"WebRTCDirectTransportComponents": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_webrtc.WebRTCDirectTransportComponents.html",
|
5
|
-
"WebRTCTransportComponents": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_webrtc.WebRTCTransportComponents.html",
|
6
|
-
"WebRTCTransportDirectInit": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_webrtc.WebRTCTransportDirectInit.html",
|
7
|
-
"WebRTCTransportInit": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_webrtc.WebRTCTransportInit.html",
|
8
|
-
"webRTC": "https://libp2p.github.io/js-libp2p/functions/_libp2p_webrtc.webRTC.html",
|
9
|
-
".:webRTC": "https://libp2p.github.io/js-libp2p/functions/_libp2p_webrtc.webRTC.html",
|
10
|
-
"webRTCDirect": "https://libp2p.github.io/js-libp2p/functions/_libp2p_webrtc.webRTCDirect.html",
|
11
|
-
".:webRTCDirect": "https://libp2p.github.io/js-libp2p/functions/_libp2p_webrtc.webRTCDirect.html"
|
12
|
-
}
|