UNPKG

@libp2p/websockets

Version:

JavaScript implementation of the WebSockets module that libp2p uses and that implements the interface-transport spec

5 lines (4 loc) • 48.6 kB
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PWebsockets = factory()}(typeof self !== 'undefined' ? self : this, function () { "use strict";var Libp2PWebsockets=(()=>{var dn=Object.create;var Ce=Object.defineProperty;var fn=Object.getOwnPropertyDescriptor;var hn=Object.getOwnPropertyNames;var mn=Object.getPrototypeOf,xn=Object.prototype.hasOwnProperty;var jt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),T=(e,t)=>{for(var r in t)Ce(e,r,{get:t[r],enumerable:!0})},Qt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of hn(t))!xn.call(e,o)&&o!==r&&Ce(e,o,{get:()=>t[o],enumerable:!(n=fn(t,o))||n.enumerable});return e};var wn=(e,t,r)=>(r=e!=null?dn(mn(e)):{},Qt(t||!e||!e.__esModule?Ce(r,"default",{value:e,enumerable:!0}):r,e)),gn=e=>Qt(Ce({},"__esModule",{value:!0}),e);var Wr=jt(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});var $t=class{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(t){if(this.isStopped)return;let r={value:t,done:!1};if(this.pullQueue.length){let n=this.pullQueue.shift();n&&n.resolve(r)}else this.pushQueue.push(Promise.resolve(r)),this.highWaterMark!==void 0&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(let t of this.pullQueue)t.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(t){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(let r of this.pullQueue)r.reject(t);this.pullQueue.length=0}else{let r=Promise.reject(t);r.catch(()=>{}),this.pushQueue.push(r)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:t=>{let r=this.pushQueue.shift();return r?(this.lowWaterMark!==void 0&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),r):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((n,o)=>{this.pullQueue.push({resolve:n,reject:o})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}},Re=class{constructor(t,{highWaterMark:r=100,lowWaterMark:n=1}={}){let o=new $t;o.highWaterMark=r,o.lowWaterMark=n,o.removeCallback=t({push:s=>o.push(s),stop:()=>o.stop(),fail:s=>o.fail(s),on:(s,i)=>{o.eventHandlers[s]=i}})||(()=>{}),this[Symbol.asyncIterator]=()=>o[Symbol.asyncIterator](),Object.freeze(this)}};ze.EventIterator=Re;ze.default=Re});var kr=jt(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});var Bt=Wr();be.EventIterator=Bt.EventIterator;function Ps(e,t,r){return new Bt.EventIterator(({push:n})=>(this.addEventListener(e,n,t),()=>this.removeEventListener(e,n,t)),r)}be.subscribe=Ps;be.default=Bt.EventIterator});var Ms={};T(Ms,{webSockets:()=>zs});var qt=Symbol.for("@libp2p/transport");var Ht;(function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(Ht||(Ht={}));var Se=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var Ie=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}};var Gt=Symbol.for("@libp2p/service-capabilities"),ks=Symbol.for("@libp2p/service-dependencies");var Je={};T(Je,{base10:()=>In});var pi=new Uint8Array(0);function Xt(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function F(e){if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}function Jt(e){return new TextEncoder().encode(e)}function Kt(e){return new TextDecoder().decode(e)}function bn(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<e.length;o++){var s=e.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function b(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var S=0,q=0,U=0,$=m.length;U!==$&&m[U]===0;)U++,S++;for(var B=($-U)*d+1>>>0,A=new Uint8Array(B);U!==$;){for(var R=m[U],k=0,N=B-1;(R!==0||k<q)&&N!==-1;N--,k++)R+=256*A[N]>>>0,A[N]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");q=k,U++}for(var M=B-q;M!==B&&A[M]===0;)M++;for(var ve=c.repeat(S);M<B;++M)ve+=e.charAt(A[M]);return ve}function D(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var S=0;if(m[S]!==" "){for(var q=0,U=0;m[S]===c;)q++,S++;for(var $=(m.length-S)*l+1>>>0,B=new Uint8Array($);m[S];){var A=r[m.charCodeAt(S)];if(A===255)return;for(var R=0,k=$-1;(A!==0||R<U)&&k!==-1;k--,R++)A+=a*B[k]>>>0,B[k]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");U=R,S++}if(m[S]!==" "){for(var N=$-U;N!==$&&B[N]===0;)N++;for(var M=new Uint8Array(q+($-N)),ve=q;N!==$;)M[ve++]=B[N++];return M}}}function pn(m){var S=D(m);if(S)return S;throw new Error(`Non-${t} character`)}return{encode:b,decodeUnsafe:D,decode:pn}}var yn=bn,En=yn,Yt=En;var He=class{name;prefix;baseEncode;constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},qe=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,r,n){this.name=t,this.prefix=r;let o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return er(this,t)}},Ge=class{decoders;constructor(t){this.decoders=t}or(t){return er(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function er(e,t){return new Ge({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var Xe=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new He(t,r,n),this.decoder=new qe(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function K({name:e,prefix:t,encode:r,decode:n}){return new Xe(e,t,r,n)}function j({name:e,prefix:t,alphabet:r}){let{encode:n,decode:o}=Yt(r,e);return K({prefix:t,name:e,encode:n,decode:s=>F(o(s))})}function vn(e,t,r,n){let o=e.length;for(;e[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let d=t[e[l]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|d,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Cn(e,t,r){let n=t[t.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],i+=8;i>r;)i-=r,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function Sn(e){let t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}function g({name:e,prefix:t,bitsPerChar:r,alphabet:n}){let o=Sn(n);return K({prefix:t,name:e,encode(s){return Cn(s,n,r)},decode(s){return vn(s,o,r,e)}})}var In=j({prefix:"9",name:"base10",alphabet:"0123456789"});var Ke={};T(Ke,{base16:()=>Pn,base16upper:()=>Dn});var Pn=g({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Dn=g({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ze={};T(Ze,{base2:()=>Tn});var Tn=g({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ye={};T(Ye,{base256emoji:()=>Nn});var tr=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),An=tr.reduce((e,t,r)=>(e[r]=t,e),[]),On=tr.reduce((e,t,r)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return e[n]=r,e},[]);function _n(e){return e.reduce((t,r)=>(t+=An[r],t),"")}function Un(e){let t=[];for(let r of e){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=On[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);t.push(o)}return new Uint8Array(t)}var Nn=K({prefix:"\u{1F680}",name:"base256emoji",encode:_n,decode:Un});var et={};T(et,{base32:()=>Q,base32hex:()=>Rn,base32hexpad:()=>Mn,base32hexpadupper:()=>Fn,base32hexupper:()=>zn,base32pad:()=>$n,base32padupper:()=>Bn,base32upper:()=>Ln,base32z:()=>Vn});var Q=g({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ln=g({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),$n=g({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Bn=g({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Rn=g({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),zn=g({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Mn=g({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Fn=g({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Vn=g({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var tt={};T(tt,{base36:()=>ie,base36upper:()=>Wn});var ie=j({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Wn=j({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var rt={};T(rt,{base58btc:()=>I,base58flickr:()=>kn});var I=j({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),kn=j({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var nt={};T(nt,{base64:()=>jn,base64pad:()=>Qn,base64url:()=>ae,base64urlpad:()=>Hn});var jn=g({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Qn=g({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ae=g({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Hn=g({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ot={};T(ot,{base8:()=>qn});var qn=g({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var st={};T(st,{identity:()=>Gn});var Gn=K({prefix:"\0",name:"identity",encode:e=>Kt(e),decode:e=>Jt(e)});var Di=new TextEncoder,Ti=new TextDecoder;var at={};T(at,{identity:()=>go});var Kn=or,rr=128,Zn=127,Yn=~Zn,eo=Math.pow(2,31);function or(e,t,r){t=t||[],r=r||0;for(var n=r;e>=eo;)t[r++]=e&255|rr,e/=128;for(;e&Yn;)t[r++]=e&255|rr,e>>>=7;return t[r]=e|0,or.bytes=r-n+1,t}var to=it,ro=128,nr=127;function it(e,n){var r=0,n=n||0,o=0,s=n,i,a=e.length;do{if(s>=a)throw it.bytes=0,new RangeError("Could not decode varint");i=e[s++],r+=o<28?(i&nr)<<o:(i&nr)*Math.pow(2,o),o+=7}while(i>=ro);return it.bytes=s-n,r}var no=Math.pow(2,7),oo=Math.pow(2,14),so=Math.pow(2,21),io=Math.pow(2,28),ao=Math.pow(2,35),co=Math.pow(2,42),lo=Math.pow(2,49),uo=Math.pow(2,56),po=Math.pow(2,63),fo=function(e){return e<no?1:e<oo?2:e<so?3:e<io?4:e<ao?5:e<co?6:e<lo?7:e<uo?8:e<po?9:10},ho={encode:Kn,decode:to,encodingLength:fo},mo=ho,ce=mo;function le(e,t=0){return[ce.decode(e,t),ce.decode.bytes]}function Z(e,t,r=0){return ce.encode(e,t,r),t}function Y(e){return ce.encodingLength(e)}function G(e,t){let r=t.byteLength,n=Y(e),o=n+Y(r),s=new Uint8Array(o+r);return Z(e,s,0),Z(r,s,n),s.set(t,o),new ee(e,r,t,s)}function sr(e){let t=F(e),[r,n]=le(t),[o,s]=le(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new ee(r,o,i,t)}function ir(e,t){if(e===t)return!0;{let r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&Xt(e.bytes,r.bytes)}}var ee=class{code;size;digest;bytes;constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}};var ar=0,xo="identity",cr=F;function wo(e){return G(ar,cr(e))}var go={code:ar,name:xo,encode:cr,digest:wo};var ut={};T(ut,{sha256:()=>bo,sha512:()=>yo});function lt({name:e,code:t,encode:r}){return new ct(e,t,r)}var ct=class{name;code;encode;constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){let r=this.encode(t);return r instanceof Uint8Array?G(this.code,r):r.then(n=>G(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ur(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}var bo=lt({name:"sha2-256",code:18,encode:ur("SHA-256")}),yo=lt({name:"sha2-512",code:19,encode:ur("SHA-512")});function pr(e,t){let{bytes:r,version:n}=e;switch(n){case 0:return vo(r,pt(e),t??I.encoder);default:return Co(r,pt(e),t??Q.encoder)}}var dr=new WeakMap;function pt(e){let t=dr.get(e);if(t==null){let r=new Map;return dr.set(e,r),r}return t}var H=class e{code;version;multihash;bytes;"/";constructor(t,r,n,o){this.code=r,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:r}=this;if(t!==pe)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==So)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:r}=this.multihash,n=G(t,r);return e.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return e.equals(this,t)}static equals(t,r){let n=r;return n!=null&&t.code===n.code&&t.version===n.version&&ir(t.multihash,n.multihash)}toString(t){return pr(this,t)}toJSON(){return{"/":pr(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let r=t;if(r instanceof e)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new e(n,o,s,i??fr(n,o,s.bytes))}else if(r[Io]===!0){let{version:n,multihash:o,code:s}=r,i=sr(o);return e.create(n,s,i)}else return null}static create(t,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(r!==pe)throw new Error(`Version 0 CID must use dag-pb (code: ${pe}) block encoding`);return new e(t,r,n,n.bytes)}case 1:{let o=fr(t,r,n.bytes);return new e(t,r,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,pe,t)}static createV1(t,r){return e.create(1,t,r)}static decode(t){let[r,n]=e.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=e.inspectBytes(t),n=r.size-r.multihashSize,o=F(t.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new ee(r.multihashCode,r.digestSize,s,o);return[r.version===0?e.createV0(i):e.createV1(r.codec,i),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[b,D]=le(t.subarray(r));return r+=D,b},o=n(),s=pe;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),l=r+c,d=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(t,r){let[n,o]=Eo(t,r),s=e.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return pt(s).set(n,t),s}};function Eo(e,t){switch(e[0]){case"Q":{let r=t??I;return[I.prefix,r.decode(`${I.prefix}${e}`)]}case I.prefix:{let r=t??I;return[I.prefix,r.decode(e)]}case Q.prefix:{let r=t??Q;return[Q.prefix,r.decode(e)]}case ie.prefix:{let r=t??ie;return[ie.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function vo(e,t,r){let{prefix:n}=r;if(n!==I.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=t.get(n);if(o==null){let s=r.encode(e).slice(1);return t.set(n,s),s}else return o}function Co(e,t,r){let{prefix:n}=r,o=t.get(n);if(o==null){let s=r.encode(e);return t.set(n,s),s}else return o}var pe=112,So=18;function fr(e,t,r){let n=Y(e),o=n+Y(t),s=new Uint8Array(o+r.byteLength);return Z(e,s,0),Z(t,s,n),s.set(r,o),s}var Io=Symbol.for("@ipld/js-cid/CID");var de={...st,...Ze,...ot,...Je,...Ke,...et,...tt,...rt,...nt,...Ye},Ji={...ut,...at};function fe(e=0){return new Uint8Array(e)}function mr(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var hr=mr("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),dt=mr("ascii","a",e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},e=>{e=e.substring(1);let t=fe(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}),Po={utf8:hr,"utf-8":hr,hex:de.base16,latin1:dt,ascii:dt,binary:dt,...de},De=Po;function O(e,t="utf8"){let r=De[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}var y=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},V=class extends Error{static name="ValidationError";name="ValidationError"},he=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Te=class extends Error{static name="InvalidProtocolError";name="InvalidProtocolError"};function xr(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function z(e,t="utf8"){let r=De[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}var Do=Math.pow(2,7),To=Math.pow(2,14),Ao=Math.pow(2,21),ft=Math.pow(2,28),ht=Math.pow(2,35),mt=Math.pow(2,42),xt=Math.pow(2,49),w=128,v=127;function te(e){if(e<Do)return 1;if(e<To)return 2;if(e<Ao)return 3;if(e<ft)return 4;if(e<ht)return 5;if(e<mt)return 6;if(e<xt)return 7;if(Number.MAX_SAFE_INTEGER!=null&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function wt(e,t,r=0){switch(te(e)){case 8:t[r++]=e&255|w,e/=128;case 7:t[r++]=e&255|w,e/=128;case 6:t[r++]=e&255|w,e/=128;case 5:t[r++]=e&255|w,e/=128;case 4:t[r++]=e&255|w,e>>>=7;case 3:t[r++]=e&255|w,e>>>=7;case 2:t[r++]=e&255|w,e>>>=7;case 1:{t[r++]=e&255,e>>>=7;break}default:throw new Error("unreachable")}return t}function Oo(e,t){let r=e[t],n=0;if(n+=r&v,r<w||(r=e[t+1],n+=(r&v)<<7,r<w)||(r=e[t+2],n+=(r&v)<<14,r<w)||(r=e[t+3],n+=(r&v)<<21,r<w)||(r=e[t+4],n+=(r&v)*ft,r<w)||(r=e[t+5],n+=(r&v)*ht,r<w)||(r=e[t+6],n+=(r&v)*mt,r<w)||(r=e[t+7],n+=(r&v)*xt,r<w))return n;throw new RangeError("Could not decode varint")}function _o(e,t){let r=e.get(t),n=0;if(n+=r&v,r<w||(r=e.get(t+1),n+=(r&v)<<7,r<w)||(r=e.get(t+2),n+=(r&v)<<14,r<w)||(r=e.get(t+3),n+=(r&v)<<21,r<w)||(r=e.get(t+4),n+=(r&v)*ft,r<w)||(r=e.get(t+5),n+=(r&v)*ht,r<w)||(r=e.get(t+6),n+=(r&v)*mt,r<w)||(r=e.get(t+7),n+=(r&v)*xt,r<w))return n;throw new RangeError("Could not decode varint")}function gt(e,t=0){return e instanceof Uint8Array?Oo(e,t):_o(e,t)}function me(e,t){t==null&&(t=e.reduce((o,s)=>o+s.length,0));let r=fe(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}var Ae=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let r=this.index,n=t();return n===void 0&&(this.index=r),n}parseWith(t){let r=t();if(this.index===this.input.length)return r}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let r=this.readChar();if(r===t)return r})}readSeparator(t,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,r,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let d=this.readAtomically(()=>{let b=this.readChar();if(b===void 0)return;let D=Number.parseInt(b,t);if(!Number.isNaN(D))return D});if(d===void 0)break;if(s*=t,s+=d,s>l||(i+=1,r!==void 0&&i>r))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let r=0;r<t.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[r]=n}return t})}readIPv6Addr(){let t=r=>{for(let n=0;n<r.length/2;n++){let o=n*2;if(n<r.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return r[o]=i[0],r[o+1]=i[1],r[o+2]=i[2],r[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];r[o]=s>>8,r[o+1]=s&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,o]=t(r);if(n===16)return r;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var No=45,Lo=15,Oe=new Ae;function bt(e){if(!(e.length>Lo))return Oe.new(e).parseWith(()=>Oe.readIPv4Addr())}function yt(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>No))return Oe.new(e).parseWith(()=>Oe.readIPv6Addr())}function re(e){return!!bt(e)}function _e(e){return!!yt(e)}function vt(e){return t=>O(t,e)}function Ct(e){return t=>z(t,e)}function ne(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function X(e){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof e=="string"?parseInt(e):e),new Uint8Array(t)}function gr(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let r=z(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=X(n);return me([r,o],r.length+o.length)}function br(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let r=Q.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=X(n);return me([r,o],r.length+o.length)}function St(e){let t=e.subarray(0,e.length-2),r=e.subarray(e.length-2),n=O(t,"base32"),o=ne(r);return`${n}:${o}`}var It=function(e){e=e.toString().trim();let t=new Uint8Array(4);return e.split(/\./g).forEach((r,n)=>{let o=parseInt(r,10);if(isNaN(o)||o<0||o>255)throw new y("Invalid byte value in IP address");t[n]=o}),t},yr=function(e){let t=0;e=e.toString().trim();let r=e.split(":",8),n;for(n=0;n<r.length;n++){let s=re(r[n]),i;s&&(i=It(r[n]),r[n]=O(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,O(i.subarray(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let s=[n,1];for(n=9-r.length;n>0;n--)s.push("0");r.splice.apply(r,s)}let o=new Uint8Array(t+16);for(n=0;n<r.length;n++){r[n]===""&&(r[n]="0");let s=parseInt(r[n],16);if(isNaN(s)||s<0||s>65535)throw new y("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},Er=function(e){if(e.byteLength!==4)throw new y("IPv4 address was incorrect length");let t=[];for(let r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},vr=function(e){if(e.byteLength!==16)throw new y("IPv6 address was incorrect length");let t=[];for(let n=0;n<e.byteLength;n+=2){let o=e[n],s=e[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}let r=t.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new y(`Invalid IPv6 address "${r}"`)}};function Cr(e){try{let t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new y(`Invalid IPv6 address "${e}"`)}}var Et=Object.values(de).map(e=>e.decoder),$o=function(){let e=Et[0].or(Et[1]);return Et.slice(2).forEach(t=>e=e.or(t)),e}();function Sr(e){return $o.decode(e)}function Ir(e){return t=>e.encoder.encode(t)}function Bo(e){if(parseInt(e).toString()!==e)throw new V("Value must be an integer")}function Ro(e){if(e<0)throw new V("Value must be a positive integer, or zero")}function zo(e){return t=>{if(t>e)throw new V(`Value must be smaller than or equal to ${e}`)}}function Mo(...e){return t=>{for(let r of e)r(t)}}var xe=Mo(Bo,Ro,zo(65535));var E=-1,Pt=class{protocolsByCode=new Map;protocolsByName=new Map;getCodec(t){let r;if(typeof t=="string"?r=this.protocolsByName.get(t):r=this.protocolsByCode.get(t),r==null)throw new Te(`Protocol ${t} was unknown`);return r}addCodec(t,r,n){this.protocolsByCode.set(t,r),this.protocolsByName.set(r.name,r),n?.forEach(o=>{this.protocolsByName.set(o,r)})}deleteCodec(t){let r=this.getCodec(t);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},P=new Pt,ms=[{code:4,name:"ip4",size:32,valueToBytes:It,bytesToValue:Er,validate:e=>{if(!re(e))throw new V(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:X,bytesToValue:ne,validate:xe},{code:273,name:"udp",size:16,valueToBytes:X,bytesToValue:ne,validate:xe},{code:33,name:"dccp",size:16,valueToBytes:X,bytesToValue:ne,validate:xe},{code:41,name:"ip6",size:128,valueToBytes:yr,bytesToValue:vr,stringToValue:Cr,validate:e=>{if(!_e(e))throw new V(`Invalid IPv6 address "${e}"`)}},{code:42,name:"ip6zone",size:E},{code:43,name:"ipcidr",size:8,bytesToValue:vt("base10"),valueToBytes:Ct("base10")},{code:53,name:"dns",size:E,resolvable:!0},{code:54,name:"dns4",size:E,resolvable:!0},{code:55,name:"dns6",size:E,resolvable:!0},{code:56,name:"dnsaddr",size:E,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:X,bytesToValue:ne,validate:xe},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:E,path:!0,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:E,bytesToValue:vt("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?Ct("base58btc")(e):H.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:St,valueToBytes:gr},{code:445,name:"onion3",size:296,bytesToValue:St,valueToBytes:br},{code:446,name:"garlic64",size:E},{code:447,name:"garlic32",size:E},{code:448,name:"tls"},{code:449,name:"sni",size:E},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:E,bytesToValue:Ir(ae),valueToBytes:Sr},{code:480,name:"http"},{code:481,name:"http-path",size:E,stringToValue:e=>`/${decodeURIComponent(e)}`,valueToString:e=>encodeURIComponent(e.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:E}];ms.forEach(e=>{P.addCodec(e.code,e,e.aliases)});function Pr(e){let t=[],r=0;for(;r<e.length;){let n=gt(e,r),o=P.getCodec(n),s=te(n),i=xs(o,e,r+s),a=0;i>0&&o.size===E&&(a=te(i));let c=s+a+i,l={code:n,name:o.name,bytes:e.subarray(r,r+c)};if(i>0){let d=r+s+a,b=e.subarray(d,d+i);l.value=o.bytesToValue?.(b)??O(b)}t.push(l),r+=c}return t}function Dr(e){let t=0,r=[];for(let n of e){if(n.bytes==null){let o=P.getCodec(n.code),s=te(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??z(n.value),a=i.byteLength,o.size===E&&(c=te(a)));let l=new Uint8Array(s+c+a),d=0;wt(n.code,l,d),d+=s,i!=null&&(o.size===E&&(wt(a,l,d),d+=c),l.set(i,d)),n.bytes=l}r.push(n.bytes),t+=n.bytes.byteLength}return me(r,t)}function Tr(e){if(e.charAt(0)!=="/")throw new y('String multiaddr must start with "/"');let t=[],r="protocol",n="",o="";for(let s=1;s<e.length;s++){let i=e.charAt(s);i!=="/"&&(r==="protocol"?o+=e.charAt(s):n+=e.charAt(s));let a=s===e.length-1;if(i==="/"||a){let c=P.getCodec(o);if(r==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",r="protocol";continue}else if(a)throw new y(`Component ${o} was missing value`);r="value"}else if(r==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new y(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}t.push(l),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new y("Incomplete multiaddr");return t}function Ar(e){return`/${e.flatMap(t=>{if(t.value==null)return t.name;let r=P.getCodec(t.code);if(r==null)throw new y(`Unknown protocol code ${t.code}`);return[t.name,r.valueToString?.(t.value)??t.value]}).join("/")}`}function xs(e,t,r){return e.size==null||e.size===0?0:e.size>0?e.size/8:gt(t,r)}var ws=Symbol.for("nodejs.util.inspect.custom"),Lt=Symbol.for("@multiformats/multiaddr"),gs=[53,54,55,56],Nt=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}};function bs(e){if(e==null&&(e="/"),_r(e))return e.getComponents();if(e instanceof Uint8Array)return Pr(e);if(typeof e=="string")return e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),e===""&&(e="/"),Tr(e);if(Array.isArray(e))return e;throw new y("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Be=class e{[Lt]=!0;#e;#t;#r;constructor(t="/",r={}){this.#e=bs(t),r.validate!==!1&&ys(this)}get bytes(){return this.#r==null&&(this.#r=Dr(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Ar(this.#e)),this.#t}toJSON(){return this.toString()}toOptions(){let t,r,n,o,s="";for(let{code:a,name:c,value:l}of this.#e)a===42&&(s=`%${l??""}`),gs.includes(a)&&(r="tcp",o=443,n=`${l??""}${s}`,t=a===55?6:4),(a===6||a===273)&&(r=c==="tcp"?"tcp":"udp",o=parseInt(l??"")),(a===4||a===41)&&(r="tcp",n=`${l??""}${s}`,t=a===41?6:4);if(t==null||r==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:r,port:o}}getComponents(){return[...this.#e]}protos(){return this.#e.map(({code:t,value:r})=>{let n=P.getCodec(t);return{code:t,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#e.map(({code:t})=>t)}protoNames(){return this.#e.map(({name:t})=>t)}tuples(){return this.#e.map(({code:t,value:r})=>{if(r==null)return[t];let n=P.getCodec(t),o=[t];return r!=null&&o.push(n.valueToBytes?.(r)??z(r)),o})}stringTuples(){return this.#e.map(({code:t,value:r})=>r==null?[t]:[t,r])}encapsulate(t){let r=new e(t);return new e([...this.#e,...r.getComponents()],{validate:!1})}decapsulate(t){let r=t.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new he(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new e(n.slice(0,o),{validate:!1})}decapsulateCode(t){let r;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===t){r=n;break}return new e(this.#e.slice(0,r),{validate:!1})}getPeerId(){try{let t=[];this.#e.forEach(({code:n,value:o})=>{n===421&&t.push([n,o]),n===290&&(t=[])});let r=t.pop();if(r?.[1]!=null){let n=r[1];return n[0]==="Q"||n[0]==="1"?O(I.decode(`z${n}`),"base58btc"):O(H.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let t of this.#e)if(P.getCodec(t.code).path)return t.value??null;return null}equals(t){return xr(this.bytes,t.bytes)}async resolve(t){let r=this.protos().find(s=>s.resolvable);if(r==null)return[this];let n=Or.get(r.name);if(n==null)throw new Nt(`no available resolver for ${r.name}`);return(await n(this,t)).map(s=>ge(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(){return!(this.#e.length!==2||this.#e[0].code!==4&&this.#e[0].code!==41||this.#e[1].code!==6&&this.#e[1].code!==273)}[ws](){return`Multiaddr(${this.toString()})`}};function ys(e){e.getComponents().forEach(t=>{let r=P.getCodec(t.code);t.value!=null&&r.validate?.(t.value)})}var ac=parseInt("0xFFFF",16),cc=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Or=new Map;function _r(e){return!!e?.[Lt]}function ge(e){return new Be(e)}function _(e){let t=P.getCodec(e);return{code:t.code,size:t.size??0,name:t.name,resolvable:!!t.resolvable,path:!!t.path}}var Is=[_("tcp").code,_("dns").code,_("dnsaddr").code,_("dns4").code,_("dns6").code];function Lr(e){return Rr("sni",e)?.[1]}function $r(e){let t=Rr("tcp",e)?.[1];return t==null?"":`:${t}`}function Rr(e,t){let r;try{r=_(e).code}catch{return}for(let[n,o]of t)if(n===r&&o!=null)return[n,o]}function Br(e){return e.some(([t,r])=>t===_("tls").code)}function L(e,t,r){let n=zr[_(e).name];if(n==null)throw new Error(`Can't interpret protocol ${_(e).name}`);let o=n(t,r);return e===_("ip6").code?`[${o}]`:o}var zr={ip4:(e,t)=>e,ip6:(e,t)=>t.length===0?e:`[${e}]`,tcp:(e,t)=>{let r=t.pop();if(r==null)throw new Error("Unexpected end of multiaddr");return`tcp://${L(r[0],r[1]??"",t)}:${e}`},udp:(e,t)=>{let r=t.pop();if(r==null)throw new Error("Unexpected end of multiaddr");return`udp://${L(r[0],r[1]??"",t)}:${e}`},dnsaddr:(e,t)=>e,dns4:(e,t)=>e,dns6:(e,t)=>e,dns:(e,t)=>e,ipfs:(e,t)=>{let r=t.pop();if(r==null)throw new Error("Unexpected end of multiaddr");return`${L(r[0],r[1]??"",t)}`},p2p:(e,t)=>{let r=t.pop();if(r==null)throw new Error("Unexpected end of multiaddr");return`${L(r[0],r[1]??"",t)}`},http:(e,t)=>{let r=Br(t),n=Lr(t),o=$r(t);if(r&&n!=null)return`https://${n}${o}`;let s=r?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=L(i[0],i[1]??"",t);return a=a.replace("tcp://",""),`${s}${a}`},"http-path":(e,t)=>{let r=t.pop();if(r==null)throw new Error("Unexpected end of multiaddr");let n=L(r[0],r[1]??"",t),o=decodeURIComponent(e);return`${n}/${o}`},tls:(e,t)=>{let r=t.pop();if(r==null)throw new Error("Unexpected end of multiaddr");return L(r[0],r[1]??"",t)},sni:(e,t)=>{let r=t.pop();if(r==null)throw new Error("Unexpected end of multiaddr");return L(r[0],r[1]??"",t)},https:(e,t)=>{let r=t.pop();if(r==null)throw new Error("Unexpected end of multiaddr");let n=L(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(e,t)=>{let r=Br(t),n=Lr(t),o=$r(t);if(r&&n!=null)return`wss://${n}${o}`;let s=r?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=L(i[0],i[1]??"",t);return a=a.replace("tcp://",""),`${s}${a}`},wss:(e,t)=>{let r=t.pop();if(r==null)throw new Error("Unexpected end of multiaddr");let n=L(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`}};function Mr(e,t){let n=ge(e).stringTuples(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=_(o[0]),i=zr[s.name];if(i==null)throw new Error(`No interpreter found for ${s.name}`);let a=i(o[1]??"",n);return t?.assumeHttp!==!1&&Is.includes(o[0])&&(a=a.replace(/^.*:\/\//,""),o[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://")||a.startsWith("ws://")||a.startsWith("wss://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var Fr=async e=>{if(e.readyState>=2)throw new Error("socket closed");e.readyState!==1&&await new Promise((t,r)=>{function n(){e.removeEventListener("open",o),e.removeEventListener("error",s)}function o(){n(),t()}function s(i){n(),r(i.error??new Error(`connect ECONNREFUSED ${e.url}`))}e.addEventListener("open",o),e.addEventListener("error",s)})};var Vr=(e,t)=>(t=t??{},t.closeOnEnd=t.closeOnEnd!==!1,async n=>{for await(let o of n){try{await Fr(e)}catch(s){if(s.message==="socket closed")break;throw s}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(o)}t.closeOnEnd!=null&&e.readyState<=1&&await new Promise((o,s)=>{e.addEventListener("close",i=>{if(i.wasClean||i.code===1006)o();else{let a=Object.assign(new Error("ws error"),{event:i});s(a)}}),setTimeout(()=>{e.close()})})});var Qr=wn(kr(),1);function jr(e){return e instanceof ArrayBuffer||e?.constructor?.name==="ArrayBuffer"&&typeof e?.byteLength=="number"}var Hr=e=>{e.binaryType="arraybuffer";let t=async()=>{await new Promise((s,i)=>{if(n){s();return}if(o!=null){i(o);return}let a=d=>{e.removeEventListener("open",c),e.removeEventListener("error",l),d()},c=()=>{a(s)},l=d=>{a(()=>{i(d.error??new Error(`connect ECONNREFUSED ${e.url}`))})};e.addEventListener("open",c),e.addEventListener("error",l)})},r=async function*(){let s=new Qr.EventIterator(({push:i,stop:a,fail:c})=>{let l=b=>{let D=null;typeof b.data=="string"&&(D=z(b.data)),jr(b.data)&&(D=new Uint8Array(b.data)),b.data instanceof Uint8Array&&(D=b.data),D!=null&&i(D)},d=b=>{c(b.error??new Error("Socket error"))};return e.addEventListener("message",l),e.addEventListener("error",d),e.addEventListener("close",a),()=>{e.removeEventListener("message",l),e.removeEventListener("error",d),e.removeEventListener("close",a)}},{highWaterMark:1/0});await t();for await(let i of s)yield jr(i)?new Uint8Array(i):i}(),n=e.readyState===1,o;return e.addEventListener("open",()=>{n=!0,o=null}),e.addEventListener("close",()=>{n=!1,o=null}),e.addEventListener("error",s=>{n||(o=s.error??new Error(`connect ECONNREFUSED ${e.url}`))}),Object.assign(r,{connected:t})};var qr=(e,t)=>{t=t??{};let r=Hr(e),n=t.remoteAddress,o=t.remotePort;if(e.url!=null)try{let i=new URL(e.url);n=i.hostname,o=parseInt(i.port,10)}catch{}if(n==null||o==null)throw new Error("Remote connection did not have address and/or port");return{sink:Vr(e,t),source:r,connected:async()=>{await r.connected()},close:async()=>{(e.readyState===e.CONNECTING||e.readyState===e.OPEN)&&await new Promise(i=>{e.addEventListener("close",()=>{i()}),e.close()})},destroy:()=>{e.terminate!=null?e.terminate():e.close()},remoteAddress:n,remotePort:o,socket:e}};var Gr=WebSocket;var Ds={"http:":"ws:","https:":"wss:"},Xr="ws:",Jr=(e,t)=>{if(e.startsWith("//")&&(e=`${t?.protocol??Xr}${e}`),e.startsWith("/")&&t!=null){let n=t.protocol??Xr,o=t.host,s=t.port!=null&&o?.endsWith(`:${t.port}`)!==!0?`:${t.port}`:"";e=`${n}//${o}${s}${e}`}let r=new URL(e);for(let[n,o]of Object.entries(Ds))r.protocol===n&&(r.protocol=o);return r};function Kr(e,t){let r=typeof window>"u"?void 0:window.location;t=t??{};let n=Jr(e,r),o=new Gr(n.toString(),t.websocket);return qr(o,t)}function Rt(){let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}var Me=class extends Event{type;detail;constructor(t,r){super(t),this.type=t,this.detail=r}};var Fe=class extends Error{type;code;constructor(t,r,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=r??"ABORT_ERR"}};async function Zr(e,t,r){if(t==null)return e;if(t.aborted)return e.catch(()=>{}),Promise.reject(new Fe(r?.errorMessage,r?.errorCode,r?.errorName));let n,o=new Fe(r?.errorMessage,r?.errorCode,r?.errorName);try{return await Promise.race([e,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Ts=e=>e.toString().split("/").slice(1),oe=e=>({match:t=>t.length<1?!1:e(t[0])?t.slice(1):!1,pattern:"fn"}),u=e=>({match:t=>oe(r=>r===e).match(t),pattern:e}),J=()=>({match:e=>oe(t=>typeof t=="string").match(e),pattern:"{string}"}),se=()=>({match:e=>oe(t=>!isNaN(parseInt(t))).match(e),pattern:"{number}"}),h=()=>({match:e=>{if(e.length<2||e[0]!=="p2p"&&e[0]!=="ipfs")return!1;if(e[1].startsWith("Q")||e[1].startsWith("1"))try{I.decode(`z${e[1]}`)}catch{return!1}else return!1;return e.slice(2)},pattern:"/p2p/{peerid}"}),ye=()=>({match:e=>{if(e.length<2||e[0]!=="certhash")return!1;try{ae.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),f=e=>({match:t=>{let r=e.match(t);return r===!1?t:r},pattern:`optional(${e.pattern})`}),C=(...e)=>({match:t=>{let r;for(let n of e){let o=n.match(t);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1},pattern:`or(${e.map(t=>t.pattern).join(", ")})`}),p=(...e)=>({match:t=>{for(let r of e){let n=r.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${e.map(t=>t.pattern).join(", ")})`});function x(...e){function t(o){let s=Ts(o);for(let i of e){let a=i.match(s);if(a===!1)return!1;s=a}return s}function r(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:e,matches:r,exactMatch:n}}var As=h(),bl=x(As),We=p(u("dns4"),J()),ke=p(u("dns6"),J()),je=p(u("dnsaddr"),J()),Mt=p(u("dns"),J()),yl=x(We,f(h())),El=x(ke,f(h())),vl=x(je,f(h())),Os=x(C(Mt,je,We,ke),f(h())),Yr=p(u("ip4"),oe(re)),en=p(u("ip6"),oe(_e)),Ft=C(Yr,en),W=C(Ft,Mt,We,ke,je),Cl=x(C(Ft,p(C(Mt,je,We,ke),f(h())))),Sl=x(Yr),Il=x(en),Pl=x(Ft),Vt=p(W,u("tcp"),se()),Ee=p(W,u("udp"),se()),Dl=x(p(Vt,f(h()))),Tl=x(Ee),Wt=p(Ee,u("quic"),f(h())),Qe=p(Ee,u("quic-v1"),f(h())),_s=C(Wt,Qe),Al=x(Wt),Ol=x(Qe),zt=C(W,Vt,Ee,Wt,Qe),tn=C(p(zt,u("ws"),f(h()))),rn=x(tn),nn=C(p(zt,u("wss"),f(h())),p(zt,u("tls"),f(p(u("sni"),J())),u("ws"),f(h()))),on=x(nn),sn=p(Ee,u("webrtc-direct"),f(ye()),f(ye()),f(h())),_l=x(sn),an=p(Qe,u("webtransport"),f(ye()),f(ye()),f(h())),Ul=x(an),Ve=C(tn,nn,p(Vt,f(h())),p(_s,f(h())),p(W,f(h())),sn,an,h()),Nl=x(Ve),Us=p(Ve,u("p2p-circuit"),h()),Ll=x(Us),Ns=C(p(Ve,u("p2p-circuit"),u("webrtc"),f(h())),p(Ve,u("webrtc"),f(h())),p(u("webrtc"),f(h()))),$l=x(Ns),Ls=C(p(W,u("tcp"),se(),u("http"),f(h())),p(W,u("http"),f(h()))),Bl=x(Ls),$s=C(p(W,u("tcp"),C(p(u("443"),u("http")),p(se(),u("https")),p(se(),u("tls"),u("http"))),f(h())),p(W,u("tls"),u("http"),f(h())),p(W,u("https"),f(h()))),Rl=x($s),Bs=C(p(u("memory"),J(),f(h()))),zl=x(Bs);function cn(e){return e.filter(t=>on.exactMatch(t)||rn.exactMatch(t))}function ln(){throw new Error("WebSocket Servers can not be created in the browser!")}function un(e,t,r){let n=r.logger.forComponent("libp2p:websockets:maconn"),o=r.metrics,s=r.metricPrefix??"",i={log:n,async sink(a){try{await e.sink(async function*(){for await(let c of a)c instanceof Uint8Array?yield c:yield c.subarray()}())}catch(c){c.type!=="aborted"&&n.error(c)}},source:e.source,remoteAddr:t,timeline:{open:Date.now()},async close(a={}){let c=Date.now();if(a.signal==null){let d=AbortSignal.timeout(500);a={...a,signal:d}}let l=()=>{let{host:d,port:b}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",d,b,Date.now()-c),this.abort(new Se("Socket close timeout"))};a.signal?.addEventListener("abort",l);try{await e.close()}catch(d){n.error("error closing WebSocket gracefully",d),this.abort(d)}finally{a.signal?.removeEventListener("abort",l),i.timeline.close=Date.now()}},abort(a){let{host:c,port:l}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",c,l,a),e.destroy(),i.timeline.close=Date.now(),o?.increment({[`${s}error`]:!0})}};return e.socket.addEventListener("close",()=>{o?.increment({[`${s}close`]:!0}),i.timeline.close==null&&(i.timeline.close=Date.now())},{once:!0}),i}var kt=class{log;init;logger;metrics;components;constructor(t,r={}){this.log=t.logger.forComponent("libp2p:websockets"),this.logger=t.logger,this.components=t,this.init=r,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[qt]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Gt]=["@libp2p/transport"];async dial(t,r){this.log("dialing %s",t),r=r??{};let n=await this._connect(t,r),o=un(n,t,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",o.remoteAddr);let s=await r.upgrader.upgradeOutbound(o,r);return this.log("outbound connection %s upgraded",o.remoteAddr),s}async _connect(t,r){r?.signal?.throwIfAborted();let n=t.toOptions();this.log("dialing %s:%s",n.host,n.port);let o=Rt(),s=Kr(Mr(t),this.init);s.socket.addEventListener("error",()=>{let i=new Ie(`Could not connect to ${t.toString()}`);this.log.error("connection error:",i),this.metrics?.dialerEvents.increment({error:!0}),o.reject(i)});try{r.onProgress?.(new Me("websockets:open-connection")),await Zr(Promise.race([s.connected(),o.promise]),r.signal)}catch(i){throw r.signal?.aborted&&this.metrics?.dialerEvents.increment({abort:!0}),s.close().catch(a=>{this.log.error("error closing raw socket",a)}),i}return this.log("connected %s",t),this.metrics?.dialerEvents.increment({connect:!0}),s}createListener(t){return ln({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...t})}listenFilter(t){return t=Array.isArray(t)?t:[t],this.init?.filter!=null?this.init?.filter(t):cn(t)}dialFilter(t){return this.listenFilter(t)}};function zs(e={}){return t=>new kt(t,e)}return gn(Ms);})(); return Libp2PWebsockets})); //# sourceMappingURL=index.min.js.map