From c85fa245ddf98f88a8ec71811c745fca7b50824a Mon Sep 17 00:00:00 2001 From: vol4tim Date: Fri, 1 Dec 2023 07:03:09 +0000 Subject: [PATCH] deploy: 86683c6c8d6fb6e95f4f2cee1922259ff16e4df7 --- assets/{index.519a9e7d.js => index.10e62293.js} | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename assets/{index.519a9e7d.js => index.10e62293.js} (99%) diff --git a/assets/index.519a9e7d.js b/assets/index.10e62293.js similarity index 99% rename from assets/index.519a9e7d.js rename to assets/index.10e62293.js index 0b94536..4e2ef74 100644 --- a/assets/index.519a9e7d.js +++ b/assets/index.10e62293.js @@ -144,7 +144,7 @@ You can find the project at: https://github.com/domoritz/leaflet-locatecontrol )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1 `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),v46Exact=new RegExp(`(?:^${v4}$)|(?:^${v6}$)`),v4exact=new RegExp(`^${v4}$`),v6exact=new RegExp(`^${v6}$`),ipRegex=e=>e&&e.exact?v46Exact:new RegExp(`(?:${boundry(e)}${v4}${boundry(e)})|(?:${boundry(e)}${v6}${boundry(e)})`,"g");ipRegex.v4=e=>e&&e.exact?v4exact:new RegExp(`${boundry(e)}${v4}${boundry(e)}`,"g");ipRegex.v6=e=>e&&e.exact?v6exact:new RegExp(`${boundry(e)}${v6}${boundry(e)}`,"g");var ipaddr$1={exports:{}};(function(e){(function(t){const r="(0?\\d+|0x[a-f0-9]+)",n={fourOctet:new RegExp(`^${r}\\.${r}\\.${r}\\.${r}$`,"i"),threeOctet:new RegExp(`^${r}\\.${r}\\.${r}$`,"i"),twoOctet:new RegExp(`^${r}\\.${r}$`,"i"),longValue:new RegExp(`^${r}$`,"i")},o=new RegExp("^0[0-7]+$","i"),a=new RegExp("^0x[a-f0-9]+$","i"),l="%[0-9a-z]{1,}",c="(?:[0-9a-f]+::?)+",u={zoneIndex:new RegExp(l,"i"),native:new RegExp(`^(::)?(${c})?([0-9a-f]+)?(::)?(${l})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${r}\\.${r}\\.${r}\\.${r}(${l})?)$`,"i"),transitional:new RegExp(`^((?:${c})|(?:::)(?:${c})?)${r}\\.${r}\\.${r}\\.${r}(${l})?$`,"i")};function g(T,k){if(T.indexOf("::")!==T.lastIndexOf("::"))return null;let O=0,$=-1,D=(T.match(u.zoneIndex)||[])[0],N,H;for(D&&(D=D.substring(1),T=T.replace(/%.+$/,""));($=T.indexOf(":",$+1))>=0;)O++;if(T.substr(0,2)==="::"&&O--,T.substr(-2,2)==="::"&&O--,O>k)return null;for(H=k-O,N=":";H--;)N+="0:";return T=T.replace("::",N),T[0]===":"&&(T=T.slice(1)),T[T.length-1]===":"&&(T=T.slice(0,-1)),k=function(){const se=T.split(":"),ue=[];for(let de=0;de0;){if(N=O-$,N<0&&(N=0),T[D]>>N!==k[D]>>N)return!1;$-=O,D+=1}return!0}function x(T){if(a.test(T))return parseInt(T,16);if(T[0]==="0"&&!isNaN(parseInt(T[1],10))){if(o.test(T))return parseInt(T,8);throw new Error(`ipaddr: cannot parse ${T} as octal`)}return parseInt(T,10)}function E(T,k){for(;T.length=0;D-=1)if(N=this.octets[D],N in $){if(H=$[N],O&&H!==0)return null;H!==8&&(O=!0),k+=H}else return null;return 32-k},T.prototype.range=function(){return I.subnetMatch(this,this.SpecialRanges)},T.prototype.toByteArray=function(){return this.octets.slice(0)},T.prototype.toIPv4MappedAddress=function(){return I.IPv6.parse(`::ffff:${this.toString()}`)},T.prototype.toNormalizedString=function(){return this.toString()},T.prototype.toString=function(){return this.octets.join(".")},T}(),I.IPv4.broadcastAddressFromCIDR=function(T){try{const k=this.parseCIDR(T),O=k[0].toByteArray(),$=this.subnetMaskFromPrefixLength(k[1]).toByteArray(),D=[];let N=0;for(;N<4;)D.push(parseInt(O[N],10)|parseInt($[N],10)^255),N++;return new this(D)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},I.IPv4.isIPv4=function(T){return this.parser(T)!==null},I.IPv4.isValid=function(T){try{return new this(this.parser(T)),!0}catch{return!1}},I.IPv4.isValidFourPartDecimal=function(T){return!!(I.IPv4.isValid(T)&&T.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},I.IPv4.networkAddressFromCIDR=function(T){let k,O,$,D,N;try{for(k=this.parseCIDR(T),$=k[0].toByteArray(),N=this.subnetMaskFromPrefixLength(k[1]).toByteArray(),D=[],O=0;O<4;)D.push(parseInt($[O],10)&parseInt(N[O],10)),O++;return new this(D)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},I.IPv4.parse=function(T){const k=this.parser(T);if(k===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(k)},I.IPv4.parseCIDR=function(T){let k;if(k=T.match(/^(.+)\/(\d+)$/)){const O=parseInt(k[2]);if(O>=0&&O<=32){const $=[this.parse(k[1]),O];return Object.defineProperty($,"toString",{value:function(){return this.join("/")}}),$}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},I.IPv4.parser=function(T){let k,O,$;if(k=T.match(n.fourOctet))return function(){const D=k.slice(1,6),N=[];for(let H=0;H4294967295||$<0)throw new Error("ipaddr: address outside defined range");return function(){const D=[];let N;for(N=0;N<=24;N+=8)D.push($>>N&255);return D}().reverse()}else return(k=T.match(n.twoOctet))?function(){const D=k.slice(1,4),N=[];if($=x(D[1]),$>16777215||$<0)throw new Error("ipaddr: address outside defined range");return N.push(x(D[0])),N.push($>>16&255),N.push($>>8&255),N.push($&255),N}():(k=T.match(n.threeOctet))?function(){const D=k.slice(1,5),N=[];if($=x(D[2]),$>65535||$<0)throw new Error("ipaddr: address outside defined range");return N.push(x(D[0])),N.push(x(D[1])),N.push($>>8&255),N.push($&255),N}():null},I.IPv4.subnetMaskFromPrefixLength=function(T){if(T=parseInt(T),T<0||T>32)throw new Error("ipaddr: invalid IPv4 prefix length");const k=[0,0,0,0];let O=0;const $=Math.floor(T/8);for(;O<$;)k[O]=255,O++;return $<4&&(k[$]=Math.pow(2,T%8)-1<<8-T%8),new this(k)},I.IPv6=function(){function T(k,O){let $,D;if(k.length===16)for(this.parts=[],$=0;$<=14;$+=2)this.parts.push(k[$]<<8|k[$+1]);else if(k.length===8)this.parts=k;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for($=0;$=0;H-=1)if(D=this.parts[H],D in $){if(N=$[D],O&&N!==0)return null;N!==16&&(O=!0),k+=N}else return null;return 128-k},T.prototype.range=function(){return I.subnetMatch(this,this.SpecialRanges)},T.prototype.toByteArray=function(){let k;const O=[],$=this.parts;for(let D=0;D<$.length;D++)k=$[D],O.push(k>>8),O.push(k&255);return O},T.prototype.toFixedLengthString=function(){const k=function(){const $=[];for(let D=0;D>8,O&255,$>>8,$&255])},T.prototype.toNormalizedString=function(){const k=function(){const $=[];for(let D=0;DD&&($=N.index,D=N[0].length);return D<0?O:`${O.substring(0,$)}::${O.substring($+D)}`},T.prototype.toString=function(){return this.toRFC5952String()},T}(),I.IPv6.broadcastAddressFromCIDR=function(T){try{const k=this.parseCIDR(T),O=k[0].toByteArray(),$=this.subnetMaskFromPrefixLength(k[1]).toByteArray(),D=[];let N=0;for(;N<16;)D.push(parseInt(O[N],10)|parseInt($[N],10)^255),N++;return new this(D)}catch(k){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${k})`)}},I.IPv6.isIPv6=function(T){return this.parser(T)!==null},I.IPv6.isValid=function(T){if(typeof T=="string"&&T.indexOf(":")===-1)return!1;try{const k=this.parser(T);return new this(k.parts,k.zoneId),!0}catch{return!1}},I.IPv6.networkAddressFromCIDR=function(T){let k,O,$,D,N;try{for(k=this.parseCIDR(T),$=k[0].toByteArray(),N=this.subnetMaskFromPrefixLength(k[1]).toByteArray(),D=[],O=0;O<16;)D.push(parseInt($[O],10)&parseInt(N[O],10)),O++;return new this(D)}catch(H){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${H})`)}},I.IPv6.parse=function(T){const k=this.parser(T);if(k.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(k.parts,k.zoneId)},I.IPv6.parseCIDR=function(T){let k,O,$;if((O=T.match(/^(.+)\/(\d+)$/))&&(k=parseInt(O[2]),k>=0&&k<=128))return $=[this.parse(O[1]),k],Object.defineProperty($,"toString",{value:function(){return this.join("/")}}),$;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},I.IPv6.parser=function(T){let k,O,$,D,N,H;if($=T.match(u.deprecatedTransitional))return this.parser(`::ffff:${$[1]}`);if(u.native.test(T))return g(T,8);if(($=T.match(u.transitional))&&(H=$[6]||"",k=g($[1].slice(0,-1)+H,6),k.parts)){for(N=[parseInt($[2]),parseInt($[3]),parseInt($[4]),parseInt($[5])],O=0;O128)throw new Error("ipaddr: invalid IPv6 prefix length");const k=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];let O=0;const $=Math.floor(T/8);for(;O<$;)k[O]=255,O++;return $<16&&(k[$]=Math.pow(2,T%8)-1<<8-T%8),new this(k)},I.fromByteArray=function(T){const k=T.length;if(k===4)return new I.IPv4(T);if(k===16)return new I.IPv6(T);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},I.isValid=function(T){return I.IPv6.isValid(T)||I.IPv4.isValid(T)},I.parse=function(T){if(I.IPv6.isValid(T))return I.IPv6.parse(T);if(I.IPv4.isValid(T))return I.IPv4.parse(T);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},I.parseCIDR=function(T){try{return I.IPv6.parseCIDR(T)}catch{try{return I.IPv4.parseCIDR(T)}catch{throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},I.process=function(T){const k=this.parse(T);return k.kind()==="ipv6"&&k.isIPv4MappedAddress()?k.toIPv4Address():k},I.subnetMatch=function(T,k,O){let $,D,N,H;O==null&&(O="unicast");for(D in k)if(Object.prototype.hasOwnProperty.call(k,D)){for(N=k[D],N[0]&&!(N[0]instanceof Array)&&(N=[N]),$=0;$new Netmask_1(e));function ipv4_check(e){for(let t of NETMASK_RANGES)if(t.contains(e))return!0;return!1}function ipv6_check(e){return/^::$/.test(e)||/^::1$/.test(e)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e)}const is_ip_private=e=>{if(is_valid(e)){const t=parse$6(e);if(t.kind()==="ipv4")return ipv4_check(t.toNormalizedString());if(t.kind()==="ipv6")return ipv6_check(e)}else if(isIP(e)&&ipRegex.v6().test(e))return ipv6_check(e)};function connectionGater(e={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{const r=t.stringTuples();return r[0][0]===4||r[0][0]===41?Boolean(is_ip_private(`${r[0][1]}`)):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...e}}const toParts=e=>e.toString().split("/").slice(1),func=e=>({match:t=>t.length<1?!1:e(t[0])?t.slice(1):!1,pattern:"fn"}),literal=e=>({match:t=>func(r=>r===e).match(t),pattern:e}),string=()=>({match:e=>func(t=>typeof t=="string").match(e),pattern:"{string}"}),number$1=()=>({match:e=>func(t=>!isNaN(parseInt(t))).match(e),pattern:"{number}"}),peerId=()=>({match:e=>{if(e.length<2||e[0]!=="p2p"&&e[0]!=="ipfs")return!1;if(e[1].startsWith("Q")||e[1].startsWith("1"))try{base58btc$1.decode(`z${e[1]}`)}catch{return!1}else return!1;return e.slice(2)},pattern:"/p2p/{peerid}"}),certhash=()=>({match:e=>{if(e.length<2||e[0]!=="certhash")return!1;try{base64url$1.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),optional=e=>({match:t=>{const r=e.match(t);return r===!1?t:r},pattern:`optional(${e.pattern})`}),or=(...e)=>({match:t=>{let r;for(const n of e){const o=n.match(t);o!==!1&&(r==null||o.lengtht.pattern).join(", ")})`}),and=(...e)=>({match:t=>{for(const r of e){const n=r.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${e.map(t=>t.pattern).join(", ")})`});function fmt(...e){function t(o){let a=toParts(o);for(const l of e){const c=l.match(a);if(c===!1)return!1;a=c}return a}function r(o){return t(o)!==!1}function n(o){const a=t(o);return a===!1?!1:a.length===0}return{matches:r,exactMatch:n}}const _DNS4=and(literal("dns4"),string()),_DNS6=and(literal("dns6"),string()),_DNSADDR=and(literal("dnsaddr"),string()),_DNS=and(literal("dns"),string());fmt(or(_DNS,_DNSADDR,_DNS4,_DNS6));const _IP4=and(literal("ip4"),func(isIPv4)),_IP6=and(literal("ip6"),func(isIPv6)),_IP=or(_IP4,_IP6),IP_OR_DOMAIN=or(_IP,_DNS,_DNS4,_DNS6,_DNSADDR),_TCP=and(IP_OR_DOMAIN,literal("tcp"),number$1()),_UDP=and(IP_OR_DOMAIN,literal("udp"),number$1()),TCP_OR_UDP=or(_TCP,_UDP),_QUIC=and(_UDP,literal("quic")),_QUICV1=and(_UDP,literal("quic-v1")),QUIC_V0_OR_V1=or(_QUIC,_QUICV1),_WEB=or(IP_OR_DOMAIN,_TCP,_UDP,_QUIC,_QUICV1),_WebSockets=or(and(_WEB,literal("ws"),optional(peerId()))),_WebSocketsSecure=or(and(_WEB,literal("wss"),optional(peerId())),and(_WEB,literal("tls"),literal("ws"),optional(peerId()))),_WebRTCDirect=and(TCP_OR_UDP,literal("webrtc-direct"),certhash(),optional(certhash()),optional(peerId())),_WebTransport=and(_QUICV1,literal("webtransport"),certhash(),certhash(),optional(peerId())),_P2P=or(_WebSockets,_WebSocketsSecure,and(_TCP,optional(peerId())),and(QUIC_V0_OR_V1,optional(peerId())),and(IP_OR_DOMAIN,optional(peerId())),_WebRTCDirect,_WebTransport,peerId()),_Circuit=and(_P2P,literal("p2p-circuit"),peerId()),Circuit=fmt(_Circuit);or(and(_P2P,literal("p2p-circuit"),literal("webrtc"),peerId()),and(_P2P,literal("webrtc"),optional(peerId())),literal("webrtc"));function isPrivate(e){try{const{address:t}=e.nodeAddress();return Boolean(is_ip_private(t))}catch{return!0}}function publicAddressesFirst(e,t){const r=isPrivate(e.multiaddr),n=isPrivate(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function certifiedAddressesFirst(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function circuitRelayAddressesLast(e,t){const r=Circuit.exactMatch(e.multiaddr),n=Circuit.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function defaultAddressSort(e,t){const r=publicAddressesFirst(e,t);if(r!==0)return r;const n=circuitRelayAddressesLast(e,t);return n!==0?n:certifiedAddressesFirst(e,t)}var s$3=1e3,m$4=s$3*60,h$4=m$4*60,d$5=h$4*24,w$2=d$5*7,y$3=d$5*365.25,ms$3=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0)return parse$5(e);if(r==="number"&&isFinite(e))return t.long?fmtLong$3(e):fmtShort$3(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse$5(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!!t){var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*y$3;case"weeks":case"week":case"w":return r*w$2;case"days":case"day":case"d":return r*d$5;case"hours":case"hour":case"hrs":case"hr":case"h":return r*h$4;case"minutes":case"minute":case"mins":case"min":case"m":return r*m$4;case"seconds":case"second":case"secs":case"sec":case"s":return r*s$3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function fmtShort$3(e){var t=Math.abs(e);return t>=d$5?Math.round(e/d$5)+"d":t>=h$4?Math.round(e/h$4)+"h":t>=m$4?Math.round(e/m$4)+"m":t>=s$3?Math.round(e/s$3)+"s":e+"ms"}function fmtLong$3(e){var t=Math.abs(e);return t>=d$5?plural$3(e,t,d$5,"day"):t>=h$4?plural$3(e,t,h$4,"hour"):t>=m$4?plural$3(e,t,m$4,"minute"):t>=s$3?plural$3(e,t,s$3,"second"):e+" ms"}function plural$3(e,t,r,n){var o=t>=r*1.5;return Math.round(e/r)+" "+n+(o?"s":"")}var receptacle=Receptacle,toMS=ms$3,cache$1=Receptacle.prototype,counter=new Date%1e9;function getUID(){return(Math.random()*1e9>>>0)+counter++}function Receptacle(e){e=e||{},this.id=e.id||getUID(),this.max=e.max||1/0,this.items=e.items||[],this._lookup={},this.size=this.items.length,this.lastModified=new Date(e.lastModified||new Date);for(var t,r,n=this.items.length;n--;)t=this.items[n],r=new Date(t.expires)-new Date,this._lookup[t.key]=t,r>0?this.expire(t.key,r):r<=0&&this.delete(t.key)}cache$1.has=function(e){return e in this._lookup};cache$1.get=function(e){if(!this.has(e))return null;var t=this._lookup[e];return t.refresh&&this.expire(e,t.refresh),this.items.splice(this.items.indexOf(t),1),this.items.push(t),t.value};cache$1.meta=function(e){if(!this.has(e))return null;var t=this._lookup[e];return"meta"in t?t.meta:null};cache$1.set=function(e,t,r){var n=this._lookup[e],o=this._lookup[e]={key:e,value:t};return this.lastModified=new Date,n?(clearTimeout(n.timeout),this.items.splice(this.items.indexOf(n),1,o)):(this.size>=this.max&&this.delete(this.items[0].key),this.items.push(o),this.size++),r&&("ttl"in r&&this.expire(e,r.ttl),"meta"in r&&(o.meta=r.meta),r.refresh&&(o.refresh=r.ttl)),this};cache$1.delete=function(e){var t=this._lookup[e];return t?(this.lastModified=new Date,this.items.splice(this.items.indexOf(t),1),clearTimeout(t.timeout),delete this._lookup[e],this.size--,this):!1};cache$1.expire=function(e,t){var r=t||0,n=this._lookup[e];if(!n)return this;if(typeof r=="string"&&(r=toMS(t)),typeof r!="number")throw new TypeError("Expiration time must be a string or number.");return clearTimeout(n.timeout),n.timeout=setTimeout(this.delete.bind(this,n.key),r),n.expires=Number(new Date)+r,this};cache$1.clear=function(){for(var e=this.items.length;e--;)this.delete(this.items[e].key);return this};cache$1.toJSON=function(){for(var e=new Array(this.items.length),t,r=e.length;r--;)t=this.items[r],e[r]={key:t.key,meta:t.meta,value:t.value,expires:t.expires,refresh:t.refresh};return{id:this.id,max:isFinite(this.max)?this.max:void 0,lastModified:this.lastModified,items:e}};const globalFetch=globalThis.fetch,globalHeaders=globalThis.Headers;function buildResource(e,t,r){return`${e}?name=${t}&type=${r}`}async function request(e,t){return await(await globalFetch(e,{headers:new globalHeaders({accept:"application/dns-json"}),signal:t})).json()}function getCacheKey(e,t){return`${t}_${e}`}const log$m=Object.assign(debug$9("dns-over-http-resolver"),{error:debug$9("dns-over-http-resolver:error")});class Resolver{constructor(t={}){this._cache=new receptacle({max:t?.maxCache??100}),this._TXTcache=new receptacle({max:t?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=t.request??request,this._abortControllers=[]}cancel(){this._abortControllers.forEach(t=>t.abort())}getServers(){return this._servers}_getShuffledServers(){const t=[...this._servers];for(let r=t.length-1;r>0;r--){const n=Math.floor(Math.random()*r),o=t[r];t[r]=t[n],t[n]=o}return t}setServers(t){this._servers=t}async resolve(t,r="A"){switch(r){case"A":return await this.resolve4(t);case"AAAA":return await this.resolve6(t);case"TXT":return await this.resolveTxt(t);default:throw new Error(`${r} is not supported`)}}async resolve4(t){const r="A",n=this._cache.get(getCacheKey(t,r));if(n!=null)return n;let o=!1;for(const a of this._getShuffledServers()){const l=new AbortController;this._abortControllers.push(l);try{const c=await this._request(buildResource(a,t,r),l.signal),u=c.Answer.map(b=>b.data),g=Math.min(...c.Answer.map(b=>b.TTL));return this._cache.set(getCacheKey(t,r),u,{ttl:g}),u}catch{l.signal.aborted&&(o=!0),log$m.error(`${a} could not resolve ${t} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(c=>c!==l)}}throw o?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${t} record ${r}`)}async resolve6(t){const r="AAAA",n=this._cache.get(getCacheKey(t,r));if(n!=null)return n;let o=!1;for(const a of this._getShuffledServers()){const l=new AbortController;this._abortControllers.push(l);try{const c=await this._request(buildResource(a,t,r),l.signal),u=c.Answer.map(b=>b.data),g=Math.min(...c.Answer.map(b=>b.TTL));return this._cache.set(getCacheKey(t,r),u,{ttl:g}),u}catch{l.signal.aborted&&(o=!0),log$m.error(`${a} could not resolve ${t} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(c=>c!==l)}}throw o?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${t} record ${r}`)}async resolveTxt(t){const r="TXT",n=this._TXTcache.get(getCacheKey(t,r));if(n!=null)return n;let o=!1;for(const a of this._getShuffledServers()){const l=new AbortController;this._abortControllers.push(l);try{const c=await this._request(buildResource(a,t,r),l.signal),u=c.Answer.map(b=>[b.data.replace(/['"]+/g,"")]),g=Math.min(...c.Answer.map(b=>b.TTL));return this._TXTcache.set(getCacheKey(t,r),u,{ttl:g}),u}catch{l.signal.aborted&&(o=!0),log$m.error(`${a} could not resolve ${t} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(c=>c!==l)}}throw o?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${t} record ${r}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}}const{code:dnsaddrCode}=getProtocol("dnsaddr");async function dnsaddrResolver(e,t={}){const r=new Resolver;t.signal!=null&&t.signal.addEventListener("abort",()=>{r.cancel()});const n=e.getPeerId(),[,o]=e.stringTuples().find(([c])=>c===dnsaddrCode)??[];if(o==null)throw new Error("No hostname found in multiaddr");let l=(await r.resolveTxt(`_dnsaddr.${o}`)).flat().map(c=>c.split("=")[1]).filter(Boolean);return n!=null&&(l=l.filter(c=>c.includes(n))),l}var messages$1;(function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.DHT_DISABLED="DHT is not available",e.PUBSUB_DISABLED="PubSub is not available",e.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",e.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",e.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",e.NOT_FOUND="Not found"})(messages$1||(messages$1={}));var codes;(function(e){e.DHT_DISABLED="ERR_DHT_DISABLED",e.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",e.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",e.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",e.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",e.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",e.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",e.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",e.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",e.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",e.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",e.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",e.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",e.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",e.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",e.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",e.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",e.ERR_DIALED_SELF="ERR_DIALED_SELF",e.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",e.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",e.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",e.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",e.ERR_INVALID_KEY="ERR_INVALID_KEY",e.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",e.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",e.ERR_INVALID_PEER="ERR_INVALID_PEER",e.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",e.ERR_NOT_FOUND="ERR_NOT_FOUND",e.ERR_TIMEOUT="ERR_TIMEOUT",e.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",e.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",e.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",e.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",e.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",e.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",e.ERR_FIND_SELF="ERR_FIND_SELF",e.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",e.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",e.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",e.ERR_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",e.ERR_INVALID_CMS="ERR_INVALID_CMS",e.ERR_MISSING_KEYS="ERR_MISSING_KEYS",e.ERR_NO_KEY="ERR_NO_KEY",e.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",e.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",e.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",e.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",e.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",e.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",e.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",e.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",e.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",e.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",e.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",e.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",e.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",e.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",e.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",e.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",e.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",e.ERR_INVALID_RECORD="ERR_INVALID_RECORD",e.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",e.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",e.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",e.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",e.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",e.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(codes||(codes={}));const DefaultConfig={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:dnsaddrResolver},addressSorter:defaultAddressSort},transportManager:{faultTolerance:FaultTolerance.FATAL_ALL}};function validateConfig(e){const t=mergeOptions(DefaultConfig,e);if(t.transports==null||t.transports.length<1)throw new CodeError(messages$1.ERR_TRANSPORTS_REQUIRED,codes.ERR_TRANSPORTS_REQUIRED);if(t.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new CodeError(messages$1.ERR_PROTECTOR_REQUIRED,codes.ERR_PROTECTOR_REQUIRED);return t}const KEEP_ALIVE="keep-alive",log$l=logger("libp2p:get-peer");function getPeerAddress(e){if(isPeerId(e))return{peerId:e,multiaddrs:[]};Array.isArray(e)||(e=[e]);let t;if(e.length>0){const r=e[0].getPeerId();t=r==null?void 0:peerIdFromString(r),e.forEach(n=>{if(!isMultiaddr(n))throw log$l.error("multiaddr %s was invalid",n),new CodeError("Invalid Multiaddr",codes.ERR_INVALID_MULTIADDR);const o=n.getPeerId();if(o==null){if(t!=null)throw new CodeError("Multiaddrs must all have the same peer id or have no peer id",codes.ERR_INVALID_PARAMETERS)}else{const a=peerIdFromString(o);if(t==null||!t.equals(a))throw new CodeError("Multiaddrs must all have the same peer id or have no peer id",codes.ERR_INVALID_PARAMETERS)}})}return{peerId:t,multiaddrs:e}}function lowerBound(e,t,r){let n=0,o=e.length;for(;o>0;){const a=Math.trunc(o/2);let l=n+a;r(e[l],t)<=0?(n=++l,o-=a+1):o=a}return n}var Ur;class PeerPriorityQueue{constructor(){_r(this,Ur,[])}enqueue(t,r){const n=r?.peerId,o=r?.priority??0;if(n==null)throw new CodeError("missing peer id",codes.ERR_INVALID_PARAMETERS);const a={priority:o,peerId:n,run:t};if(this.size>0&&Jt(this,Ur)[this.size-1].priority>=o){Jt(this,Ur).push(a);return}const l=lowerBound(Jt(this,Ur),a,(c,u)=>u.priority-c.priority);Jt(this,Ur).splice(l,0,a)}dequeue(){return Jt(this,Ur).shift()?.run}filter(t){if(t.peerId!=null){const r=t.peerId;return Jt(this,Ur).filter(n=>r.equals(n.peerId)).map(n=>n.run)}return Jt(this,Ur).filter(r=>r.priority===t.priority).map(r=>r.run)}get size(){return Jt(this,Ur).length}}Ur=new WeakMap;class PeerJobQueue extends PQueue{constructor(t={}){super({...t,queueClass:PeerPriorityQueue})}hasJob(t){return this.sizeBy({peerId:t})>0}}const DIAL_TIMEOUT=3e4,INBOUND_UPGRADE_TIMEOUT=3e4,MAX_PEER_ADDRS_TO_DIAL=25,MAX_PARALLEL_DIALS_PER_PEER=1,AUTO_DIAL_INTERVAL=5e3,AUTO_DIAL_CONCURRENCY=25,AUTO_DIAL_PRIORITY=0,AUTO_DIAL_MAX_QUEUE_LENGTH=100,AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE=10,INBOUND_CONNECTION_THRESHOLD=5,MAX_INCOMING_PENDING_CONNECTIONS=10,LAST_DIAL_FAILURE_KEY="last-dial-failure",MIN_CONNECTIONS=5,MAX_CONNECTIONS=100,MAX_PARALLEL_DIALS=50,AUTO_DIAL_PEER_RETRY_THRESHOLD=1e3*60*7,log$k=logger("libp2p:connection-manager:auto-dial"),defaultOptions$3={minConnections:MIN_CONNECTIONS,maxQueueLength:AUTO_DIAL_MAX_QUEUE_LENGTH,autoDialConcurrency:AUTO_DIAL_CONCURRENCY,autoDialPriority:AUTO_DIAL_PRIORITY,autoDialInterval:AUTO_DIAL_INTERVAL,autoDialPeerRetryThreshold:AUTO_DIAL_PEER_RETRY_THRESHOLD,autoDialDiscoveredPeersDebounce:AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE};class AutoDial{constructor(t,r){Ke(this,"connectionManager");Ke(this,"peerStore");Ke(this,"queue");Ke(this,"minConnections");Ke(this,"autoDialPriority");Ke(this,"autoDialIntervalMs");Ke(this,"autoDialMaxQueueLength");Ke(this,"autoDialPeerRetryThresholdMs");Ke(this,"autoDialDiscoveredPeersDebounce");Ke(this,"autoDialInterval");Ke(this,"started");Ke(this,"running");this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.minConnections=r.minConnections??defaultOptions$3.minConnections,this.autoDialPriority=r.autoDialPriority??defaultOptions$3.autoDialPriority,this.autoDialIntervalMs=r.autoDialInterval??defaultOptions$3.autoDialInterval,this.autoDialMaxQueueLength=r.maxQueueLength??defaultOptions$3.maxQueueLength,this.autoDialPeerRetryThresholdMs=r.autoDialPeerRetryThreshold??defaultOptions$3.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=r.autoDialDiscoveredPeersDebounce??defaultOptions$3.autoDialDiscoveredPeersDebounce,this.started=!1,this.running=!1,this.queue=new PeerJobQueue({concurrency:r.autoDialConcurrency??defaultOptions$3.autoDialConcurrency}),this.queue.addListener("error",o=>{log$k.error("error during auto-dial",o)}),t.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{log$k.error(o)})});let n;t.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{log$k.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(t=>{log$k.error("error while autodialing",t)})},this.autoDialIntervalMs),this.started=!0}afterStart(){this.autoDial().catch(t=>{log$k.error("error while autodialing",t)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started)return;const t=this.connectionManager.getConnectionsMap(),r=t.size;if(r>=this.minConnections){this.minConnections>0&&log$k.trace("have enough connections %d/%d",r,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){log$k("not enough connections %d/%d but auto dial queue is full",r,this.minConnections);return}if(this.running){log$k("not enough connections %d/%d - but skipping autodial as it is already running",r,this.minConnections);return}this.running=!0,log$k("not enough connections %d/%d - will dial peers to increase the number of connections",r,this.minConnections);const n=new PeerSet(this.connectionManager.getDialQueue().map(g=>g.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[g=>g.addresses.length===0?(log$k.trace("not autodialing %p because they have no addresses"),!1):t.has(g.id)?(log$k.trace("not autodialing %p because they are already connected"),!1):n.has(g.id)?(log$k.trace("not autodialing %p because they are already being dialed"),!1):this.queue.hasJob(g.id)?(log$k.trace("not autodialing %p because they are already being autodialed"),!1):!0]}),a=o.sort(()=>Math.random()>.5?1:-1),l=new PeerMap;for(const g of a)l.has(g.id)||l.set(g.id,[...g.tags.values()].reduce((b,x)=>b+x.value,0));const u=a.sort((g,b)=>{const x=l.get(g.id)??0,E=l.get(b.id)??0;return x>E?-1:x{const b=g.metadata.get(LAST_DIAL_FAILURE_KEY);if(b==null)return!0;const x=parseInt(toString$5(b));return isNaN(x)?!0:Date.now()-x>this.autoDialPeerRetryThresholdMs});log$k("selected %d/%d peers to dial",u.length,o.length);for(const g of u)this.queue.add(async()=>{const b=this.connectionManager.getConnectionsMap().size;if(b>=this.minConnections){log$k("got enough connections now %d/%d",b,this.minConnections),this.queue.clear();return}log$k("connecting to a peerStore stored peer %p",g.id),await this.connectionManager.openConnection(g.id,{priority:this.autoDialPriority})},{peerId:g.id}).catch(b=>{log$k.error("could not connect to peerStore stored peer",b)});this.running=!1,this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(g=>{log$k.error("error while autodialing",g)})},this.autoDialIntervalMs))}}const log$j=logger("libp2p:connection-manager:connection-pruner"),defaultOptions$2={maxConnections:MAX_CONNECTIONS,allow:[]};class ConnectionPruner{constructor(t,r={}){Ke(this,"maxConnections");Ke(this,"connectionManager");Ke(this,"peerStore");Ke(this,"allow");Ke(this,"events");this.maxConnections=r.maxConnections??defaultOptions$2.maxConnections,this.allow=r.allow??defaultOptions$2.allow,this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,t.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{log$j.error(n)})})}async maybePruneConnections(){const t=this.connectionManager.getConnections(),r=t.length,n=Math.max(r-this.maxConnections,0);if(log$j("checking max connections limit %d/%d",r,this.maxConnections),r<=this.maxConnections)return;log$j("max connections limit exceeded %d/%d, pruning %d connection(s)",r,this.maxConnections,n);const o=new PeerMap;for(const c of t){const u=c.remotePeer;if(!o.has(u)){o.set(u,0);try{const g=await this.peerStore.get(u);o.set(u,[...g.tags.values()].reduce((b,x)=>b+x.value,0))}catch(g){g.code!=="ERR_NOT_FOUND"&&log$j.error("error loading peer tags",g)}}}const a=t.sort((c,u)=>{const g=o.get(c.remotePeer)??0,b=o.get(u.remotePeer)??0;if(g>b)return 1;if(gE?-1:0}),l=[];for(const c of a)if(log$j("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(g=>c.remoteAddr.toString().startsWith(g.toString()))||l.push(c),l.length===n)break;await Promise.all(l.map(async c=>{try{await c.close()}catch(u){log$j.error(u)}})),this.events.safeDispatchEvent("connection:prune",{detail:l})}}function anySignal(e){const t=new globalThis.AbortController;function r(){t.abort();for(const a of e)a?.removeEventListener!=null&&a.removeEventListener("abort",r)}for(const a of e){if(a?.aborted===!0){r();break}a?.addEventListener!=null&&a.addEventListener("abort",r)}function n(){for(const a of e)a?.removeEventListener!=null&&a.removeEventListener("abort",r)}const o=t.signal;return o.clear=n,o}const log$i=logger("libp2p:connection-manager:utils");async function resolveMultiaddrs(e,t){if(!e.protoNames().includes("dnsaddr"))return[e];const n=await resolveRecord(e,t),l=(await Promise.all(n.map(async c=>resolveMultiaddrs(c,t)))).flat().reduce((c,u)=>(c.find(g=>g.equals(u))==null&&c.push(u),c),[]);return log$i("resolved %s to",e,l.map(c=>c.toString())),l}async function resolveRecord(e,t){try{return e=multiaddr(e.toString()),await e.resolve(t)}catch(r){return log$i.error(`multiaddr ${e.toString()} could not be resolved`,r),[]}}function combineSignals(...e){const t=[];for(const n of e)if(n!=null){try{events$1.exports.setMaxListeners?.(1/0,n)}catch{}t.push(n)}const r=anySignal(t);try{events$1.exports.setMaxListeners?.(1/0,r)}catch{}return r}const log$h=logger("libp2p:connection-manager:dial-queue"),defaultOptions$1={addressSorter:defaultAddressSort,maxParallelDials:MAX_PARALLEL_DIALS,maxPeerAddrsToDial:MAX_PEER_ADDRS_TO_DIAL,maxParallelDialsPerPeer:MAX_PARALLEL_DIALS_PER_PEER,dialTimeout:DIAL_TIMEOUT,resolvers:{dnsaddr:dnsaddrResolver}};class DialQueue{constructor(t,r={}){Ke(this,"pendingDials");Ke(this,"queue");Ke(this,"peerId");Ke(this,"peerStore");Ke(this,"connectionGater");Ke(this,"transportManager");Ke(this,"addressSorter");Ke(this,"maxPeerAddrsToDial");Ke(this,"maxParallelDialsPerPeer");Ke(this,"dialTimeout");Ke(this,"inProgressDialCount");Ke(this,"pendingDialCount");Ke(this,"shutDownController");this.addressSorter=r.addressSorter??defaultOptions$1.addressSorter,this.maxPeerAddrsToDial=r.maxPeerAddrsToDial??defaultOptions$1.maxPeerAddrsToDial,this.maxParallelDialsPerPeer=r.maxParallelDialsPerPeer??defaultOptions$1.maxParallelDialsPerPeer,this.dialTimeout=r.dialTimeout??defaultOptions$1.dialTimeout,this.peerId=t.peerId,this.peerStore=t.peerStore,this.connectionGater=t.connectionGater,this.transportManager=t.transportManager,this.shutDownController=new AbortController;try{events$1.exports.setMaxListeners?.(1/0,this.shutDownController.signal)}catch{}this.pendingDialCount=t.metrics?.registerMetric("libp2p_dialler_pending_dials"),this.inProgressDialCount=t.metrics?.registerMetric("libp2p_dialler_in_progress_dials"),this.pendingDials=[];for(const[n,o]of Object.entries(r.resolvers??{}))resolvers.set(n,o);this.queue=new PQueue({concurrency:r.maxParallelDials??defaultOptions$1.maxParallelDials}),this.queue.on("add",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("active",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("completed",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("error",n=>{log$h.error("error in dial queue",n),this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("empty",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("idle",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)})}stop(){this.shutDownController.abort()}async dial(t,r={}){const{peerId:n,multiaddrs:o}=getPeerAddress(t),a=o.map(b=>({multiaddr:b,isCertified:!1})),l=this.createDialAbortControllers(r.signal);let c;try{c=await this.calculateMultiaddrs(n,a,{...r,signal:l})}catch(b){throw l.clear(),b}const u=this.pendingDials.find(b=>!!(b.peerId!=null&&n!=null&&b.peerId.equals(n)||c.map(({multiaddr:x})=>x.toString()).join()===b.multiaddrs.map(x=>x.toString()).join()));if(u!=null)return log$h("joining existing dial target for %p",n),l.clear(),u.promise;log$h("creating dial target for",c.map(({multiaddr:b})=>b.toString()));const g={id:randomId(),status:"queued",peerId:n,multiaddrs:c.map(({multiaddr:b})=>b)};return g.promise=this.performDial(g,{...r,signal:l}).finally(()=>{this.pendingDials=this.pendingDials.filter(b=>b.id!==g.id),l.clear()}).catch(async b=>{if(log$h.error("dial failed to %s",g.multiaddrs.map(x=>x.toString()).join(", "),b),n!=null)try{await this.peerStore.patch(n,{metadata:{[LAST_DIAL_FAILURE_KEY]:fromString$1(Date.now().toString())}})}catch(x){log$h.error("could not update last dial failure key for %p",n,x)}throw l.aborted?new CodeError(b.message,codes.ERR_TIMEOUT):b}),this.pendingDials.push(g),g.promise}createDialAbortControllers(t){const r=anySignal([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,t]);try{events$1.exports.setMaxListeners?.(1/0,r)}catch{}return r}async calculateMultiaddrs(t,r=[],n={}){if(t!=null){if(this.peerId.equals(t))throw new CodeError("Tried to dial self",codes.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(t)===!0)throw new CodeError("The dial request is blocked by gater.allowDialPeer",codes.ERR_PEER_DIAL_INTERCEPTED);if(r.length===0){log$h("loading multiaddrs for %p",t);try{const b=await this.peerStore.get(t);r.push(...b.addresses),log$h("loaded multiaddrs for %p",t,r.map(({multiaddr:x})=>x.toString()))}catch(b){if(b.code!==codes.ERR_NOT_FOUND)throw b}}}const o=(await Promise.all(r.map(async b=>{const x=await resolveMultiaddrs(b.multiaddr,n);return x.length===1&&x[0].equals(b.multiaddr)?b:x.map(E=>({multiaddr:E,isCertified:!1}))}))).flat(),a=o.filter(b=>{if(this.transportManager.transportForMultiaddr(b.multiaddr)==null)return!1;const x=b.multiaddr.getPeerId();return t!=null&&x!=null?t.equals(x):!0}),l=new Map;for(const b of a){const x=b.multiaddr.toString(),E=l.get(x);if(E!=null){E.isCertified=E.isCertified||b.isCertified||!1;continue}l.set(x,b)}let c=[...l.values()];if((c.length===0||c.length>this.maxPeerAddrsToDial)&&(log$h("addresses for %p before filtering",t??"unknown peer",o.map(({multiaddr:b})=>b.toString())),log$h("addresses for %p after filtering",t??"unknown peer",c.map(({multiaddr:b})=>b.toString()))),c.length===0)throw new CodeError("The dial request has no valid addresses",codes.ERR_NO_VALID_ADDRESSES);if(c.length>this.maxPeerAddrsToDial)throw new CodeError("dial with more addresses than allowed",codes.ERR_TOO_MANY_ADDRESSES);if(t!=null){const b=`/p2p/${t.toString()}`;c=c.map(x=>{const E=x.multiaddr.getPeerId();return x.multiaddr.protos().pop()?.path===!0?x:E!==t.toString()?{multiaddr:x.multiaddr.encapsulate(b),isCertified:x.isCertified}:x})}const u=[];for(const b of c)this.connectionGater.denyDialMultiaddr!=null&&await this.connectionGater.denyDialMultiaddr(b.multiaddr)||u.push(b);const g=u.sort(this.addressSorter);if(g.length===0)throw new CodeError("The connection gater denied all addresses in the dial request",codes.ERR_NO_VALID_ADDRESSES);return g}async performDial(t,r={}){const n=t.multiaddrs.map(()=>new AbortController);try{const o=new PQueue({concurrency:this.maxParallelDialsPerPeer});o.on("error",l=>{log$h.error("error dialling",l)});const a=await Promise.any(t.multiaddrs.map(async(l,c)=>{const u=n[c];if(u==null)throw new CodeError("dialAction did not come with an AbortController",codes.ERR_INVALID_PARAMETERS);const g=combineSignals(u.signal,r.signal);g.addEventListener("abort",()=>{log$h("dial to %a aborted",l)});const b=pDefer();return await o.add(async()=>{if(g.aborted){log$h("dial to %a was aborted before reaching the head of the peer dial queue",l),b.reject(new AbortError$4);return}await this.queue.add(async()=>{try{if(g.aborted){log$h("dial to %a was aborted before reaching the head of the dial queue",l),b.reject(new AbortError$4);return}t.status="active";const x=await this.transportManager.dial(l,{...r,signal:g});if(u.signal.aborted){log$h("multiple dials succeeded, closing superfluous connection"),x.close().catch(E=>{log$h.error("error closing superfluous connection",E)}),b.reject(new AbortError$4);return}n[c]=void 0,n.forEach(E=>{E!==void 0&&E.abort()}),log$h("dial to %a succeeded",l),b.resolve(x)}catch(x){log$h.error("error during dial of %a",l,x),b.reject(x)}},{...r,signal:g}).catch(x=>{b.reject(x)})},{signal:g}).catch(x=>{b.reject(x)}).finally(()=>{g.clear()}),b.promise}));if(a==null)throw new CodeError("successful dial led to empty object returned from peer dial queue",codes.ERR_TRANSPORT_DIAL_FAILED);return t.status="success",a}catch(o){throw t.status="error",t.multiaddrs.length===1&&o.name==="AggregateError"?o.errors[0]:o}}}function randomId(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}const log$g=logger("libp2p:connection-manager"),DEFAULT_DIAL_PRIORITY=50,defaultOptions={minConnections:MIN_CONNECTIONS,maxConnections:MAX_CONNECTIONS,inboundConnectionThreshold:INBOUND_CONNECTION_THRESHOLD,maxIncomingPendingConnections:MAX_INCOMING_PENDING_CONNECTIONS,autoDialConcurrency:AUTO_DIAL_CONCURRENCY,autoDialPriority:AUTO_DIAL_PRIORITY,autoDialMaxQueueLength:AUTO_DIAL_MAX_QUEUE_LENGTH};class DefaultConnectionManager{constructor(t,r={}){Ke(this,"started");Ke(this,"connections");Ke(this,"allow");Ke(this,"deny");Ke(this,"maxIncomingPendingConnections");Ke(this,"incomingPendingConnections");Ke(this,"maxConnections");Ke(this,"dialQueue");Ke(this,"autoDial");Ke(this,"connectionPruner");Ke(this,"inboundConnectionRateLimiter");Ke(this,"peerStore");Ke(this,"metrics");Ke(this,"events");this.maxConnections=r.maxConnections??defaultOptions.maxConnections;const n=r.minConnections??defaultOptions.minConnections;if(this.maxConnectionsmultiaddr(o)),this.deny=(r.deny??[]).map(o=>multiaddr(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=r.maxIncomingPendingConnections??defaultOptions.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new rateLimiterFlexible.RateLimiterMemory({points:r.inboundConnectionThreshold??defaultOptions.inboundConnectionThreshold,duration:1}),this.autoDial=new AutoDial({connectionManager:this,peerStore:t.peerStore,events:t.events},{minConnections:n,autoDialConcurrency:r.autoDialConcurrency??defaultOptions.autoDialConcurrency,autoDialPriority:r.autoDialPriority??defaultOptions.autoDialPriority,maxQueueLength:r.autoDialMaxQueueLength??defaultOptions.autoDialMaxQueueLength}),this.connectionPruner=new ConnectionPruner({connectionManager:this,peerStore:t.peerStore,events:t.events},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new DialQueue({peerId:t.peerId,metrics:t.metrics,peerStore:t.peerStore,transportManager:t.transportManager,connectionGater:t.connectionGater},{addressSorter:r.addressSorter??defaultAddressSort,maxParallelDials:r.maxParallelDials??MAX_PARALLEL_DIALS,maxPeerAddrsToDial:r.maxPeerAddrsToDial??MAX_PEER_ADDRS_TO_DIAL,maxParallelDialsPerPeer:r.maxParallelDialsPerPeer??MAX_PARALLEL_DIALS_PER_PEER,dialTimeout:r.dialTimeout??DIAL_TIMEOUT,resolvers:r.resolvers??{dnsaddr:dnsaddrResolver}})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const t={inbound:0,outbound:0};for(const r of this.connections.values())for(const n of r)n.direction==="inbound"?t.inbound++:t.outbound++;return t}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const t={};for(const r of this.connections.values())for(const n of r)for(const o of n.streams){const a=`${o.direction} ${o.protocol??"unnegotiated"}`;t[a]=(t[a]??0)+1}return t}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const t={};for(const n of this.connections.values())for(const o of n){const a={};for(const l of o.streams){const c=`${l.direction} ${l.protocol??"unnegotiated"}`;a[c]=(a[c]??0)+1}for(const[l,c]of Object.entries(a))t[l]=t[l]??[],t[l].push(c)}const r={};for(let[n,o]of Object.entries(t)){o=o.sort((l,c)=>l-c);const a=Math.floor(o.length*.9);r[n]=o[a]}return r}}),this.autoDial.start(),this.started=!0,log$g("started")}async afterStart(){Promise.resolve().then(async()=>{const t=await this.peerStore.all({filters:[r=>r.tags.has(KEEP_ALIVE)]});await Promise.all(t.map(async r=>{await this.openConnection(r.id).catch(n=>{log$g.error(n)})}))}).catch(t=>{log$g.error(t)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();const t=[];for(const r of this.connections.values())for(const n of r)t.push((async()=>{try{await n.close()}catch(o){log$g.error(o)}})());log$g("closing %d connections",t.length),await Promise.all(t),this.connections.clear(),log$g("stopped")}onConnect(t){this._onConnect(t).catch(r=>{log$g.error(r)})}async _onConnect(t){const{detail:r}=t;if(!this.started){await r.close();return}const n=r.remotePeer,o=this.connections.get(n);let a=!1;o!=null?o.push(r):(a=!0,this.connections.set(n,[r])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),a&&this.events.safeDispatchEvent("peer:connect",{detail:r.remotePeer})}onDisconnect(t){const{detail:r}=t;if(!this.started)return;const n=r.remotePeer;let o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(a=>a.id!==r.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(t){if(t!=null)return this.connections.get(t)??[];let r=[];for(const n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}async openConnection(t,r={}){if(!this.isStarted())throw new CodeError("Not started",codes.ERR_NODE_NOT_STARTED);r.signal?.throwIfAborted();const{peerId:n}=getPeerAddress(t);if(n!=null&&r.force!==!0){log$g("dial %p",n);const c=this.getConnections(n);if(c.length>0)return log$g("had an existing connection to %p",n),c[0]}const o=await this.dialQueue.dial(t,{...r,priority:r.priority??DEFAULT_DIAL_PRIORITY});let a=this.connections.get(o.remotePeer);a==null&&(a=[],this.connections.set(o.remotePeer,a));let l=!1;for(const c of a)c.id===o.id&&(l=!0);return l||a.push(o),o}async closeConnections(t,r={}){const n=this.connections.get(t)??[];await Promise.all(n.map(async o=>{try{await o.close(r)}catch(a){o.abort(a)}}))}async acceptIncomingConnection(t){if(this.deny.some(o=>t.remoteAddr.toString().startsWith(o.toString())))return log$g("connection from %a refused - connection remote address was in deny list",t.remoteAddr),!1;if(this.allow.some(o=>t.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return log$g("connection from %a refused - incomingPendingConnections exceeded by host",t.remoteAddr),!1;if(t.remoteAddr.isThinWaistAddress()){const o=t.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return log$g("connection from %a refused - inboundConnectionThreshold exceeded by host %s",t.remoteAddr,o),!1}}return this.getConnections().length(await t.merge(r.id,{multiaddrs:r.multiaddrs}),r))}function uniquePeers(e){const t=new Set;return filter(e,r=>t.has(r.id.toString())?!1:(t.add(r.id.toString()),!0))}async function*requirePeers(e,t=1){let r=0;for await(const n of e)r++,yield n;if(rn.findProviders(t,r))),n=>storeAddresses(n,this.components.peerStore),n=>uniquePeers(n),n=>requirePeers(n))}async provide(t,r={}){if(this.routers.length===0)throw new CodeError("No content routers available",codes.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(t,r)}))}async put(t,r,n){if(!this.isStarted())throw new CodeError(messages$1.NOT_STARTED_YET,codes.DHT_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(t,r,n)}))}async get(t,r){if(!this.isStarted())throw new CodeError(messages$1.NOT_STARTED_YET,codes.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(t,r)))}}function isAsyncIterable(e){return e[Symbol.asyncIterator]!=null}function first(e){if(isAsyncIterable(e))return(async()=>{for await(const t of e)return t})();for(const t of e)return t}const log$f=logger("libp2p:peer-routing");class DefaultPeerRouting{constructor(t,r){Ke(this,"components");Ke(this,"routers");this.components=t,this.routers=r.routers??[]}async findPeer(t,r){if(this.routers.length===0)throw new CodeError("No peer routers available",codes.ERR_NO_ROUTERS_AVAILABLE);if(t.toString()===this.components.peerId.toString())throw new CodeError("Should not try to find self",codes.ERR_FIND_SELF);const n=await pipe(merge$1(...this.routers.map(o=>async function*(){try{yield await o.findPeer(t,r)}catch(a){log$f.error(a)}}())),o=>filter(o,Boolean),o=>storeAddresses(o,this.components.peerStore),async o=>first(o));if(n!=null)return n;throw new CodeError(messages$1.NOT_FOUND,codes.ERR_NOT_FOUND)}async*getClosestPeers(t,r){if(this.routers.length===0)throw new CodeError("No peer routers available",codes.ERR_NO_ROUTERS_AVAILABLE);yield*pipe(merge$1(...this.routers.map(n=>n.getClosestPeers(t,r))),n=>storeAddresses(n,this.components.peerStore),n=>uniquePeers(n),n=>requirePeers(n))}}const log$e=logger("libp2p:registrar"),DEFAULT_MAX_INBOUND_STREAMS=32,DEFAULT_MAX_OUTBOUND_STREAMS=64;class DefaultRegistrar{constructor(t){Ke(this,"topologies");Ke(this,"handlers");Ke(this,"components");this.topologies=new Map,this.handlers=new Map,this.components=t,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onConnect=this._onConnect.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:connect",this._onConnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(t){const r=this.handlers.get(t);if(r==null)throw new CodeError(`No handler registered for protocol ${t}`,codes.ERR_NO_HANDLER_FOR_PROTOCOL);return r}getTopologies(t){const r=this.topologies.get(t);return r==null?[]:[...r.values()]}async handle(t,r,n){if(this.handlers.has(t))throw new CodeError(`Handler already registered for protocol ${t}`,codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);const o=mergeOptions.bind({ignoreUndefined:!0})({maxInboundStreams:DEFAULT_MAX_INBOUND_STREAMS,maxOutboundStreams:DEFAULT_MAX_OUTBOUND_STREAMS},n);this.handlers.set(t,{handler:r,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[t]})}async unhandle(t){(Array.isArray(t)?t:[t]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(t,r){if(r==null)throw new CodeError("invalid topology",codes.ERR_INVALID_PARAMETERS);const n=`${(Math.random()*1e9).toString(36)}${Date.now()}`;let o=this.topologies.get(t);return o==null&&(o=new Map,this.topologies.set(t,o)),o.set(n,r),n}unregister(t){for(const[r,n]of this.topologies.entries())n.has(t)&&(n.delete(t),n.size===0&&this.topologies.delete(r))}_onDisconnect(t){const r=t.detail;this.components.peerStore.get(r).then(n=>{for(const o of n.protocols){const a=this.topologies.get(o);if(a!=null)for(const l of a.values())l.onDisconnect?.(r)}}).catch(n=>{n.code!==codes.ERR_NOT_FOUND&&log$e.error("could not inform topologies of disconnecting peer %p",r,n)})}_onConnect(t){const r=t.detail;this.components.peerStore.get(r).then(n=>{const o=this.components.connectionManager.getConnections(n.id)[0];if(o==null){log$e("peer %p connected but the connection manager did not have a connection",n);return}for(const a of n.protocols){const l=this.topologies.get(a);if(l!=null)for(const c of l.values())c.onConnect?.(r,o)}}).catch(n=>{n.code!==codes.ERR_NOT_FOUND&&log$e.error("could not inform topologies of connecting peer %p",r,n)})}_onPeerUpdate(t){const{peer:r,previous:n}=t.detail,o=(n?.protocols??[]).filter(l=>!r.protocols.includes(l)),a=r.protocols.filter(l=>!(n?.protocols??[]).includes(l));for(const l of o){const c=this.topologies.get(l);if(c!=null)for(const u of c.values())u.onDisconnect?.(r.id)}for(const l of a){const c=this.topologies.get(l);if(c!=null)for(const u of c.values()){const g=this.components.connectionManager.getConnections(r.id)[0];g!=null&&u.onConnect?.(r.id,g)}}}}class TrackedMap extends Map{constructor(r){super();Ke(this,"metric");const{name:n,metrics:o}=r;this.metric=o.registerMetric(n),this.updateComponentMetric()}set(r,n){return super.set(r,n),this.updateComponentMetric(),this}delete(r){const n=super.delete(r);return this.updateComponentMetric(),n}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function trackedMap(e){const{name:t,metrics:r}=e;let n;return r!=null?n=new TrackedMap({name:t,metrics:r}):n=new Map,n}const log$d=logger("libp2p:transports");class DefaultTransportManager{constructor(t,r={}){Ke(this,"components");Ke(this,"transports");Ke(this,"listeners");Ke(this,"faultTolerance");Ke(this,"started");this.components=t,this.started=!1,this.transports=new Map,this.listeners=trackedMap({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??FaultTolerance.FATAL_ALL}add(t){const r=t[Symbol.toStringTag];if(r==null)throw new CodeError("Transport must have a valid tag",codes.ERR_INVALID_KEY);if(this.transports.has(r))throw new CodeError(`There is already a transport with the tag ${r}`,codes.ERR_DUPLICATE_TRANSPORT);log$d("adding transport %s",r),this.transports.set(r,t),this.listeners.has(r)||this.listeners.set(r,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const t=this.components.addressManager.getListenAddrs();await this.listen(t)}async stop(){const t=[];for(const[r,n]of this.listeners)for(log$d("closing listeners for %s",r);n.length>0;){const o=n.pop();o!=null&&t.push(o.close())}await Promise.all(t),log$d("all listeners closed");for(const r of this.listeners.keys())this.listeners.set(r,[]);this.started=!1}async dial(t,r){const n=this.transportForMultiaddr(t);if(n==null)throw new CodeError(`No transport available for address ${String(t)}`,codes.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(t,{...r,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=codes.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let t=[];for(const r of this.listeners.values())for(const n of r)t=[...t,...n.getAddrs()];return t}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(t){for(const r of this.transports.values())if(r.filter([t]).length>0)return r}async listen(t){if(!this.isStarted())throw new CodeError("Not started",codes.ERR_NODE_NOT_STARTED);if(t==null||t.length===0){log$d("no addresses were provided for listening, this node is dial only");return}const r=[];for(const[n,o]of this.transports.entries()){const a=o.filter(t),l=[];for(const g of a){log$d("creating listener for %s on %a",n,g);const b=o.createListener({upgrader:this.components.upgrader});let x=this.listeners.get(n)??[];x==null&&(x=[],this.listeners.set(n,x)),x.push(b),b.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:b})}),b.addEventListener("close",()=>{const E=x.findIndex(I=>I===b);x.splice(E,1),this.components.events.safeDispatchEvent("transport:close",{detail:b})}),l.push(b.listen(g))}if(l.length===0){r.push(n);continue}if((await Promise.allSettled(l)).find(g=>g.status==="fulfilled")==null&&this.faultTolerance!==FaultTolerance.NO_FATAL)throw new CodeError(`Transport (${n}) could not listen on any available address`,codes.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){const n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===FaultTolerance.FATAL_ALL)throw new CodeError(n,codes.ERR_NO_VALID_ADDRESSES);log$d(`libp2p in dial mode only: ${n}`)}}async remove(t){log$d("removing %s",t);for(const r of this.listeners.get(t)??[])await r.close();this.transports.delete(t),this.listeners.delete(t)}async removeAll(){const t=[];for(const r of this.transports.keys())t.push(this.remove(r));await Promise.all(t)}}const PROTOCOL_ID="/multistream/1.0.0",MAX_PROTOCOL_LENGTH=1024;function reader(e){const t=async function*(){let r=yield,n=new Uint8ArrayList;for await(const o of e){if(r==null){n.append(o),r=yield n,n=new Uint8ArrayList;continue}for(n.append(o);n.length>=r;){const a=n.sublist(0,r);if(n.consume(r),r=yield a,r==null){n.length>0&&(r=yield n,n=new Uint8ArrayList);break}}}if(r!=null)throw Object.assign(new Error(`stream ended before ${r} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return t.next(),t}function handshake(e){const t=pushable(),r=reader(e.source),n=pDefer();let o;const a=e.sink(async function*(){yield*t,yield*await n.promise}());return a.catch(c=>{o=c}),{reader:r,writer:t,stream:{sink:async c=>{if(o!=null){await Promise.reject(o);return}n.resolve(c),await a},source:r},rest:()=>t.end(),write:t.push,read:async()=>{const c=await r.next();if(c.value!=null)return c.value}}}const log$c=logger("libp2p:mss"),NewLine=fromString$1(` `);function encode$1(e){const t=new Uint8ArrayList(e,NewLine);return encode$c.single(t)}function write(e,t,r={}){const n=encode$1(t);r.writeBytes===!0?e.push(n.subarray()):e.push(n)}function writeAll(e,t,r={}){const n=new Uint8ArrayList;for(const o of t)n.append(encode$1(o));r.writeBytes===!0?e.push(n.subarray()):e.push(n)}async function read(e,t){let r=1;const n={[Symbol.asyncIterator]:()=>n,next:async()=>e.next(r)};let o=n;t?.signal!=null&&(o=abortableSource(n,t.signal));const a=c=>{r=c},l=await pipe(o,c=>decode$a(c,{onLength:a,maxDataLength:MAX_PROTOCOL_LENGTH}),async c=>first(c));if(l==null||l.length===0)throw new CodeError("no buffer returned","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(l.get(l.byteLength-1)!==NewLine[0])throw log$c.error("Invalid mss message - missing newline - %s",l.subarray()),new CodeError("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return l.sublist(0,-1)}async function readString(e,t){const r=await read(e,t);return toString$5(r.subarray())}const log$b=logger("libp2p:mss:select");async function select(e,t,r={}){t=Array.isArray(t)?[...t]:[t];const{reader:n,writer:o,rest:a,stream:l}=handshake(e),c=t.shift();if(c==null)throw new Error("At least one protocol must be specified");log$b.trace('select: write ["%s", "%s"]',PROTOCOL_ID,c);const u=fromString$1(PROTOCOL_ID),g=fromString$1(c);writeAll(o,[u,g],r);let b=await readString(n,r);if(log$b.trace('select: read "%s"',b),b===PROTOCOL_ID&&(b=await readString(n,r),log$b.trace('select: read "%s"',b)),b===c)return a(),{stream:l,protocol:c};for(const x of t){log$b.trace('select: write "%s"',x),write(o,fromString$1(x),r);const E=await readString(n,r);if(log$b.trace('select: read "%s" for "%s"',E,x),E===x)return a(),{stream:l,protocol:x}}throw a(),new CodeError("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}const log$a=logger("libp2p:mss:handle");async function handle(e,t,r){t=Array.isArray(t)?t:[t];const{writer:n,reader:o,rest:a,stream:l}=handshake(e);for(;;){const c=await readString(o,r);if(log$a.trace('read "%s"',c),c===PROTOCOL_ID){log$a.trace('respond with "%s" for "%s"',PROTOCOL_ID,c),write(n,fromString$1(PROTOCOL_ID),r);continue}if(t.includes(c))return write(n,fromString$1(c),r),log$a.trace('respond with "%s" for "%s"',c,c),a(),{stream:l,protocol:c};if(c==="ls"){write(n,new Uint8ArrayList(...t.map(u=>encode$1(fromString$1(u)))),r),log$a.trace('respond with "%s" for %s',t,c);continue}write(n,fromString$1("na"),r),log$a('respond with "na" for "%s"',c)}}const symbol=Symbol.for("@libp2p/connection"),log$9=logger("libp2p:connection"),CLOSE_TIMEOUT=500;var ic,sc;class ConnectionImpl{constructor(t){Ke(this,"id");Ke(this,"remoteAddr");Ke(this,"remotePeer");Ke(this,"direction");Ke(this,"timeline");Ke(this,"multiplexer");Ke(this,"encryption");Ke(this,"status");Ke(this,"transient");Ke(this,"tags");Ke(this,"_newStream");Ke(this,"_close");Ke(this,"_abort");Ke(this,"_getStreams");Ke(this,ic,"Connection");Ke(this,sc,!0);const{remoteAddr:r,remotePeer:n,newStream:o,close:a,abort:l,getStreams:c}=t;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=r,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.transient=t.transient??!1,this._newStream=o,this._close=a,this._abort=l,this._getStreams=c,this.tags=[]}get streams(){return this._getStreams()}async newStream(t,r){if(this.status==="closing")throw new CodeError("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new CodeError("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(t)||(t=[t]),this.transient&&r?.runOnTransientConnection!==!0)throw new CodeError("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");const n=await this._newStream(t,r);return n.direction="outbound",n}async close(t={}){if(!(this.status==="closed"||this.status==="closing")){log$9("closing connection to %a",this.remoteAddr),this.status="closing",t.signal=t?.signal??AbortSignal.timeout(CLOSE_TIMEOUT);try{events$1.exports.setMaxListeners?.(1/0,t.signal)}catch{}try{await Promise.all(this.streams.map(async r=>r.close(t))),await this._close(t),this.timeline.close=Date.now(),this.status="closed"}catch(r){log$9.error("error encountered during graceful close of connection to %a",this.remoteAddr,r),this.abort(r)}}}abort(t){log$9.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this.streams.forEach(r=>{r.abort(t)}),log$9.error("all streams aborted",this.streams.length),this._abort(t),this.timeline.close=Date.now(),this.status="closed"}}ic=Symbol.toStringTag,sc=symbol;function createConnection(e){return new ConnectionImpl(e)}const log$8=logger("libp2p:upgrader");function findIncomingStreamLimit(e,t){try{const{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(r){if(r.code!==codes.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return DEFAULT_MAX_INBOUND_STREAMS}function findOutgoingStreamLimit(e,t,r={}){try{const{options:n}=t.getHandler(e);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==codes.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return r.maxOutboundStreams??DEFAULT_MAX_OUTBOUND_STREAMS}function countStreams(e,t,r){let n=0;return r.streams.forEach(o=>{o.direction===t&&o.protocol===e&&n++}),n}class DefaultUpgrader{constructor(t,r){Ke(this,"components");Ke(this,"connectionEncryption");Ke(this,"muxers");Ke(this,"inboundUpgradeTimeout");Ke(this,"events");this.components=t,this.connectionEncryption=new Map,r.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,r.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=r.inboundUpgradeTimeout??INBOUND_UPGRADE_TIMEOUT,this.events=t.events}async shouldBlockConnection(t,r,n){const o=this.components.connectionGater[n];if(o!==void 0&&await o(t,r))throw new CodeError(`The multiaddr connection is blocked by gater.${n}`,codes.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(t,r){if(!await this.components.connectionManager.acceptIncomingConnection(t))throw new CodeError("connection denied",codes.ERR_CONNECTION_DENIED);let o,a,l,c,u;const g=AbortSignal.timeout(this.inboundUpgradeTimeout),b=()=>{t.abort(new CodeError("inbound upgrade timeout",codes.ERR_TIMEOUT))};g.addEventListener("abort",b,{once:!0});try{events$1.exports.setMaxListeners?.(1/0,g)}catch{}try{if(await this.components.connectionGater.denyInboundConnection?.(t)===!0)throw new CodeError("The multiaddr connection is blocked by gater.acceptConnection",codes.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(t),log$8("starting the inbound connection upgrade");let x=t;if(r?.skipProtection!==!0){const E=this.components.connectionProtector;E!=null&&(log$8("protecting the inbound connection"),x=await E.protect(t))}try{if(o=x,r?.skipEncryption!==!0){({conn:o,remotePeer:a,protocol:u}=await this._encryptInbound(x));const E={...x,...o};await this.shouldBlockConnection(a,E,"denyInboundEncryptedConnection")}else{const E=t.remoteAddr.getPeerId();if(E==null)throw new CodeError("inbound connection that skipped encryption must have a peer id",codes.ERR_INVALID_MULTIADDR);const I=peerIdFromString(E);u="native",a=I}if(l=o,r?.muxerFactory!=null)c=r.muxerFactory;else if(this.muxers.size>0){const E=await this._multiplexInbound({...x,...o},this.muxers);c=E.muxerFactory,l=E.stream}}catch(E){throw log$8.error("Failed to upgrade inbound connection",E),E}return await this.shouldBlockConnection(a,t,"denyInboundUpgradedConnection"),log$8("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:u,direction:"inbound",maConn:t,upgradedConn:l,muxerFactory:c,remotePeer:a,transient:r?.transient})}finally{g.removeEventListener("abort",b),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,r){const n=t.remoteAddr.getPeerId();let o;n!=null&&(o=peerIdFromString(n),await this.shouldBlockConnection(o,t,"denyOutboundConnection"));let a,l,c,u,g;this.components.metrics?.trackMultiaddrConnection(t),log$8("Starting the outbound connection upgrade");let b=t;if(r?.skipProtection!==!0){const x=this.components.connectionProtector;x!=null&&(b=await x.protect(t))}try{if(a=b,r?.skipEncryption!==!0){({conn:a,remotePeer:l,protocol:u}=await this._encryptOutbound(b,o));const x={...b,...a};await this.shouldBlockConnection(l,x,"denyOutboundEncryptedConnection")}else{if(o==null)throw new CodeError("Encryption was skipped but no peer id was passed",codes.ERR_INVALID_PEER);u="native",l=o}if(c=a,r?.muxerFactory!=null)g=r.muxerFactory;else if(this.muxers.size>0){const x=await this._multiplexOutbound({...b,...a},this.muxers);g=x.muxerFactory,c=x.stream}}catch(x){throw log$8.error("Failed to upgrade outbound connection",x),await t.close(x),x}return await this.shouldBlockConnection(l,t,"denyOutboundUpgradedConnection"),log$8("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:u,direction:"outbound",maConn:t,upgradedConn:c,muxerFactory:g,remotePeer:l,transient:r?.transient})}_createConnection(t){const{cryptoProtocol:r,direction:n,maConn:o,upgradedConn:a,remotePeer:l,muxerFactory:c,transient:u}=t;let g,b,x;c!=null&&(g=c.createStreamMuxer({direction:n,onIncomingStream:T=>{x!=null&&Promise.resolve().then(async()=>{const k=this.components.registrar.getProtocols(),{stream:O,protocol:$}=await handle(T,k);if(log$8("%s: incoming stream opened on %s",n,$),x==null)return;const D=findIncomingStreamLimit($,this.components.registrar);if(countStreams($,"inbound",x)===D){const H=new CodeError(`Too many inbound protocol streams for protocol "${$}" - limit ${D}`,codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw T.abort(H),H}T.source=O.source,T.sink=O.sink,T.protocol=$,await this.components.peerStore.merge(l,{protocols:[$]}),this.components.metrics?.trackProtocolStream(T,x),this._onStream({connection:x,stream:T,protocol:$})}).catch(async k=>{log$8.error(k),T.timeline.close==null&&await T.close()})}}),b=async(T,k={})=>{if(g==null)throw new CodeError("Stream is not multiplexed",codes.ERR_MUXER_UNAVAILABLE);log$8("%s: starting new stream on %s",n,T);const O=await g.newStream();try{if(k.signal==null){log$8("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",T),k.signal=AbortSignal.timeout(3e4);try{events$1.exports.setMaxListeners?.(1/0,k.signal)}catch{}}const{stream:$,protocol:D}=await select(O,T,k),N=findOutgoingStreamLimit(D,this.components.registrar,k);if(countStreams(D,"outbound",x)>=N){const se=new CodeError(`Too many outbound protocol streams for protocol "${D}" - limit ${N}`,codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw O.abort(se),se}return await this.components.peerStore.merge(l,{protocols:[D]}),O.source=$.source,O.sink=$.sink,O.protocol=D,this.components.metrics?.trackProtocolStream(O,x),O}catch($){throw log$8.error("could not create new stream",$),O.timeline.close==null&&O.abort($),$.code!=null?$:new CodeError(String($),codes.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([g.sink(a.source),a.sink(g.source)]).catch(T=>{log$8.error(T)}));const E=o.timeline;o.timeline=new Proxy(E,{set:(...T)=>(x!=null&&T[1]==="close"&&T[2]!=null&&E.close==null&&(async()=>{try{x.status==="open"&&await x.close()}catch(k){log$8.error(k)}finally{this.events.safeDispatchEvent("connection:close",{detail:x})}})().catch(k=>{log$8.error(k)}),Reflect.set(...T))}),o.timeline.upgraded=Date.now();const I=()=>{throw new CodeError("connection is not multiplexed",codes.ERR_CONNECTION_NOT_MULTIPLEXED)};return x=createConnection({remoteAddr:o.remoteAddr,remotePeer:l,status:"open",direction:n,timeline:o.timeline,multiplexer:g?.protocol,encryption:r,transient:u,newStream:b??I,getStreams:()=>g!=null?g.streams:[],close:async T=>{await o.close(T),g!=null&&await g.close(T)},abort:T=>{o.abort(T),g?.abort(T)}}),this.events.safeDispatchEvent("connection:open",{detail:x}),x}_onStream(t){const{connection:r,stream:n,protocol:o}=t,{handler:a,options:l}=this.components.registrar.getHandler(o);if(r.transient&&l.runOnTransientConnection!==!0)throw new CodeError("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");a({connection:r,stream:n})}async _encryptInbound(t){const r=Array.from(this.connectionEncryption.keys());log$8("handling inbound crypto protocol selection",r);try{const{stream:n,protocol:o}=await handle(t,r,{writeBytes:!0}),a=this.connectionEncryption.get(o);if(a==null)throw new Error(`no crypto module found for ${o}`);return log$8("encrypting inbound connection..."),{...await a.secureInbound(this.components.peerId,n),protocol:o}}catch(n){throw new CodeError(String(n),codes.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(t,r){const n=Array.from(this.connectionEncryption.keys());log$8("selecting outbound crypto protocol",n);try{const{stream:o,protocol:a}=await select(t,n,{writeBytes:!0}),l=this.connectionEncryption.get(a);if(l==null)throw new Error(`no crypto module found for ${a}`);return log$8("encrypting outbound connection to %p",r),{...await l.secureOutbound(this.components.peerId,o,r),protocol:a}}catch(o){throw new CodeError(String(o),codes.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(t,r){const n=Array.from(r.keys());log$8("outbound selecting muxer %s",n);try{const{stream:o,protocol:a}=await select(t,n,{writeBytes:!0});log$8("%s selected as muxer protocol",a);const l=r.get(a);return{stream:o,muxerFactory:l}}catch(o){throw log$8.error("error multiplexing outbound stream",o),new CodeError(String(o),codes.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(t,r){const n=Array.from(r.keys());log$8("inbound handling muxers %s",n);try{const{stream:o,protocol:a}=await handle(t,n,{writeBytes:!0}),l=r.get(a);return{stream:o,muxerFactory:l}}catch(o){throw log$8.error("error multiplexing inbound stream",o),new CodeError(String(o),codes.ERR_MUXER_UNAVAILABLE)}}}const log$7=logger("libp2p");var un,ts,ga;class Libp2pNode extends EventEmitter$2{constructor(r){super();_r(this,ts);Ke(this,"peerId");Ke(this,"peerStore");Ke(this,"contentRouting");Ke(this,"peerRouting");Ke(this,"keychain");Ke(this,"metrics");Ke(this,"services");Ke(this,"components");_r(this,un,void 0);const n=new EventEmitter$2,o=n.dispatchEvent.bind(n);n.dispatchEvent=g=>{const b=o(g),x=this.dispatchEvent(new CustomEvent$1(g.type,{detail:g.detail}));return b||x};try{events$1.exports.setMaxListeners?.(1/0,n)}catch{}wn(this,un,!1),this.peerId=r.peerId,this.services={};const a=this.components=defaultComponents({peerId:r.peerId,events:n,datastore:r.datastore??new MemoryDatastore,connectionGater:connectionGater(r.connectionGater)});this.peerStore=this.configureComponent("peerStore",new PersistentPeerStore(a,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...r.peerStore})),r.metrics!=null&&(this.metrics=this.configureComponent("metrics",r.metrics(this.components))),a.events.addEventListener("peer:update",g=>{if(g.detail.previous==null){const b={id:g.detail.peer.id,multiaddrs:g.detail.peer.addresses.map(x=>x.multiaddr),protocols:g.detail.peer.protocols};a.events.safeDispatchEvent("peer:discovery",{detail:b})}}),r.connectionProtector!=null&&this.configureComponent("connectionProtector",r.connectionProtector(a)),this.components.upgrader=new DefaultUpgrader(this.components,{connectionEncryption:(r.connectionEncryption??[]).map((g,b)=>this.configureComponent(`connection-encryption-${b}`,g(this.components))),muxers:(r.streamMuxers??[]).map((g,b)=>this.configureComponent(`stream-muxers-${b}`,g(this.components))),inboundUpgradeTimeout:r.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new DefaultTransportManager(this.components,r.transportManager)),this.configureComponent("connectionManager",new DefaultConnectionManager(this.components,r.connectionManager)),this.configureComponent("registrar",new DefaultRegistrar(this.components)),this.configureComponent("addressManager",new DefaultAddressManager(this.components,r.addresses));const l=DefaultKeyChain.generateOptions();this.keychain=this.configureComponent("keyChain",new DefaultKeyChain(this.components,{...l,...r.keychain}));const c=(r.peerRouters??[]).map((g,b)=>this.configureComponent(`peer-router-${b}`,g(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new DefaultPeerRouting(this.components,{routers:c}));const u=(r.contentRouters??[]).map((g,b)=>this.configureComponent(`content-router-${b}`,g(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new CompoundContentRouting(this.components,{routers:u})),(r.peerDiscovery??[]).forEach((g,b)=>{this.configureComponent(`peer-discovery-${b}`,g(this.components)).addEventListener("peer",E=>{vr(this,ts,ga).call(this,E)})}),r.transports.forEach((g,b)=>{this.components.transportManager.add(this.configureComponent(`transport-${b}`,g(this.components)))}),r.services!=null)for(const g of Object.keys(r.services)){const b=r.services[g],x=b(this.components);if(x==null){log$7.error("service factory %s returned null or undefined instance",g);continue}this.services[g]=x,this.configureComponent(g,x),x[contentRouting]!=null&&(log$7("registering service %s for content routing",g),u.push(x[contentRouting])),x[peerRouting]!=null&&(log$7("registering service %s for peer routing",g),c.push(x[peerRouting])),x[peerDiscovery]!=null&&(log$7("registering service %s for peer discovery",g),x[peerDiscovery].addEventListener("peer",E=>{vr(this,ts,ga).call(this,E)}))}}configureComponent(r,n){return n==null&&log$7.error("component %s was null or undefined",r),this.components[r]=n,n}async start(){if(Jt(this,un))return;wn(this,un,!0),log$7("libp2p is starting"),(await this.keychain.listKeys()).find(n=>n.name==="self")==null&&(log$7("importing self key into keychain"),await this.keychain.importPeer("self",this.components.peerId));try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.safeDispatchEvent("start",{detail:this}),log$7("libp2p has started")}catch(n){throw log$7.error("An error occurred starting libp2p",n),await this.stop(),n}}async stop(){!Jt(this,un)||(log$7("libp2p is stopping"),wn(this,un,!1),await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.safeDispatchEvent("stop",{detail:this}),log$7("libp2p has stopped"))}isStarted(){return Jt(this,un)}getConnections(r){return this.components.connectionManager.getConnections(r)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const r=new PeerSet;for(const n of this.components.connectionManager.getConnections())r.add(n.remotePeer);return Array.from(r)}async dial(r,n={}){return this.components.connectionManager.openConnection(r,n)}async dialProtocol(r,n,o={}){if(n==null)throw new CodeError("no protocols were provided to open a stream",codes.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(n=Array.isArray(n)?n:[n],n.length===0)throw new CodeError("no protocols were provided to open a stream",codes.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(r,o)).newStream(n,o)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(r,n={}){isMultiaddr(r)&&(r=peerIdFromString(r.getPeerId()??"")),await this.components.connectionManager.closeConnections(r,n)}async getPublicKey(r,n={}){if(log$7("getPublicKey %p",r),r.publicKey!=null)return r.publicKey;const o=await this.peerStore.get(r);if(o.id.publicKey!=null)return o.id.publicKey;const a=concat$1([fromString$1("/pk/"),r.multihash.digest]),l=await this.contentRouting.get(a,n);return unmarshalPublicKey(l),await this.peerStore.patch(r,{publicKey:l}),l}async handle(r,n,o){Array.isArray(r)||(r=[r]),await Promise.all(r.map(async a=>{await this.components.registrar.handle(a,n,o)}))}async unhandle(r){Array.isArray(r)||(r=[r]),await Promise.all(r.map(async n=>{await this.components.registrar.unhandle(n)}))}async register(r,n){return this.components.registrar.register(r,n)}unregister(r){this.components.registrar.unregister(r)}}un=new WeakMap,ts=new WeakSet,ga=function(r){const{detail:n}=r;if(n.id.toString()===this.peerId.toString()){log$7.error(new Error(codes.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(n.id,{multiaddrs:n.multiaddrs,protocols:n.protocols}).catch(o=>{log$7.error(o)})};async function createLibp2pNode(e){if(e.peerId==null){const t=e.datastore;if(t!=null)try{const r=new DefaultKeyChain({datastore:t},mergeOptions(DefaultKeyChain.generateOptions(),e.keychain));e.peerId=await r.exportPeerId("self")}catch(r){if(r.code!=="ERR_NOT_FOUND")throw r}}return e.peerId==null&&(e.peerId=await createEd25519PeerId()),new Libp2pNode(validateConfig(e))}async function createLibp2p(e){const t=await createLibp2pNode(e);return e.start!==!1&&await t.start(),t}const CIRCUIT_PROTO_CODE=290,RELAY_RENDEZVOUS_NS="/libp2p/relay",DEFAULT_RESERVATION_CONCURRENCY=1,RELAY_TAG="circuit-relay-relay";BigInt(1<<17);const RELAY_V2_HOP_CODEC="/libp2p/circuit/relay/0.2.0/hop",RELAY_V2_STOP_CODEC="/libp2p/circuit/relay/0.2.0/stop";var HopMessage;(function(e){(function(n){n.RESERVE="RESERVE",n.CONNECT="CONNECT",n.STATUS="STATUS"})(e.Type||(e.Type={}));let t;(function(n){n[n.RESERVE=0]="RESERVE",n[n.CONNECT=1]="CONNECT",n[n.STATUS=2]="STATUS"})(t||(t={})),function(n){n.codec=()=>enumeration(t)}(e.Type||(e.Type={}));let r;e.codec=()=>(r==null&&(r=message((n,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),n.type!=null&&(o.uint32(8),e.Type.codec().encode(n.type,o)),n.peer!=null&&(o.uint32(18),Peer.codec().encode(n.peer,o)),n.reservation!=null&&(o.uint32(26),Reservation.codec().encode(n.reservation,o)),n.limit!=null&&(o.uint32(34),Limit.codec().encode(n.limit,o)),n.status!=null&&(o.uint32(40),Status.codec().encode(n.status,o)),a.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{const a={},l=o==null?n.len:n.pos+o;for(;n.pos>>3){case 1:a.type=e.Type.codec().decode(n);break;case 2:a.peer=Peer.codec().decode(n,n.uint32());break;case 3:a.reservation=Reservation.codec().decode(n,n.uint32());break;case 4:a.limit=Limit.codec().decode(n,n.uint32());break;case 5:a.status=Status.codec().decode(n);break;default:n.skipType(c&7);break}}return a})),r),e.encode=n=>encodeMessage(n,e.codec()),e.decode=n=>decodeMessage(n,e.codec())})(HopMessage||(HopMessage={}));var StopMessage;(function(e){(function(n){n.CONNECT="CONNECT",n.STATUS="STATUS"})(e.Type||(e.Type={}));let t;(function(n){n[n.CONNECT=0]="CONNECT",n[n.STATUS=1]="STATUS"})(t||(t={})),function(n){n.codec=()=>enumeration(t)}(e.Type||(e.Type={}));let r;e.codec=()=>(r==null&&(r=message((n,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),n.type!=null&&(o.uint32(8),e.Type.codec().encode(n.type,o)),n.peer!=null&&(o.uint32(18),Peer.codec().encode(n.peer,o)),n.limit!=null&&(o.uint32(26),Limit.codec().encode(n.limit,o)),n.status!=null&&(o.uint32(32),Status.codec().encode(n.status,o)),a.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{const a={},l=o==null?n.len:n.pos+o;for(;n.pos>>3){case 1:a.type=e.Type.codec().decode(n);break;case 2:a.peer=Peer.codec().decode(n,n.uint32());break;case 3:a.limit=Limit.codec().decode(n,n.uint32());break;case 4:a.status=Status.codec().decode(n);break;default:n.skipType(c&7);break}}return a})),r),e.encode=n=>encodeMessage(n,e.codec()),e.decode=n=>decodeMessage(n,e.codec())})(StopMessage||(StopMessage={}));var Peer;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.id!=null&&r.id.byteLength>0&&(n.uint32(10),n.bytes(r.id)),r.addrs!=null)for(const a of r.addrs)n.uint32(18),n.bytes(a);o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={id:new Uint8Array(0),addrs:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.id=r.bytes();break;case 2:o.addrs.push(r.bytes());break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(Peer||(Peer={}));var Reservation;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.expire!=null&&r.expire!==0n&&(n.uint32(8),n.uint64(r.expire)),r.addrs!=null)for(const a of r.addrs)n.uint32(18),n.bytes(a);r.voucher!=null&&(n.uint32(26),n.bytes(r.voucher)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={expire:0n,addrs:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.expire=r.uint64();break;case 2:o.addrs.push(r.bytes());break;case 3:o.voucher=r.bytes();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(Reservation||(Reservation={}));var Limit;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.duration!=null&&(n.uint32(8),n.uint32(r.duration)),r.data!=null&&(n.uint32(16),n.uint64(r.data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.duration=r.uint32();break;case 2:o.data=r.uint64();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(Limit||(Limit={}));var Status;(function(e){e.UNUSED="UNUSED",e.OK="OK",e.RESERVATION_REFUSED="RESERVATION_REFUSED",e.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",e.PERMISSION_DENIED="PERMISSION_DENIED",e.CONNECTION_FAILED="CONNECTION_FAILED",e.NO_RESERVATION="NO_RESERVATION",e.MALFORMED_MESSAGE="MALFORMED_MESSAGE",e.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(Status||(Status={}));var __StatusValues;(function(e){e[e.UNUSED=0]="UNUSED",e[e.OK=100]="OK",e[e.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",e[e.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",e[e.PERMISSION_DENIED=202]="PERMISSION_DENIED",e[e.CONNECTION_FAILED=203]="CONNECTION_FAILED",e[e.NO_RESERVATION=204]="NO_RESERVATION",e[e.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",e[e.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(__StatusValues||(__StatusValues={}));(function(e){e.codec=()=>enumeration(__StatusValues)})(Status||(Status={}));var ReservationVoucher;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.relay!=null&&r.relay.byteLength>0&&(n.uint32(10),n.bytes(r.relay)),r.peer!=null&&r.peer.byteLength>0&&(n.uint32(18),n.bytes(r.peer)),r.expiration!=null&&r.expiration!==0n&&(n.uint32(24),n.uint64(r.expiration)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={relay:new Uint8Array(0),peer:new Uint8Array(0),expiration:0n},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 1:o.relay=r.bytes();break;case 2:o.peer=r.bytes();break;case 3:o.expiration=r.uint64();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(ReservationVoucher||(ReservationVoucher={}));logger("libp2p:circuit-relay:utils");async function namespaceToCid(e){const t=new TextEncoder().encode(e),r=await sha256$1.digest(t);return CID.createV0(r)}function getExpirationMilliseconds(e){const t=e*BigInt(1e3),r=new Date().getTime();return Number(t-BigInt(r))}var retry$1={exports:{}},retry={};function RetryOperation(e,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}var retry_operation=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},r),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)};RetryOperation.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,r=0,n=0;n=r&&(t=o,r=l)}return t};(function(e){var t=retry_operation;e.operation=function(r){var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(r){if(r instanceof Array)return[].concat(r);var n={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var o in r)n[o]=r[o];if(n.minTimeout>n.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var a=[],l=0;l{this.safeDispatchEvent("relay:discover",{detail:r})}}),this.discover().catch(r=>{log$5.error("error listening on relays",r)}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async discover(){log$5("searching peer store for relays");const r=await this.peerStore.all({filters:[n=>n.protocols.includes(RELAY_V2_HOP_CODEC)],orders:[()=>Math.random()<.5?1:-1]});for(const n of r)log$5("found relay peer %p in content peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});log$5("found %d relay peers in peer store",r.length);try{log$5("searching content routing for relays");const n=await namespaceToCid(RELAY_RENDEZVOUS_NS);let o=0;for await(const a of this.contentRouting.findProviders(n))if(a.multiaddrs.length>0&&!a.id.equals(this.peerId)){const l=a.id;o++,await this.peerStore.merge(l,{multiaddrs:a.multiaddrs}),log$5("found relay peer %p in content routing",l),this.safeDispatchEvent("relay:discover",{detail:l})}log$5("found %d relay peers in content routing",o)}catch(n){log$5.error("failed when finding relays on the network",n)}}}const log$4=logger("libp2p:circuit-relay:transport:listener");var co,Ua;class CircuitRelayTransportListener extends EventEmitter$2{constructor(r){super();_r(this,co);Ke(this,"connectionManager");Ke(this,"relayStore");Ke(this,"listeningAddrs");this.connectionManager=r.connectionManager,this.relayStore=r.relayStore,this.listeningAddrs=new PeerMap,this.relayStore.addEventListener("relay:removed",n=>{vr(this,co,Ua).call(this,n.detail)})}async listen(r){log$4("listen on %a",r);const n=r.getPeerId();let o;if(n!=null){const l=peerIdFromString(n),c=this.connectionManager.getConnectionsMap().get(l)??[];c.length>0&&(o=c[0])}if(o==null){const l=r.toString().split("/p2p-circuit").find(u=>u!==""),c=multiaddr(l);o=await this.connectionManager.openConnection(c)}if(!this.relayStore.hasReservation(o.remotePeer)){await this.relayStore.addRelay(o.remotePeer,"configured");return}const a=this.relayStore.getReservation(o.remotePeer);if(a==null)throw new CodeError("Did not have reservation after making reservation","ERR_NO_RESERVATION");if(this.listeningAddrs.has(o.remotePeer)){log$4("already listening on relay %p",o.remotePeer);return}this.listeningAddrs.set(o.remotePeer,a.addrs.map(l=>multiaddr(l).encapsulate("/p2p-circuit"))),this.safeDispatchEvent("listening",{})}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){}}co=new WeakSet,Ua=function(r){const n=this.listeningAddrs.has(r);log$4("relay peer removed %p - had reservation",r,n),this.listeningAddrs.delete(r),n&&this.safeDispatchEvent("close",{})};function createListener(e){return new CircuitRelayTransportListener(e)}const log$3=logger("libp2p:circuit-relay:transport:reservation-store"),REFRESH_WINDOW=60*1e3*10,REFRESH_TIMEOUT=60*1e3*5,REFRESH_TIMEOUT_MIN=30*1e3;var uo,za,ho,Ha;class ReservationStore extends EventEmitter$2{constructor(r,n){super();_r(this,uo);_r(this,ho);Ke(this,"peerId");Ke(this,"connectionManager");Ke(this,"transportManager");Ke(this,"peerStore");Ke(this,"events");Ke(this,"reserveQueue");Ke(this,"reservations");Ke(this,"maxDiscoveredRelays");Ke(this,"maxReservationQueueLength");Ke(this,"reservationCompletionTimeout");Ke(this,"started");this.peerId=r.peerId,this.connectionManager=r.connectionManager,this.transportManager=r.transportManager,this.peerStore=r.peerStore,this.events=r.events,this.reservations=new PeerMap,this.maxDiscoveredRelays=n?.discoverRelays??0,this.maxReservationQueueLength=n?.maxReservationQueueLength??100,this.reservationCompletionTimeout=n?.reservationCompletionTimeout??1e4,this.started=!1,this.reserveQueue=new PeerJobQueue({concurrency:n?.reservationConcurrency??DEFAULT_RESERVATION_CONCURRENCY}),this.events.addEventListener("peer:disconnect",o=>{vr(this,ho,Ha).call(this,o.detail)})}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:r})=>{clearTimeout(r)}),this.reservations.clear(),this.started=!1}async addRelay(r,n){if(this.peerId.equals(r)){log$3("not trying to use self as relay");return}if(this.reserveQueue.size>this.maxReservationQueueLength){log$3("not adding relay as the queue is full");return}if(this.reserveQueue.hasJob(r)){log$3("relay peer is already in the reservation queue");return}log$3("add relay %p",r),await this.reserveQueue.add(async()=>{try{const o=this.reservations.get(r);if(o!=null){if(getExpirationMilliseconds(o.reservation.expire)>REFRESH_WINDOW){log$3("already have reservation on relay peer %p and it expires in more than 10 minutes",r);return}clearTimeout(o.timeout),this.reservations.delete(r)}if(n==="discovered"&&[...this.reservations.values()].reduce((x,E)=>(E.type==="discovered"&&x++,x),0)>=this.maxDiscoveredRelays){log$3("already have enough discovered relays");return}const a=AbortSignal.timeout(this.reservationCompletionTimeout),l=await this.connectionManager.openConnection(r,{signal:a});if(l.remoteAddr.protoNames().includes("p2p-circuit")){log$3("not creating reservation over relayed connection");return}const c=await vr(this,uo,za).call(this,l,{signal:a});log$3("created reservation on relay peer %p",r);const u=getExpirationMilliseconds(c.expire),g=Math.min(Math.max(u-REFRESH_TIMEOUT,REFRESH_TIMEOUT_MIN),Math.pow(2,31)-1),b=setTimeout(()=>{this.addRelay(r,n).catch(x=>{log$3.error("could not refresh reservation to relay %p",r,x)})},g);this.reservations.set(r,{timeout:b,reservation:c,type:n}),await this.peerStore.merge(r,{tags:{[RELAY_TAG]:{value:1,ttl:u}}}),await this.transportManager.listen([multiaddr(`/p2p/${r.toString()}/p2p-circuit`)])}catch(o){log$3.error("could not reserve slot on %p",r,o);const a=this.reservations.get(r);a!=null&&clearTimeout(a.timeout),this.reservations.delete(r)}},{peerId:r})}hasReservation(r){return this.reservations.has(r)}getReservation(r){return this.reservations.get(r)?.reservation}}uo=new WeakSet,za=async function(r,n){n.signal?.throwIfAborted(),log$3("requesting reservation from %p",r.remotePeer);const o=await r.newStream(RELAY_V2_HOP_CODEC,n),l=pbStream(o).pb(HopMessage);await l.write({type:HopMessage.Type.RESERVE},n);let c;try{c=await l.read(n)}catch(g){throw log$3.error("error parsing reserve message response from %p because",r.remotePeer,g),g}finally{await o.close()}if(c.status===Status.OK&&c.reservation!=null)return c.reservation;const u=`reservation failed with status ${c.status??"undefined"}`;throw log$3.error(u),new Error(u)},ho=new WeakSet,Ha=function(r){const n=this.reservations.get(r);n!=null&&(log$3("connection to relay %p closed, removing reservation from local store",r),clearTimeout(n.timeout),this.reservations.delete(r),this.safeDispatchEvent("relay:removed",{detail:r}),this.reservations.size{if(e.peer==null)return!1;try{e.peer.addrs.forEach(multiaddr)}catch{return!1}return!0},defaults={maxInboundStopStreams:MAX_CONNECTIONS,maxOutboundStopStreams:MAX_CONNECTIONS,stopTimeout:3e4};var oc,ac;class CircuitRelayTransport{constructor(t,r){Ke(this,"discovery");Ke(this,"registrar");Ke(this,"peerStore");Ke(this,"connectionManager");Ke(this,"peerId");Ke(this,"upgrader");Ke(this,"addressManager");Ke(this,"connectionGater");Ke(this,"reservationStore");Ke(this,"maxInboundStopStreams");Ke(this,"maxOutboundStopStreams");Ke(this,"stopTimeout");Ke(this,"started");Ke(this,oc,!0);Ke(this,ac,"libp2p/circuit-relay-v2");this.registrar=t.registrar,this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.peerId=t.peerId,this.upgrader=t.upgrader,this.addressManager=t.addressManager,this.connectionGater=t.connectionGater,this.maxInboundStopStreams=r.maxInboundStopStreams??defaults.maxInboundStopStreams,this.maxOutboundStopStreams=r.maxOutboundStopStreams??defaults.maxOutboundStopStreams,this.stopTimeout=r.stopTimeout??defaults.stopTimeout,r.discoverRelays!=null&&r.discoverRelays>0&&(this.discovery=new RelayDiscovery(t),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{log$2.error("could not add discovered relay %p",n.detail,o)})})),this.reservationStore=new ReservationStore(t,r),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.discover().catch(n=>{log$2.error("could not discover relays",n)})}),this.started=!1}isStarted(){return this.started}async start(){await this.reservationStore.start(),await this.discovery?.start(),await this.registrar.handle(RELAY_V2_STOP_CODEC,t=>{this.onStop(t).catch(r=>{log$2.error("error while handling STOP protocol",r),t.stream.abort(r)})},{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnTransientConnection:!0}),this.started=!0}async stop(){this.discovery?.stop(),await this.reservationStore.stop(),await this.registrar.unhandle(RELAY_V2_STOP_CODEC),this.started=!1}async dial(t,r={}){if(t.protoCodes().filter(T=>T===CIRCUIT_PROTO_CODE).length!==1){const T="Invalid circuit relay address";throw log$2.error(T,t),new CodeError(T,codes.ERR_RELAYED_DIAL)}const n=t.toString().split("/p2p-circuit"),o=multiaddr(n[0]),a=multiaddr(n[n.length-1]),l=o.getPeerId(),c=a.getPeerId();if(l==null||c==null){const T=`Circuit relay dial to ${t.toString()} failed as address did not have peer ids`;throw log$2.error(T),new CodeError(T,codes.ERR_RELAYED_DIAL)}const u=peerIdFromString(l),g=peerIdFromString(c);let b=!1,E=this.connectionManager.getConnections(u)[0];E==null&&(await this.peerStore.merge(u,{multiaddrs:[o]}),E=await this.connectionManager.openConnection(u,r),b=!0);let I;try{return I=await E.newStream([RELAY_V2_HOP_CODEC]),await this.connectV2({stream:I,connection:E,destinationPeer:g,destinationAddr:a,relayAddr:o,ma:t,disconnectOnFailure:b})}catch(T){throw log$2.error(`Circuit relay dial to destination ${g.toString()} via relay ${u.toString()} failed`,T),I?.abort(T),b&&await E.close(),T}}async connectV2({stream:t,connection:r,destinationPeer:n,destinationAddr:o,relayAddr:a,ma:l,disconnectOnFailure:c}){try{const u=pbStream(t),g=u.pb(HopMessage);await g.write({type:HopMessage.Type.CONNECT,peer:{id:n.toBytes(),addrs:[multiaddr(o).bytes]}});const b=await g.read();if(b.status!==Status.OK)throw new CodeError(`failed to connect via relay with status ${b?.status?.toString()??"undefined"}`,codes.ERR_HOP_REQUEST_FAILED);const x=streamToMaConnection({stream:u.unwrap(),remoteAddr:l,localAddr:a.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`)});return log$2("new outbound transient connection %a",x.remoteAddr),await this.upgrader.upgradeOutbound(x,{transient:!0})}catch(u){throw log$2.error(`Circuit relay dial to destination ${n.toString()} via relay ${r.remotePeer.toString()} failed`,u),c&&await r.close(),u}}createListener(t){return createListener({connectionManager:this.connectionManager,relayStore:this.reservationStore})}filter(t){return t=Array.isArray(t)?t:[t],t.filter(r=>Circuit$1.matches(r))}async onStop({connection:t,stream:r}){const n=AbortSignal.timeout(this.stopTimeout),o=pbStream(r).pb(StopMessage),a=await o.read({signal:n});if(log$2("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,a.type),a?.type===void 0){log$2.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:StopMessage.Type.STATUS,status:Status.MALFORMED_MESSAGE},{signal:n}),await r.close();return}if(a.type!==StopMessage.Type.CONNECT){log$2.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:StopMessage.Type.STATUS,status:Status.UNEXPECTED_MESSAGE},{signal:n}),await r.close();return}if(!isValidStop(a)){log$2.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:StopMessage.Type.STATUS,status:Status.MALFORMED_MESSAGE},{signal:n}),await r.close();return}const l=peerIdFromBytes(a.peer.id);if(await this.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,l)===!0){log$2.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await o.write({type:StopMessage.Type.STATUS,status:Status.PERMISSION_DENIED},{signal:n}),await r.close();return}log$2.trace("sending success response to %p",t.remotePeer),await o.write({type:StopMessage.Type.STATUS,status:Status.OK},{signal:n});const c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${l.toString()}`),u=this.addressManager.getAddresses()[0],g=streamToMaConnection({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:u});log$2("new inbound transient connection %a",g.remoteAddr),await this.upgrader.upgradeInbound(g,{transient:!0}),log$2("%s connection %a upgraded","inbound",g.remoteAddr)}}oc=symbol$1,ac=Symbol.toStringTag;function circuitRelayTransport(e={}){return t=>new CircuitRelayTransport(t,e)}const version="0.46.11",AGENT_VERSION=`js-libp2p/${version}`,IDENTIFY_PROTOCOL_VERSION="0.1.0",MULTICODEC_IDENTIFY_PROTOCOL_NAME="id",MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME="id/push",MULTICODEC_IDENTIFY_PROTOCOL_VERSION="1.0.0",MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION="1.0.0";var Identify;(function(e){let t;e.codec=()=>(t==null&&(t=message((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.protocolVersion!=null&&(n.uint32(42),n.string(r.protocolVersion)),r.agentVersion!=null&&(n.uint32(50),n.string(r.agentVersion)),r.publicKey!=null&&(n.uint32(10),n.bytes(r.publicKey)),r.listenAddrs!=null)for(const a of r.listenAddrs)n.uint32(18),n.bytes(a);if(r.observedAddr!=null&&(n.uint32(34),n.bytes(r.observedAddr)),r.protocols!=null)for(const a of r.protocols)n.uint32(26),n.string(a);r.signedPeerRecord!=null&&(n.uint32(66),n.bytes(r.signedPeerRecord)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{const o={listenAddrs:[],protocols:[]},a=n==null?r.len:r.pos+n;for(;r.pos>>3){case 5:o.protocolVersion=r.string();break;case 6:o.agentVersion=r.string();break;case 1:o.publicKey=r.bytes();break;case 2:o.listenAddrs.push(r.bytes());break;case 4:o.observedAddr=r.bytes();break;case 3:o.protocols.push(r.string());break;case 8:o.signedPeerRecord=r.bytes();break;default:r.skipType(l&7);break}}return o})),t),e.encode=r=>encodeMessage(r,e.codec()),e.decode=r=>decodeMessage(r,e.codec())})(Identify||(Identify={}));const log$1=logger("libp2p:identify"),MAX_IDENTIFY_MESSAGE_SIZE=1024*8,defaultValues={protocolPrefix:"ipfs",agentVersion:AGENT_VERSION,timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192,runOnConnectionOpen:!0,runOnTransientConnection:!0};var rs,ya;class DefaultIdentifyService{constructor(t,r){_r(this,rs);Ke(this,"identifyProtocolStr");Ke(this,"identifyPushProtocolStr");Ke(this,"host");Ke(this,"started");Ke(this,"timeout");Ke(this,"peerId");Ke(this,"peerStore");Ke(this,"registrar");Ke(this,"connectionManager");Ke(this,"addressManager");Ke(this,"maxInboundStreams");Ke(this,"maxOutboundStreams");Ke(this,"maxPushIncomingStreams");Ke(this,"maxPushOutgoingStreams");Ke(this,"maxIdentifyMessageSize");Ke(this,"maxObservedAddresses");Ke(this,"events");Ke(this,"runOnTransientConnection");this.started=!1,this.peerId=t.peerId,this.peerStore=t.peerStore,this.registrar=t.registrar,this.addressManager=t.addressManager,this.connectionManager=t.connectionManager,this.events=t.events,this.identifyProtocolStr=`/${r.protocolPrefix??defaultValues.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`,this.identifyPushProtocolStr=`/${r.protocolPrefix??defaultValues.protocolPrefix}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION}`,this.timeout=r.timeout??defaultValues.timeout,this.maxInboundStreams=r.maxInboundStreams??defaultValues.maxInboundStreams,this.maxOutboundStreams=r.maxOutboundStreams??defaultValues.maxOutboundStreams,this.maxPushIncomingStreams=r.maxPushIncomingStreams??defaultValues.maxPushIncomingStreams,this.maxPushOutgoingStreams=r.maxPushOutgoingStreams??defaultValues.maxPushOutgoingStreams,this.maxIdentifyMessageSize=r.maxIdentifyMessageSize??defaultValues.maxIdentifyMessageSize,this.maxObservedAddresses=r.maxObservedAddresses??defaultValues.maxObservedAddresses,this.runOnTransientConnection=r.runOnTransientConnection??defaultValues.runOnTransientConnection,this.host={protocolVersion:`${r.protocolPrefix??defaultValues.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,agentVersion:r.agentVersion??defaultValues.agentVersion},(r.runOnConnectionOpen??defaultValues.runOnConnectionOpen)&&t.events.addEventListener("connection:open",n=>{const o=n.detail;this.identify(o).catch(a=>{log$1.error("error during identify trigged by connection:open",a)})}),t.events.addEventListener("self:peer:update",n=>{this.push().catch(o=>{log$1.error(o)})}),this.host.agentVersion===AGENT_VERSION&&(isNode||isElectronMain?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(isBrowser||isWebWorker||isElectronRenderer||isReactNative)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:fromString$1(this.host.agentVersion),ProtocolVersion:fromString$1(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,t=>{this._handleIdentify(t).catch(r=>{log$1.error(r)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),await this.registrar.handle(this.identifyPushProtocolStr,t=>{this._handlePush(t).catch(r=>{log$1.error(r)})},{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(t){const r=this.addressManager.getAddresses().map(b=>b.decapsulateCode(getProtocol("p2p").code)),n=new PeerRecord({peerId:this.peerId,multiaddrs:r}),o=await RecordEnvelope.seal(n,this.peerId),a=this.registrar.getProtocols(),l=await this.peerStore.get(this.peerId),c=toString$5(l.metadata.get("AgentVersion")??fromString$1(this.host.agentVersion)),u=toString$5(l.metadata.get("ProtocolVersion")??fromString$1(this.host.protocolVersion)),g=t.map(async b=>{let x;const E=AbortSignal.timeout(this.timeout);try{events$1.exports.setMaxListeners?.(1/0,E)}catch{}try{x=await b.newStream([this.identifyPushProtocolStr],{signal:E,runOnTransientConnection:this.runOnTransientConnection}),await pbStream(x,{maxDataLength:this.maxIdentifyMessageSize??MAX_IDENTIFY_MESSAGE_SIZE}).pb(Identify).write({listenAddrs:r.map(T=>T.bytes),signedPeerRecord:o.marshal(),protocols:a,agentVersion:c,protocolVersion:u},{signal:E}),await x.close({signal:E})}catch(I){log$1.error("could not push identify update to peer",I),x?.abort(I)}});await Promise.all(g)}async push(){if(!this.isStarted())return;const t=[];await Promise.all(this.connectionManager.getConnections().map(async r=>{try{if(!(await this.peerStore.get(r.remotePeer)).protocols.includes(this.identifyPushProtocolStr))return;t.push(r)}catch(n){if(n.code!==codes.ERR_NOT_FOUND)throw n}})),await this.pushToConnections(t)}async _identify(t,r={}){let n;r.signal=r.signal??AbortSignal.timeout(this.timeout);try{n=await t.newStream([this.identifyProtocolStr],{...r,runOnTransientConnection:this.runOnTransientConnection});const a=await pbStream(n,{maxDataLength:this.maxIdentifyMessageSize??MAX_IDENTIFY_MESSAGE_SIZE}).pb(Identify).read(r);return await n.close(r),a}catch(o){throw log$1.error("error while reading identify message",o),n?.abort(o),o}}async identify(t,r={}){const n=await this._identify(t,r),{publicKey:o,protocols:a,observedAddr:l}=n;if(o==null)throw new CodeError("public key was missing from identify message",codes.ERR_MISSING_PUBLIC_KEY);const c=await peerIdFromKeys(o);if(!t.remotePeer.equals(c))throw new CodeError("identified peer does not match the expected peer",codes.ERR_INVALID_PEER);if(this.peerId.equals(c))throw new CodeError("identified peer is our own peer id?",codes.ERR_INVALID_PEER);const u=getCleanMultiaddr(l);log$1("identify completed for peer %p and protocols %o",c,a),log$1("our observed address is %a",u),u!=null&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(log$1("storing our observed address %a",u),this.addressManager.addObservedAddr(u));const g=await vr(this,rs,ya).call(this,t.remotePeer,n),b={peerId:c,protocolVersion:n.protocolVersion,agentVersion:n.agentVersion,publicKey:n.publicKey,listenAddrs:n.listenAddrs.map(x=>multiaddr(x)),observedAddr:n.observedAddr==null?void 0:multiaddr(n.observedAddr),protocols:n.protocols,signedPeerRecord:g};return this.events.safeDispatchEvent("peer:identify",{detail:b}),b}async _handleIdentify(t){const{connection:r,stream:n}=t,o=AbortSignal.timeout(this.timeout);try{events$1.exports.setMaxListeners?.(1/0,o)}catch{}try{const a=this.peerId.publicKey??new Uint8Array(0),l=await this.peerStore.get(this.peerId),c=this.addressManager.getAddresses().map(b=>b.decapsulateCode(getProtocol("p2p").code));let u=l.peerRecordEnvelope;if(c.length>0&&u==null){const b=new PeerRecord({peerId:this.peerId,multiaddrs:c});u=(await RecordEnvelope.seal(b,this.peerId)).marshal().subarray()}await pbStream(n).pb(Identify).write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:a,listenAddrs:c.map(b=>b.bytes),signedPeerRecord:u,observedAddr:r.remoteAddr.bytes,protocols:l.protocols},{signal:o}),await n.close({signal:o})}catch(a){log$1.error("could not respond to identify request",a),n.abort(a)}}async _handlePush(t){const{connection:r,stream:n}=t;try{if(this.peerId.equals(r.remotePeer))throw new Error("received push from ourselves?");const o={signal:AbortSignal.timeout(this.timeout)},l=await pbStream(n,{maxDataLength:this.maxIdentifyMessageSize??MAX_IDENTIFY_MESSAGE_SIZE}).pb(Identify).read(o);await n.close(o),await vr(this,rs,ya).call(this,r.remotePeer,l)}catch(o){log$1.error("received invalid message",o),n.abort(o);return}log$1("handled push from %p",r.remotePeer)}}rs=new WeakSet,ya=async function(t,r){if(log$1("received identify from %p",t),r==null)throw new Error("Message was null or undefined");const n={addresses:r.listenAddrs.map(a=>({isCertified:!1,multiaddr:multiaddr(a)})),protocols:r.protocols,metadata:new Map,peerRecordEnvelope:r.signedPeerRecord};let o;if(r.signedPeerRecord!=null){log$1("received signedPeerRecord in push from %p",t);let a=r.signedPeerRecord;const l=await RecordEnvelope.openAndCertify(a,PeerRecord.DOMAIN);let c=PeerRecord.createFromProtobuf(l.payload);if(!c.peerId.equals(l.peerId))throw new Error("signing key does not match PeerId in the PeerRecord");if(!t.equals(c.peerId))throw new Error("signing key does not match remote PeerId");let u;try{u=await this.peerStore.get(c.peerId)}catch(g){if(g.code!=="ERR_NOT_FOUND")throw g}if(u!=null&&(n.metadata=u.metadata,u.peerRecordEnvelope!=null)){const g=await RecordEnvelope.createFromProtobuf(u.peerRecordEnvelope),b=PeerRecord.createFromProtobuf(g.payload);b.seqNumber>=c.seqNumber&&(log$1("sequence number was lower or equal to existing sequence number - stored: %d received: %d",b.seqNumber,c.seqNumber),c=b,a=u.peerRecordEnvelope)}n.peerRecordEnvelope=a,n.addresses=c.multiaddrs.map(g=>({isCertified:!0,multiaddr:g})),o={seq:c.seqNumber,addresses:c.multiaddrs}}else log$1("%p did not send a signed peer record",t);return r.agentVersion!=null&&n.metadata.set("AgentVersion",fromString$1(r.agentVersion)),r.protocolVersion!=null&&n.metadata.set("ProtocolVersion",fromString$1(r.protocolVersion)),await this.peerStore.patch(t,n),o};function getCleanMultiaddr(e){if(e!=null&&e.length>0)try{return multiaddr(e)}catch{}}function identifyService(e={}){return t=>new DefaultIdentifyService(t,e)}const createNode=async e=>await createLibp2p({addresses:{listen:["/webrtc"]},transports:[webSockets({filter:all$1}),webRTC(),circuitRelayTransport({discoverRelays:1})],streamMuxers:[mplex()],connectionEncryption:[noise()],services:{pubsub:floodsub(),identify:identifyService()},peerDiscovery:[bootstrap({list:e.bootstrappers})],connectionGater:{denyDialMultiaddr:()=>!1}}),topic="airalab.lighthouse.5.robonomics.eth";class Provider$1{constructor(t){this.node=null,this.isReady=!1,this.whiteListAccounts=[],this.history={},this.init(t).then(()=>{this.isReady=!0,window.pubsubPeers=()=>{console.log("peers",this.node.services.pubsub.getPeers().map(r=>r.toString())),console.log("pubsub",this.node.services.pubsub.getSubscribers(topic).map(r=>r.toString()))}})}async init(t){this.node=await createNode(t),this.whiteListAccounts=getAgents()}ready(){return new Promise(t=>{const r=setInterval(()=>{this.isReady&&(t(),clearInterval(r))},100)})}getHistoryBySensor(t){return Promise.resolve(this.history[t]?this.history[t]:[])}watch(t){this.node.services.pubsub.subscribe(topic),this.node.services.pubsub.addEventListener("message",r=>{const n=r.detail.from.toString();if(!this.whiteListAccounts.includes(n))return;let o;try{o=JSON.parse(Buffer.from(r.detail.data).toString("utf8"))}catch(l){console.error(l.message);return}for(const l in o){const c=o[l];if(Object.prototype.hasOwnProperty.call(c,"model")&&(!Object.prototype.hasOwnProperty.call(this.history,l)||this.history[l].find(u=>u.timestamp===c.measurement.timestamp)===void 0)){const{timestamp:u,...g}=c.measurement,b={};for(var a in g){const k=a.toLowerCase();b[k]=measurements[k]?.calc?measurements[k].calc(g[a]):g[a]}const[x,E]=c.geo.split(","),I=c.donated_by||void 0,T={sensor_id:l,sender:n,model:c.model,geo:{lat:x,lng:E},data:b,donated_by:I,timestamp:u};Object.prototype.hasOwnProperty.call(this.history,l)||(this.history[l]=[]),this.history[l].push(T),t(T)}}})}}var lib$1={exports:{}},re=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],parseuri$2=function e(t){var r=t,n=t.indexOf("["),o=t.indexOf("]");n!=-1&&o!=-1&&(t=t.substring(0,n)+t.substring(n,o).replace(/:/g,";")+t.substring(o,t.length));for(var a=re.exec(t||""),l={},c=14;c--;)l[parts[c]]=a[c]||"";return n!=-1&&o!=-1&&(l.source=r,l.host=l.host.substring(1,l.host.length-1).replace(/;/g,":"),l.authority=l.authority.replace("[","").replace("]","").replace(/;/g,":"),l.ipv6uri=!0),l.pathNames=pathNames(l,l.path),l.queryKey=queryKey(l,l.query),l};function pathNames(e,t){var r=/\/{2,9}/g,n=t.replace(r,"/").split("/");return(t.substr(0,1)=="/"||t.length===0)&&n.splice(0,1),t.substr(t.length-1,1)=="/"&&n.splice(n.length-1,1),n}function queryKey(e,t){var r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,o,a){o&&(r[o]=a)}),r}var browser$3={exports:{}},debug$8={exports:{}},s$2=1e3,m$3=s$2*60,h$3=m$3*60,d$4=h$3*24,y$2=d$4*365.25,ms$2=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0)return parse$4(e);if(r==="number"&&isNaN(e)===!1)return t.long?fmtLong$2(e):fmtShort$2(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse$4(e){if(e=String(e),!(e.length>100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!!t){var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*y$2;case"days":case"day":case"d":return r*d$4;case"hours":case"hour":case"hrs":case"hr":case"h":return r*h$3;case"minutes":case"minute":case"mins":case"min":case"m":return r*m$3;case"seconds":case"second":case"secs":case"sec":case"s":return r*s$2;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function fmtShort$2(e){return e>=d$4?Math.round(e/d$4)+"d":e>=h$3?Math.round(e/h$3)+"h":e>=m$3?Math.round(e/m$3)+"m":e>=s$2?Math.round(e/s$2)+"s":e+"ms"}function fmtLong$2(e){return plural$2(e,d$4,"day")||plural$2(e,h$3,"hour")||plural$2(e,m$3,"minute")||plural$2(e,s$2,"second")||e+" ms"}function plural$2(e,t,r){if(!(e=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}t.formatters.j=function(u){try{return JSON.stringify(u)}catch(g){return"[UnexpectedJSONParseError]: "+g.message}};function n(u){var g=this.useColors;if(u[0]=(g?"%c":"")+this.namespace+(g?" %c":" ")+u[0]+(g?"%c ":" ")+"+"+t.humanize(this.diff),!!g){var b="color: "+this.color;u.splice(1,0,b,"color: inherit");var x=0,E=0;u[0].replace(/%[a-zA-Z%]/g,function(I){I!=="%%"&&(x++,I==="%c"&&(E=x))}),u.splice(E,0,b)}}function o(){return typeof console=="object"&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(u){try{u==null?t.storage.removeItem("debug"):t.storage.debug=u}catch{}}function l(){var u;try{u=t.storage.debug}catch{}return!u&&typeof process<"u"&&"env"in process&&(u={}.DEBUG),u}t.enable(l());function c(){try{return window.localStorage}catch{}}})(browser$3,browser$3.exports);var parseuri$1=parseuri$2,debug$7=browser$3.exports("socket.io-client:url"),url_1=url;function url(e,t){var r=e;t=t||typeof location<"u"&&location,e==null&&(e=t.protocol+"//"+t.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=t.protocol+e:e=t.host+e),/^(https?|wss?):\/\//.test(e)||(debug$7("protocol-less url %s",e),typeof t<"u"?e=t.protocol+"//"+e:e="https://"+e),debug$7("parse %s",e),r=parseuri$1(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";var n=r.host.indexOf(":")!==-1,o=n?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+o+":"+r.port,r.href=r.protocol+"://"+o+(t&&t.port===r.port?"":":"+r.port),r}var socket_ioParser={},browser$2={exports:{}},debug$6={exports:{}},s$1=1e3,m$2=s$1*60,h$2=m$2*60,d$3=h$2*24,y$1=d$3*365.25,ms$1=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0)return parse$3(e);if(r==="number"&&isNaN(e)===!1)return t.long?fmtLong$1(e):fmtShort$1(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse$3(e){if(e=String(e),!(e.length>100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!!t){var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*y$1;case"days":case"day":case"d":return r*d$3;case"hours":case"hour":case"hrs":case"hr":case"h":return r*h$2;case"minutes":case"minute":case"mins":case"min":case"m":return r*m$2;case"seconds":case"second":case"secs":case"sec":case"s":return r*s$1;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function fmtShort$1(e){return e>=d$3?Math.round(e/d$3)+"d":e>=h$2?Math.round(e/h$2)+"h":e>=m$2?Math.round(e/m$2)+"m":e>=s$1?Math.round(e/s$1)+"s":e+"ms"}function fmtLong$1(e){return plural$1(e,d$3,"day")||plural$1(e,h$2,"hour")||plural$1(e,m$2,"minute")||plural$1(e,s$1,"second")||e+" ms"}function plural$1(e,t,r){if(!(e=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}t.formatters.j=function(u){try{return JSON.stringify(u)}catch(g){return"[UnexpectedJSONParseError]: "+g.message}};function n(u){var g=this.useColors;if(u[0]=(g?"%c":"")+this.namespace+(g?" %c":" ")+u[0]+(g?"%c ":" ")+"+"+t.humanize(this.diff),!!g){var b="color: "+this.color;u.splice(1,0,b,"color: inherit");var x=0,E=0;u[0].replace(/%[a-zA-Z%]/g,function(I){I!=="%%"&&(x++,I==="%c"&&(E=x))}),u.splice(E,0,b)}}function o(){return typeof console=="object"&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(u){try{u==null?t.storage.removeItem("debug"):t.storage.debug=u}catch{}}function l(){var u;try{u=t.storage.debug}catch{}return!u&&typeof process<"u"&&"env"in process&&(u={}.DEBUG),u}t.enable(l());function c(){try{return window.localStorage}catch{}}})(browser$2,browser$2.exports);var componentEmitter={exports:{}};(function(e){e.exports=t;function t(n){if(n)return r(n)}function r(n){for(var o in t.prototype)n[o]=t.prototype[o];return n}t.prototype.on=t.prototype.addEventListener=function(n,o){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(o),this},t.prototype.once=function(n,o){function a(){this.off(n,a),o.apply(this,arguments)}return a.fn=o,this.on(n,a),this},t.prototype.off=t.prototype.removeListener=t.prototype.removeAllListeners=t.prototype.removeEventListener=function(n,o){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var a=this._callbacks["$"+n];if(!a)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var l,c=0;c=0&&e.numn&&(r=n),t>=n||t>=r||n===0)return new ArrayBuffer(0);for(var o=new Uint8Array(e),a=new Uint8Array(r-t),l=t,c=0;l=55296&&o<=56319&&r65535&&(n-=65536,o+=stringFromCharCode(n>>>10&1023|55296),n=56320|n&1023),o+=stringFromCharCode(n);return o}function checkScalarValue(e,t){if(e>=55296&&e<=57343){if(t)throw Error("Lone surrogate U+"+e.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function createByte(e,t){return stringFromCharCode(e>>t&63|128)}function encodeCodePoint(e,t){if((e&4294967168)==0)return stringFromCharCode(e);var r="";return(e&4294965248)==0?r=stringFromCharCode(e>>6&31|192):(e&4294901760)==0?(checkScalarValue(e,t)||(e=65533),r=stringFromCharCode(e>>12&15|224),r+=createByte(e,6)):(e&4292870144)==0&&(r=stringFromCharCode(e>>18&7|240),r+=createByte(e,12),r+=createByte(e,6)),r+=stringFromCharCode(e&63|128),r}function utf8encode(e,t){t=t||{};for(var r=t.strict!==!1,n=ucs2decode$1(e),o=n.length,a=-1,l,c="";++a=byteCount)throw Error("Invalid byte index");var e=byteArray[byteIndex]&255;if(byteIndex++,(e&192)==128)return e&63;throw Error("Invalid continuation byte")}function decodeSymbol(e){var t,r,n,o,a;if(byteIndex>byteCount)throw Error("Invalid byte index");if(byteIndex==byteCount)return!1;if(t=byteArray[byteIndex]&255,byteIndex++,(t&128)==0)return t;if((t&224)==192){if(r=readContinuationByte(),a=(t&31)<<6|r,a>=128)return a;throw Error("Invalid continuation byte")}if((t&240)==224){if(r=readContinuationByte(),n=readContinuationByte(),a=(t&15)<<12|r<<6|n,a>=2048)return checkScalarValue(a,e)?a:65533;throw Error("Invalid continuation byte")}if((t&248)==240&&(r=readContinuationByte(),n=readContinuationByte(),o=readContinuationByte(),a=(t&7)<<18|r<<12|n<<6|o,a>=65536&&a<=1114111))return a;throw Error("Invalid UTF-8 detected")}var byteArray,byteCount,byteIndex;function utf8decode(e,t){t=t||{};var r=t.strict!==!1;byteArray=ucs2decode$1(e),byteCount=byteArray.length,byteIndex=0;for(var n=[],o;(o=decodeSymbol(r))!==!1;)n.push(o);return ucs2encode(n)}var utf8={version:"2.1.2",encode:utf8encode,decode:utf8decode},base64Arraybuffer={},hasRequiredBase64Arraybuffer;function requireBase64Arraybuffer(){return hasRequiredBase64Arraybuffer||(hasRequiredBase64Arraybuffer=1,function(e){base64Arraybuffer.encode=function(t){var r=new Uint8Array(t),n,o=r.length,a="";for(n=0;n>2],a+=e[(r[n]&3)<<4|r[n+1]>>4],a+=e[(r[n+1]&15)<<2|r[n+2]>>6],a+=e[r[n+2]&63];return o%3===2?a=a.substring(0,a.length-1)+"=":o%3===1&&(a=a.substring(0,a.length-2)+"=="),a},base64Arraybuffer.decode=function(t){var r=t.length*.75,n=t.length,o,a=0,l,c,u,g;t[t.length-1]==="="&&(r--,t[t.length-2]==="="&&r--);var b=new ArrayBuffer(r),x=new Uint8Array(b);for(o=0;o>4,x[a++]=(c&15)<<4|u>>2,x[a++]=(u&3)<<6|g&63;return b}}("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")),base64Arraybuffer}var blob,hasRequiredBlob;function requireBlob(){if(hasRequiredBlob)return blob;hasRequiredBlob=1;var e=typeof e<"u"?e:typeof WebKitBlobBuilder<"u"?WebKitBlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:!1,t=function(){try{var c=new Blob(["hi"]);return c.size===2}catch{return!1}}(),r=t&&function(){try{var c=new Blob([new Uint8Array([1,2])]);return c.size===2}catch{return!1}}(),n=e&&e.prototype.append&&e.prototype.getBlob;function o(c){return c.map(function(u){if(u.buffer instanceof ArrayBuffer){var g=u.buffer;if(u.byteLength!==g.byteLength){var b=new Uint8Array(u.byteLength);b.set(new Uint8Array(g,u.byteOffset,u.byteLength)),g=b.buffer}return g}return u})}function a(c,u){u=u||{};var g=new e;return o(c).forEach(function(b){g.append(b)}),u.type?g.getBlob(u.type):g.getBlob()}function l(c,u){return new Blob(o(c),u||{})}return typeof Blob<"u"&&(a.prototype=Blob.prototype,l.prototype=Blob.prototype),blob=function(){return t?r?Blob:l:n?a:void 0}(),blob}(function(e){var t=keys,r=hasBinary2,n=arraybuffer_slice,o=after_1,a=utf8,l;typeof ArrayBuffer<"u"&&(l=requireBase64Arraybuffer());var c=typeof navigator<"u"&&/Android/i.test(navigator.userAgent),u=typeof navigator<"u"&&/PhantomJS/i.test(navigator.userAgent),g=c||u;e.protocol=3;var b=e.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6},x=t(b),E={type:"error",data:"parser error"},I=requireBlob();e.encodePacket=function(H,se,ue,de){typeof se=="function"&&(de=se,se=!1),typeof ue=="function"&&(de=ue,ue=null);var le=H.data===void 0?void 0:H.data.buffer||H.data;if(typeof ArrayBuffer<"u"&&le instanceof ArrayBuffer)return k(H,se,de);if(typeof I<"u"&&le instanceof I)return $(H,se,de);if(le&&le.base64)return T(H,de);var ce=b[H.type];return H.data!==void 0&&(ce+=ue?a.encode(String(H.data),{strict:!1}):String(H.data)),de(""+ce)};function T(H,se){var ue="b"+e.packets[H.type]+H.data.data;return se(ue)}function k(H,se,ue){if(!se)return e.encodeBase64Packet(H,ue);var de=H.data,le=new Uint8Array(de),ce=new Uint8Array(1+de.byteLength);ce[0]=b[H.type];for(var ve=0;ve1?{type:x[le],data:H.substring(1)}:{type:x[le]}}var de=new Uint8Array(H),le=de[0],ce=n(H,1);return I&&se==="blob"&&(ce=new I([ce])),{type:x[le],data:ce}};function D(H){try{H=a.decode(H,{strict:!1})}catch{return!1}return H}e.decodeBase64Packet=function(H,se){var ue=x[H.charAt(0)];if(!l)return{type:ue,data:{base64:!0,data:H.substr(1)}};var de=l.decode(H.substr(1));return se==="blob"&&I&&(de=new I([de])),{type:ue,data:de}},e.encodePayload=function(H,se,ue){typeof se=="function"&&(ue=se,se=null);var de=r(H);if(se&&de)return I&&!g?e.encodePayloadAsBlob(H,ue):e.encodePayloadAsArrayBuffer(H,ue);if(!H.length)return ue("0:");function le(ve){return ve.length+":"+ve}function ce(ve,ee){e.encodePacket(ve,de?se:!1,!1,function(he){ee(null,le(he))})}N(H,ce,function(ve,ee){return ue(ee.join(""))})};function N(H,se,ue){for(var de=new Array(H.length),le=o(H.length,ue),ce=function(ee,he,ne){se(he,function(xe,te){de[ee]=te,ne(xe,de)})},ve=0;ve0;){for(var ce=new Uint8Array(de),ve=ce[0]===0,ee="",he=1;ce[he]!==255;he++){if(ee.length>310)return ue(E,0,1);ee+=ce[he]}de=n(de,2+ee.length),ee=parseInt(ee);var ne=n(de,0,ee);if(ve)try{ne=String.fromCharCode.apply(null,new Uint8Array(ne))}catch{var xe=new Uint8Array(ne);ne="";for(var he=0;he0);return t}function decode(e){var t=0;for(i=0;i0)return parse$2(e);if(r==="number"&&isNaN(e)===!1)return t.long?fmtLong(e):fmtShort(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse$2(e){if(e=String(e),!(e.length>100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!!t){var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*y;case"days":case"day":case"d":return r*d$2;case"hours":case"hour":case"hrs":case"hr":case"h":return r*h$1;case"minutes":case"minute":case"mins":case"min":case"m":return r*m$1;case"seconds":case"second":case"secs":case"sec":case"s":return r*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function fmtShort(e){return e>=d$2?Math.round(e/d$2)+"d":e>=h$1?Math.round(e/h$1)+"h":e>=m$1?Math.round(e/m$1)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function fmtLong(e){return plural(e,d$2,"day")||plural(e,h$1,"hour")||plural(e,m$1,"minute")||plural(e,s,"second")||e+" ms"}function plural(e,t,r){if(!(e=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}t.formatters.j=function(u){try{return JSON.stringify(u)}catch(g){return"[UnexpectedJSONParseError]: "+g.message}};function n(u){var g=this.useColors;if(u[0]=(g?"%c":"")+this.namespace+(g?" %c":" ")+u[0]+(g?"%c ":" ")+"+"+t.humanize(this.diff),!!g){var b="color: "+this.color;u.splice(1,0,b,"color: inherit");var x=0,E=0;u[0].replace(/%[a-zA-Z%]/g,function(I){I!=="%%"&&(x++,I==="%c"&&(E=x))}),u.splice(E,0,b)}}function o(){return typeof console=="object"&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(u){try{u==null?t.storage.removeItem("debug"):t.storage.debug=u}catch{}}function l(){var u;try{u=t.storage.debug}catch{}return!u&&typeof process<"u"&&"env"in process&&(u={}.DEBUG),u}t.enable(l());function c(){try{return window.localStorage}catch{}}})(browser,browser.exports);var Transport$1=requireTransport(),parseqs$2=parseqs$3,parser$3=browser$1,inherit$3=componentInherit,yeast$1=yeast_1,debug$4=browser.exports("engine.io-client:polling"),polling$1=Polling$2,hasXHR2=function(){var e=xmlhttprequest_browser,t=new e({xdomain:!1});return t.responseType!=null}();function Polling$2(e){var t=e&&e.forceBase64;(!hasXHR2||t)&&(this.supportsBinary=!1),Transport$1.call(this,e)}inherit$3(Polling$2,Transport$1);Polling$2.prototype.name="polling";Polling$2.prototype.doOpen=function(){this.poll()};Polling$2.prototype.pause=function(e){var t=this;this.readyState="pausing";function r(){debug$4("paused"),t.readyState="paused",e()}if(this.polling||!this.writable){var n=0;this.polling&&(debug$4("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){debug$4("pre-pause polling complete"),--n||r()})),this.writable||(debug$4("we are currently writing - waiting to pause"),n++,this.once("drain",function(){debug$4("pre-pause writing complete"),--n||r()}))}else r()};Polling$2.prototype.poll=function(){debug$4("polling"),this.polling=!0,this.doPoll(),this.emit("poll")};Polling$2.prototype.onData=function(e){var t=this;debug$4("polling got data %s",e);var r=function(n,o,a){if(t.readyState==="opening"&&n.type==="open"&&t.onOpen(),n.type==="close")return t.onClose(),!1;t.onPacket(n)};parser$3.decodePayload(e,this.socket.binaryType,r),this.readyState!=="closed"&&(this.polling=!1,this.emit("pollComplete"),this.readyState==="open"?this.poll():debug$4('ignoring poll - transport state "%s"',this.readyState))};Polling$2.prototype.doClose=function(){var e=this;function t(){debug$4("writing close packet"),e.write([{type:"close"}])}this.readyState==="open"?(debug$4("transport open - closing"),t()):(debug$4("transport not open - deferring close"),this.once("open",t))};Polling$2.prototype.write=function(e){var t=this;this.writable=!1;var r=function(){t.writable=!0,t.emit("drain")};parser$3.encodePayload(e,this.supportsBinary,function(n){t.doWrite(n,r)})};Polling$2.prototype.uri=function(){var e=this.query||{},t=this.secure?"https":"http",r="";this.timestampRequests!==!1&&(e[this.timestampParam]=yeast$1()),!this.supportsBinary&&!e.sid&&(e.b64=1),e=parseqs$2.encode(e),this.port&&(t==="https"&&Number(this.port)!==443||t==="http"&&Number(this.port)!==80)&&(r=":"+this.port),e.length&&(e="?"+e);var n=this.hostname.indexOf(":")!==-1;return t+"://"+(n?"["+this.hostname+"]":this.hostname)+r+this.path+e};var XMLHttpRequest$2=xmlhttprequest_browser,Polling$1=polling$1,Emitter$2=componentEmitter.exports,inherit$2=componentInherit,debug$3=browser.exports("engine.io-client:polling-xhr"),globalThis$2=globalThis_browser;pollingXhr.exports=XHR$1;pollingXhr.exports.Request=Request;function empty$1(){}function XHR$1(e){if(Polling$1.call(this,e),this.requestTimeout=e.requestTimeout,this.extraHeaders=e.extraHeaders,typeof location<"u"){var t=location.protocol==="https:",r=location.port;r||(r=t?443:80),this.xd=typeof location<"u"&&e.hostname!==location.hostname||r!==e.port,this.xs=e.secure!==t}}inherit$2(XHR$1,Polling$1);XHR$1.prototype.supportsBinary=!0;XHR$1.prototype.request=function(e){return e=e||{},e.uri=this.uri(),e.xd=this.xd,e.xs=this.xs,e.agent=this.agent||!1,e.supportsBinary=this.supportsBinary,e.enablesXDR=this.enablesXDR,e.withCredentials=this.withCredentials,e.pfx=this.pfx,e.key=this.key,e.passphrase=this.passphrase,e.cert=this.cert,e.ca=this.ca,e.ciphers=this.ciphers,e.rejectUnauthorized=this.rejectUnauthorized,e.requestTimeout=this.requestTimeout,e.extraHeaders=this.extraHeaders,new Request(e)};XHR$1.prototype.doWrite=function(e,t){var r=typeof e!="string"&&e!==void 0,n=this.request({method:"POST",data:e,isBinary:r}),o=this;n.on("success",t),n.on("error",function(a){o.onError("xhr post error",a)}),this.sendXhr=n};XHR$1.prototype.doPoll=function(){debug$3("xhr poll");var e=this.request(),t=this;e.on("data",function(r){t.onData(r)}),e.on("error",function(r){t.onError("xhr poll error",r)}),this.pollXhr=e};function Request(e){this.method=e.method||"GET",this.uri=e.uri,this.xd=!!e.xd,this.xs=!!e.xs,this.async=e.async!==!1,this.data=e.data!==void 0?e.data:null,this.agent=e.agent,this.isBinary=e.isBinary,this.supportsBinary=e.supportsBinary,this.enablesXDR=e.enablesXDR,this.withCredentials=e.withCredentials,this.requestTimeout=e.requestTimeout,this.pfx=e.pfx,this.key=e.key,this.passphrase=e.passphrase,this.cert=e.cert,this.ca=e.ca,this.ciphers=e.ciphers,this.rejectUnauthorized=e.rejectUnauthorized,this.extraHeaders=e.extraHeaders,this.create()}Emitter$2(Request.prototype);Request.prototype.create=function(){var e={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};e.pfx=this.pfx,e.key=this.key,e.passphrase=this.passphrase,e.cert=this.cert,e.ca=this.ca,e.ciphers=this.ciphers,e.rejectUnauthorized=this.rejectUnauthorized;var t=this.xhr=new XMLHttpRequest$2(e),r=this;try{debug$3("xhr open %s: %s",this.method,this.uri),t.open(this.method,this.uri,this.async);try{if(this.extraHeaders){t.setDisableHeaderCheck&&t.setDisableHeaderCheck(!0);for(var n in this.extraHeaders)this.extraHeaders.hasOwnProperty(n)&&t.setRequestHeader(n,this.extraHeaders[n])}}catch{}if(this.method==="POST")try{this.isBinary?t.setRequestHeader("Content-type","application/octet-stream"):t.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{t.setRequestHeader("Accept","*/*")}catch{}"withCredentials"in t&&(t.withCredentials=this.withCredentials),this.requestTimeout&&(t.timeout=this.requestTimeout),this.hasXDR()?(t.onload=function(){r.onLoad()},t.onerror=function(){r.onError(t.responseText)}):t.onreadystatechange=function(){if(t.readyState===2)try{var o=t.getResponseHeader("Content-Type");(r.supportsBinary&&o==="application/octet-stream"||o==="application/octet-stream; charset=UTF-8")&&(t.responseType="arraybuffer")}catch{}t.readyState===4&&(t.status===200||t.status===1223?r.onLoad():setTimeout(function(){r.onError(typeof t.status=="number"?t.status:0)},0))},debug$3("xhr data %s",this.data),t.send(this.data)}catch(o){setTimeout(function(){r.onError(o)},0);return}typeof document<"u"&&(this.index=Request.requestsCount++,Request.requests[this.index]=this)};Request.prototype.onSuccess=function(){this.emit("success"),this.cleanup()};Request.prototype.onData=function(e){this.emit("data",e),this.onSuccess()};Request.prototype.onError=function(e){this.emit("error",e),this.cleanup(!0)};Request.prototype.cleanup=function(e){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.hasXDR()?this.xhr.onload=this.xhr.onerror=empty$1:this.xhr.onreadystatechange=empty$1,e)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Request.requests[this.index],this.xhr=null}};Request.prototype.onLoad=function(){var e;try{var t;try{t=this.xhr.getResponseHeader("Content-Type")}catch{}t==="application/octet-stream"||t==="application/octet-stream; charset=UTF-8"?e=this.xhr.response||this.xhr.responseText:e=this.xhr.responseText}catch(r){this.onError(r)}e!=null&&this.onData(e)};Request.prototype.hasXDR=function(){return typeof XDomainRequest<"u"&&!this.xs&&this.enablesXDR};Request.prototype.abort=function(){this.cleanup()};Request.requestsCount=0;Request.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",unloadHandler);else if(typeof addEventListener=="function"){var terminationEvent="onpagehide"in globalThis$2?"pagehide":"unload";addEventListener(terminationEvent,unloadHandler,!1)}}function unloadHandler(){for(var e in Request.requests)Request.requests.hasOwnProperty(e)&&Request.requests[e].abort()}var Polling=polling$1,inherit$1=componentInherit,globalThis$1=globalThis_browser,pollingJsonp=JSONPPolling,rNewline=/\n/g,rEscapedNewline=/\\n/g,callbacks;function empty(){}function JSONPPolling(e){Polling.call(this,e),this.query=this.query||{},callbacks||(callbacks=globalThis$1.___eio=globalThis$1.___eio||[]),this.index=callbacks.length;var t=this;callbacks.push(function(r){t.onData(r)}),this.query.j=this.index,typeof addEventListener=="function"&&addEventListener("beforeunload",function(){t.script&&(t.script.onerror=empty)},!1)}inherit$1(JSONPPolling,Polling);JSONPPolling.prototype.supportsBinary=!1;JSONPPolling.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),Polling.prototype.doClose.call(this)};JSONPPolling.prototype.doPoll=function(){var e=this,t=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),t.async=!0,t.src=this.uri(),t.onerror=function(o){e.onError("jsonp poll error",o)};var r=document.getElementsByTagName("script")[0];r?r.parentNode.insertBefore(t,r):(document.head||document.body).appendChild(t),this.script=t;var n=typeof navigator<"u"&&/gecko/i.test(navigator.userAgent);n&&setTimeout(function(){var o=document.createElement("iframe");document.body.appendChild(o),document.body.removeChild(o)},100)};JSONPPolling.prototype.doWrite=function(e,t){var r=this;if(!this.form){var n=document.createElement("form"),o=document.createElement("textarea"),a=this.iframeId="eio_iframe_"+this.index,l;n.className="socketio",n.style.position="absolute",n.style.top="-1000px",n.style.left="-1000px",n.target=a,n.method="POST",n.setAttribute("accept-charset","utf-8"),o.name="d",n.appendChild(o),document.body.appendChild(n),this.form=n,this.area=o}this.form.action=this.uri();function c(){u(),t()}function u(){if(r.iframe)try{r.form.removeChild(r.iframe)}catch(b){r.onError("jsonp polling iframe removal error",b)}try{var g='